diff --git a/.github/scripts/forge_release.py b/.github/scripts/forge_release.py index e41647b5d..e875f4795 100644 --- a/.github/scripts/forge_release.py +++ b/.github/scripts/forge_release.py @@ -168,20 +168,37 @@ def diff(old, new): return result +# Where a pending Forge update is accepted. Jira's own Manage apps page has no +# Update for it, so it is never named as the place. +ADMIN_PATH = ( + "Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, " + "Connected apps, Coderhelm, View app details, Update" +) + + +def admin_steps(install_url=""): + """The admin's steps, with the installation link first when there is one.""" + if install_url: + return (f"An Atlassian site admin opens the app's installation link ({install_url}), " + f"chooses the site and clicks Update, or uses {ADMIN_PATH}.") + return f"An Atlassian site admin accepts the update in {ADMIN_PATH}." + + def summary_markdown(result): """The run summary text. Holds manifest facts only, never site names.""" lines = ["## Jira app permissions", ""] if result["needs_admin"]: lines += [ - "**A site admin must accept this update in Jira.** The new version asks for:", + "**An Atlassian site admin must accept this update.** The new version asks for:", "", *[f"- {r}" for r in result["reasons"]], "", "Forge rolls out code-only changes by itself, but not new access. On each site,", - "an admin opens **Jira settings (gear) → Apps → Manage apps**, finds **Coderhelm**", - "and clicks **Update**. Until then the site keeps running the previous major version.", + admin_steps() + " Until then the site keeps running the previous major version.", "The workflow also runs `forge install --upgrade` itself; that succeeds only on", - "sites where the Forge token's account is a site admin.", + "sites where the Forge token's account is a site admin. Its refusals elsewhere", + "(\"insufficient permissions\", or a suggestion to install for another product) are", + "about the token's account, not something the site is missing.", ] else: lines.append("No new access. Every site gets this version automatically; no one needs to do anything.") @@ -242,13 +259,24 @@ def latest_version(versions): return ".".join(map(str, max(found))) if found else None -def latest_pointer(versions, manifest, commit="", published_at=""): - """The pointer CoderHelm reads; None when no version is known.""" +INSTALL_LINK = re.compile(r"^https://developer\.atlassian\.com/console/install/[^\s]+$") + + +def latest_pointer(versions, manifest, commit="", published_at="", install_url=""): + """The pointer CoderHelm reads; None when no version is known. + + `install_url` is the app's installation link from the developer console + (Distribution); CoderHelm offers it to site admins as the one-click update. + Anything else is left out. + """ version = latest_version(versions) if not version: return None app_id = str(((manifest or {}).get("app") or {}).get("id") or "") - return {"version": version, "appId": app_id, "commit": commit, "publishedAt": published_at} + out = {"version": version, "appId": app_id, "commit": commit, "publishedAt": published_at} + if install_url and INSTALL_LINK.match(install_url.strip()): + out["installUrl"] = install_url.strip() + return out def load_features(path): @@ -282,8 +310,8 @@ def behind_report(lines, latest, features): return "", "" latest_text = f"latest {latest}" if latest else "latest unknown" md = ["", "## Sites still behind", ""] - md.append("Each one runs an older Coderhelm app until its Jira admin accepts the update:") - md.append("Jira Settings, Apps, Manage apps, Coderhelm, Update. CoderHelm shows the same on the team's Integrations page.") + md.append("Each one runs an older Coderhelm app until a site admin accepts the update.") + md.append(admin_steps() + " CoderHelm shows the same on the team's Integrations page.") md.append("") lacking = [] for i, (major, product) in enumerate(rows, 1): @@ -295,7 +323,7 @@ def behind_report(lines, latest, features): what = f" They lack: {', '.join(lacking)}." if lacking else "" warning = ( f"{len(rows)} installation(s) still run an older Coderhelm app ({latest_text}).{what}" - " A Jira admin on each site must accept the update: Jira Settings, Apps, Manage apps, Coderhelm, Update." + " " + admin_steps() ) return "\n".join(md) + "\n", warning @@ -327,6 +355,7 @@ def main(argv=None): la.add_argument("--manifest", required=True) la.add_argument("--commit", default="") la.add_argument("--published-at", default="") + la.add_argument("--install-url", default="", help="the app's installation link (developer console, Distribution)") be = sub.add_parser("behind", help="summary and warning for installations still behind") be.add_argument("--failed", required=True, help='"majorproduct" lines') @@ -357,7 +386,7 @@ def main(argv=None): if args.cmd == "latest": with open(args.versions, encoding="utf-8") as f: versions = json.load(f) - pointer = latest_pointer(versions, load_manifest(args.manifest), args.commit, args.published_at) + pointer = latest_pointer(versions, load_manifest(args.manifest), args.commit, args.published_at, args.install_url) if not pointer: print("no production version found", file=sys.stderr) return 1 diff --git a/.github/scripts/incidents_table.py b/.github/scripts/incidents_table.py new file mode 100644 index 000000000..3ef951488 --- /dev/null +++ b/.github/scripts/incidents_table.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Prints the incident regression cases as one Markdown table. + +Each case has its own page, docs/incidents/.md, with a title +("# . ``"), a **What happened:** paragraph and a +**The guarantee:** part. There is no committed table: two pull requests +that each add a case would collide on it. This builds it on demand. + +Usage: python3 .github/scripts/incidents_table.py [DOCS_DIR] +""" + +import os +import re +import sys + + +def one_line(text: str) -> str: + return " ".join(text.replace("|", "\\|").split()) + + +def row(path: str) -> str: + text = open(path, encoding="utf-8").read() + title = text.splitlines()[0].lstrip("# ").strip() if text else os.path.basename(path) + what = re.search(r"\*\*What happened:\*\*(.*?)(?=\*\*The guarantee:\*\*|$)", text, re.S) + guarantee = re.search(r"\*\*The guarantee:\*\*(.*)$", text, re.S) + return "| {} | {} | {} |".format( + one_line(title), + one_line(what.group(1) if what else ""), + one_line(guarantee.group(1) if guarantee else ""), + ) + + +def main() -> None: + docs = sys.argv[1] if len(sys.argv) > 1 else os.path.join( + os.path.dirname(__file__), "..", "..", "docs", "incidents" + ) + pages = sorted(p for p in os.listdir(docs) if p.endswith(".md")) + print("| Case | What happened | The guarantee |") + print("|---|---|---|") + for p in pages: + print(row(os.path.join(docs, p))) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/rust_affected.py b/.github/scripts/rust_affected.py new file mode 100644 index 000000000..974a82077 --- /dev/null +++ b/.github/scripts/rust_affected.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Does this pull request change anything the Rust jobs build, lint or test? + +CI's "Rust (clippy)" and "Rust (tests)" jobs run on every pull request (the +required "Rust (workspace)" check waits on both) but skip their steps when +the answer is no, so a pull request that only moves a pin +(selfhost/versions.json) finishes them in seconds instead of most of an hour. + +The list is wider than the crates because the workspace reads more than its +own sources: +- include_str!/include_bytes! embed files from lambda/, infra/cfn/, + infra/lib/, installer/lib/ and docs/api/; +- worker/build.rs hashes services/worker/src and services/common/src; +- tests read or scan files across the repository: model_call_sites.rs walks + every .js/.mjs/.cjs/.ts/.tsx file, model_ids.rs and run_status.rs read + lambda/ and infra/lib/, and tests/no_hosted_urls.rs scans services, lambda, + infra/lib, infra/bin, installer/lib, installer/bin and selfhost. + +Anything uncertain (no diff, an unexpected checkout) counts as a change, so +the jobs run in full rather than pass without running. + +Usage: rust_affected.py [FILE ...] (no files: read names from stdin) +Prints "true" or "false". +""" + +import sys + +# Every file under these runs the Rust jobs. +DIRS = ( + "services/", + "lambda/", + "docs/api/", + # The incident suite checks every case has its page. + "docs/incidents/", + "infra/cfn/", + "infra/lib/", + "infra/bin/", + "installer/lib/", + "installer/bin/", +) + +# The files that decide how this workflow runs them. +FILES = ( + ".github/workflows/ci.yml", + ".github/scripts/rust_affected.py", +) + +# Cargo, toolchain and formatter settings, wherever they sit. +NAMES = ( + "Cargo.toml", + "Cargo.lock", + "rustfmt.toml", + ".rustfmt.toml", + "clippy.toml", + ".clippy.toml", +) + +# Rust sources anywhere, and the JS/TS model_call_sites.rs scans repo-wide. +EXTS = (".rs", ".js", ".mjs", ".cjs", ".ts", ".tsx") + +# What tests/no_hosted_urls.rs scans under selfhost/ (versions.json is not). +SELFHOST_EXTS = (".rs", ".ts", ".mjs", ".js", ".py", ".sh", ".yaml", ".yml", ".html") + + +def affects_rust(path): + path = path.strip() + name = path.rsplit("/", 1)[-1] + return ( + path.startswith(DIRS) + or path in FILES + or name in NAMES + or name.startswith("rust-toolchain") + or path.startswith(".cargo/") + or "/.cargo/" in path + or path.endswith(EXTS) + or (path.startswith("selfhost/") and path.endswith(SELFHOST_EXTS)) + ) + + +def main(argv): + paths = argv[1:] or sys.stdin.read().splitlines() + paths = [p for p in paths if p.strip()] + # No changed files means the diff did not work: run everything. + run = not paths or any(affects_rust(p) for p in paths) + print("true" if run else "false") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/.github/scripts/test_forge_release.py b/.github/scripts/test_forge_release.py index cfde3d71e..55b03f8eb 100644 --- a/.github/scripts/test_forge_release.py +++ b/.github/scripts/test_forge_release.py @@ -58,8 +58,9 @@ def test_widened_scopes_need_admin(self): self.assertTrue(r["needs_admin"]) self.assertEqual(r["scopes_added"], ["write:jira-work"]) md = fr.summary_markdown(r) - self.assertIn("A site admin must accept", md) - self.assertIn("Apps → Manage apps", md) + self.assertIn("An Atlassian site admin must accept", md) + self.assertIn("Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, Connected apps, Coderhelm, View app details, Update", md) + self.assertNotIn("Manage apps", md) self.assertIn("write:jira-work", md) def test_removed_scope_still_needs_admin(self): @@ -141,7 +142,9 @@ def test_diff_dry_run_writes_summary_and_json(self): with open(out) as f: self.assertEqual(json.load(f)["scopes_added"], ["read:me"]) with open(summary) as f: - self.assertIn("Manage apps", f.read()) + text = f.read() + self.assertIn("Connected apps", text) + self.assertNotIn("Manage apps", text) def test_summary_from_saved_result(self): with tempfile.TemporaryDirectory() as d: @@ -151,7 +154,7 @@ def test_summary_from_saved_result(self): with open(out, "w") as f: json.dump(r, f) text = self.run_cli("summary", "--json", out) - self.assertIn("A site admin must accept", text) + self.assertIn("An Atlassian site admin must accept", text) self.assertNotIn("no one needs to do anything", text) def test_diff_missing_old_file(self): @@ -170,6 +173,15 @@ def test_pending_lists_only_behind_production_installs(self): self.assertEqual(self.run_cli("pending", "--installs", path), "a.example.net\tjira\t5\n") self.assertEqual(self.run_cli("pending", "--installs", path, "--environment", "staging"), "c.example.net\tjira\t1\n") + def test_the_installation_link_rides_on_the_pointer_and_the_steps(self): + link = "https://developer.atlassian.com/console/install/00000000-0000-0000-0000-000000000002?signature=abc&product=jira" + p = fr.latest_pointer([{"version": "7.0.0"}], {"app": {"id": "ari:x"}}, install_url=link) + self.assertEqual(p["installUrl"], link) + self.assertNotIn("installUrl", fr.latest_pointer([{"version": "7.0.0"}], {}, install_url="https://example.com/x")) + self.assertIn(link, fr.admin_steps(link)) + self.assertIn("Connected apps", fr.admin_steps(link)) + self.assertNotIn("Manage apps", fr.admin_steps() + fr.admin_steps(link)) + def test_latest_pointer_is_the_highest_production_version(self): versions = [{"version": "5.20.0"}, {"version": "6.11.0"}, {"version": "6.9.0"}, {"version": "soon"}] manifest = {"app": {"id": "ari:cloud:ecosystem::app/00000000-0000-0000-0000-000000000001"}} @@ -197,7 +209,8 @@ def test_behind_lists_each_site_by_number_with_what_it_lacks(self): self.assertIn("threaded replies", md) self.assertNotIn("example", md) self.assertTrue(warning.startswith("2 installation(s) still run an older Coderhelm app (latest 6.11.0). They lack: ")) - self.assertIn("Jira Settings, Apps, Manage apps, Coderhelm, Update.", warning) + self.assertIn("Connected apps, Coderhelm, View app details, Update.", warning) + self.assertNotIn("Manage apps", warning + md) self.assertEqual(fr.behind_report([], "6.11.0", features), ("", "")) self.assertEqual(fr.parse_version("6.10"), (6, 10, 0)) self.assertIsNone(fr.parse_version("6.x")) diff --git a/.github/scripts/test_rust_affected.py b/.github/scripts/test_rust_affected.py new file mode 100644 index 000000000..b7ab9b2a3 --- /dev/null +++ b/.github/scripts/test_rust_affected.py @@ -0,0 +1,45 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(__file__)) + +from rust_affected import affects_rust # noqa: E402 + + +class AffectsRust(unittest.TestCase): + def test_pin_and_docs_only_skip(self): + for p in [ + "selfhost/versions.json", + "README.md", + "docs/incidents.md", + "coderhelm-jira/manifest.yml", + ".github/workflows/deploy.yml", + ]: + self.assertFalse(affects_rust(p), p) + + def test_rust_inputs_run(self): + for p in [ + "services/worker/src/main.rs", + "services/common/contract/messages.json", + "services/Cargo.lock", + "services/rust-toolchain.toml", + "rustfmt.toml", + ".cargo/config.toml", + "services/.cargo/config.toml", + ".github/workflows/ci.yml", + ".github/scripts/rust_affected.py", + "lambda/log-analyzer/model_prices.json", + "infra/cfn/coderhelm-log-reader.yaml", + "docs/api/openapi.json", + "docs/incidents/a_whole_branch.md", + "installer/lib/github-app.mjs", + "coderhelm-jira/src/index.js", + "selfhost/install.sh", + "selfhost/launch/check.mjs", + ]: + self.assertTrue(affects_rust(p), p) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51d7e0be3..858f3341f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,21 +58,54 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + # The merge commit and its first parent (the base it merged onto). + fetch-depth: 2 + # Skip the steps below when nothing the Rust build reads changed (a pin + # bump in selfhost/versions.json): the job still reports, in seconds. + # The list and why: .github/scripts/rust_affected.py. + - name: Rust-affecting changes + id: changes + working-directory: . + run: | + if git rev-parse --verify -q HEAD^2 >/dev/null; then + run=$(git diff --name-only HEAD^1 HEAD | python3 .github/scripts/rust_affected.py) + else + run=true + fi + echo "run=$run" >> "$GITHUB_OUTPUT" + echo "Rust steps run: $run" + - if: steps.changes.outputs.run == 'true' + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - if: steps.changes.outputs.run == 'true' + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services cache-on-failure: true - - run: cargo fmt --check --all + - if: steps.changes.outputs.run == 'true' + run: cargo fmt --check --all + # The incident cases are compiled through a generated include + # (worker/build.rs), which cargo fmt doesn't follow: checked by name. + - if: steps.changes.outputs.run == 'true' + run: rustfmt --check --edition 2021 worker/src/passes/incidents/*.rs # --all-targets: tests are linted too (a test-only lint once failed # only on a local --all-targets run). - - run: cargo clippy --workspace --all-targets -- -D warnings + - if: steps.changes.outputs.run == 'true' + run: cargo clippy --workspace --all-targets -- -D warnings rust-test: name: Rust (tests) runs-on: ubuntu-latest + # Five times since 13 November the runner stopped answering during the + # first cargo step and GitHub failed the job after 55 minutes as "lost + # communication": no test log, and every rerun passed. That step built + # the whole workspace with full debug info at four jobs, on a runner with + # 16 GB of memory (disk is not short: 87 GB free). With line tables the + # build peaks near 11 GB (the build step logs it each minute), builds in + # about a third of the time, and panics and backtraces keep file:line. + env: + CARGO_PROFILE_DEV_DEBUG: line-tables-only defaults: run: working-directory: services @@ -80,29 +113,74 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + # The merge commit and its first parent (the base it merged onto). + fetch-depth: 2 + # Skip the steps below when nothing the Rust build reads changed (a pin + # bump in selfhost/versions.json): the job still reports, in seconds. + # The list and why: .github/scripts/rust_affected.py. + - name: Rust-affecting changes + id: changes + working-directory: . + run: | + if git rev-parse --verify -q HEAD^2 >/dev/null; then + run=$(git diff --name-only HEAD^1 HEAD | python3 .github/scripts/rust_affected.py) + else + run=true + fi + echo "run=$run" >> "$GITHUB_OUTPUT" + echo "Rust steps run: $run" + - if: steps.changes.outputs.run == 'true' + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - if: steps.changes.outputs.run == 'true' + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services cache-on-failure: true + # Each test in its own process, ended and failed under its own name + # after two minutes (services/.config/nextest.toml). + - if: steps.changes.outputs.run == 'true' + uses: taiki-e/install-action@1919c4a95903d2c33e4a221102edca87309fc14b # v2.89.0 + with: + tool: cargo-nextest@0.9.151 + # The build on its own step, with its own time limit. --workspace + # everywhere: one feature set, so one build (`-p worker` alone resolves + # features differently and compiles everything again). + # Disk and memory every minute while it builds, so a runner that runs + # out of either says so in the log. + - name: Build tests + if: steps.changes.outputs.run == 'true' + timeout-minutes: 30 + run: | + usage() { echo "$(date -u +%T) disk free $(df -h --output=avail / | tail -1 | tr -d ' '), memory used $(free -m | awk '/^Mem/{print $3 " of " $2 " MB"}')"; } + usage + (while sleep 60; do usage; done) & + cargo test --workspace --no-run + usage # Every run failure that reached a person, replayed through the # pipeline's decision code with fakes only at the edges # (docs/incidents.md). Its own step, so a regression names itself. - # --workspace on both steps: one feature set, so one build (`-p worker` - # alone resolves features differently and compiles everything again). - name: Incident regressions - run: cargo test --workspace -- 'incidents::' + if: steps.changes.outputs.run == 'true' + timeout-minutes: 10 + run: cargo nextest run --workspace --no-fail-fast -E 'test(/incidents::/)' # Stops, asks, blocks and loops replayed through the real decision # functions and graded on the decision, with the stop judge's recorded # answers k = 3 times each (pass^k; passes/replay/README.md). It gates # any prompt, model or effort change to a judgment step. - name: Replay suite - run: cargo test --workspace -- 'replay::' + if: steps.changes.outputs.run == 'true' + timeout-minutes: 10 + run: cargo nextest run --workspace --no-fail-fast -E 'test(/replay::/)' # Includes the reviewer evals (worker passes::review_eval): recorded # review histories replayed through the real decision code, no model. # The incident and replay suites already ran above, on the same build. + # nextest runs no doc tests, so cargo test runs those. - name: Workspace tests - run: cargo test --workspace -- --skip 'incidents::' --skip 'replay::' + if: steps.changes.outputs.run == 'true' + timeout-minutes: 15 + run: | + cargo nextest run --workspace --no-fail-fast -E 'not (test(/incidents::/) | test(/replay::/))' + cargo test --workspace --doc rust: name: Rust (workspace) @@ -129,6 +207,7 @@ jobs: - run: python3 -m unittest discover -s lambda/tests # The Cognito pre-sign-up trigger, against the cases the gateway uses. - run: node --test lambda/pre-signup/handler.test.js + - run: node --test lambda/custom-message/handler.test.js mcp-proxy: name: MCP Proxy (Node) diff --git a/.github/workflows/jira-app-release.yml b/.github/workflows/jira-app-release.yml index f56a34b54..80300be51 100644 --- a/.github/workflows/jira-app-release.yml +++ b/.github/workflows/jira-app-release.yml @@ -178,10 +178,16 @@ jobs: # numbers each deploy, so the version is read back from Forge. - name: Read the released version id: version + env: + # The app's installation link (developer console, Distribution), + # kept as a repository variable: site admins get it as the + # one-click update. + FORGE_INSTALL_URL: ${{ vars.FORGE_INSTALL_URL }} run: | if forge version list --environment production --non-interactive --json > "$RUNNER_TEMP/versions.json" 2> "$RUNNER_TEMP/versions.err" \ && python3 "$RUNNER_TEMP/forge_release.py" latest --versions "$RUNNER_TEMP/versions.json" --manifest manifest.yml \ - --commit "$(git rev-parse HEAD)" --published-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$RUNNER_TEMP/jira-app.json"; then + --commit "$(git rev-parse HEAD)" --published-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --install-url "${FORGE_INSTALL_URL}" > "$RUNNER_TEMP/jira-app.json"; then version=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["version"])' "$RUNNER_TEMP/jira-app.json") echo "Released version: $version" echo "version=$version" >> "$GITHUB_OUTPUT" @@ -221,7 +227,7 @@ jobs: # Minor versions reach every site by themselves. Installations still # on an older major version are upgraded here; that works on sites # where the token's account is a site admin, and elsewhere waits for - # that site's admin to accept the update in Jira. + # that site's admin to accept the update in Atlassian Administration. forge install list --json > "$RUNNER_TEMP/installs.json" 2> "$RUNNER_TEMP/installs.err" || { echo "::warning::Could not list installations"; echo "listed=false" >> "$GITHUB_OUTPUT"; exit 0; } python3 "$RUNNER_TEMP/forge_release.py" pending --installs "$RUNNER_TEMP/installs.json" > "$RUNNER_TEMP/pending.tsv" @@ -234,10 +240,15 @@ jobs: while IFS=$'\t' read -r site product major; do [ -n "$site" ] || continue echo "::add-mask::$site" + # The CLI's own refusal (insufficient permissions, or advice to + # install for another product) is about the token's account, not + # the site: it stays in the log, quietly, and the summary says + # what the site's admin does. if forge install --upgrade --site "$site" --product "$product" \ - --environment production --non-interactive --confirm-scopes; then + --environment production --non-interactive --confirm-scopes > "$RUNNER_TEMP/upgrade.log" 2>&1; then upgraded=$((upgraded + 1)) else + echo "Not upgraded from CI (the Forge token's account isn't an admin on this site); its admin accepts the update." failed=$((failed + 1)) printf '%s\t%s\n' "$major" "$product" >> "$RUNNER_TEMP/behind.tsv" fi @@ -269,6 +280,7 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} FAILED: ${{ steps.upgrade.outputs.failed || '0' }} BEHIND: ${{ steps.upgrade.outputs.warning }} + FORGE_INSTALL_URL: ${{ vars.FORGE_INSTALL_URL }} run: | # The issue holds counts and manifest facts only, never site names. title="Jira app update needs a site admin" @@ -278,7 +290,7 @@ jobs: "$reasons" \ "Installations not upgraded from CI: ${FAILED}." \ "${BEHIND}" \ - "On each site, a Jira admin accepts the update: Jira Settings, Apps, Manage apps, Coderhelm, Update." \ + "$(python3 -c 'import sys;sys.path.insert(0,sys.argv[1]);import forge_release as f;print(f.admin_steps(sys.argv[2]))' "$RUNNER_TEMP" "${FORGE_INSTALL_URL}")" \ "Run: ${RUN_URL}") existing=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number --jq '.[0].number // empty') if [ -n "$existing" ]; then diff --git a/coderhelm-jira/manifest.yml b/coderhelm-jira/manifest.yml index 12b8d5514..0eaedb8fa 100644 --- a/coderhelm-jira/manifest.yml +++ b/coderhelm-jira/manifest.yml @@ -21,12 +21,8 @@ modules: function: addCommentHandler - key: get-site-url-trigger function: getSiteUrlHandler - - key: publish-release-trigger - function: publishReleaseHandler - key: get-issues-trigger function: getIssuesHandler - - key: confluence-trigger - function: confluenceHandler jira:adminPage: - key: coderhelm-admin-page resource: adminPage @@ -46,12 +42,8 @@ modules: handler: index.addCommentHandler - key: getSiteUrlHandler handler: index.getSiteUrlHandler - - key: publishReleaseHandler - handler: release.publishReleaseHandler - key: getIssuesHandler handler: release.getIssuesHandler - - key: confluenceHandler - handler: confluence.confluenceHandler - key: lifecycleHandler handler: register.lifecycleHandler resources: @@ -63,9 +55,6 @@ permissions: - write:jira-work - storage:app - read:attachment:jira - - read:page:confluence - - read:space:confluence - - write:page:confluence external: fetch: backend: diff --git a/coderhelm-jira/src/confluence-rules.js b/coderhelm-jira/src/confluence-rules.js deleted file mode 100644 index c612f7a5e..000000000 --- a/coderhelm-jira/src/confluence-rules.js +++ /dev/null @@ -1,72 +0,0 @@ -// Pure rules for the Confluence web trigger (no Forge imports, so they can be -// tested with plain Node): which requests are accepted, and how an append -// becomes a page update. - -/** The most markup one append may add (CoderHelm caps the text at 10k chars). */ -const MAX_APPEND_MARKUP = 60000; -/** The longest CQL accepted (CoderHelm's own searches are far shorter). */ -const MAX_CQL = 1000; - -/** A Confluence id: digits only, at most 20 of them. */ -function isId(v) { - return /^\d{1,20}$/.test(String(v === undefined || v === null ? "" : v)); -} - -/** - * Checks one request body and says which Confluence call it maps to, or why - * it is refused. Returns { error } or { op, ... } with only checked values. - */ -function parseRequest(body) { - const op = String(body.op || ""); - switch (op) { - case "whoami": - return { op }; - case "page": - case "space": - case "children": - if (!isId(body.id)) return { error: "id must be a Confluence id (digits)" }; - return { op, id: String(body.id) }; - case "search": { - const cql = typeof body.cql === "string" ? body.cql.trim() : ""; - // Only page searches: CoderHelm always starts its CQL this way. - if (!cql || cql.length > MAX_CQL || !cql.startsWith("type = page")) { - return { error: "cql must be a page search (type = page ...)" }; - } - return { op, cql }; - } - case "append": { - if (!isId(body.id)) return { error: "id must be a Confluence id (digits)" }; - const html = typeof body.html === "string" ? body.html : ""; - if (!html.trim() || html.length > MAX_APPEND_MARKUP) { - return { error: `html must be 1 to ${MAX_APPEND_MARKUP} characters` }; - } - const version = Number(body.version); - if (!Number.isInteger(version) || version < 1) { - return { error: "version must be the page version that was read" }; - } - return { op, id: String(body.id), html, version }; - } - default: - return { error: "unknown op" }; - } -} - -/** - * The page update for an append: the current body with `html` added at the - * end, as the next version. Refuses (returns null) when the page moved past - * the version CoderHelm read, so someone else's newer edit is never lost. - */ -function appendUpdate(page, html, readVersion) { - const current = page && page.version && Number(page.version.number); - if (!current || current !== readVersion) return null; - const old = (page.body && page.body.storage && page.body.storage.value) || ""; - return { - id: String(page.id), - status: "current", - title: page.title, - body: { representation: "storage", value: old + html }, - version: { number: current + 1, message: "Added by Coderhelm" }, - }; -} - -module.exports = { isId, parseRequest, appendUpdate, MAX_APPEND_MARKUP, MAX_CQL }; diff --git a/coderhelm-jira/src/confluence.js b/coderhelm-jira/src/confluence.js deleted file mode 100644 index 62481f842..000000000 --- a/coderhelm-jira/src/confluence.js +++ /dev/null @@ -1,88 +0,0 @@ -// Confluence reads (and one guarded write) for CoderHelm agents, through this -// app's own Confluence access on the site it is installed on. -// -// The CoderHelm backend calls this web trigger with the shared secret the -// admin saved on the settings page (the same check as the release-notes -// triggers). It mirrors exactly what CoderHelm's Confluence connection may do -// with an API token, and nothing more: -// -// whoami - who the app signs in as (the connection check) -// page - one page by id, with its storage body -// space - one space by id (so CoderHelm can check its key) -// search - a CQL search for pages (CoderHelm builds and checks the CQL) -// children - the pages directly under a page -// append - add markup to the END of one page, only when the page is -// still at the version CoderHelm read; never replaces, creates, -// moves or deletes a page -// -// Which pages may be appended to (the team's write switch and page list) is -// decided by CoderHelm before it calls; this trigger adds the version check -// and the "append only" rule on its side. - -const api = require("@forge/api"); -const { route } = api; -const { authorized, json } = require("./release"); -const { parseRequest, appendUpdate } = require("./confluence-rules"); - -// ── Confluence calls ───────────────────────────────────────────────────────── - -/** One Confluence call; returns { status, data } whatever the status. */ -async function call(path, init) { - const res = await api.asApp().requestConfluence(path, init); - const text = await res.text(); - let data = null; - try { - data = text ? JSON.parse(text) : null; - } catch (_) { - data = { message: text.slice(0, 500) }; - } - return { status: res.status, data }; -} - -/** Passes Confluence's answer back with its own status, so CoderHelm can explain it. */ -const answer = ({ status, data }) => json(status, data === null ? {} : data); - -/** - * POST { forge_secret, op, ... } → Confluence's answer (same status and JSON - * as Confluence's REST API gives for that call). - */ -exports.confluenceHandler = async (request) => { - try { - const body = JSON.parse(request.body || "{}"); - // 401, not 403: a 403 means "Confluence won't show the app this page". - if (!(await authorized(body))) return json(401, { error: "forbidden" }); - const req = parseRequest(body); - if (req.error) return json(400, { error: req.error }); - - switch (req.op) { - case "whoami": - return answer(await call(route`/wiki/rest/api/user/current`)); - case "page": - return answer(await call(route`/wiki/api/v2/pages/${req.id}?body-format=storage`)); - case "space": - return answer(await call(route`/wiki/api/v2/spaces/${req.id}`)); - case "children": - return answer(await call(route`/wiki/api/v2/pages/${req.id}/children?limit=50`)); - case "search": - return answer(await call(route`/wiki/rest/api/search?limit=15&cql=${req.cql}`)); - case "append": { - const read = await call(route`/wiki/api/v2/pages/${req.id}?body-format=storage`); - if (read.status < 200 || read.status > 299) return answer(read); - const update = appendUpdate(read.data, req.html, req.version); - if (!update) return json(409, { error: "the page changed since it was read" }); - return answer( - await call(route`/wiki/api/v2/pages/${req.id}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(update), - }) - ); - } - default: - return json(400, { error: "unknown op" }); - } - } catch (e) { - console.error("confluence trigger error:", e); - return json(502, { error: String(e.message || e) }); - } -}; diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index 10ae86b45..d2daf3b23 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -7,6 +7,7 @@ const { GATEWAY_URL } = require("./gateway"); const { existingComments } = require("./comments"); const { postReply, parentIdOf } = require("./thread-reply"); const { versionFields } = require("./version"); +const { relatedTickets } = require("./related"); /** Jira's comment calls as the app, for a threaded reply (see thread-reply.js). */ const jiraComments = { @@ -23,6 +24,14 @@ const jiraComments = { // see whether Jira's comment events carry a parent id. let loggedCommentKeys = false; +/** A related ticket's summary, status and description, read as the app. */ +async function readRelatedIssue(key) { + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,description,status`); + if (!res.ok) return null; + const full = await res.json(); + return full.fields || null; +} + /** The parts of a Jira user CoderHelm keeps: account id, name, email. */ function jiraUser(u) { return { accountId: u.accountId, displayName: u.displayName, emailAddress: u.emailAddress }; @@ -188,7 +197,7 @@ exports.handler = async (event, context) => { let fields = {}; if (issue.id) { try { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment`); + const res = await api.asApp().requestJira(route`/rest/api/3/issue/${issue.id}?fields=summary,description,labels,assignee,reporter,creator,project,attachment,issuetype,comment,issuelinks`); if (res.ok) { const full = await res.json(); fields = full.fields || {}; @@ -238,6 +247,9 @@ exports.handler = async (event, context) => { // What people already wrote on the ticket: the run that starts reads it // before it plans (the gateway keeps each comment once, by its id). comments: existingComments(fields), + // The tickets linked to this one and the ones its text names: their + // acceptance criteria are part of the change (see related.js). + related: await relatedTickets(issue.key, fields, readRelatedIssue), user: requester(event.atlassianId, fields), coderhelm: { repo_owner: repoOwner || undefined, diff --git a/coderhelm-jira/src/issues.js b/coderhelm-jira/src/issues.js index 86cf18cfe..47cda6d69 100644 --- a/coderhelm-jira/src/issues.js +++ b/coderhelm-jira/src/issues.js @@ -35,6 +35,43 @@ function jqlFor(query) { return `text ~ "${words}" ORDER BY updated DESC`; } +/** + * The account ids an Atlassian document mentions (`@Name` nodes), each once, + * in reading order. A mention is a node of type "mention" whose `attrs.id` + * is the person's account id. + */ +function adfMentions(node, out = []) { + if (!node || typeof node !== "object") return out; + if (node.type === "mention" && node.attrs && typeof node.attrs.id === "string" && node.attrs.id) { + if (!out.includes(node.attrs.id)) out.push(node.attrs.id); + } + for (const child of Array.isArray(node.content) ? node.content : []) adfMentions(child, out); + return out; +} + +/** + * The account id in a Jira user object, or "" when there is none. Jira user + * objects carry `accountId`; anything else (an old payload) has no id. + */ +function accountIdOf(user) { + return (user && typeof user.accountId === "string" && user.accountId) || ""; +} + +/** + * The JQL for "what is waiting on this person": the open issues assigned to + * them, most important and newest change first; and the open issues they + * watch or reported that changed lately (where they may be asked something). + * The account id is checked to be an account id, so it can't end the string. + */ +function mineJql(accountId) { + const id = String(accountId || ""); + if (!/^[A-Za-z0-9:-]{8,128}$/.test(id)) return null; + return { + assigned: `assignee = "${id}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`, + involved: `(watcher = "${id}" OR reporter = "${id}") AND statusCategory != Done AND updated >= -14d ORDER BY updated DESC`, + }; +} + /** One issue as CoderHelm reads it, from the issue REST API's shape. */ function issueOf(raw, links) { const f = (raw && raw.fields) || {}; @@ -42,6 +79,10 @@ function issueOf(raw, links) { .slice(-MAX_ISSUE_COMMENTS) .map((c) => ({ author: (c.author && c.author.displayName) || "", + // Who wrote it and who it mentions, as account ids, so CoderHelm can + // tell a question to a person they haven't answered yet. + author_id: accountIdOf(c.author), + mentions: adfMentions(c.body), created: c.created || "", text: adfText(c.body).trim().slice(0, MAX_COMMENT_CHARS), })); @@ -50,8 +91,13 @@ function issueOf(raw, links) { summary: f.summary || "", type: (f.issuetype && f.issuetype.name) || "", status: (f.status && f.status.name) || "", + // "new", "indeterminate" or "done": where the status sits in the workflow. + status_category: (f.status && f.status.statusCategory && f.status.statusCategory.key) || "", assignee: (f.assignee && f.assignee.displayName) || "", + assignee_id: accountIdOf(f.assignee), + reporter_id: accountIdOf(f.reporter), priority: (f.priority && f.priority.name) || "", + due: f.duedate || "", updated: f.updated || "", created: f.created || "", comments, @@ -63,4 +109,17 @@ function issueOf(raw, links) { }; } -module.exports = { adfText, jqlFor, issueOf, MAX_SEARCH, MAX_ISSUE_COMMENTS, MAX_COMMENT_CHARS }; +/** The most issues one "what is waiting on me" read returns, of each kind. */ +const MAX_MINE = 15; + +module.exports = { + adfText, + adfMentions, + jqlFor, + mineJql, + issueOf, + MAX_SEARCH, + MAX_MINE, + MAX_ISSUE_COMMENTS, + MAX_COMMENT_CHARS, +}; diff --git a/coderhelm-jira/src/register.js b/coderhelm-jira/src/register.js index a77f50170..9dcffb07a 100644 --- a/coderhelm-jira/src/register.js +++ b/coderhelm-jira/src/register.js @@ -26,21 +26,6 @@ async function siteUrl() { return ""; } -/** - * Whether this site has Confluence the app can read. Only then does the - * Confluence trigger get registered, so CoderHelm shows Confluence as - * connected only on sites that have it. - */ -async function hasConfluence() { - try { - const res = await api.asApp().requestConfluence(route`/wiki/api/v2/spaces?limit=1`); - return res.ok; - } catch (e) { - console.log("Confluence isn't reachable on this site:", e); - return false; - } -} - /** * Sends every trigger URL to the gateway for `config` ({ teamId, forgeSecret }). * Returns { urlsRegistered, urlError? }. @@ -53,9 +38,12 @@ async function registerWithGateway(config) { list_projects_url: await webTrigger.getUrl("list-projects-trigger"), create_ticket_url: await webTrigger.getUrl("create-ticket-trigger"), add_comment_url: await webTrigger.getUrl("add-comment-trigger"), - publish_release_url: await webTrigger.getUrl("publish-release-trigger"), + // The app is Jira-only: Confluence (pages for agents, release notes) + // goes through the Atlassian connection in CoderHelm. Empty addresses + // tell CoderHelm this site's app no longer does either. + publish_release_url: "", get_issues_url: await webTrigger.getUrl("get-issues-trigger"), - confluence_trigger_url: (await hasConfluence()) ? await webTrigger.getUrl("confluence-trigger") : "", + confluence_trigger_url: "", site_url: await siteUrl(), // The version that registers: after an accepted update, CoderHelm // knows the site caught up at once. diff --git a/coderhelm-jira/src/related.js b/coderhelm-jira/src/related.js new file mode 100644 index 000000000..41bf5f470 --- /dev/null +++ b/coderhelm-jira/src/related.js @@ -0,0 +1,81 @@ +/** + * The tickets related to the one CoderHelm works on: its issue links ("relates + * to", "blocks", "is cloned by") and the tickets its description names. Their + * acceptance criteria are part of the change, so the run reads them before it + * plans and checks them before the pull request is called ready. + * + * A pull request was once closed by a person who expected a linked ticket's + * pull request to cover it; that pull request had never read the linked + * ticket, and the button it was about still pointed to the old address. + */ + +/** The most related tickets sent with one ticket event. */ +const MAX_RELATED = 6; + +/** The most characters of one related ticket's description sent. */ +const MAX_BODY_CHARS = 8000; + +/** Ticket keys a text names (`ABC-123`), in order, without repeats. */ +function keysInText(text, own) { + const out = []; + const re = /(^|[^A-Za-z0-9-])([A-Z][A-Z0-9]+-\d+)(?![A-Za-z0-9])/g; + let m; + while ((m = re.exec(text || "")) !== null) { + const key = m[2]; + if (key !== own && !out.includes(key)) out.push(key); + } + return out; +} + +/** + * The related tickets' keys with how each relates, issue links first. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields (with `issuelinks` and `description`). + * @returns {{key: string, relation: string}[]} + */ +function relatedKeys(own, fields) { + const out = []; + for (const l of (fields && fields.issuelinks) || []) { + const other = l.outwardIssue || l.inwardIssue; + if (!other || !other.key || other.key === own) continue; + const type = l.type || {}; + const relation = (l.outwardIssue ? type.outward : type.inward) || type.name || "relates to"; + if (!out.some((r) => r.key === other.key)) out.push({ key: other.key, relation }); + } + const text = typeof fields?.description === "string" ? fields.description : JSON.stringify(fields?.description || ""); + for (const key of keysInText(text, own)) { + if (!out.some((r) => r.key === key)) out.push({ key, relation: "named in the ticket" }); + } + return out.slice(0, MAX_RELATED); +} + +/** + * Each related ticket with its summary, status and description (the + * gateway reads the description's words), read as the app. + * @param {string} own The ticket's own key. + * @param {object} fields The ticket's fields. + * @param {(key: string) => Promise} readIssue The issue's fields, or null. + */ +async function relatedTickets(own, fields, readIssue) { + const out = []; + for (const { key, relation } of relatedKeys(own, fields)) { + let f = null; + try { + f = await readIssue(key); + } catch (e) { + f = null; + } + if (!f) continue; + const body = typeof f.description === "string" ? f.description : JSON.stringify(f.description || ""); + out.push({ + key, + relation, + summary: f.summary || "", + status: (f.status && f.status.name) || "", + description: body.slice(0, MAX_BODY_CHARS), + }); + } + return out; +} + +module.exports = { keysInText, relatedKeys, relatedTickets, MAX_RELATED }; diff --git a/coderhelm-jira/src/release.js b/coderhelm-jira/src/release.js index 7d1eeae95..50b10fb52 100644 --- a/coderhelm-jira/src/release.js +++ b/coderhelm-jira/src/release.js @@ -1,12 +1,13 @@ -// Release notes: Confluence publishing + Jira lookups for CoderHelm. +// Jira issue lookups for CoderHelm (release notes and Chat). Release notes +// reach Confluence through the Atlassian connection in CoderHelm, not this app. // -// Both web triggers are called by the CoderHelm backend and require the +// The web trigger is called by the CoderHelm backend and require the // shared secret the admin saved on the settings page (same secret the gateway // verifies on forge-register). const api = require("@forge/api"); const { storage, route } = api; -const { jqlFor, issueOf, MAX_SEARCH } = require("./issues"); +const { jqlFor, mineJql, issueOf, MAX_SEARCH, MAX_MINE } = require("./issues"); const json = (statusCode, obj) => ({ statusCode, @@ -19,154 +20,13 @@ async function authorized(body) { return Boolean(config && config.forgeSecret && body.forge_secret === config.forgeSecret); } -// ── Pure helpers (exported for tests) ──────────────────────────────────────── - -/** Anchor macro that marks one CoderHelm entry, so a re-publish replaces it. */ -function anchorFor(entryKey) { - const slug = `coderhelm-${String(entryKey).replace(/[^A-Za-z0-9._-]+/g, "-")}`; - return `${slug}`; -} - -/** - * Put `entryHtml` (marked with its anchor) at the top of the year page — right - * after the page's first

when there is one — or, when the page already has - * this entry, replace it in place. An entry runs from its anchor to the next - * anchor or the next

after its own heading. - */ -function upsertEntry(pageHtml, entryKey, entryHtml) { - const anchor = anchorFor(entryKey); - const block = anchor + entryHtml; - const at = pageHtml.indexOf(anchor); - if (at >= 0) { - const afterAnchor = at + anchor.length; - const ownHeading = pageHtml.indexOf("', afterAnchor); - const nextHeading = ownHeading >= 0 ? pageHtml.indexOf(" i >= 0); - const end = ends.length ? Math.min(...ends) : pageHtml.length; - return pageHtml.slice(0, at) + block + pageHtml.slice(end); - } - const h1 = pageHtml.indexOf("

"); - if (h1 >= 0) { - const cut = h1 + "".length; - return pageHtml.slice(0, cut) + block + pageHtml.slice(cut); - } - return block + pageHtml; -} - -// ── Confluence calls ───────────────────────────────────────────────────────── - -async function confluence(path, init) { - const res = await api.asApp().requestConfluence(path, init); - const text = await res.text(); - let data = null; - try { - data = text ? JSON.parse(text) : null; - } catch (_) { - data = text; - } - if (!res.ok) { - throw new Error(`Confluence ${res.status}: ${typeof data === "string" ? data : JSON.stringify(data)}`.slice(0, 600)); - } - return data; -} - -async function childByTitle(parentId, title) { - let cursor = ""; - for (let i = 0; i < 20; i++) { - const page = await confluence( - cursor - ? route`/wiki/api/v2/pages/${parentId}/children?limit=250&cursor=${cursor}` - : route`/wiki/api/v2/pages/${parentId}/children?limit=250` - ); - const hit = (page.results || []).find((p) => p.title === title); - if (hit) return hit; - const next = page._links && page._links.next; - if (!next) return null; - const m = /cursor=([^&]+)/.exec(next); - if (!m) return null; - cursor = decodeURIComponent(m[1]); - } - return null; -} - -async function findOrCreateChild(spaceId, parentId, title, seedHtml) { - const existing = await childByTitle(parentId, title); - if (existing) return existing.id; - const created = await confluence(route`/wiki/api/v2/pages`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - spaceId, - status: "current", - title, - parentId, - body: { representation: "storage", value: seedHtml }, - }), - }); - return created.id; -} - -/** - * POST { forge_secret, parentId, containerTitle, year, entryKey, entryHtml } - * → { url }. Parent → container ("Changelog") → year page; entry upserted at top. - */ -exports.publishReleaseHandler = async (request) => { - try { - const body = JSON.parse(request.body || "{}"); - if (!(await authorized(body))) return json(403, { error: "forbidden" }); - const { parentId, containerTitle, year, entryKey, entryHtml } = body; - if (!/^\d+$/.test(String(parentId || "")) || !year || !entryKey || !entryHtml) { - return json(400, { error: "parentId, year, entryKey and entryHtml are required" }); - } - const parent = await confluence(route`/wiki/api/v2/pages/${parentId}`); - const spaceId = parent.spaceId; - const container = containerTitle || "Changelog"; - const containerId = await findOrCreateChild( - spaceId, - parentId, - container, - `

${container}

Release notes published by CoderHelm, one page per year.

` - ); - const yearTitle = String(year); - const yearId = await findOrCreateChild(spaceId, containerId, yearTitle, `

${yearTitle}

`); - - // Read → upsert → write, retrying once on a version conflict. - for (let attempt = 0; attempt < 2; attempt++) { - const page = await confluence(route`/wiki/api/v2/pages/${yearId}?body-format=storage`); - const current = (page.body && page.body.storage && page.body.storage.value) || ""; - const next = upsertEntry(current, entryKey, entryHtml); - try { - await confluence(route`/wiki/api/v2/pages/${yearId}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - id: yearId, - status: "current", - title: page.title, - body: { representation: "storage", value: next }, - version: { number: page.version.number + 1, message: `Release notes: ${entryKey}` }, - }), - }); - const base = (page._links && page._links.base) || ""; - const webui = (page._links && page._links.webui) || ""; - return json(200, { url: base && webui ? base + webui : "", pageId: yearId }); - } catch (e) { - if (attempt === 1 || !String(e.message).includes("409")) throw e; - } - } - return json(500, { error: "unreachable" }); - } catch (e) { - console.error("publishRelease error:", e); - return json(502, { error: String(e.message || e) }); - } -}; - // ── Issue lookups (release notes and CoderHelm's Chat) ─────────────────────── /** One issue with its remote links; null when it can't be read. */ async function readIssue(key) { - const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,priority,updated,created,comment`); + const res = await api + .asApp() + .requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,reporter,priority,duedate,updated,created,comment`); if (!res.ok) return null; // unknown key / no access → dropped const raw = await res.json(); let links = []; @@ -179,17 +39,72 @@ async function readIssue(key) { return issueOf(raw, links); } +/** The issue keys a JQL search finds (up to `max`), or [] when it can't run. */ +async function keysFor(jql, max) { + const res = await api.asApp().requestJira(route`/rest/api/3/search/jql`, { + method: "POST", + headers: { Accept: "application/json", "Content-Type": "application/json" }, + body: JSON.stringify({ jql, maxResults: max, fields: ["summary"] }), + }); + if (!res.ok) return { keys: [], ok: false }; + const found = await res.json(); + return { keys: ((found && found.issues) || []).map((i) => i.key).filter(Boolean).slice(0, max), ok: true }; +} + +/** Reads issues by key, a few at a time, skipping any that can't be read. */ +async function readIssues(keys) { + const issues = []; + for (let i = 0; i < keys.length; i += 5) { + const batch = await Promise.all(keys.slice(i, i + 5).map((k) => readIssue(k).catch(() => null))); + issues.push(...batch.filter(Boolean)); + } + return issues; +} + +/** + * The "what is waiting on me" read: the open issues assigned to the person, + * and the open ones they watch or reported that changed in the last two + * weeks (CoderHelm reads those for questions to them they haven't answered). + */ +async function mineHandler(mine) { + // CoderHelm sends the person's account id (from the Jira events it has + // seen); the app reads no user directory, so it needs no user scope. + const accountId = String((mine && mine.account_id) || ""); + const jql = mineJql(accountId); + if (!jql) { + return json(200, { issues: [], mine: { found: false, why: "no Jira account id was sent" } }); + } + const assigned = await keysFor(jql.assigned, MAX_MINE); + // Watchers can be hidden from the app; then only assigned issues are read. + const involved = await keysFor(jql.involved, MAX_MINE).catch(() => ({ keys: [], ok: false })); + const keys = [...new Set([...assigned.keys, ...involved.keys])]; + return json(200, { + issues: await readIssues(keys), + mine: { + found: true, + account_id: accountId, + assigned: assigned.keys, + assigned_read: assigned.ok, + involved_read: involved.ok, + }, + }); +} + /** * POST { forge_secret, keys: ["ABC-1", ...] } or { forge_secret, query: "words" } + * or { forge_secret, mine: { account_id?, email? } } * → { issues: [{key, summary, type, status, assignee, priority, updated, created, comments, links}] } * * By keys: each issue the app can read (release notes, Chat). By query: the - * issues whose text matches, newest change first (Chat's ticket lookup). + * issues whose text matches, newest change first (Chat's ticket lookup). By + * mine: what is waiting on one person (Chat's "what needs me"), with a `mine` + * object that says whose it is; an older app version leaves `mine` out. */ exports.getIssuesHandler = async (request) => { try { const body = JSON.parse(request.body || "{}"); if (!(await authorized(body))) return json(403, { error: "forbidden" }); + if (body.mine && typeof body.mine === "object") return await mineHandler(body.mine); let keys = (Array.isArray(body.keys) ? body.keys : []) .filter((k) => /^[A-Z][A-Z0-9]+-\d+$/.test(k)) .slice(0, 50); @@ -224,5 +139,3 @@ exports.getIssuesHandler = async (request) => { exports.authorized = authorized; exports.json = json; -exports.upsertEntry = upsertEntry; -exports.anchorFor = anchorFor; diff --git a/coderhelm-jira/test/confluence-rules.test.js b/coderhelm-jira/test/confluence-rules.test.js deleted file mode 100644 index 1c0d3a899..000000000 --- a/coderhelm-jira/test/confluence-rules.test.js +++ /dev/null @@ -1,61 +0,0 @@ -// Run with `npm test` (plain Node; no Forge runtime needed). -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { parseRequest, appendUpdate, MAX_APPEND_MARKUP } = require("../src/confluence-rules"); - -test("reads take only numeric ids", () => { - assert.deepEqual(parseRequest({ op: "page", id: "42" }), { op: "page", id: "42" }); - assert.deepEqual(parseRequest({ op: "children", id: 42 }), { op: "children", id: "42" }); - assert.ok(parseRequest({ op: "page", id: "42/../1" }).error); - assert.ok(parseRequest({ op: "space", id: "" }).error); - assert.ok(parseRequest({ op: "page" }).error); -}); - -test("searches must be page searches", () => { - const cql = 'type = page AND text ~ "deploy" ORDER BY lastmodified DESC'; - assert.deepEqual(parseRequest({ op: "search", cql }), { op: "search", cql }); - assert.ok(parseRequest({ op: "search", cql: "type = attachment" }).error); - assert.ok(parseRequest({ op: "search", cql: "type = page " + "x".repeat(2000) }).error); - assert.ok(parseRequest({ op: "search" }).error); -}); - -test("only the listed operations exist", () => { - for (const op of ["create", "delete", "move", "update", "", undefined]) { - assert.ok(parseRequest({ op, id: "42" }).error, `op ${op}`); - } -}); - -test("an append needs markup and the version that was read", () => { - assert.deepEqual(parseRequest({ op: "append", id: "42", html: "

x

", version: 3 }), { - op: "append", - id: "42", - html: "

x

", - version: 3, - }); - assert.ok(parseRequest({ op: "append", id: "42", html: "", version: 3 }).error); - assert.ok(parseRequest({ op: "append", id: "42", html: "

x

" }).error); - assert.ok(parseRequest({ op: "append", id: "42", html: "

x

", version: 0 }).error); - assert.ok( - parseRequest({ op: "append", id: "42", html: "x".repeat(MAX_APPEND_MARKUP + 1), version: 3 }).error - ); -}); - -const PAGE = { - id: "42", - title: "Lessons", - version: { number: 3 }, - body: { storage: { value: "

Lessons

one

" } }, -}; - -test("an append keeps the page and adds to its end as the next version", () => { - const u = appendUpdate(PAGE, "

two

", 3); - assert.equal(u.body.value, "

Lessons

one

two

"); - assert.equal(u.version.number, 4); - assert.equal(u.title, "Lessons"); - assert.equal(u.id, "42"); -}); - -test("an append to a page that changed since it was read is refused", () => { - assert.equal(appendUpdate(PAGE, "

two

", 2), null); - assert.equal(appendUpdate({ ...PAGE, version: undefined }, "

two

", 3), null); -}); diff --git a/coderhelm-jira/test/issues.test.js b/coderhelm-jira/test/issues.test.js index 7abf7fd85..81d6c607b 100644 --- a/coderhelm-jira/test/issues.test.js +++ b/coderhelm-jira/test/issues.test.js @@ -1,6 +1,6 @@ const { test } = require("node:test"); const assert = require("node:assert/strict"); -const { adfText, jqlFor, issueOf } = require("../src/issues"); +const { adfText, adfMentions, jqlFor, mineJql, issueOf } = require("../src/issues"); const doc = (text) => ({ type: "doc", version: 1, content: [{ type: "paragraph", content: [{ type: "text", text }] }] }); @@ -36,3 +36,37 @@ test("an issue carries its status, people, dates, newest comments and https link assert.deepEqual(i.links, [{ title: "PR #5", url: "https://github.com/acme/web/pull/5" }]); assert.equal(adfText(doc("hi")).trim(), "hi"); }); + +test("mentions and account ids come with each comment, for questions a person hasn't answered", () => { + const mention = (id, text) => ({ type: "mention", attrs: { id, text } }); + const body = { + type: "doc", + content: [{ type: "paragraph", content: [mention("acc-dana-0001", "@Dana"), { type: "text", text: " can you confirm?" }, mention("acc-dana-0001", "@Dana")] }], + }; + const i = issueOf({ + key: "ABC-8", + fields: { + summary: "Pick the retry limit", + status: { name: "To Do", statusCategory: { key: "new" } }, + assignee: { accountId: "acc-dana-0001", displayName: "Dana" }, + reporter: { accountId: "acc-sam-0002", displayName: "Sam" }, + duedate: "2026-11-20", + comment: { comments: [{ author: { accountId: "acc-sam-0002", displayName: "Sam" }, created: "c1", body }] }, + }, + }); + assert.equal(i.status_category, "new"); + assert.equal(i.assignee_id, "acc-dana-0001"); + assert.equal(i.reporter_id, "acc-sam-0002"); + assert.equal(i.due, "2026-11-20"); + assert.equal(i.comments[0].author_id, "acc-sam-0002"); + assert.deepEqual(i.comments[0].mentions, ["acc-dana-0001"]); + assert.deepEqual(adfMentions(null), []); +}); + +test("the waiting-on-me JQL takes only an account id, never more clauses", () => { + const q = mineJql("557058:0a1b2c3d-1111-2222-3333-444455556666"); + assert.match(q.assigned, /^assignee = "557058:0a1b2c3d-1111-2222-3333-444455556666" AND statusCategory != Done/); + assert.match(q.involved, /watcher = .* OR reporter = /); + assert.equal(mineJql('x" OR project = SECRET'), null); + assert.equal(mineJql(""), null); +}); diff --git a/coderhelm-jira/test/manifest.test.js b/coderhelm-jira/test/manifest.test.js new file mode 100644 index 000000000..00641eaec --- /dev/null +++ b/coderhelm-jira/test/manifest.test.js @@ -0,0 +1,27 @@ +// The Jira app is Jira-only: no Confluence scope, module or call. Confluence +// goes through the Atlassian connection in CoderHelm, so a release of this +// app never asks an admin for access to a second Atlassian product. + +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("node:fs"); +const path = require("node:path"); + +const root = path.join(__dirname, ".."); +const manifest = fs.readFileSync(path.join(root, "manifest.yml"), "utf8"); + +test("the manifest asks for no Confluence scope", () => { + assert.doesNotMatch(manifest, /confluence/i); + const scopes = manifest.split("scopes:")[1].split("external:")[0]; + assert.deepStrictEqual( + scopes.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- ")).map((l) => l.slice(2)), + ["read:jira-work", "write:jira-work", "storage:app", "read:attachment:jira"], + ); +}); + +test("no source file calls Confluence", () => { + for (const f of fs.readdirSync(path.join(root, "src"))) { + if (!f.endsWith(".js")) continue; + assert.doesNotMatch(fs.readFileSync(path.join(root, "src", f), "utf8"), /requestConfluence/, f); + } +}); diff --git a/coderhelm-jira/test/related.test.js b/coderhelm-jira/test/related.test.js new file mode 100644 index 000000000..0901fb412 --- /dev/null +++ b/coderhelm-jira/test/related.test.js @@ -0,0 +1,37 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { keysInText, relatedKeys, relatedTickets, MAX_RELATED } = require("../src/related"); + +test("keys named in a text, without the ticket's own", () => { + assert.deepEqual(keysInText("See ABC-2 and XY-3, not ABC-1 or abc-4. ABC-2 again.", "ABC-1"), ["ABC-2", "XY-3"]); +}); + +test("issue links come first, with how they relate, then keys in the description", () => { + const fields = { + issuelinks: [ + { type: { name: "Relates", inward: "relates to", outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, + { type: { name: "Blocks", inward: "is blocked by", outward: "blocks" }, inwardIssue: { key: "ABC-3" } }, + ], + description: { type: "doc", content: [{ type: "text", text: "Also covers ABC-4 and ABC-2." }] }, + }; + assert.deepEqual(relatedKeys("ABC-1", fields), [ + { key: "ABC-2", relation: "relates to" }, + { key: "ABC-3", relation: "is blocked by" }, + { key: "ABC-4", relation: "named in the ticket" }, + ]); +}); + +test("each related ticket is read with its summary and description; an unreadable one is left out", async () => { + const fields = { issuelinks: [{ type: { outward: "relates to" }, outwardIssue: { key: "ABC-2" } }, { type: { outward: "relates to" }, outwardIssue: { key: "ABC-9" } }] }; + const read = async (key) => (key === "ABC-2" ? { summary: "Point the drawer button to the new page", status: { name: "Closed" }, description: "Acceptance criteria\n- The drawer Register button links to /new/register" } : null); + const got = await relatedTickets("ABC-1", fields, read); + assert.equal(got.length, 1); + assert.equal(got[0].key, "ABC-2"); + assert.equal(got[0].status, "Closed"); + assert.match(got[0].description, /links to \/new\/register/); +}); + +test("at most a handful are sent", () => { + const links = Array.from({ length: 10 }, (_, i) => ({ type: { outward: "relates to" }, outwardIssue: { key: `ABC-${i + 2}` } })); + assert.equal(relatedKeys("ABC-1", { issuelinks: links }).length, MAX_RELATED); +}); diff --git a/docs/api/openapi.json b/docs/api/openapi.json index bdf06cdd0..eda456b65 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3982,6 +3982,17 @@ "null" ] }, + "preview": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPreview", + "description": "Where the preview of the pull request's head stands: its checks,\naddress and captured pages. Null when nothing was recorded." + } + ] + }, "progress_notes": { "description": "Notes it wrote while working, in order.", "examples": [ @@ -4083,7 +4094,7 @@ ] }, "stop_kind": { - "description": "Why the run stopped, when it was its own environment rather than a\nquestion: `tooling` (a command the run ran failed for want of a\ndependency or tool; see `tooling_failure`).", + "description": "Why the run stopped, when it was its own environment rather than a\nquestion: `tooling` (a command the run ran failed for want of a\ndependency or tool; see `tooling_failure`), or `already_merged` (a\npull request for the ticket had already merged: the run ended\n`covered_by_pr` because it already did all of what the ticket asks,\nor waits because CoderHelm couldn't tell whether it does; Retry runs\nthe ticket again anyway).", "examples": [ null ], @@ -4165,6 +4176,16 @@ "null" ] }, + "waiting_line": { + "description": "What the run's pull request waits on, in one plain line, and\nwhether it is ready for review: \"Waiting on: an approving review from\na person on #12 (this repo requires one before CoderHelm merges).\nReady for review: checks passed, preview checked.\" Built from\n`merge_standing`, `draft_hold` and `preview`. Null before the run\nhas a pull request.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "waiting_on": { "oneOf": [ { @@ -4804,6 +4825,165 @@ ], "type": "object" }, + "RunPreview": { + "description": "Where the preview of the run's pull request head stands\n(`common::preview`).", + "properties": { + "checks": { + "description": "The preview and end-to-end checks that cover the change, on the head.", + "examples": [ + [ + { + "name": "E2E on preview", + "outcome": "passed", + "url": "https://github.com/acme/web/actions/runs/1/job/2" + } + ] + ], + "items": { + "$ref": "#/components/schemas/RunPreviewCheck" + }, + "type": "array" + }, + "e2e_covered": { + "description": "The change adds or updates an end-to-end spec.", + "examples": [ + true + ], + "type": "boolean" + }, + "e2e_required": { + "description": "The change alters what a person sees in a repository with an\nend-to-end suite, so it needs an end-to-end spec.", + "examples": [ + true + ], + "type": "boolean" + }, + "labels_added": { + "description": "Labels CoderHelm added to start the preview and its end-to-end checks.", + "examples": [ + [ + "E2E:signup" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "shots": { + "description": "The changed pages captured on the preview, at desktop and phone width.", + "examples": [ + [ + { + "page": "/signup", + "src": "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true", + "width": "desktop" + } + ] + ], + "items": { + "$ref": "#/components/schemas/RunPreviewShot" + }, + "type": "array" + }, + "stage": { + "description": "`not_needed`, `triggered`, `deploying`, `ready`, `checked`,\n`failed` or `blocked`.", + "examples": [ + "checked" + ], + "type": "string" + }, + "url": { + "description": "The preview's address; empty when it isn't known.", + "examples": [ + "https://pr-1.preview-web.example.com" + ], + "type": "string" + }, + "why": { + "description": "Why there is no preview or no capture, one line; empty otherwise.", + "examples": [ + "" + ], + "type": "string" + } + }, + "required": [ + "stage", + "url", + "labels_added", + "checks", + "shots", + "why", + "e2e_required", + "e2e_covered" + ], + "type": "object" + }, + "RunPreviewCheck": { + "description": "One preview or end-to-end check on the head of the run's pull request.", + "properties": { + "name": { + "description": "The check's name, as GitHub shows it.", + "examples": [ + "E2E on preview" + ], + "type": "string" + }, + "outcome": { + "description": "`passed`, `failed`, `running` or `skipped`.", + "examples": [ + "passed" + ], + "type": "string" + }, + "url": { + "description": "The check's page on GitHub; empty when it has none.", + "examples": [ + "https://github.com/acme/web/actions/runs/1/job/2" + ], + "type": "string" + } + }, + "required": [ + "name", + "outcome", + "url" + ], + "type": "object" + }, + "RunPreviewShot": { + "description": "One page captured on the preview.", + "properties": { + "page": { + "description": "The page's path on the preview.", + "examples": [ + "/signup" + ], + "type": "string" + }, + "src": { + "description": "The image's address.", + "examples": [ + "https://github.com/acme/web/blob/abc/pr-1/abc/signup-desktop.png?raw=true" + ], + "type": "string" + }, + "width": { + "description": "`desktop` or `phone`.", + "examples": [ + "desktop" + ], + "type": "string" + } + }, + "required": [ + "page", + "width", + "src" + ], + "type": "object" + }, "RunQuestion": { "description": "A question a run asked a person.", "properties": { @@ -8451,7 +8631,7 @@ }, "/api/runs/{run_id}/retry": { "post": { - "description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `covered_by_pr`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=`.\n\nA `completed` run whose `round_incomplete` is set (its pull request is open but the last fix round on it didn't finish) is resumed instead: the same run picks the round up again on the same pull request, with a fresh time budget, and the answer's status is `resuming`.", + "description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `covered_by_pr`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=`.\n\nA run whose `stop_kind` is `already_merged` built nothing because a pull request for its ticket had already merged: it already did all of what the ticket asks (`covered_by_pr`), or CoderHelm couldn't tell whether it does (`needs_input`). Retrying it is how a person asks for the ticket to run again anyway: the new run goes ahead without that check, and later runs on the ticket skip it for the same merge.\n\nA `completed` run whose `round_incomplete` is set (its pull request is open but the last fix round on it didn't finish) is resumed instead: the same run picks the round up again on the same pull request, with a fresh time budget, and the answer's status is `resuming`.", "operationId": "retryRun", "parameters": [ { diff --git a/docs/coder-loop.md b/docs/coder-loop.md new file mode 100644 index 000000000..24c710f4c --- /dev/null +++ b/docs/coder-loop.md @@ -0,0 +1,255 @@ +# The coder's loop + +How CoderHelm turns a ticket into a change: explore, measure, plan the smallest +change, implement, review it against the ticket, prove it. Each step has a check +in code, so the loop holds whatever the model writes. + +## Why + +Two pull requests show what went wrong. + +- **A data-pipeline ticket** asked to link four camps to a second sport. The plan + added a second map and helpers beside the existing overrides map, and made an + insert-only link sync replace and delete links. The build added warnings, three + counters and a log level change in shared code, plus a 432-line test with fake + hooks and an invented payload. The right change was four map entries, an insert + that does nothing on conflict, and one small test. +- **A web ticket's** end-to-end tests for a vendor's embedded portal were rewritten + three times, each time on a guess about the vendor's page. When a criterion met + the vendor's behaviour, the test was changed instead of the page. + +The causes were in the loop, not only in prompt wording: + +- The planner was told to use "2-4 tool calls" on a simple ticket and not to read + whole files. It never saw the map it should have extended. +- The data rules told every change that touched a pipeline to add counters and a + warning for each skip, and a fix round enforced it. +- Nothing compared the diff with the ticket. The scope checks compared files with + the plan, and the plan was already too wide. +- Nothing stopped the coder writing before it searched, or adding a twin of a + structure that was already there. +- Outside pages were never measured, and nothing caught a test bent to a vendor + against a criterion. + +## The loop + +1. **Explore.** Before the planner runs, the worker searches the repository for the + ticket's own names (backticked code, identifiers, quoted names, capitalised + names) and gives the planner the hits (`plan_shape::existing_for_ticket`). + The planner is told to read the structure it extends in full, along with its + writers and readers. + +2. **Measure.** The plan has a `## Measure first` section listing every outside + system the change or its tests rest on, and how each was measured: `probe_page` + for a page (from #734), a read-only lookup for data, or `None`. A plan for a + ticket about an embed, vendor, portal, webhook or partner that measured nothing + is sent back. + +3. **Plan the smallest change.** design.md has five sections: + - `## Reuse` + - `## Must not change` + - `## Measure first` + - `## Smallest change` + - `## Proof` + + `plan_shape::plan_gaps` sends the plan back when a section is missing. It also + sends it back when the plan: + - adds a name parallel to one it reuses or one the search found; + - deletes, overwrites, upserts or prunes when the ticket asks for none of that; + - changes logging or adds reporting the ticket doesn't ask for; + - would change a test to match an outside system while the ticket's acceptance + criteria say what the product must do. + + The Reuse section also says, for each helper that writes data, whether it + only inserts or replaces and deletes. The worker reads each reused helper's + body (`minimal_change::write_semantics`: a `DELETE`, an `ON CONFLICT DO + UPDATE`, a delete-then-insert, a relation `.set(`). A plan that reuses a + replacing helper on a path that only inserts today is sent back unless the + ticket asks to replace. The camps run's plan named the right map, then + reused the link helper that deletes every link it isn't given. + + Whatever is still open after the one send-back stays on the decision. + +4. **Implement.** In the coder's tool loop (`explore_guard`): + - The first write of a build is refused until a search has run and the write + names what it reuses (`reuses`). + - An edit that adds a top-level map, helper or config beside a similar existing + one is refused unless it says why (`why_new`). + + Both are kept as evidence lines. The coder's prompt carries the same rules + (`SMALLEST_CHANGE_RULES`). The data rules ask for reporting on a skip only when + the ticket asks for it. + +5. **Review against the ticket.** After the build, the habits check reads the diff + against the base and the ticket (`minimal_change::check`). It flags: + - parallel structures; + - deleting or overwriting semantics where the base only added; + - log level changes; + - new counters and log calls nobody asked for; + - tests out of proportion to the code; + - large fake payloads with no probe record. + + Each goes to the fix round as "make it smaller". A `Wider than the ticket: + : ` line keeps an item, except deletes and invented payloads: only + the ticket can ask for those. The reviewer runs the same check. Deletes, an + unobserved payload, and a test assertion flipped to an outside page's + behaviour against an acceptance criterion are required findings + (`review_rules::SMALLEST_RULE`). + +6. **Prove.** + The first round works out how the repository's CI installs and + runs its tests (`common::test_env`: the test job's working folder, Python + and Node versions, install steps and test steps). It records this on the + run (`test_setup`). Every sandbox build of every later round, and the proof + step's runs, restore that install from a cache named by the install steps + and the manifests' blob ids. Only the first build installs and saves it. + The coder is told the environment is ready and how the tests run. One run + reinstalled its dependencies eighteen times, about 25 minutes of builds. + The CI job chosen is the one whose tests run for the plan's files + (`test_env::from_workflows_for`). A workflow filtered to other paths, or a + job in a folder none of the files is in, is used only when nothing fits + better. A web change in a monorepo was once given a lambda's `npm ci` and + `npm test` (`incidents::cm_test_env_for_the_change`). + + Each new or changed test runs in the sandbox with and without the + change (`habits_check`). A test the runner finds nothing in goes back to the + coder, and the coder quotes the run's output in its Evidence. End-to-end code + against another company's page uses only what a probe observed (#734). + + A proof fix round that answers a gap by looking (a query, a page, a check + run) is judged again with what it found, even when it wrote no code + (`proof::round_answered`, `incidents::cn_proof_answer_judged`). + +7. **Commit and push.** + Each gate runs where the commit is made, not as a line in the prompt + (`common::push_gate`, `passes/push_checks.rs`). + + - **The checks come from the repository.** `run_checks` adds the scripts + of each package that owns a touched file: its test script, its type + check (`check-types`, `typecheck`) and its lint. When a non-test file + changed, the package's whole unit suite runs, because a shared helper + breaks callers outside the diff. Only a change to nothing but test + files runs just those files. This step replaces the test line taken + from the first workflow that had one. On one pull request that line was + another package's `npm test --passWithNoTests`: it reported "2 of 2 + checks passed" while `vitest` on the touched files exited 1. + - **Checks before every push** (`push_checks::before_push`, in the CI fix + round before `round::land`). If the checks ran on the fix's last edit + and passed, the fix is pushed and the commit records what ran. If they + failed, or never ran on the last edit, the fix is not pushed: the next + attempt continues on the same edits with the failing output. If the + sandbox couldn't run them (the install failed, or there is no sandbox), + the fix is pushed with an `Unverified:` line saying why and what ran. + - **The message matches the diff** (`round::land`, + `push_gate::true_message`). A message is rewritten from the diff when + it says revert, remove or drop while the diff adds test lines or more + than it removes, when it says add while the diff only removes, or when + it names a file the commit doesn't touch. + - **A revert takes its tests with it** (`push_gate::removed_symbols`, + `still_expected`). A commit that removes a definition a test still + names is held until that test is reverted or updated in the same + commit. + - **Two fixes per failing test** (`push_gate::FixLedger`, kept on the run + as `ci_test_fixes`). The failing tests are read from the failure report + or the log (vitest, jest, Playwright, pytest, cargo, go), or, when they + can't be, the failing checks are used. After two pushed fixes a test that + is still red stops the rounds: the pull request and the run name the + test and its error, and nothing more is pushed. The branch is never + rolled back to an older green head, and a planned task is never taken + out to turn CI green. Only a dependency run's newest set of bumps comes + out (`resume::take_out_failing_bumps`). Five of 53 runs had rolled back, + two of them with tests left behind that expected the reverted code. + - **No log is no reason to stop** (`push_gate::logs_unread_brief`, + `hold_no_logs`). When CI's job log can't be read, the fix brief gives + the owning package's commands so the fixer reproduces the failure in the + sandbox. Any sentence that blames the missing log is replaced. + - **Fixtures use looked-up ids, and tests are sized to the behaviour** + (`minimal_change::made_up_ids`, `repeated_cases`, in the habits check). + Ids like `sport-a` or `id-1` are sent back when the run's lookups + returned real ids. Three or more added cases that differ only in their + values are sent back as one case per behaviour. The size check (test + lines against code lines) runs too; it fires on the roughly 415 test + lines one run added for 50 lines of code. + +8. **Rounds agree.** + Planned work that a review commit on the pull request took out is not + built again by a planned-work round, and the run says which commit took it + out. When an acceptance criterion of the ticket asks for it, the ticket + wins: it is built, and the reply to the review says why + (`round_agree`, `incidents::co_rounds_agree`). + +9. **Scope is decided once.** + The plan writes `## Out of scope` in design.md, one `- : ` line + each, naming the code that would show it (backticked names, paths, routes). + A product question the ticket doesn't settle is decided there with its + default; it is never asked in the pull request. The plan goes back when the + section is missing, a question is left open, an item has no reason, an + acceptance criterion asks for an item it leaves out, a task names an + out-of-scope item, or a task is open-ended ("switch any other caller") + (`scope_ledger::plan_gaps`). + When the plan is generated, before any code, the run keeps a scope ledger + (`common::scope_ledger`, run attribute `scope_ledger`): the ticket's + acceptance criteria as read by `stop_judge::acceptance` (the same list the + criteria-to-test mapping reads) are in scope, the plan's out-of-scope lines + are out. A plan revision never rewrites it. Every later round is held to it: + - the tests and scope check reads the diff, tests included, and sends back + each out-of-scope item it brings in (tests are exempt from "inside the + plan", never from the ledger); + - a planned-work round never builds an item the ledger leaves out, next to + `round_agree`'s rule for what a review took out; + - a round that must build one writes `Scope change: : `; it is + accepted only when the why cites an acceptance criterion or a person's + comment on the pull request, and the ledger records who moved it in. + (`incidents::sl_scope_decided_once`) + +10. **The description describes the head.** + On every push the description is rebuilt from the head's facts + (`description::build`; Problem, Changes, Risk, Verification). The written + text is held to the head and the ledger (`description_facts::hold_scope`): + - sections about earlier attempts, pushes and waits go; the revert and + "CI is failing" lines stay for `ci_lines`, which drops them once untrue; + - a sentence saying something is out of scope, untouched or put back while + the diff changes it goes (`scope_ledger::contradictions`), and a change + to a file not in the diff goes (`pr_claims`); + - open product questions become out-of-scope defaults; + - the written notes fit a length scaled to the changed lines of code, tests + and generated files left out (150 to 600 words), with the run page for + the rest. + Changes ends with one Out of scope line rendered from the ledger. An item + the diff brings back is never shown as out of scope; it is listed as not + verified until it is taken out or moved in. `pr_body::defects` fails a body + that asks an open product question. + (`incidents::sm_description_of_the_head`) + +## What is deterministic + +Everything above except the model's own writing: the searches, section checks, +word checks, definition parsing, diff checks and refusals are plain code with unit +tests. `incidents::bz_smallest_change` replays both pull requests through the plan +gate, the coder's guard, the habits check and the reviewer. The plans and diffs +as they were are sent back; the small ones pass. + +## Sources + +- Claude Code best practices: explore, then plan, then code; give the agent a way + to verify; review against the spec. https://code.claude.com/docs/en/best-practices +- Claude prompting best practices: the minimum complexity the task needs; don't + touch code you weren't asked to change; tests check correctness and don't define + the solution. + https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices +- Building effective agents: ground truth from the environment at each step; tools + that are hard to misuse. https://www.anthropic.com/engineering/building-effective-agents +- SWE-agent: search tools, a bounded file viewer, and edits checked as they are + made. https://arxiv.org/abs/2405.15793 +- OpenHands: agents that browse and run code in a sandbox to see the real system. + https://arxiv.org/abs/2407.16741 +- Agentless: find the files, then the functions, then the lines, before editing; + keep only reproduction tests that fail on the original code. + https://arxiv.org/abs/2407.01489 +- Aider: a repository map so the model reuses what exists; edits that send only + the changed parts. https://aider.chat/docs/repomap.html, + https://aider.chat/docs/more/edit-formats.html +- Google engineering practices: one self-contained change per CL; reviewers look + for over-engineering and features nobody asked for. + https://google.github.io/eng-practices/review/developer/small-cls.html, + https://google.github.io/eng-practices/review/reviewer/looking-for.html diff --git a/docs/incidents.md b/docs/incidents.md index 775c06be5..786144bf7 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -3,7 +3,10 @@ Every run failure that reached a person is a case in `services/worker/src/passes/incidents/`, so it can't come back without a failing test. CI runs the suite as its own step, **Incident regressions** in **Rust (tests)** -(`cargo test --workspace -- incidents::`), on every pull request. +(`cargo nextest run --workspace -E 'test(/incidents::/)'`; locally, +`cargo test --workspace -- incidents::` runs the same tests), on every pull +request. A case still running after two minutes fails under its own name +(`services/.config/nextest.toml`). Each case replays the failure on one invented monorepo: @@ -27,68 +30,14 @@ decision is made inside the pipeline itself, the case also checks that the pipeline still calls it there. ## Cases +Each case has its own page in [`docs/incidents/`](incidents/), named after +its module (`docs/incidents/.md`): what happened, and the guarantee it +protects. A new case is two new files, the test in +`services/worker/src/passes/incidents/` and its page here, and nothing +shared is edited: `services/worker/build.rs` finds every case file, and a +test fails when a case has no page or a page no case. To print all cases as +one table, run `python3 .github/scripts/incidents_table.py`. -| Case | What happened | The guarantee | -|---|---|---| -| a. `a_whole_branch` | The plan check said 5 of 7 tasks were done. The last step wrote nothing, and the run ended "I ran but produced no file changes". | A step that writes nothing is judged on the whole branch. Work on the branch goes on to the checks and the pull request. With nothing on the branch, the run names the planned tasks that weren't built and never asks generic questions. | -| b. `b_open_pr_retry` | A retry started over on a branch whose earlier run was still fixing CI. | A retry continues the earlier run's open pull request and opens no other. While the earlier run still works on the branch, the retry stops before writing anything and says why. That covers a run that is running, waiting on CI, holding a writer slot, or has a round under way or parked. | -| c. `c_codegen_egress` | The sandbox's network allowlist refused the CMS host. The run blamed the change: "its generated files were not regenerated". | Builds that run a generator may reach the hosts it needs. A host that is still refused is a tooling failure that names the host. | -| d. `d_echoed_markers` | The echoed buildspec holds the upload markers, so every build read as "could not be uploaded". | A marker counts only on a line of its own. The exit code is the last one printed. A failed generator's reason quotes what the generator printed, not the echoed buildspec. | -| e. `e_large_generated_output` | A types file over 5 MB, written through `../`, was dropped silently. The run said "regenerated 1 file(s)" and opened no pull request. | Every changed file is committed, or named as a tooling failure. Paths have one spelling. A generated task its generator settled counts as done in the plan check and the proof check. | -| f. `f_steps` | The generator check ran out of time and the run failed "not enough time left". | A gate that lacks time continues in a fresh step at that gate, as a new queue message. A run that keeps making progress continues past 20 steps. Two steps in a row without progress stop it, and it says where it was stuck. | -| g. `g_large_plan` | A 40-file ticket was capped and narrowed. | A plan holds every file the ticket needs. Nothing caps or narrows it, and every later round is told every task. | -| h. `h_pr_updates` | A PR updated over several runs went stale. Its description was out of date, a ticket comment was posted twice, a question was asked on every update, an e2e test skipped itself when content was missing, and a note said "could not look up" content that was readable. | Each one is caught by its own check. The description is rewritten when a round lands. A notice is posted once per ticket, and so is a question. A spec that skips on missing content fails the checklist. A note that didn't look, when it could have, goes back to the planner. | -| i. `i_finished_work_pr` | A run with one planned task left ended with no pull request. Later the run opened a draft but left the work to a person. | Finished work always ends with a pull request. Planned work that is still open puts a draft PR up with a "Not finished" section. CoderHelm then keeps working those tasks in rounds on the PR and marks it ready when the section is empty. It stops only after two rounds in a row without progress. It then names the tasks and why, and sets the run to `needs_input`, never `completed`. | -| j. `j_post_merge_watch` | After an auto-merge, the health check gave up after about 22 minutes and posted "inconclusive" while the deploy was still running. It read the base branch, so later merges kept checks running and could put another commit's deploy in the verdict. | The check judges the merge commit's own check runs and push workflow runs, and waits as long as they run, each look a new queue message. It posts a verdict only: green after a 15-minute window that starts when the deploy completes, or red naming each new failing job with its link. Baseline failures are ignored, later commits never change the verdict, and a superseded deploy is followed to the run that includes the commit. One comment per merge, edited in place. A deploy held for an environment approval is not stuck: the comment reports what finished and names the job waiting for approval, in which environment, with a link, and is updated once the approved deploy finishes; the safety ceiling does not count the wait. A deploy cancelled with no later run is reported as cancelled (yellow), never as a failure. | -| k. `k_own_review_findings` | CoderHelm's own review of its own PR posted three findings as notes and APPROVE. Three seconds later the PR was marked ready and the merge armed, with none of the three fixed and no thread resolved. | On its own PR, CoderHelm fixes every finding of its own review that isn't strictly optional (an inferred preference, or an optional improvement to correct code) before the PR is marked ready or the merge armed. The review requests changes and lists them at the top of the description. The run takes them in review-fix rounds, and the next review resolves the threads the new commit settled. It goes on while rounds make progress. Two rounds without progress stop it: the PR stays a draft with the findings listed, and the run is `needs_input`. A verdict is never APPROVE while a finding holds the merge. | -| l. `l_plan_time` | A schedule data fix failed in planning after about 14 minutes: "no work is committed to continue from". It planned, switched repository and planned again, was sent back by a release check that read a column it writes (`updated_at`) as removed and by a demand for production and staging proof its claims never needed, then re-planned a third time for one file tag and ran out of time. | Planning that runs out of time continues in a fresh step at the plan gate, from the repository it settled on, its last plan, its open gaps and its re-plans, and keeps going while each step makes a new plan revision or leaves fewer open gaps. The checks re-plan once in all: a switch plans once, with the file check in that plan's one send-back, and every check's gaps share that one send-back; what is still open stays on the decision. Writing a column is not removing it, and proof for an environment is asked only when the plan's claims rest on that environment's data. | -| m. `m_data_pipeline_rules` | A data-pipeline PR kept one column stable by no longer advancing `updated_at` on some update and upsert paths. Two incremental readers used that timestamp (a `MAX(updated_at)` watermark and a `GREATEST(...)` change key), so edited rows refetched every run and other changes stopped reaching the search index. It also picked a winner among sibling rows with different tie-breaks from the full sync, skipped records without a parent silently, and showed nothing on real data. | The plan check sends back a plan that changes how a cursor column is written without listing its readers, or picks a winner among rows without naming the other path that makes the same choice. Before the pull request, for every ticket kind, the checklist fails a cursor write that can stop advancing, names each reader code search finds that the plan leaves out, wants a test that the column still advances, fails an ordering key that differs from the other path's, wants a test with ties and nulls, and fails a skip over records that is silent or logs per row (one warning per run with the ids, counts in the summary). With a data source connected, the proof check holds a data change until the evidence lists the ticket's records and edge cases before and after, and the description shows them in Verification. | -| n. `n_suite_setup_broke` | A review fix round finished every requested change, then ran the full test suite in the sandbox. The suite came from the CI workflow, and its `uses: astral-sh/setup-uv` step was written into the setup as words. The sandbox's `/bin/sh` failed on a "(" (exit 2, no counts), and the round was held as "Full test suite FAILED". The test loop the requester named never ran. | A `uses:` step becomes real shell or is left out with a note, never words. The suite runs under bash after `bash -n`, with its setup and its tests marked apart. A command CoderHelm built that breaks before any test runs (not valid bash, a missing tool, a failed setup, exit 2 within seconds with no counts) is CoderHelm's own failure. The round then tries the requester's command, the repository's instructions, and the simplest test command, in that order. When none runs, the fix lands and the description says plainly that the tests didn't run in the sandbox and why. A command the requester named runs first and is quoted in the result. Tests that ran and failed still hold the fix. | -| o. `o_mention_resumes_held_work` | A requester asked for five changes on a PR CoderHelm opened, and for no PR comments. The feedback round did all five, then the sandbox test step broke on CoderHelm's own setup, so the round was held and its WIP branch kept, with nothing about it on the run record. The next day the owner commented a bare `@coderhelm` to get the work landed. A bare mention was the re-review command, so CoderHelm posted a fresh verdict and nothing landed. | Work a round left held or unfinished on CoderHelm's own PR comes first. A held round stays on the run record (its WIP branch, where it started, what it was asked) until it lands, and a WIP branch ahead of the PR counts too. A bare mention resumes that round: the checks run again on the WIP with the current setup, and the work lands, or is fixed and then lands. Words are read by the model, told about the held work: "do it", "redo", "continue" and fix requests run a fix round on the held WIP, and only an ask for a review is a review. The person is told what CoderHelm is doing, on the run and the ticket when the requester asked for no PR comments. | -| p. `p_finished_work_loop` | A small ticket finished its 11 tasks, then spent 2.5 hours and $41.96 with no pull request: each 15-minute step re-ran the checks before the pull request from nothing and started fresh fix rounds. | The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends one way: a draft with Open items, waiting on a person. | -| q. `q_run_ceiling` | The same bug had been fixed in one loop at a time. | A run has an absolute ceiling on passes, continuations, worked time and spend that only a person's Retry renews, held at the worker's one entry point, at every model call, and by the stuck-run sweep, each without the others. | -| r. `r_github_limit` | A fix round hit GitHub's hourly limit. 29 writes and the diff came back "403 rate limit exceeded", and the run ended "the coder wrote no file ... That is CoderHelm's miss". | GitHub refusing for a while (its rate limit, a 5xx, no answer) never ends a run and is never blamed on the coder. The model is told the run pauses, the pass ends, and the run goes on as itself at GitHub's reset, with its page saying when. The wait adds no step and no pass. Writes GitHub rejected for a real reason are reported with that reason. A review waits for the reset without spending its retries. | -| s. `s_silent_draft` | A new-feature run finished with CI green and CoderHelm's review approving, and its pull request stayed a draft. Four of CoderHelm's own sandbox checks had failed on the head, the mark-ready step returned without a word, and the run page said completed. The same day, mark-ready messages that hit GitHub's rate limit were dropped and five more pull requests stayed drafts. | One decision settles every pull request a finished run leaves, on every path. With CI green and the review approving, CoderHelm's own sandbox failures and checklist items never hold the draft: the pull request is marked ready with them under Open items. A hold that remains names each reason and what to do at the top of the description, at warn in the log, and on the run, which is `needs_input` while a person must act. A mark-ready GitHub refuses is tried again after its reset, a bounded number of times, and the last refusal is recorded on the run. A sweep decides again for finished runs left a draft with no recorded reason, respecting a person's draft and a closed pull request. | -| t. `t_unrun_check_hold` | A check's gate couldn't install its package's dependencies (`pnpm: command not found` in CoderHelm's sandbox). The tooling failure went under Open items as a check the change didn't pass, and the pull request stayed a draft after CI passed. | A check CoderHelm's own tools couldn't run becomes an Open item CI settles, never a hold. A line written the old way stops holding once CI is green on the head and leaves the description when the pull request is marked ready. A check the change really failed still holds. The decision reads the repository's CI whenever such a line is in the description, not only when CoderHelm's own feature checks have findings: without that read, CI counted as not green and the line kept holding on every sweep. | -| u. `u_stacked_plan_check` | A run stacked on an earlier part's open pull request reset to the default branch in every step, rebuilt and force-pushed its branch each time, and measured its plan against the other branch: 13 files that branch already changed read as not done, the coder found nothing to write, and the guard stopped the run after seven continuations. | A later step keeps the base an earlier step stacked it on; a planned file the stacked-on branch already changes is done there, and the plan check's note says so; a fall in the done count is reported on the run page, and its recovery counts as progress a bounded number of times. | -| w. `w_stale_hold_recheck` | A finished run's pull request stayed a draft on an Open items line a wrong rule wrote ("the change makes the staging content its end-to-end tests read out of date"). The rule was fixed, but the line was text in the description and nothing checked it again, so the hold stayed until a person edited it. The same run spent three steps writing nothing while its plan check fell from 37 to 23 and came back each step, and the guard counted each return as progress. | Every blocked line names the version of the code that wrote it. A pull request held on a line other code wrote is checked again on its head in a fresh step of the run, once per run and code version, with the checks whose failure is a hold run again on an unchanged head; the Open items are then written from what they find. A line the running code wrote never starts another check. A fall in the plan check's count and its return count as progress only when the run's coder wrote code in between, and every plan check measures with the stacked base. | -| x. `x_silent_review_hold` | A new-feature run handed its draft pull request over for review. The review job skipped the draft ("reviewed when it is marked ready") on a path that logged nothing, and its ending was dropped because nothing had marked the job queued: no verdict, no record, no status. The ready gate kept the draft until CoderHelm's review approved the head, so each waited on the other and the pull request was held on every sweep with CI green. Its four held items were CoderHelm's own sandbox: Node switched to the repository's version had no pnpm, and every step exited 127. Another pull request lost its review the same night to the claim and dedup key of a push review CoderHelm had skipped as its own push. | Every review job ends in one visible outcome (a verdict, a skip with its reason, a retry or a failure): one `review_job_ended` line and a live status, created when none exists, and every early return names its reason. A run's hand-off reviews its pull request, draft or not; a held head claim makes it wait and look again, never skip; a skipped push review gives its claim and dedup key back. When the draft decision needs CoderHelm's approval and no review of the head exists, the gate queues one once per head and waits ("CoderHelm is reviewing this head"), and the verdict asks for the decision again; a reviewer that is off is named. A sandbox step that exited 127 or printed a tooling error, and every step after such an install, is CoderHelm's tooling and never counts against the change; the sandbox makes the root's package manager available first. | -| y. `y_skipped_checks_wait` | A failing-test fix opened its pull request as a draft; CI passed and CoderHelm's review approved, and the ready check kept the draft until the checks that test the fix were green on its head. In that repository the preview and staging deploys and the end-to-end tests run only on a pull request that isn't a draft, so on the draft every one was skipped: draft, so skipped, so still a draft. A rerun replays the same draft event (and the app had no Actions write), so CoderHelm waited, deciding every ten minutes for six hours before giving up. Each recheck was decided twice, fifteen seconds apart: the run's own decision and the one its review verdict asked for each scheduled their own next recheck, so two chains ran side by side and spent the twelve-hour budget in six. | Why a check was skipped is read from its workflow file (draft conditions, a trigger only on `ready_for_review`, the labels its conditions ask for) and kept per repository. A draft never waits on checks that skip drafts: when the proof the decision waits on (a failing-test fix's checks, an end-to-end fix's repeat runs) skips drafts, the pull request is marked ready so it runs, the description says it is still being proven, and the result decides: ready once it passes, a hold with the reason when it fails. A check skipped for a label CoderHelm may not add (deploy, staging and production labels never are) or for a reason the workflow doesn't show is a hold with one plain action, never a wait. Every wait is bounded: unchanged on the same head for two hours, it is a hold that names what didn't happen. One recheck is pending per pull request, claimed with one conditional write. | -| z. `z_run_facts` | A run's plan check found 3 of 3 tasks done; a later fix round wrote 1 file and its task tracker, built from the plan's unchecked copy, saved 1 of 3 over the plan check's checklist. The same runs showed no changed files: `files_modified` was written only by a completion step nothing called. | A round's coder starts from the checklist as saved and only adds ticks; only the plan check unchecks a task. `files_modified` is the branch's work against its base, without the plan files, written when the pull request opens and after every round that records the run's status, capped at 500 paths. | -| aa. `aa_promised_round` | A ticket run's own review requested changes. The run took review fix rounds until its automatic fix budget was spent, handed its pull request over with two of its own review's findings still listed, and finished. The draft was then held every hour for three days on "CoderHelm fixes them in its review rounds", and no round ever ran after the run was done. | A hold never promises CoderHelm work that isn't queued. A finished run's draft held on its own review's findings queues one review fix round for them, once per head, while the run has rounds left (its own review rounds, its automatic fix pushes and its fix cycles), and waits for it ("CoderHelm is fixing N findings from its review"), a wait bounded like every other. With no round left, after the run stopped its rounds itself, or once a round ran on the head and the findings are still there, the hold names what a person does and promises nothing. The security and planned work holds name a person's action too, since nothing runs those again once the run is over. A review of a finished run's pull request leaves its findings to that decision, so they are never fixed twice or outside the run's budget. | -| ab. `ab_label_prefix` | A failing-test fix's staging deploy and staging end-to-end checks were skipped on its draft. The reading of why went through the staging workflow line by line and kept every quoted string next to a label test as a label name, so a prefix test (`startsWith(github.event.label.name, 'E2E:')`) became a label named `E2E:`, and a condition that needs the staging label *and* `CI:E2E` read as either one. The staging label was refused, the team's `E2E:*` family let the bare `E2E:` through, and CoderHelm added `CI:E2E` and `E2E:`. Adding a missing label creates it, so the repository got an `E2E:` label that matches no area, and `CI:E2E` alone could never run the job. | A job's `if:` is read as an expression (multi-line blocks included) into the label combinations that run it, with those of the jobs it needs. A prefix or substring test is a pattern, never a label: CoderHelm adds only an existing repository label that satisfies it, the one the team's settings name when several do, and nothing when that isn't one certain label; a family allows `E2E:nav`, never `E2E:`. A label is added only when it alone runs the check, the settings allow it, it isn't a deploy, staging or production label and none is on the pull request; otherwise the hold names the exact real label for a person to add. Labels the old reading added that were a bare prefix or couldn't run their check alone come off when CoderHelm itself put them on, and a bare-prefix repository label GitHub made for that add is deleted when nothing else carries it. | -| ac. `ac_partial_and_red_ci` | A Jira run stopped after two steps that changed nothing (the coder twice said the last planned file needed no change, in words the plan check did not know) and a separate salvage path opened "⚠️ Partial", "Closes #0", "ran out of time" and marked it completed; another run's CI fix changed nothing and the run was completed with its pull request marked ready while every check was red. | One path opens a stopped run's pull request (`stop_pr`: ticket line, Not finished with done and left tasks and the recorded reason); no body names issue `#0` (client guard); a planned file the coder says needs no change settles and stays settled across steps; a step after a stalled one takes one task with a different approach; a CI fix that changes nothing tries again with fresh evidence (reporter comments, annotations, rerun on infrastructure failures), then holds the draft with what fails and the run needs a person; `ready::decide` never marks a pull request ready with a failing or running check; a source scan allows `create_pull_request` and `mark_pr_ready` only in their one place each. | -| ad. `ad_hand_back_reply` | A coder ended its step with "I couldn't finish, please complete the remaining tasks manually". Nothing it lacked was a credential, access, a product decision, an ambiguous ticket or an approval; its words alone handed the work to a person. | A model reply that hands the work back for a reason not on the human-only list is not an ending: the implement pass tells the coder to change its approach and runs it again, and a reply that still changes nothing is a step without progress, which climbs the supervisor's ladder (one task, other tools, a re-split, the strongest model, then the stuck task deferred with its reason) until the run finishes with what is done. Only a reply naming something on the list makes a hand-back. Every coder's system prompt carries the same stance (`ownership::coder_stance`), and a source scan fails on a hand-off phrase in any prompt or message (`ownership`). | -| ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | -| af. `af_lockfiles_out_of_sync` | A security update's pull request changed three `package.json` files (a pnpm workspace root and two npm packages with their own lockfiles) and none of the lockfiles, so every CI job failed at its frozen install. A retry planned its bumps by rule, then handed the red pull request to a model instead of building the plan. The model changed nothing; landing "nothing" removed the round's work branch, so the next attempt wrote to a branch that was gone (every write a 404, a hand edit of a lockfile among them). The round was called unfinished and the run ended failed after one attempt of three, with the same vague sentence twice. | A lockfile out of sync with its manifest is repaired by code before any model round, for any ticket and every package manager CoderHelm writes lockfiles for: each manager writes its own lockfile in the sandbox (with another mode and the LTS Node as fallbacks), one commit, and one that can't be written never hides the others. Any run that changes a manifest gets its lockfile written before the pull request opens. A retry of a dependency fix rebuilds its change from its plan on the same branch. A model's write to a lockfile is refused and pointed to the regenerate tool. Every attempt of a CI fix round opens its work branch first; a fault inside the round (no work branch, a compare or push GitHub refuses, a sandbox failure, anything else) is classified and has a way around it, and the catch-all runs the round again from a clean state, then once in a fresh step, before the supervisor's ending is asked. An attempt that changed nothing is followed by the repairs by code, then fresh evidence, then the strongest model. A run about to complete with red checks goes back to its CI fix round first, and an ending for red checks names the recorded cause, once. | -| ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | -| ah. `ah_dep_run_choice_and_proof` | A dependency security run of 64 packages finished with its checks passed. Two packages had been forced onto a new major version through an override although a patched release existed on the installed line (a unit listed one bump per package, to the highest target of all of the package's copies); CoderHelm's reviewer caught it and a fix round pinned them back. Four overrides did have to cross a major version and nothing showed their parents work on it: the sandbox ran the install, the type check, the linter and the unit tests, never the application's build or its start. One pull request carried all 64 bumps, and it did not say how many advisories stayed open or why. | A bump stays on its installed version line with that line's lowest patched release, one bump per package and line; it crosses a major version only when the advisory data lists no patched release on the line, and says which advisory. A fix that crosses a major version is a pull request of its own from the start (a person who asks for one pull request still gets one), its release notes read before any patch bump's, with the parent of a transitive package named and the range it declares. After the batches, the repository's real build (the command its CI runs, else its build script) and its declared start command run in a sandbox build of their own with a full time window, on the base branch and on the branch; what passes on the base and fails with the bumps takes out the newest commit of bumps and defers it with the cause, and only the set whose removal made it pass is held as breaking. What did not run is said, never claimed. The description ends with the advisories that stay open, counted by reason. | -| ai. `ai_open_items_settled` | A dependency update finished completed with five Open items on its pull request for a person: the package manager's audit never ran so the advisory counts were unknown (listed twice, in different words), nothing showed that the packages an override moved still built and passed their tests, a README line claimed checks no run had made (and was still listed after a later round rewrote it), and the plan had no end-to-end checklist for a change with nothing to deploy. The coder's full checks had been refused twice for lack of time after two lockfile regenerations in one step, and nothing carried them anywhere. | A run settles its own open items before it finishes (`settle`). Each item is classified: CoderHelm runs it in its sandbox, the repository's CI settles it, it does not apply to the run, or only a person has what it needs (a reason on the human-only list). What CoderHelm can run it runs in a step with a full sandbox window, a fresh step when this one has too little time, and a check the coder was refused for lack of time is owed whether or not an item names it. A change to the dependencies is always audited by its package manager after the bumps (`common::dep_audit`, one row per manager) and the counts left are quoted. A passing result closes the item and is quoted under "Checked by CoderHelm"; a failing one takes out a dependency fix's newest verified set of bumps, or gives any other run a fix round with the real output. An end-to-end checklist is not raised for upkeep, the same missing fact is one item, every item names the head it was written on, and a run about to finish with items of an earlier head derives them again first. What stays says why. Lockfiles are regenerated once per state of the branch. | -| aj. `aj_coder_habits` | A bug fix was right on its face and wrong four ways. Its plan named two files and nothing about them. The fix was written first and its test after, and the test passed with or without the fix. It rounded per line, an approach one pull request had shipped and another had reverted two months earlier, with the reason one commit list away. It changed a response field another of the team's repositories read and never named that repository. Its one real doubt (half up or half even) was listed at the bottom of the finished pull request, and a helper file no task named was reformatted along the way. | Before code, a bug's plan names the test that fails on the code as it is (or why none can and the next best proof), and that test is the first task. The worker itself reads the commits of the files the plan modifies and what depends on them (the code graph, a search of the team's other repositories for each changed name); a revert must be answered by name, and every dependent is updated by a task or called safe with the reason. A doubt that changes what is built is asked at planning time with the default the run builds. After the build each new or changed test runs with and without the change: one that passes either way, a bug's test that can't build on the base, a changed file outside the plan with no reason and a planned dependent left untouched all go back to the coder. The pull request carries the failing and the passing result, the history, and who the change affects. | -| al. `al_learning_loop` | A person pushed the same fix on top of two of CoderHelm's pull requests two weeks apart, and the same reviewer asked for the same test both times. All that was kept from the first was "PR #101 was rewritten by people before merging", and nobody could say how often its pull requests were edited, closed or reverted without reading the runs. | What becomes of every pull request CoderHelm opens is counted from the webhooks, each pull request once however often an event is delivered: merged, closed, reverted, review rounds, a person's commit on top, open items. A person's edit, a close with a comment and a revert with a reason each become a lesson that names the code and says how to check a change against it, with the evidence attached. The same lesson from another pull request is counted on the kept one, and a lesson people go against loses weight until it is no longer given. What a reviewer asked for on several pull requests is given to the next build when that reviewer is likely to review it, and nothing personal is kept. A lesson seen on enough pull requests is proposed for the repository's guide file as one pull request at a time, never as a push to the default branch. | -| am. `am_description_from_the_head` | A dependency security run's pull request had the right code after a review round and the wrong description. Its table still showed the plan (five packages as major version jumps the final manifest no longer makes, a headline counting twenty major versions), its count of fixed advisories had never been compared with the final lockfile, the round that fixed the code wrote that it could not edit the description and left the corrections to a person, and the repository's second app (a CMS studio no CI job builds) took a package an override moved to a new major and was never built. | The description is a function of the head. A dependency pull request's table and headline are what the lockfile on the head resolves compared with the base branch; an advisory counts as fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. Every write of a description goes through `description::save`, every path that moves the head rebuilds it through `description::head_moved`, and a round's sentence that hands the description to a person is taken out and becomes the rebuild. A sentence a run writes into a file that says a check passes needs that check's recorded passing result, or it is taken out. Every workspace project that takes a changed package line is built when its manifest declares a build, CI job or not; a project that can't be proven in the sandbox is named with why, and a build only the bumps break feeds the take-out. | -| an. `an_six_database_findings` | Security, Infrastructure showed six database findings, every one a one-command runbook with no pull request although the databases were in the team's code. The same CVE stood on an operating system update, an Aurora PostgreSQL patch and a MySQL upgrade. A database with a Terraform-generated identifier and an Aurora cluster defined through a module were "not found in code". A patch and an upgrade pending on one cluster were unrelated rows, an update on a second instance was dropped, and the account was read one page deep. | An advisory is attached only where it applies (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. An action is named for what it means on its ARN. One database's pending actions are one ordered set of rows. The defining code is found from stack records, resource type and attributes, module calls and variable files, graded, and a guess never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value; one that cannot be expressed in code stays a complete runbook and says why. A change that would replace a database is refused. | -| ao. `ao_stopped_log_finding` | Two log findings of one production service stayed on the Logs page as Critical and New, each with "Create fix PR" and "Not started automatically: not sure the repo is ...; check it and start the fix", a day and a half after their error had stopped: 735 matching lines in one six-hour window, then none while the service wrote its usual volume. The team had fixed the cause the day before. Only time closed a finding (three days without a line), so a problem that was over read as a live emergency that needed a person. | Every analysis counts each open finding's own lines on its own log group and keeps the count with the lines the group wrote. Two analyses in a row with no matching line at the service's usual volume make the finding stopped: shown and counted as stopped, never New or a live critical, with no automatic fix and no stale "choose a repo" reason. When the service itself went quiet nobody can tell, and it stays as it was. A burst that stopped after a change in its repo resolves after one day instead of three, with that evidence in the reason; an error that keeps coming back keeps its longer period. Seen again, it is live again and its fix may start. Evidence for the repo that couldn't be weighed is weighed again next sweep and never put to a person. | -| ap. `ap_closed_pr_keeps_findings` | An admin closed CoderHelm's dependency fix pull request for a repository to start again and cancelled its fix run. On the Security page every checkbox for that repository was off, the header's too, with nothing to say why: 274 findings still read "in a pull request" a day later. The pull request webhook recorded the close on the run and never told the findings, cancelling a run wrote only the run, and the one comparison with GitHub was the last step of the scheduled sweep, behind the time every team's sources and triage left, reading a failed request as "still open". | A finding is `pr_open` only while its pull request is open and `fixing` only while its run works (`common::security_release`). A pull request closed unmerged gives its findings back with who closed it and when, a cancelled or closed run releases what it claimed, a reopened pull request takes its findings back, and a merge fixes them: on the webhook or the person's action, and again on every sweep, first for each team and on a clock of its own, bounded and in turn, so a missed webhook and records stale from before heal within a sweep. A person asking for a fix always gets one; automatic fixes wait a week after a person said no. Retry on the run is a new request from the findings as they are now and opens a new pull request. GitHub not answering is never read as open, closed or merged. | -| aq. `aq_comment_during_run` | A run asked three questions on its ticket, proposed defaults and kept building. A person answered on the ticket twenty minutes later; the gateway logged that a run was in progress and dropped the comment. Nothing acknowledged it, the run never saw it, and its notes kept saying it went on without the answers. Comments written before any run existed were dropped too, and nothing read them when the run started. | A person who writes on a ticket CoderHelm is working on gets an acknowledgement, and what they wrote is acted on. The comment is kept once per comment id and acknowledged once (a reaction on GitHub, one short reply in Jira; never for CoderHelm's own comments or other bots). The run reads its open comments together at its next step boundary: answers and instructions go into the plan while it is being made; once the plan is final they become one round on the pull request when the step ends, where the code changes in the place the plan put the choice, and the ticket is told; a comment that says to stop ends the run at once. A comment nobody read yet stays open for what comes next (the next step, the round on the finished run's pull request, the ticket started again, or the next run), and comments written before a run started are read at its first boundary. | -| ar. `ar_description_stamped_to_the_head` | A dependency run's pull request was described from a head, and the head then moved on without it. A feedback round changed an override in the manifest and the description was rebuilt on that commit, where the lockfile still resolved the old version ("not moved on the head"); the lockfile was regenerated in the commits after it and the run completed. The description still said not moved, still counted the advisory as not fixed, still listed the package under open findings and "the lockfile is out of sync" under Open items, and CoderHelm's own review of the final head left that as a note. The checks step on an open pull request never rebuilt the computed sections, a regenerated lockfile was pushed with nothing after it, a review wrote its findings into the copy of the description it had read when it started (undoing a rebuild made meanwhile), and nits on CoderHelm's own pull request ended the loop. | The description names the head it was built for, and whenever that is not the pull request's head it is rebuilt: after every message in which CoderHelm moved the branch (seen in the one place every request leaves the GitHub client), in the checks and settle step, before a review of its own pull request, in the pull request watch, and at the end of the run, which never completes while the two differ. A review writes on the description as it is now and only for the head it reviewed. An item that says a lockfile is out of sync is checked on the head, never carried. A finding that the description is behind the code is settled by the rebuild, and every finding on CoderHelm's own pull request that is not pure style is its own to act on. | -| as. `as_infra_closed_pr_keeps_record` | The same gap as `ap` in the other store. An infrastructure finding keeps its own record and nothing released it: after a person closed its fix pull request the record stayed `pr_open`, so the Infrastructure tab kept the closed pull request and never offered "Open fix PR" again; a cancelled or failed fix run left the record `fixing` for good; a reopened pull request was never noticed. | Infrastructure records go through the same reconciliation as dependency findings (one `reconcile` over `common::security_release::Claim`, not a copy): the same reads of GitHub and the run records, events, sweep bounds, person-closed record, holds and Retry. What is this store's own stays: a merge never closes a finding (only a read of the account does), a pull request the replacement guard made a draft is not closed and is left as it is, a finding on its runbook stays there until its code or target changes, a pull request is recorded only after the guard read it, and a fix round that ends without settling its pull request becomes the guard's second step (a draft), never a ready pull request. | -| at. `at_round_scope` | A feature run opened its draft pull request and the proof check found three gaps. The fix round went to edit the existing file that builds a page's metadata, which the pull request had not touched yet: two edits were "rejected: outside the ticket's files" and a third failed. The guard held every fix round to the files the pull request already changed and gave way after two refusals of one path, so the round started for work the branch had not done was refused the file that work lives in. A planned task stayed not done, planned-work rounds went on for about an hour on a pull request whose checks passed, and one that hit GitHub's hourly limit was read as "it met an error": its work branch was deleted during the limit, an attempt was spent and the next try started five seconds later. | A round may edit what it was started for (`write_guard`): the pull request's files, the plan's task files (done or not) and listed dependents, and the files its gap, finding or failing check names; a check's output names the files that fail, never the ones it only warns about. Any other existing file is refused every time, however often it is tried, with one message that says how to justify the edit (`outside_plan`, one sentence); a justified edit is made and listed on the pull request under "Changed outside the plan's files". A round that ends with an edit refused and no task finished made no progress whatever it pushed: the next round is told what was refused, and a second one stops and names the file once. GitHub's limit inside a round on the pull request is a wait: the round is parked as it stands (its work branch, its attempt) and goes on after the reset. | -| au. `au_upgrade_decided_and_proven` | An outside reviewer checked a dependency security pull request of about fifty packages, four across a major version. The code was sound and the account of it was not: its count of advisories left was CoderHelm's own and disagreed with the package manager's production audit of the same head; one package of a framework was raised while its siblings from the same source repository stayed behind; no type check was recorded, because the repository's CI has none and CoderHelm's checks mirrored CI; it said "contract unchanged" although a validation library's major changed the 400 error bodies of an endpoint; and each override across a major lacked why it is safe. | A dependency update is decided and proven by the pipeline (`common::upgrade_quality`). Packages released together are found from the registry's source repository and the base branch's lockfile, move as one bump, and a lockfile that splits them fails the set like any check. The set a dependency change is verified with (frozen install with the manifest's package manager version and the deployment image's, type check when the project is typed, build, lint, tests, production audit) is found in the project whatever CI runs, budgeted to the sandbox's time, compared with the base branch, and recorded against the head; the settle stage cites the record, so "check not run" never stays open for a check of the set. Advisories are counted once: the base branch and the head read the same way and laid beside the package manager's audit, each disagreement with its cause, each remaining advisory with its package, whether the change touches it and why it stays. Each major carries its dependency paths, where they run, whether the repository uses it, the reachability verdict with its limit, and how it is fixed (a parent release that declares the fixed range before an override). A major the repository calls is probed through its call sites on the base branch's build and the head's; a changed answer is a known behaviour change, and a sentence that calls the contract or the behaviour unchanged without a probe that shows it is taken out. The record is of one commit, and a head that has moved since is said to have. | -| av. `av_description_from_facts` | An outside reviewer found a dependency security pull request's code sound and its description wrong in five places (a package row "not moved on the head" that the lockfile resolves at the patched version, an open item saying the lockfile was out of sync when a frozen install passes, a fixed advisory listed as not fixed, a wrong count of high advisories left, the package still listed as open). The title read `fix(deps): ...` where every merged pull request reads a ticket key and a summary, commits carried the prefix `KEY-1:` (a sample key CoderHelm had learned from its own description), a sentence said "contract unchanged" with nothing behind it, no major version jump said why it was safe, and CoderHelm's own review thread about the description stayed open. A second pull request, a three-file feature, carried a page about its outside steps that nobody could act on: a raw 403 with its JSON body twice, "needs access" beside "owner: CoderHelm", "after the pull request opens" long after it had opened, and found facts and a query already run listed as items with owners. | A description is a view of the facts recorded for its head. Every sentence a person or a model wrote is held against them on every rebuild of every kind of run, and one they do not bear out is rewritten from them or removed; what a model writes is checked before it is saved. What a reader sees first is rendered from the facts (the change, how to check it, the risk, what they have to do or that nothing is needed, anything out of the ordinary with its evidence) within a budget; everything else is collapsed. A step outside the code has one owner and one state, generated every build; a check CoderHelm can make is made and reported as a result; a raw error is said as a cause with what lifts it. Titles and commits follow the form detected in the repository with a real key or none. A lesson that holds a placeholder is refused when learned and removed when found. A rebuild resolves CoderHelm's own thread that said the description was behind. The quality eval (`description_eval`) keeps both pull requests as cases. | -| aw. `aw_quarantine_dead_end` | Sixteen end-to-end tests of one team sat in quarantine, some for over three weeks, each with one button (release) and nothing happening. The week's two automatic fixes went to whichever flaky test a default-branch run listed first and only to tests that cost CI time that week, which a quarantined test never does; a test whose fix failed once was never looked at again; a person's "Fix this test" was dropped by the worker as a duplicate of the gateway's own mark, and refused for a quarantined test whose health had gone back to healthy. One test had failed three times and then passed about thirty-five runs in a row on several pull requests; it stayed quarantined under a cause sentence its history had disproved. | A quarantined test always shows where it stands and what happens next (`common::e2e::quarantine`): its fix pull request with its state, the run that is working, or the actions (fix, remove) with the one reason nothing happened by itself. A test that proved healthy (20 clean passes in a row, on more than one pull request or branch, over two hours) leaves by itself with the evidence and its ticket is closed; one that bounces back twice in 30 days is called unstable and needs a quiet week. A cause the runs disprove is marked out of date and worked out again on the next failure. Automatic fixes go to the longest quarantined first, a fix that did not hold is tried again after a week, and the weekly number is said with the day it starts again; a person's request is never counted and never dropped. A removal is a pull request for the team with why it is reasonable: CoderHelm proposes one only when the test was quarantined 30 days, two fixes did not hold and another healthy test covers it, and never merges it. | -| ax. `ax_github_budget` | An installation used up GitHub's hourly request budget: sweeps on timers spent it beside the runs. A review fix round that had worked for two hours met the limit, the next step logged `Resume failed: RateLimited`, the run read "the last fix round didn't finish" and its review's findings were deferred to a person; three sweeps failed on the same limit, one warning per item. | A rate limit is a wait, everywhere: the resume is sent for the reset as the same run and round (no attempt spent, nothing unfinished, nothing deferred) and the run page says "Waiting for GitHub's hourly limit; continues by itself at