diff --git a/.abcd/development/brief/04-surfaces/01-ahoy.md b/.abcd/development/brief/04-surfaces/01-ahoy.md index 0a0749332d..d09dca3a61 100644 --- a/.abcd/development/brief/04-surfaces/01-ahoy.md +++ b/.abcd/development/brief/04-surfaces/01-ahoy.md @@ -1227,6 +1227,22 @@ file, which setup reads but never edits once it exists. A missing or unloadable config raises nothing here, and an entry that is not a plain path inside the repository is not looked up: the check's own refusal names both. +**A stale main checkout of abcd's own source is a report-only gap** +(iss-2612022220481334). `scripts/abcd.sh` builds the tree it lives in, so a +main checkout left behind runs every verb through an abcd that old. Where the +repository's main working tree holds `cmd/abcd/main.go`, and its `HEAD` lacks +changes that landed on origin's default branch, as last fetched, the oldest of +them more than a day ago (a change is a commit on the branch's first-parent +line, so its age is when the branch moved past the checkout), the passes a +person starts raise one non-required, non-resolvable `user-state` gap, +`source.main_checkout_behind`, from the checkout or any of its worktrees. Its +detail names the checkout, how many days and changes it is behind, and its fix +hint the way on, an up-to-date worktree cut from the worktree store; abcd never +moves the checkout, where peers may stand. Its git reads run under a deadline +of their own. The hooks' pass never reads it, and nothing fetches. The +script itself says the same of the tree it builds, in one line on stderr, +whichever checkout that is. + **The README question pair** (itd-2610031348087517, spc-2610031704338417). Setup asks whether abcd keeps parts of the project's `README.md` current and, on a yes, which. The first question, keyed `readme`, stands alone with `yes`, diff --git a/.abcd/development/brief/04-surfaces/17-guard.md b/.abcd/development/brief/04-surfaces/17-guard.md index facee62c96..7077b9396f 100644 --- a/.abcd/development/brief/04-surfaces/17-guard.md +++ b/.abcd/development/brief/04-surfaces/17-guard.md @@ -903,6 +903,29 @@ does. A `git-` program in command position, at any path, is also read as for: `remote..push`, `remote..mirror`, and on a gc `gc.pruneExpire` and the reflog expiries. +A workflow run is not cancelled (iss-2612022221042267). A cancelled job reruns +from its start, so a release cut loses a cancelled long job's whole round, and +an agent judged a release's loop shard stuck at 94 minutes on a stale estimate +when the same shard had taken 88, 115, 124 and 124 minutes in the nightly runs +of 26 to 29 Nov. The guard reads no network and no line says whose run an id is +or how long its jobs have run, so four bundled blockers refuse every cancel +made through `gh` (one sent by another HTTP client or through a `gh` alias is +not read): +`gh run cancel` (`gh-run-cancel`); a `gh api` call whose endpoint is +`actions/runs//cancel` or `…/force-cancel`, whatever its method, or a path +partly unfixed whose last segment is one of those and whose fixed segments +before its first variable and after its last can still begin and end that +route, a route word between two variables ruling nothing out +(`gh-api-run-cancel`, the `forge-run-cancel-path` shape); and a call to a path +whose last segment the line does not fix (`forge-run-cancel-open-path`) that is +a `POST`, by a `POST` or unfixed method (`gh-api-run-cancel-unread`) or, with no +method written, by a field other than a GraphQL `query` or a body from the file +gh's input option names, which gh sends as one (`gh-api-run-cancel-unread-field`). The successor says how to measure the job +(elapsed, the same job's median and maximum over recent successful runs, its +`timeout-minutes`) and leaves the cancel to the person; the refusal names no +measured numbers, as abcd keeps none, and is not allowable once +(dcn-2612022305576019, which also says how to reverse it). + The hazard entries are bundled in the binary and merged with a repo's `.abcd/guard.json`. That file is dedicated rather than a rules-loader domain, so a rules kill switch can never silently disable a safety guard, and it must diff --git a/.abcd/rules.json b/.abcd/rules.json index a54c4e43d3..5710a74d7f 100644 --- a/.abcd/rules.json +++ b/.abcd/rules.json @@ -104,7 +104,7 @@ "version" ], "rules": [ - "In a source checkout of abcd itself, every abcd invocation is `scripts/abcd.sh ` from the repo root (by the script's path from anywhere else; the verb runs where you stand) \u2014 never the plugin-root binary and never an `abcd` on PATH. Both are the last PUBLISHED version, stale by construction here and further behind with every commit, and the failure is often silent rather than a refusal: an empty `changelog --json` cut, a record written through a schema the gates no longer accept. `scripts/abcd.sh` builds this tree to `.abcd/.work.local/bin/abcd`, relinking only when an input changed, and runs it, so exit 2 and exit 3 reach you as themselves; `go run ./cmd/abcd` turns every nonzero exit into 1. The documented resolution ladder reaches the plugin-root binary first and it answers, so its `go run` fallback is never reached by following it; go straight to `scripts/abcd.sh` (AGENTS.md, Build, test, and checks).", + "In a source checkout of abcd itself, every abcd invocation is `scripts/abcd.sh ` from the repo root (by the script's path from anywhere else; the verb runs where you stand) \u2014 never the plugin-root binary and never an `abcd` on PATH. Both are the last PUBLISHED version, stale by construction here and further behind with every commit, and the failure is often silent rather than a refusal: an empty `changelog --json` cut, a record written through a schema the gates no longer accept. `scripts/abcd.sh` builds this tree to `.abcd/.work.local/bin/abcd`, relinking only when an input changed, and runs it, so exit 2 and exit 3 reach you as themselves; `go run ./cmd/abcd` turns every nonzero exit into 1. The documented resolution ladder reaches the plugin-root binary first and it answers, so its `go run` fallback is never reached by following it; go straight to `scripts/abcd.sh` (AGENTS.md, Build, test, and checks). That build is only as current as the tree: more than a day behind origin's default branch or its own upstream, as last fetched, the script says how far in one stderr line before the verb runs (it never fetches or refuses), so run it from an up-to-date worktree (`scripts/abcd.sh ahoy worktree add `); `scripts/abcd.sh ahoy` names a main checkout that far behind as the `source.main_checkout_behind` gap (iss-2612022220481334).", "In a checkout the person has listed in ~/.abcd.noindex/dogfood-roots, each line naming the checkout, a tab, the https:// or ssh URL of the remote its reviewed branch lives on, and optionally a tab and the branch (main when left out), the plugin's hooks run a build of that branch's tip as the declared remote reports it. A background builder reads the tip with git ls-remote and records it in ~/.abcd.noindex/dogfood//, and only that record chooses the build: HEAD, refs/remotes/origin/*, origin/HEAD and the checkout's remote config choose nothing, and a moved remote-tracking ref only prompts one more check of the declared remote. The remote must be one no agent can move, such as a protected branch on a forge: a filesystem path, file://, git:// or http:// remote is refused, because this account can write the first two and anyone on the network path can answer for the last two. An ssh or https remote whose host is this machine by name (localhost or a name under it, the machine's own host name, a loopback or unspecified address, or an IPv4 shorthand such as 127.1) is refused as well, and so is a bracketed scp-like host ([host]:path), which must be named with ssh:// instead. An ssh alias that resolves here is one the agent can move too, but abcd cannot tell it from a forge, so the person must not declare one. Anything running as the account can still edit the list or replace a file in the store, and the builder and the hooks inherit the account's whole environment (the go toolchain, its module cache and GOENV, PATH, git's own variables and certificate settings, proxies, ~/.ssh, among the rest). Until the build is ready, or when the check or build fails, or when the line names no remote or a refused one, the hooks run the installed release and say so on stderr, as they do when the dogfood build answers an event with any exit but 0 (the guard: any but 0 or 2), except that a dogfood guard killed by a signal holds the command (exit 2) and only its other failures fall back to the installed release; a tip the checkout has not fetched yet asks for `git fetch`. The list is the person's own opt-in: never create or edit it, and never write into ~/.abcd.noindex/dogfood/. `scripts/abcd.sh` stays the rule for every abcd invocation you make (AGENTS.md, Build, test, and checks).", "In a source checkout of abcd, a narrow test spells -trimpath: `scripts/abcd.sh implement load --wait --narrow --timeout 6h -- go test -trimpath -count=1 -timeout 40m ./internal/foo`. `scripts/abcd.sh`, every Go step a Makefile target makes and CI's check job build under it (the commit hooks do not, while a running drive pins their bytes: dcn-2611071820445224), which keeps the checkout's directory out of go's compile key, so worktrees share one build cache and preflight tests the form CI tests; a test run without it compiles its own copy of every package it reaches, in every worktree." ] diff --git a/.abcd/work/decisions/dcn-2612022254546338-scripts-abcd-sh-s-stale-tree-line-names.md b/.abcd/work/decisions/dcn-2612022254546338-scripts-abcd-sh-s-stale-tree-line-names.md new file mode 100644 index 0000000000..fa4673cd73 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022254546338-scripts-abcd-sh-s-stale-tree-line-names.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022254546338 +slug: scripts-abcd-sh-s-stale-tree-line-names +date: 2026-12-02 +--- +2026-12-02 — scripts/abcd.sh's stale-tree line names the command that makes an up-to-date worktree (scripts/abcd.sh ahoy worktree add ), not an existing up-to-date worktree as iss-2612022220481334's remedy proposed. Grounds: naming one would take a worktree listing and a log per worktree on every call, past the one or two git calls the check may spend, and a listed worktree can be a peer's lane; a new worktree is cut from origin's default branch as last fetched, so the command is always a right answer. The age is that of the oldest first-parent change on the branch that the tree lacks, so a merged branch's old commits do not read as staleness. The ahoy gap reads only the main checkout, and only on the passes a person starts, never a hook's. To reverse: list the worktrees in the line (git worktree list --porcelain, then one log each) and name the freshest. diff --git a/.abcd/work/decisions/dcn-2612022305576019-the-guard-refuses-every-cancel-of-a.md b/.abcd/work/decisions/dcn-2612022305576019-the-guard-refuses-every-cancel-of-a.md new file mode 100644 index 0000000000..c6efa3aa49 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022305576019-the-guard-refuses-every-cancel-of-a.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022305576019 +slug: the-guard-refuses-every-cancel-of-a +date: 2026-12-02 +--- +2026-12-02 — The guard refuses every cancel of a workflow run, not only a release run's job inside its measured maximum as iss-2612022221042267's remedy proposed: gh run cancel in every form (gh-run-cancel), a gh api call to actions/runs//cancel or force-cancel whatever its method (gh-api-run-cancel), and a POST, or a method the line does not fix, to a path whose end the line does not fix (gh-api-run-cancel-unread). Grounds: the guard reads no network, and no command line or local record says whose run an id is, which job is running or how long it has run, so a judge of elapsed time against a maximum could only refuse when it cannot tell, which is every time; three registry blockers cost nothing beyond the matcher's existing pass and fail closed. The refusal therefore names no measured numbers: it says how to measure the job (gh run view --json jobs, the same job's median and maximum over the workflow's recent successful runs, its timeout-minutes) and leaves the cancel to the person, and it is not allowable once. To reverse: keep per-job timings from the runs abcd's status refresh already reads and hand them to the guard as the merge mode is handed in, so the refusal names the median, maximum and timeout; allowing a cancel past the maximum would still need the run's elapsed time, which only the forge holds. diff --git a/.abcd/work/decisions/dcn-2612022356262040-scripts-abcd-sh-s-two-stale-tree-git.md b/.abcd/work/decisions/dcn-2612022356262040-scripts-abcd-sh-s-two-stale-tree-git.md new file mode 100644 index 0000000000..3c52abafbd --- /dev/null +++ b/.abcd/work/decisions/dcn-2612022356262040-scripts-abcd-sh-s-two-stale-tree-git.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612022356262040 +slug: scripts-abcd-sh-s-two-stale-tree-git +date: 2026-12-02 +--- +2026-12-02 — scripts/abcd.sh's two stale-tree git reads (one for-each-ref listing and one first-parent log) run with no deadline. Grounds: there is no portable bound in plain shell, since macOS ships no timeout and a watchdog of its own (a background sleep that kills the read by its pid) would start two more processes and a kill path on every verb, costing more than the reads; both reads are local, start no network and no hook, the log no longer verifies signatures (--no-show-signature), and the log is bounded by the first-parent changes HEAD lacks. To reverse: wrap both in timeout, or gtimeout where only that is installed, when command -v finds one, and leave them bare where neither is. diff --git a/.abcd/work/decisions/dcn-2612030017439523-the-run-cancel-guard-s-field-entry.md b/.abcd/work/decisions/dcn-2612030017439523-the-run-cancel-guard-s-field-entry.md new file mode 100644 index 0000000000..16cbf13b24 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030017439523-the-run-cancel-guard-s-field-entry.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030017439523 +slug: the-run-cancel-guard-s-field-entry +date: 2026-12-03 +--- +2026-12-03 — The run-cancel guard's field entry (gh-api-run-cancel-unread-field) applies only where the line writes no -X or --method, through a new absent_flags pattern field, and reads a field keyed query as a GraphQL query, leaving it to the merge entries; --input and every other field, an unfixed key included, still count. Grounds: gh sends a field as a POST only where no method is written, and the merge rules hold that in auto mode gh api "$EP" -f query=... and -F query=@q.graphql are not blocked, which a refusal of every field broke while naming the run-cancel entry where the merge one is owed. Known gap: a query-keyed field sent to an unfixed path that is a cancel route would cancel a run; a written POST to such a path is still refused (gh-api-run-cancel-unread). Reverse: replace the entry's rest-body-field flag_values with flags [-f|--field|-F|--raw-field|--input] and change the merge test's auto-mode expectation for those two lines. The guard's per-byte work bar rose from 76 to 80 to fit the four run-cancel entries, measured once at 76.0. diff --git a/.abcd/work/decisions/dcn-2612030127089869-the-run-cancel-guard-rules-guard-against.md b/.abcd/work/decisions/dcn-2612030127089869-the-run-cancel-guard-rules-guard-against.md new file mode 100644 index 0000000000..7c8bf33df2 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030127089869-the-run-cancel-guard-rules-guard-against.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030127089869 +slug: the-run-cancel-guard-rules-guard-against +date: 2026-12-03 +--- +2026-12-03 — The run-cancel guard rules guard against an agent cancelling a healthy run by mistake, and four known limits are left as they are. (a) A lone GraphQL query field with no method, sent to a path whose end the line does not fix, is not read as a cancel; it could later be narrowed to paths that can still be the GraphQL endpoint. (b) A -X... word that is really the value of a value flag inside a short-flag cluster stands the field rule down; only a deliberate spelling does this. (c) A POST to repos/$REPO//$VAR (a commit status, say) is refused; it passes with the owner and repository written out or as {owner}/{repo}. (d) A word that is nothing but a substitution is never read as a flag, so where it is really a value flag, a typed -X... word after it reads as a written method and stands the field rule down. Grounds: (a), (b) and (d) need a deliberate spelling, and the guard judges an honest agent's mistakes; (c) refuses rather than lets through, and nothing in the repository issues such a call. Reverse: narrow (a) to GraphQL-capable paths, parse cluster values for (b), exempt fixed routes other than actions for (c), and for (d) read a whole-substitution word as possibly a value flag and stop the method walk there. diff --git a/.abcd/work/issues/open/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md b/.abcd/work/issues/resolved/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md similarity index 64% rename from .abcd/work/issues/open/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md rename to .abcd/work/issues/resolved/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md index 542d3d3238..8f9a15a698 100644 --- a/.abcd/work/issues/open/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md +++ b/.abcd/work/issues/resolved/iss-2612022220481334-scripts-abcd-sh-builds-the-tree-it-lives.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "scripts/abcd.sh" remedy: "scripts/abcd.sh prints one line on stderr when the tree it builds is behind its upstream or origin's default branch by more than a day, naming how far and the up-to-date worktree to run from, and ahoy lists a stale main checkout as a gap; the build itself stays the tree's own" +resolution: "scripts/abcd.sh now says on stderr, in one line before the verb runs, when the tree it builds is more than a day behind origin's default branch or its upstream as last fetched: how many days and changes, and to run from an up-to-date worktree; it spends no git where there is no origin and two local reads where there is, never fetches, never refuses and keeps every exit code. ahoy's person-started passes list a source checkout's stale main checkout as the report-only source.main_checkout_behind gap (dcn-2612022254546338)" +impact: internal --- scripts/abcd.sh builds the tree it lives in, and the main checkout sits 1297 commits behind origin's default branch (still on 26 Nov), so every verb run through it from there is a six-day-old abcd with nothing saying so. A sweep run that way kept 1098 of 1107 rows on a recent-write rule the default branch fixed in c0147f43e (abcd's own reservation state counted as a session's write), and records and landings went through the old build too. diff --git a/.abcd/work/issues/open/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md b/.abcd/work/issues/resolved/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md similarity index 58% rename from .abcd/work/issues/open/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md rename to .abcd/work/issues/resolved/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md index d52f6286fe..d15b2bade3 100644 --- a/.abcd/work/issues/open/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md +++ b/.abcd/work/issues/resolved/iss-2612022221042267-nothing-stops-an-agent-cancelling-a.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/guard" remedy: "the guard judges gh run cancel and the matching API call on a release run: it refuses while the running job's elapsed time is under the recorded maximum for that job, naming the measured median and maximum and when the job's own timeout ends it; abcd keeps those timings from the nightly and release runs it already reads for the macOS verdict" +resolution: "The guard now refuses every cancel of a workflow run: gh run cancel in every form (gh-run-cancel), a gh api call to actions/runs//cancel or force-cancel whatever its method (gh-api-run-cancel), and a POST or unfixed method to a path whose end the line does not fix (gh-api-run-cancel-unread). It reads no network and nothing on a line says whose run an id is or how long its jobs have run, so it cannot judge elapsed time against a measured maximum; the refusal says how to measure the job (elapsed, the same job's median and maximum over recent successful runs, its timeout-minutes) and leaves the cancel to the person, naming no numbers since abcd keeps none (dcn-2612022305576019)" +impact: fix --- Nothing stops an agent cancelling a release run's job while it is within its measured duration. On 2 Dec an agent cancelled the v0.18.0 release's loop shard at 94 minutes, trusting a workflow comment's stale 36-minute estimate, when the same shard had taken 88, 115, 124 and 124 minutes in the nightly runs of 26 to 29 Nov, and the cut lost that shard's whole round. diff --git a/.abcd/work/issues/open/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md b/.abcd/work/issues/resolved/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md similarity index 74% rename from .abcd/work/issues/open/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md rename to .abcd/work/issues/resolved/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md index 13c4dc8b85..567a25f26b 100644 --- a/.abcd/work/issues/open/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md +++ b/.abcd/work/issues/resolved/iss-2612022221066637-a-declined-tool-call-reads-to-an-agent.md @@ -10,6 +10,8 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/surface/cli/hook_stop.go" remedy: "the stop hook's owed-work note says that a declined tool call declines that call only, that work owed goes on, and names the next owed item; the AWAY rules carry the same line" +resolution: "the stop check's owed-work note now says a declined tool call declines only that call and the owed work goes on, beside the next item it names, and the away block carries the same line (autonomy.DeclinedCallLine); the person's line on a stop the cap let go leaves it out" +impact: fix --- A declined tool call reads to an agent as a stop on all work: on 2 Dec an agent held every lane for 16 minutes after one call was declined, replying that it was holding while the stop hook said work was owed, and left the release's lost shards and finished fixes untouched until the person asked why. The stop hook's owed-work note does not say what a declined call means. diff --git a/commands/ahoy.md b/commands/ahoy.md index b0d0840696..69ec219310 100644 --- a/commands/ahoy.md +++ b/commands/ahoy.md @@ -131,7 +131,13 @@ Then summarise the JSON for the user: often a `CLAUDE.md` retired after it was listed: the documentation check refuses to run while it is there, so none of its rules, the banned names included, checks anything. Its `fix_hint` names the entry to take out of - that file (or the file to create). Never tell the user `/abcd:ahoy install` closes + that file (or the file to create). A `source.main_checkout_behind` gap, + listed only in a source checkout of abcd and only by bare `ahoy`, `install` + and `doctor`, never by a hook, names the repository's main checkout when it + is more than a day behind origin's default branch as last fetched: how far, + and that `scripts/abcd.sh` run there builds an abcd that old. Its `fix_hint` + names the way on, an up-to-date worktree; abcd never brings the checkout up + to date itself. Never tell the user `/abcd:ahoy install` closes a report-only gap. If there are actionable gaps, tell the user to run `/abcd:ahoy install` to apply diff --git a/commands/guard.md b/commands/guard.md index 006b0c6530..b415f260b7 100644 --- a/commands/guard.md +++ b/commands/guard.md @@ -1044,6 +1044,45 @@ Each refusal asks for a new commit instead: a revert, or a fix on top. A rebase or an amend is not on the list: on a commit not yet pushed it is ordinary work, and once the commit is pushed, the force push it would need is what is refused. +## A workflow run is not cancelled + +A cancelled job reruns from its start, so a release cut whose long job is +cancelled loses that job's whole round, and a job that looks stuck is usually +inside its measured time (iss-2612022221042267). The guard reads no network, +and nothing on a command line says whose run an id is or how long its jobs have +run, so it refuses every cancel of a workflow run made through `gh`, whoever's +run it is. A cancel sent by another HTTP client (`curl`, a script's own +request) or through a `gh` alias is not read. Through `gh`, it refuses: + +- `gh run cancel`, in every form (`gh-run-cancel`); +- a `gh api` call to `actions/runs//cancel` or `…/force-cancel`, a host in + front or not, whatever its method (`gh-api-run-cancel`); +- a `POST`, or a method the line does not fix, to a path whose end the line + does not fix (`"$EP"`, `"repos/$R/actions/runs/$ID"`), which can still be one + (`gh-api-run-cancel-unread`), and a call to such a path that writes no method + and carries `--input` or a field other than a GraphQL `query`, which gh sends + as a `POST` (`gh-api-run-cancel-unread-field`). + +A path the line fixes only in part is read by where its fixed segments stand, +since a variable can write any number of segments: those before the first +variable must be able to begin `repos///actions/runs`, and those +after the last must be able to end `runs//cancel`. A route word between two +variables rules nothing out, as an owner or repository can be named like one: +`"repos/acme/pages/$P/cancel"` and `"repos/$REPO/pulls/$N/cancel"` are refused, +while `"repos/owner/repo/pulls/$N/cancel"` and `"repos/$R/pulls/1/cancel"` pass. +A field beside a method the line writes (`-X GET`, `-XPATCH`) is sent with that +method and passes; a written `POST` is refused as above. A field keyed `query` +is read as a GraphQL query and left to the merge rules, so one sent with no +method to a path the line does not end is not read as a cancel +(dcn-2612030017439523 records why). + +Reading a run, rerunning one and listing a workflow's runs pass. The refusal +names no measured times, since abcd keeps none: it says how to measure the job +(its elapsed time from `gh run view --json jobs`, the same job's median and +maximum over the workflow's recent successful runs, and the `timeout-minutes` +in the workflow, which ends it anyway) and leaves the cancel to the person, told +those numbers. It is not allowable once. dcn-2612022305576019 records why. + ## Registry and overrides The bundled hazards ship inside the binary. A repo overrides them in one file in diff --git a/commands/mode.md b/commands/mode.md index 41926b7600..200ea32fc3 100644 --- a/commands/mode.md +++ b/commands/mode.md @@ -201,6 +201,13 @@ citing that decision, queues one only the person may answer with `abcd mode queue`, and takes the next ready item meanwhile rather than waiting for their return. +**A declined tool call stays declined.** While work is owed, a call the +person or a hook declined stays declined until the person says otherwise: never +reach the same act by another route, and take other owed work meanwhile, +passing over any item that needs it, the next item the note names included. The +away block says so, and so does the stop check's note each time it holds a +turn's end for owed work. + **The host's approval prompt never waits while away.** While the away mode holds, the plugin's `PermissionRequest` hook refuses the host's approval prompt for a shell command at once, in every session of the repository, the one the diff --git a/internal/core/ahoy/detect.go b/internal/core/ahoy/detect.go index 135832b43f..203a62e401 100644 --- a/internal/core/ahoy/detect.go +++ b/internal/core/ahoy/detect.go @@ -144,6 +144,12 @@ func detect(cwd string, judgeTools bool) (DetectionResult, error) { gaps = append(gaps, detectGitIdentity(abs)...) gaps = append(gaps, detectHistoryStore(identity.RootSHA)...) gaps = append(gaps, detectStoreWorktrees()...) + // A main checkout of abcd's own source left behind origin's default + // branch (iss-2612022220481334): read only on a person's pass, so a + // hook spends no git on it. + if judgeTools { + gaps = append(gaps, detectMainCheckoutBehind(abs)...) + } gaps = append(gaps, detectConfigIntegrity(abs)...) gaps = append(gaps, detectConfigValues(abs)...) gaps = append(gaps, detectMarkerDrift(abs)...) diff --git a/internal/core/ahoy/install_template_test.go b/internal/core/ahoy/install_template_test.go index 36ef325d03..ddaca8475b 100644 --- a/internal/core/ahoy/install_template_test.go +++ b/internal/core/ahoy/install_template_test.go @@ -421,7 +421,7 @@ func installSeams() map[string]string { "osExecutable": osExecutable, "afterHistoryReloadHook": afterHistoryReloadHook, "beforeHistoryIndexCreateHook": beforeHistoryIndexCreateHook, "currentVintage": currentVintage, "waitingRange": waitingRange, "waitingDefaultChanges": waitingDefaultChanges, - "runningBuild": runningBuild, + "runningBuild": runningBuild, "behindClock": behindClock, } seams := map[string]string{ "claudeCodeAgentsFloor": fmt.Sprint(claudeCodeAgentsFloor), diff --git a/internal/core/ahoy/main_checkout_behind.go b/internal/core/ahoy/main_checkout_behind.go new file mode 100644 index 0000000000..5e7610df81 --- /dev/null +++ b/internal/core/ahoy/main_checkout_behind.go @@ -0,0 +1,107 @@ +package ahoy + +import ( + "context" + "fmt" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/abcdrepo" + "github.com/intentdriven/abcd/internal/gitutil" +) + +// MainCheckoutBehindGapID names a source checkout of abcd whose main working +// tree is more than a day behind origin's default branch as last fetched +// (iss-2612022220481334). scripts/abcd.sh builds the tree it lives in, so +// every verb run through the main checkout's script is an abcd that old. The +// script says so on stderr each time it runs; this gap says it where a person +// reviews the repository's state, from the main checkout or any worktree of +// it. Report-only: bringing the checkout up to date moves a working tree peers +// may be standing in, so abcd never does it. +const MainCheckoutBehindGapID = "source.main_checkout_behind" + +// mainCheckoutBehindAfter is how long the default branch may have held +// changes the main checkout lacks before the gap is raised: the script's own +// bound. +const mainCheckoutBehindAfter = 24 * time.Hour + +// maxBehindLog caps the first-parent log the gap reads: one Unix time a line, +// so tens of thousands of changes. A longer answer is refused, not cut. +const maxBehindLog = 1 << 20 + +// behindReadTimeout bounds the gap's four local git reads together: a git +// that hangs costs the pass this long, and the gap is then not raised. +const behindReadTimeout = 5 * time.Second + +// behindClock is the seam onto now; a test moves it. +var behindClock = time.Now + +// detectMainCheckoutBehind raises the gap for the repository cwd stands in +// when its main working tree is a source checkout of abcd (it holds +// cmd/abcd/main.go) and its HEAD lacks changes that landed on origin's +// default branch, as last fetched, the oldest of them more than a day ago. A +// change is a commit on the branch's first-parent line, so the age is when the +// branch first moved past the checkout, not when a merged branch's own +// commits were made. It reads only: no fetch, and nothing where git cannot +// say (no origin, a bare repository, a log past its cap, a read past its +// deadline). +func detectMainCheckoutBehind(cwd string) []Gap { + ctx, cancel := context.WithTimeout(context.Background(), behindReadTimeout) + defer cancel() + top, err := gitutil.ToplevelContext(ctx, cwd) + if err != nil || top == "" { + return nil + } + common, err := gitutil.CommonDirContext(ctx, top) + if err != nil || filepath.Base(common) != ".git" { + return nil + } + main := filepath.Dir(common) + if !abcdrepo.LooksLikeSourceTree(main) { + return nil + } + def := gitutil.TrackedDefaultBranchContext(ctx, main, "origin") + if def == "" { + return nil + } + out, err := gitutil.RunCappedContext(ctx, main, maxBehindLog, "log", "--first-parent", "--format=%ct", "^HEAD", def, "--") + if err != nil || out == "" { + return nil + } + n, oldest := 0, int64(0) + for _, line := range strings.Split(out, "\n") { + ct, err := strconv.ParseInt(strings.TrimSpace(line), 10, 64) + if err != nil { + continue + } + n++ + if oldest == 0 || ct < oldest { + oldest = ct + } + } + if n == 0 { + return nil + } + age := behindClock().Sub(time.Unix(oldest, 0)) + if age <= mainCheckoutBehindAfter { + return nil + } + shown := displayPath(main) + return []Gap{{ + ID: MainCheckoutBehindGapID, Category: UserState, Scope: "repo", + Title: "main checkout behind origin's default branch", + Detail: fmt.Sprintf("%s is %s behind %s as last fetched (%s landed there that it lacks), so scripts/abcd.sh run there builds an abcd that old.", + shown, plural(int(age/(24*time.Hour)), "day", "days"), gitutil.ShortRef(def), plural(n, "change", "changes")), + FixHint: "Run scripts/abcd.sh from an up-to-date worktree (`scripts/abcd.sh ahoy worktree add ` cuts one from origin's default branch), or bring " + shown + " up to date once no session works in it; abcd only reports it.", + }} +} + +// plural is n with its noun, one or many. +func plural(n int, one, many string) string { + if n == 1 { + return "1 " + one + } + return strconv.Itoa(n) + " " + many +} diff --git a/internal/core/ahoy/main_checkout_behind_test.go b/internal/core/ahoy/main_checkout_behind_test.go new file mode 100644 index 0000000000..8769133e46 --- /dev/null +++ b/internal/core/ahoy/main_checkout_behind_test.go @@ -0,0 +1,121 @@ +package ahoy + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "github.com/intentdriven/abcd/internal/gittest" +) + +// behindSource is a source checkout of abcd (cmd/abcd/main.go committed) on +// main, with origin's default branch as last fetched two changes ahead of its +// HEAD, and a linked worktree at origin's tip. It returns the checkout, the +// worktree, and the time the changes landed. +func behindSource(t *testing.T) (*gittest.Repo, string, time.Time) { + t.Helper() + r := gittest.NewRepo(t) + r.Write("cmd/abcd/main.go", "package main\n") + r.Commit("base") + base := r.Git("rev-parse", "HEAD") + r.Git("commit", "--quiet", "--allow-empty", "-m", "landed first") + r.Git("commit", "--quiet", "--allow-empty", "-m", "landed since") + tip := r.Git("rev-parse", "HEAD") + landed := time.Now() + r.Git("remote", "add", "origin", "https://example.invalid/abcd.git") + r.Git("update-ref", "refs/remotes/origin/main", tip) + r.Git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + r.Git("reset", "--quiet", "--hard", base) + wt := filepath.Join(t.TempDir(), "fresh") + r.Git("worktree", "add", "--quiet", "--detach", wt, tip) + return r, wt, landed +} + +// atClock sets the gap's clock to at for the test. +func atClock(t *testing.T, at time.Time) { + t.Helper() + prev := behindClock + behindClock = func() time.Time { return at } + t.Cleanup(func() { behindClock = prev }) +} + +// iss-2612022220481334: a source checkout's main working tree more than a day +// behind origin's default branch, as last fetched, is a report-only gap, named +// from the checkout itself and from any of its worktrees, however current that +// worktree is. +func TestAStaleMainCheckoutIsAGap(t *testing.T) { + r, wt, landed := behindSource(t) + atClock(t, landed.Add(5*24*time.Hour+time.Hour)) + // git names the checkout by its real path. + real, err := filepath.EvalSymlinks(r.Root()) + if err != nil { + t.Fatal(err) + } + for _, from := range []string{r.Root(), wt} { + gaps := detectMainCheckoutBehind(from) + if len(gaps) != 1 { + t.Fatalf("from %s: want one gap, got %+v", from, gaps) + } + g := gaps[0] + if g.ID != MainCheckoutBehindGapID || g.Category != UserState || g.Resolvable || g.Required || g.Scope != "repo" { + t.Errorf("from %s: want a report-only %s gap, got %+v", from, MainCheckoutBehindGapID, g) + } + for _, want := range []string{displayPath(real) + " is 5 days behind origin/main as last fetched", "2 changes landed there that it lacks", "scripts/abcd.sh"} { + if !strings.Contains(g.Detail, want) { + t.Errorf("from %s: the detail lacks %q: %s", from, want, g.Detail) + } + } + if !strings.Contains(g.FixHint, "scripts/abcd.sh ahoy worktree add") || !strings.Contains(g.FixHint, "abcd only reports it") { + t.Errorf("from %s: the fix hint: %s", from, g.FixHint) + } + } +} + +// Changes that landed within the day, a checkout that is not abcd's source, and +// a repository with no origin are no gap. +func TestAMainCheckoutWithinTheDayIsNoGap(t *testing.T) { + r, _, landed := behindSource(t) + atClock(t, landed.Add(20*time.Hour)) + if gaps := detectMainCheckoutBehind(r.Root()); len(gaps) != 0 { + t.Errorf("changes landed within the day: %+v", gaps) + } + atClock(t, landed.Add(5*24*time.Hour)) + r.Git("remote", "remove", "origin") + if gaps := detectMainCheckoutBehind(r.Root()); len(gaps) != 0 { + t.Errorf("no origin: %+v", gaps) + } + + other := gittest.NewRepo(t) + other.Write("README.md", "not abcd\n") + other.Commit("base") + base := other.Git("rev-parse", "HEAD") + other.Git("commit", "--quiet", "--allow-empty", "-m", "landed") + other.Git("update-ref", "refs/remotes/origin/main", "HEAD") + other.Git("remote", "add", "origin", "https://example.invalid/other.git") + other.Git("reset", "--quiet", "--hard", base) + if gaps := detectMainCheckoutBehind(other.Root()); len(gaps) != 0 { + t.Errorf("a checkout that is not abcd's source: %+v", gaps) + } +} + +// The gap is read only by the passes a person starts (bare ahoy, install, +// doctor), never by the pass the hooks run. +func TestAStaleMainCheckoutIsReadOnlyOnAPersonsPass(t *testing.T) { + r, _, landed := behindSource(t) + atClock(t, landed.Add(3*24*time.Hour)) + hook, err := detect(r.Root(), false) + if err != nil { + t.Fatal(err) + } + if hasGapID(hook.Gaps, MainCheckoutBehindGapID) { + t.Errorf("the hooks' pass read the main checkout's age") + } + person, err := detect(r.Root(), true) + if err != nil { + t.Fatal(err) + } + if !hasGapID(person.Gaps, MainCheckoutBehindGapID) { + t.Errorf("a person's pass does not list the stale main checkout: %+v", person.Gaps) + } +} diff --git a/internal/core/autonomy/judge.go b/internal/core/autonomy/judge.go index b417a0b99c..b3182a7016 100644 --- a/internal/core/autonomy/judge.go +++ b/internal/core/autonomy/judge.go @@ -274,7 +274,9 @@ func holdStop(v Verdict, next SessionState, in StopInput, owed Owed, restart, wa limit = DefaultBlockCap } if next.Blocks > limit { - row, body := v.Row, strings.TrimPrefix(v.Reason, "abcd: ") + // The person's line keeps the owed reason, less the line addressed to + // the agent alone. + row, body := v.Row, strings.Replace(strings.TrimPrefix(v.Reason, "abcd: "), " "+DeclinedCallLine(), "", 1) if row == 1 && owed.Empty() && wake { // Nothing owed and a qualifying wake: the question is let go // as row 6 lets a stop go, waiting on that look, with nothing @@ -350,6 +352,17 @@ func questionReason() string { return "abcd: your last message ends on a question, and the person is away, so no one will answer it. Do not ask it.\n" + QuestionRoute() } +// DeclinedCallLine is the one line the stop's owed-work note and the away +// block both carry (iss-2612022221066637): a tool call the person or a hook +// declined stays declined until the person says otherwise, and is not to be +// reached by another route, but it never stops the rest of the work, so a +// session told work is owed takes other work rather than holding every lane. +// The judge does not know which item a declined call served, so the line +// never sends the session to the next item it names, which may be that one. +func DeclinedCallLine() string { + return "A declined tool call stays declined until the person says otherwise: do not reach that act another way; take other owed work, passing over any item that needs it." +} + func owedReason(rec *Record, owed Owed, tail string) string { item, _ := owed.Next() var b strings.Builder @@ -363,6 +376,7 @@ func owedReason(rec *Record, owed Owed, tail string) string { if tail != "" { b.WriteString(" " + tail) } + b.WriteString(" " + DeclinedCallLine()) for _, n := range owed.Notes { b.WriteString(" " + termsafe.CleanProseLine(n, maxReasonNote)) } diff --git a/internal/core/autonomy/judge_test.go b/internal/core/autonomy/judge_test.go index d150d2e439..4dd0b1ca29 100644 --- a/internal/core/autonomy/judge_test.go +++ b/internal/core/autonomy/judge_test.go @@ -640,6 +640,62 @@ func TestReasonSaysItOnce(t *testing.T) { } } +// TestOwedNoteSaysADeclinedCallDeclinesOnlyThatCall (iss-2612022221066637): +// every hold that names owed work tells the agent that a declined tool call +// stays declined until the person says otherwise, is not reached another way, +// and that other owed work goes on, beside the next item it names; the +// person's line on a stop the cap let go does not carry it, and a hold with +// nothing owed says nothing of it. +func TestOwedNoteSaysADeclinedCallDeclinesOnlyThatCall(t *testing.T) { + now := at(t, "2026-10-18 21:00") + rec := awayRec(now, false) + owed := owedOf(behindPR) + seen := SessionState{Fingerprint: owed.Fingerprint(), WakeFingerprint: owed.CappedFingerprint()} + wake := crons("*/10 * * * *") + // The line never sends the session back to the next item, which may be + // the one whose act was declined: the act stays declined, and the work + // goes on elsewhere. + const want = "A declined tool call stays declined until the person says otherwise: do not reach that act another way; take other owed work, passing over any item that needs it." + for _, c := range []struct { + name string + in StopInput + st SessionState + row int + }{ + {"2 first block", StopInput{}, SessionState{}, 2}, + {"4 two wakes", StopInput{SessionCrons: wake}, withWakes(seen, 2), 4}, + {"5 no wake", StopInput{}, seen, 5}, + } { + v := judgeAt(t, rec, owed, c.in, c.st, now) + if v.Row != c.row || !v.Block { + t.Fatalf("%s: row %d block %v, want row %d held", c.name, v.Row, v.Block, c.row) + } + if !strings.Contains(v.Reason, "Next: pull request #12") || !strings.Contains(v.Reason, want) { + t.Errorf("%s: the owed note does not name the next item and say a declined call stays declined:\n%s", c.name, v.Reason) + } + } + // Inside the conversation window the hold names the window and the owed + // work alike. + talking := SessionState{PersonPromptAt: now.Add(-time.Minute)} + if v := judgeAt(t, rec, owed, StopInput{}, talking, now); !v.Block || !strings.Contains(v.Reason, want) { + t.Errorf("conversing: the hold lacks the declined-call line (block %v):\n%s", v.Block, v.Reason) + } + if got := DeclinedCallLine(); got != want { + t.Errorf("DeclinedCallLine() = %q, want %q", got, want) + } + // Nothing owed: the hold asks for the next ready item and says nothing of + // a declined call. + if v := judgeAt(t, rec, Owed{}, StopInput{}, SessionState{}, now); strings.Contains(v.Reason, "declined") { + t.Errorf("a hold with nothing owed speaks of a declined call:\n%s", v.Reason) + } + // The person's line on a stop the cap let go is for the person: it keeps + // the owed reason and drops the agent's line. + s := newSequence(t, rec, now) + if v := holdToCap(t, s, owed); v.Block || strings.Contains(v.SystemMessage, "declined") || !strings.Contains(v.SystemMessage, "feat/behind") { + t.Errorf("the person's line past the cap (block %v): %q", v.Block, v.SystemMessage) + } +} + // TestSuggestedQueueCommandQuotesBranch: a branch name holding `$(…)`, a // backquote or a single quote, all legal in a refname, reaches the suggested // `abcd mode queue` command as one single-quoted shell word. diff --git a/internal/core/guard/config.go b/internal/core/guard/config.go index 9064882f53..103ef4b849 100644 --- a/internal/core/guard/config.go +++ b/internal/core/guard/config.go @@ -355,6 +355,9 @@ func mergePattern(base, over Pattern) Pattern { if over.FlagValues != nil { r.FlagValues = cloneFlagValues(over.FlagValues) } + if over.AbsentFlags != nil { + r.AbsentFlags = append([]string(nil), over.AbsentFlags...) + } if over.ArgPaths != nil { r.ArgPaths = append([]PathArg(nil), over.ArgPaths...) } diff --git a/internal/core/guard/config_test.go b/internal/core/guard/config_test.go index a0f52d1351..c50b9ad241 100644 --- a/internal/core/guard/config_test.go +++ b/internal/core/guard/config_test.go @@ -220,6 +220,19 @@ func TestLoadRejectsBadConfig(t *testing.T) { body: `{"schema_version":1,"entries":{"git-clean":{"pattern":{"flags":["-f","|"]}}}}`, want: ErrInvalidEntry, }, + { + // An absent-flag group naming no flag stands nothing down, and one + // naming a plain word would stand the entry down on any line that + // holds it. + name: "absent flag group that names no flag", + body: `{"schema_version":1,"entries":{"git-clean":{"pattern":{"absent_flags":["|"]}}}}`, + want: ErrInvalidEntry, + }, + { + name: "absent flag that is not a flag", + body: `{"schema_version":1,"entries":{"git-clean":{"pattern":{"absent_flags":["-n|clean"]}}}}`, + want: ErrInvalidEntry, + }, { // The command is compared against a token's basename, so a path or a // phrase could never be satisfied — the same silent defang as an diff --git a/internal/core/guard/defaults/guard.json b/internal/core/guard/defaults/guard.json index fcb5ff9b4f..4fdd4741b8 100644 --- a/internal/core/guard/defaults/guard.json +++ b/internal/core/guard/defaults/guard.json @@ -833,6 +833,118 @@ ] } }, + "gh-run-cancel": { + "tier": "blocker", + "pattern": { + "command": "gh", + "subcommand": "run", + "subcommand2": "cancel", + "value_flags": ["-R", "--repo"] + }, + "why": "Cancelling a workflow run throws away every job still running in it: a cancelled job reruns from its start, so a release cut loses its whole round, and a job that looks stuck is usually inside its measured time. The guard reads no network, and no line says whose run it is or how long its jobs have run, so every cancel is refused.", + "successor": "Measure the job first: its elapsed time (`gh run view --json jobs`), the same job's median and maximum over its workflow's recent successful runs, and its `timeout-minutes`, which ends it anyway. Then give the person those numbers and leave the cancel to them (`gh run cancel `).", + "fixtures": { + "known_bad": [ + "gh run cancel 12345", + "gh run cancel 12345 -R owner/repo", + "gh run cancel --repo owner/repo 12345", + "gh run cancel \"$RUN_ID\"", + "gh run cancel", + "cd repo && gh run cancel 12345" + ], + "known_good": [ + "gh run view 12345", + "gh run view 12345 --json jobs", + "gh run list --workflow release.yml --status success", + "gh run watch 12345", + "gh run rerun 12345 --failed", + "abcd capture \"an agent ran gh run cancel 12345 at 94 minutes\"" + ] + } + }, + "gh-api-run-cancel": { + "tier": "blocker", + "pattern": { + "command": "gh", + "subcommand": "api", + "value_flags": ["-X", "--method", "-f", "--field", "-F", "--raw-field", "-H", "--header", "-q", "--jq", "-t", "--template", "--cache", "--hostname", "--input", "-p", "--preview"], + "arg_shapes": ["forge-run-cancel-path"] + }, + "why": "A call to `actions/runs//cancel` or `/force-cancel`, or to a path a variable can still make one, is `gh run cancel` as a raw API call: every running job reruns from its start. The guard reads no network, and no line says whose run it is or how long its jobs have run, so every such call is refused, whatever its method.", + "successor": "Measure the job first: its elapsed time (`gh run view --json jobs`), the same job's median and maximum over its workflow's recent successful runs, and its `timeout-minutes`, which ends it anyway. Then give the person those numbers and leave the cancel to them (`gh run cancel `).", + "fixtures": { + "known_bad": [ + "gh api -X POST repos/owner/repo/actions/runs/12345/cancel", + "gh api --method POST repos/{owner}/{repo}/actions/runs/12345/force-cancel", + "gh api -X POST /repos/owner/repo/actions/runs/12345/cancel", + "gh api -X POST https://api.github.com/repos/owner/repo/actions/runs/12345/cancel", + "gh api -X POST \"repos/$REPO/actions/runs/$ID/cancel\"", + "gh api -X POST \"$RUN_URL/cancel\"", + "gh api -X POST \"repos/acme/pages/$P/cancel\"", + "gh api repos/owner/repo/actions/runs/12345/cancel -f reason=stuck" + ], + "known_good": [ + "gh api repos/owner/repo/actions/runs/12345", + "gh api repos/owner/repo/actions/runs/12345/jobs", + "gh api \"repos/$REPO/actions/runs/$ID/jobs\"", + "gh api -X POST repos/owner/repo/actions/runs/12345/rerun", + "gh api -X POST \"repos/owner/repo/pulls/$N/cancel\"", + "gh api -X POST \"repos/$R/pulls/1/cancel\"", + "abcd capture \"an agent ran gh api -X POST repos/o/r/actions/runs/1/cancel\"" + ] + } + }, + "gh-api-run-cancel-unread": { + "tier": "blocker", + "pattern": { + "command": "gh", + "subcommand": "api", + "value_flags": ["-X", "--method", "-f", "--field", "-F", "--raw-field", "-H", "--header", "-q", "--jq", "-t", "--template", "--cache", "--hostname", "--input", "-p", "--preview"], + "flag_values": [{"flag": "-X|--method", "values": ["POST"]}], + "arg_shapes": ["forge-run-cancel-open-path"] + }, + "why": "A `POST`, or a method the line does not fix, to a forge path whose end the line does not fix can be a call to `actions/runs//cancel`: `gh run cancel` spelled so that no check made before it runs can read it. A cancelled job reruns from its start.", + "successor": "Spell the path out, so the guard can read it. To cancel a run, measure the job first: its elapsed time (`gh run view --json jobs`), the same job's median and maximum over recent successful runs, and its `timeout-minutes`; then give the person those numbers and leave the cancel to them.", + "fixtures": { + "known_bad": [ + "gh api -X POST \"$ENDPOINT\"", + "gh api --method POST \"repos/$REPO/actions/runs/$ID\"", + "gh api -X \"$METHOD\" \"repos/$REPO/actions/runs/$TAIL\"" + ], + "known_good": [ + "gh api \"$ENDPOINT\"", + "gh api \"repos/$REPO/actions/runs/$ID\"", + "gh api -X POST \"repos/owner/repo/pulls/$N\"", + "gh api -X POST repos/owner/repo/actions/runs/12345/rerun" + ] + } + }, + "gh-api-run-cancel-unread-field": { + "tier": "blocker", + "pattern": { + "command": "gh", + "subcommand": "api", + "value_flags": ["-X", "--method", "-f", "--field", "-F", "--raw-field", "-H", "--header", "-q", "--jq", "-t", "--template", "--cache", "--hostname", "--input", "-p", "--preview"], + "flag_values": [{"flag": "-f|--field|-F|--raw-field|--input", "shape": "rest-body-field"}], + "absent_flags": ["-X|--method"], + "arg_shapes": ["forge-run-cancel-open-path"] + }, + "why": "A `gh api` call writing no method, with `--input` or a field other than a GraphQL `query`, is a `POST`; to a forge path whose end the line does not fix it can be a call to `actions/runs//cancel`: `gh run cancel` spelled so that no check made before it runs can read it.", + "successor": "Spell the path out, so the guard can read it. To cancel a run, measure the job first: its elapsed time (`gh run view --json jobs`), the same job's median and maximum over recent successful runs, and its `timeout-minutes`; then give the person those numbers and leave the cancel to them.", + "fixtures": { + "known_bad": [ + "gh api \"$ENDPOINT\" -f reason=stuck", + "gh api \"repos/$REPO/actions/runs/$ID\" --input body.json" + ], + "known_good": [ + "gh api \"$ENDPOINT\"", + "gh api \"repos/$REPO/labels\" -f name=bug", + "gh api graphql -f query=@q.graphql", + "gh api -X GET \"repos/$R/actions/runs/$ID\" -f x=1", + "gh api -XPATCH \"repos/$R/actions/runs/$ID\" -f x=1" + ] + } + }, "git-reset-hard": { "tier": "warn", "pattern": { diff --git a/internal/core/guard/guard.go b/internal/core/guard/guard.go index 73650ebc0f..4dc6141d74 100644 --- a/internal/core/guard/guard.go +++ b/internal/core/guard/guard.go @@ -77,6 +77,14 @@ type Pattern struct { // included. A line with a word a substitution helps to write among its // arguments, or with `--no-` among them, is not stood down (standsDown). NotFlags []string `json:"not_flags,omitempty"` + // AbsentFlags hold the entry to lines that write none of the listed flags: + // each element is an alternation group as Flags are, and a typed argument + // the line fixes that is one of its alternatives (`-X`, `-XGET`, + // `--method=PUT`) stands the entry down. `gh api` with a field sends a + // POST only where no method is written. Unlike NotFlags, a word a + // substitution writes elsewhere on the line does not keep the entry + // standing, and a flag a substitution may write does not stand it down. + AbsentFlags []string `json:"absent_flags,omitempty"` // FlagValues constrain what a flag is SET TO, not merely that it is present. // `gh api -X DELETE repos/owner/repo` deletes the repository and // `gh api -X GET repos/owner/repo` reads it, so an entry that could only ask @@ -135,6 +143,13 @@ type Pattern struct { // // ShapeReleaseTag is a release tag, or a word that can still be one // (releaseTagCouldBe), standing as the first operand after the subcommand. + // + // ShapeForgeRunCancelPath is a forge API path that cancels a workflow run + // (`…/actions/runs//cancel` or `…/force-cancel`), or a word a + // substitution helps to write that can still be one, its last segment + // fixed (forgeRunCancelPathCouldBe). ShapeForgeRunCancelOpenPath is one + // whose last segment the line does not fix + // (forgeRunCancelOpenPathCouldBe). ArgShapes []string `json:"arg_shapes,omitempty"` // MinOperands, when set, requires at least that many non-flag arguments // (value_flags stepped over). It is what separates a kill BY PATTERN — @@ -501,6 +516,18 @@ func validatePattern(id string, p Pattern) error { return fmt.Errorf("%w: entry %s flag-value constraint %d accepts no value and could never match", ErrInvalidEntry, id, i) } } + for i, group := range p.AbsentFlags { + if !hasAlternative(group) { + return fmt.Errorf("%w: entry %s absent_flags group %d names no flag and could never stand the entry down", ErrInvalidEntry, id, i) + } + // An alternative that is not a flag would let a plain word stand the + // entry down, the silent defang an empty flag group is. + for _, alt := range strings.Split(group, "|") { + if alt != "" && (!strings.HasPrefix(alt, "-") || alt == "-" || alt == "--") { + return fmt.Errorf("%w: entry %s absent_flags group %d holds %q, which is not a flag, so a plain word would stand the entry down", ErrInvalidEntry, id, i, alt) + } + } + } for i, group := range p.NotFlags { if !hasAlternative(group) { return fmt.Errorf("%w: entry %s not_flags group %d names no flag and could never stand the entry down", ErrInvalidEntry, id, i) @@ -1224,6 +1251,7 @@ func clonePattern(p Pattern) Pattern { out.ArgShapes = append([]string(nil), p.ArgShapes...) out.ArgPaths = append([]PathArg(nil), p.ArgPaths...) out.FlagValues = cloneFlagValues(p.FlagValues) + out.AbsentFlags = append([]string(nil), p.AbsentFlags...) out.ArgsFrom = clonePatterns(p.ArgsFrom) out.Env = append([]string(nil), p.Env...) if p.ArgPrefixesLiteral != nil { diff --git a/internal/core/guard/match.go b/internal/core/guard/match.go index 36c8ee5617..4e064d19b1 100644 --- a/internal/core/guard/match.go +++ b/internal/core/guard/match.go @@ -2512,6 +2512,9 @@ type entryMatcher struct { // tokens, valueFlags, notAlts and opts are what standsDown reads; notAlts is // empty for an entry that declares no not_flags. tokens, valueFlags, notAlts, opts []string + // absentAlts are the entry's absent_flags alternatives: one written as + // text the line fixes, before the stop, stands the entry down. + absentAlts []string // nextSig[i] is the first index at or after i holding a word the command // reads as its signal (signalWordCommands), or len(tokens); nil for a // command that reads none. @@ -2565,6 +2568,9 @@ func newEntryMatcher(p Pattern, tokens []string, spelled map[int][]string, varLe m.notAlts = append(m.notAlts, strings.Split(group, "|")...) } m.tokens, m.valueFlags, m.opts = tokens, p.ValueFlags, opts + for _, group := range p.AbsentFlags { + m.absentAlts = append(m.absentAlts, strings.Split(group, "|")...) + } if signalWordCommands[strings.ToLower(p.Command)] && len(p.Flags) > 0 { m.nextSig = next(func(i int) bool { return isSignalWord(tokens[i]) }) } @@ -2587,6 +2593,9 @@ func (m entryMatcher) matchesAfter(site int) bool { if len(m.notAlts) > 0 && m.standsDown(start, stop) { return false } + if len(m.absentAlts) > 0 && m.writesAbsent(start, stop) { + return false + } for c, nh := range m.nextHit { h := nh[start] // The command's first signal word is its signal, never a flag. @@ -3178,8 +3187,13 @@ func flagValueHit(fv FlagValue, tokens []string, i int, glob func(int) bool) boo if arg == "--" { return false } + var cur string // the alternative being read accepts := func(got string, glob bool) bool { switch { + case fv.Shape == ShapeRESTBodyField && cur == "--input": + // `--input` names the body's file, a REST body whatever the + // file is called. + return true case fv.Shape != "": return flagValueShapeHolds(fv.Shape, got, glob) } @@ -3189,6 +3203,7 @@ func flagValueHit(fv FlagValue, tokens []string, i int, glob func(int) bool) boo if alt == "" { continue } + cur = alt // An unknown word is read as unknown.go says: by its known text, // and, written with a dash, as any flag it can still become — // which, with its value attached, is a setting the constraint @@ -3197,7 +3212,7 @@ func flagValueHit(fv FlagValue, tokens []string, i int, glob func(int) bool) boo // A shape is about the setting's text, and an unknown dash-word is // on every line that has one, so the setting is still read. A field's // setting can be attached to the dash-word itself, whatever it holds. - if fv.Shape == "" || fv.Shape == ShapeRefForceField { + if fv.Shape == "" || fv.Shape == ShapeRefForceField || fv.Shape == ShapeRESTBodyField { return true } if accepts(arg, false) || (i+1 < len(tokens) && accepts(tokens[i+1], glob(i+1))) { @@ -3270,6 +3285,49 @@ func acceptsValue(values []string, got string, glob bool) bool { return false } +// writesAbsent reports whether the line, before the stop, writes one of the +// entry's absent_flags as text it fixes. A word a substitution helps to write +// writes none. A value flag the line fixes takes the next word, which is never +// read as a flag (`-H -X`). The walk ends, writing nothing, at a word a +// substitution helps to write that can take a value (`-$F`, `--header"$E"`): +// whether it takes the next word is not known, so no later word can be placed +// as a flag or a value, and the entry stays in force. +func (m entryMatcher) writesAbsent(start, stop int) bool { + for i := start; i < stop; i++ { + tok := m.tokens[i] + takes := readWord(tok, m.valueFlags).takes + if unfixed(tok) { + if takes { + return false + } + continue + } + if flagWritten(m.absentAlts, tok) { + return true + } + if takes { + i++ + } + } + return false +} + +// flagWritten reports whether tok is one of the alternatives: the flag alone +// (`-X`), or with its value attached (`-XGET`, `--method=PUT`). +// writesAbsent hands it only words the line fixes. +func flagWritten(alts []string, tok string) bool { + for _, alt := range alts { + switch { + case alt == "": + case tok == alt, strings.HasPrefix(tok, alt+"="): + return true + case isShortFlag(alt) && strings.HasPrefix(tok, alt): + return true + } + } + return false +} + // isShortFlag reports whether an alternative is a single-letter short flag // (`-X`), the only shape that can carry an attached value. func isShortFlag(alt string) bool { diff --git a/internal/core/guard/runcancel_test.go b/internal/core/guard/runcancel_test.go new file mode 100644 index 0000000000..d1047652db --- /dev/null +++ b/internal/core/guard/runcancel_test.go @@ -0,0 +1,120 @@ +package guard + +import ( + "slices" + "strings" + "testing" +) + +// iss-2612022221042267: an agent cancelled a release run's job inside its +// measured duration. The guard reads no network and no line says whose run it +// is or how long its jobs have run, so every cancel of a workflow run is +// refused, the CLI's and the API's, and the refusal says how to measure the +// job and that the cancel is the person's. +func TestARunCancelIsRefused(t *testing.T) { + r := Defaults() + for _, tc := range []struct{ line, id string }{ + {`gh run cancel 12345`, "gh-run-cancel"}, + {`gh -R owner/repo run cancel 12345`, "gh-run-cancel"}, + {`gh run cancel "$RUN_ID" --repo owner/repo`, "gh-run-cancel"}, + {`env -S 'gh run cancel 12345'`, "gh-run-cancel"}, + {`gh api -X POST repos/owner/repo/actions/runs/12345/cancel`, "gh-api-run-cancel"}, + {`gh api --method=POST repos/{owner}/{repo}/actions/runs/12345/force-cancel`, "gh-api-run-cancel"}, + {`gh api -XPOST https://api.github.com/repos/owner/repo/actions/runs/12345/cancel`, "gh-api-run-cancel"}, + {`gh api -X POST "repos/$REPO/actions/runs/$ID/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "$RUN_URL/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "$ENDPOINT"`, "gh-api-run-cancel-unread"}, + {`gh api -X "$M" "repos/$REPO/actions/runs/$ID"`, "gh-api-run-cancel-unread"}, + // A field makes gh send a POST, so a path the line does not end is a + // cancel it may be. + {`gh api $(echo repos/owner/repo/actions/runs/12345/cancel) -f reason=stuck`, "gh-api-run-cancel-unread-field"}, + {`gh api "repos/$REPO/actions/runs/$ID" --input body.json`, "gh-api-run-cancel-unread-field"}, + // An owner or repository the line does not fix, beside one named like + // a route, is still a repository's runs. + {`gh api repos/$O/pages/actions/runs/1/cancel -X POST`, "gh-api-run-cancel"}, + {`gh api -X POST "repos/issues/$R/actions/runs/1/force-cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "repos/$O/releases/actions/runs/$ID"`, "gh-api-run-cancel-unread"}, + // An owner or repository named like a route, fixed, with actions/runs + // inside a variable after it; and a repository a variable may name + // "pulls". + {`gh api -X POST "repos/acme/pages/$P/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "api/$REST/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "repositories/7/$P/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "repos/$REPO/pulls/$N/cancel"`, "gh-api-run-cancel"}, + {`gh api -X POST "repos/$O/$R/pulls/$N"`, "gh-api-run-cancel-unread"}, + // A field with no method written is a POST, whatever its key unless it + // is a GraphQL query; a method a substitution may write is not one. + {`gh api "repos/$R/actions/runs/$ID" -f x=1`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" -f -X`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" -f "$K=1"`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" -F query=@q.graphql -f x=1`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" --input body.json`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" --input query=x`, "gh-api-run-cancel-unread-field"}, + {`gh api "$EP" --input=query=x`, "gh-api-run-cancel-unread-field"}, + // A value flag's value is not a method, though it is spelled as one. + {`gh api --preview -X "$EP" -f x=1`, "gh-api-run-cancel-unread-field"}, + {`gh api -H -X -f x=1 "$EP"`, "gh-api-run-cancel-unread-field"}, + } { + d, err := r.Check(tc.line) + if err != nil { + t.Fatalf("%s: %v", tc.line, err) + } + if d.Verdict != VerdictBlock || !slices.Contains(d.Matches, tc.id) { + t.Errorf("%s: want a block as %s, got %s %v", tc.line, tc.id, d.Verdict, d.Matches) + continue + } + for _, want := range []string{"gh run view --json jobs", "median and maximum", "timeout-minutes", "leave the cancel to them"} { + if !strings.Contains(d.Successor, want) { + t.Errorf("%s: the successor lacks %q: %s", tc.line, want, d.Successor) + } + } + } + // A method a substitution may write, or any word after a flag a + // substitution may write that can take a value, stands the field entry + // down nowhere; such a line also matches entries about other methods, + // whose lesson may lead. + for _, line := range []string{ + `gh api "$EP" -f x=1 -$M GET`, + `gh api "$EP" -f x=1 -X"$M"`, + `gh api "$EP" -f x=1 -$F -X GET`, + `gh api "$EP" -f x=1 --header"$E" -H -X:y`, + } { + d, err := r.Check(line) + if err != nil { + t.Fatalf("%s: %v", line, err) + } + if d.Verdict != VerdictBlock || !slices.Contains(d.Matches, "gh-api-run-cancel-unread-field") { + t.Errorf("%s: want a block among which is gh-api-run-cancel-unread-field, got %s %v", line, d.Verdict, d.Matches) + } + } + for _, line := range []string{ + `gh run view 12345 --json jobs`, + `gh run list --workflow release.yml --status success`, + `gh run rerun 12345 --failed`, + `gh api repos/owner/repo/actions/runs/12345/jobs`, + `gh api "repos/$REPO/actions/runs/$ID"`, + `gh api "$ENDPOINT"`, + `gh api -X POST "repos/owner/repo/pulls/$N/cancel"`, + `gh api -X POST "repos/$R/pulls/1/cancel"`, + `gh api -X POST "api/v2/$P/cancel"`, + `gh api -X POST "repositories/7/pulls/$N/cancel"`, + `gh api -X POST "repos/owner/repo/pulls/$N"`, + `gh api -X POST repos/owner/repo/actions/runs/12345/rerun`, + // A field with a method written sends that method; a written POST is + // the rule above. + `gh api -X GET "repos/$R/actions/runs/$ID" -f x=1`, + `gh api "$URL" -X GET -f x=1`, + `gh api --method=get "repos/$R/actions/runs/$ID" -f x=1`, + `gh api -XPATCH "repos/$R/actions/runs/$ID" -f x=1`, + `gh api --method PATCH "repos/$R/actions/runs/$ID" -f x=1`, + `gh api -X PATCH repos/o/r/pul$N --input body.json`, + } { + d, err := r.Check(line) + if err != nil { + t.Fatalf("%s: %v", line, err) + } + if d.Verdict != VerdictAllow { + t.Errorf("%s: want it allowed, got %s %v", line, d.Verdict, d.Matches) + } + } +} diff --git a/internal/core/guard/teach.go b/internal/core/guard/teach.go index e84f444a5f..bd3f87614c 100644 --- a/internal/core/guard/teach.go +++ b/internal/core/guard/teach.go @@ -294,6 +294,12 @@ func (p Pattern) Describe() string { if shape == ShapeForgeRefPath { with = append(with, "a `…/git/refs/…` path") } + if shape == ShapeForgeRunCancelPath { + with = append(with, "a `…/actions/runs//cancel` path") + } + if shape == ShapeForgeRunCancelOpenPath { + with = append(with, "a path whose end the line does not fix") + } if shape == ShapeReleaseTag { with = append(with, "a release tag as its operand") } @@ -311,6 +317,9 @@ func (p Pattern) Describe() string { for _, group := range p.NotFlags { b.WriteString(", unless it carries " + orList(alternatives(group))) } + for _, group := range p.AbsentFlags { + b.WriteString(", where it writes no " + orList(alternatives(group))) + } if len(p.ArgsFrom) > 0 { var sources []string @@ -381,5 +390,6 @@ var flagValueShapeTaught = map[string]string{ ShapeRefUpdateQuery: "a query naming a ref update", ShapeForceField: "a field setting force", ShapeRefForceField: "a field setting force to anything but false", + ShapeRESTBodyField: "a body that is not a GraphQL query", ShapeSettingsUnchecked: "settings that turn the permission checks off or grant permission rules", } diff --git a/internal/core/guard/unknown.go b/internal/core/guard/unknown.go index 2d38a37c65..e217292d64 100644 --- a/internal/core/guard/unknown.go +++ b/internal/core/guard/unknown.go @@ -1909,7 +1909,9 @@ func operandAcceptance(tokens []string, spelled map[int][]string, varLead map[in for j, shape := range want.shapes { bit := 1 << (len(want.prefixes) + len(want.paths) + nv + j) switch { - case shape == ShapeUnguardedVariablePath && varLead[i], shape == ShapeForgeRefPath && forgeRefPathCouldBe(a): + case shape == ShapeUnguardedVariablePath && varLead[i], shape == ShapeForgeRefPath && forgeRefPathCouldBe(a), + shape == ShapeForgeRunCancelPath && forgeRunCancelPathCouldBe(a), + shape == ShapeForgeRunCancelOpenPath && forgeRunCancelOpenPathCouldBe(a): hits |= bit case shape == ShapeReleaseTag && releaseTagCouldBe(a, glob(i)): tagHit |= bit diff --git a/internal/core/guard/unknownsites_test.go b/internal/core/guard/unknownsites_test.go index 966d7cfe6c..a423ab2c61 100644 --- a/internal/core/guard/unknownsites_test.go +++ b/internal/core/guard/unknownsites_test.go @@ -59,6 +59,8 @@ var wordReaders = map[string]string{ // match.go: the words that stand an entry down. "standsDown": "isUnknown and readWord: a word a substitution helps to write stands nothing down", "notFlagUndone": "exempt: standsDown hands it only typed words", + "writesAbsent": "readWord: a word a substitution helps to write writes no flag, and one that can take a value takes the next word", + "flagWritten": "exempt: writesAbsent hands it only words the line fixes", // branchacts.go: the away mode's created-branch recorder, which records // and refuses nothing. diff --git a/internal/core/guard/varpath.go b/internal/core/guard/varpath.go index 925df8dfa8..25df305e64 100644 --- a/internal/core/guard/varpath.go +++ b/internal/core/guard/varpath.go @@ -3,6 +3,7 @@ package guard import ( "encoding/json" "path" + "regexp" "slices" "strings" "sync" @@ -28,9 +29,11 @@ const ShapeUnguardedVariablePath = "unguarded-variable-path" // argShapes are the shapes arg_shapes may name; Validate refuses any other. var argShapes = map[string]bool{ - ShapeUnguardedVariablePath: true, - ShapeForgeRefPath: true, - ShapeReleaseTag: true, + ShapeUnguardedVariablePath: true, + ShapeForgeRefPath: true, + ShapeReleaseTag: true, + ShapeForgeRunCancelPath: true, + ShapeForgeRunCancelOpenPath: true, } // guardedValues is the texts of the variables' own values, as spellParameter @@ -425,6 +428,122 @@ func forgeRefPathCouldBe(op string) bool { return forgeRefLeadCouldBe(lead) } +// ShapeForgeRunCancelPath names the shape in an entry's arg_shapes for a forge +// API path that cancels a workflow run, its last segment fixed +// (iss-2612022221042267). +const ShapeForgeRunCancelPath = "forge-run-cancel-path" + +// ShapeForgeRunCancelOpenPath names the shape in an entry's arg_shapes for a +// forge API path whose last segment the line does not fix, which can still +// cancel a workflow run. +const ShapeForgeRunCancelOpenPath = "forge-run-cancel-open-path" + +// runCancelRouteRe is the REST route that cancels a run, or force-cancels +// one, as a path the line fixes whole spells it. +var runCancelRouteRe = regexp.MustCompile(`(^|/)actions/runs/[^/]+/(force-)?cancel$`) + +// runCancelSegments are an operand's path segments, a host in front of them or +// not, lower-cased and cleaned as the forge reads them. +func runCancelSegments(op string) (string, []string) { + p := strings.ToLower(pathOf(op)) + p = strings.Trim(path.Clean("/"+strings.ReplaceAll(p, "%2f", "/")), "/") + return p, strings.Split(p, "/") +} + +// runCancelCouldFit reports whether a path partly unfixed can still be a +// run's cancel route, `repos///actions/runs//cancel`, by +// where its fixed segments stand. A substitution may print any number of +// segments, so only two places are known: the segments before the first one +// it writes, counted from the start, and those after the last, counted from +// the end. Each must fit the route there; a route word anywhere else rules +// nothing out, since an owner or repository may be named like one +// (`repos/acme/pages/$P/cancel` can be `…/pages/actions/runs/1/cancel`). +func runCancelCouldFit(segs []string) bool { + first, last := -1, -1 + for i, seg := range segs { + if isUnknown(seg) { + if first < 0 { + first = i + } + last = i + } + } + if first < 0 { + return false + } + // From the end: and the cancel word stand anywhere, runs and actions + // three and four places back. + tail := segs[last+1:] + for k, want := range map[int]string{3: "runs", 4: "actions"} { + if k <= len(tail) && tail[len(tail)-k] != want { + return false + } + } + lead := append(append([]string(nil), segs[:first]...), knownLead(segs[first])) + if len(lead) > 2 && lead[0] == "api" && lead[1] == "v3" { + lead = lead[2:] + } + fits := func(i int, want string) bool { + switch { + case i >= len(lead): + return true + case i == len(lead)-1: + return strings.HasPrefix(want, lead[i]) + } + return lead[i] == want + } + switch { + case len(lead) == 1: + return strings.HasPrefix("repos", lead[0]) || strings.HasPrefix("repositories", lead[0]) || strings.HasPrefix("api", lead[0]) + case lead[0] == "repos": + return fits(3, "actions") && fits(4, "runs") + case lead[0] == "repositories": + return fits(2, "actions") && fits(3, "runs") + case lead[0] == "api": + return fits(1, "v3") + } + return false +} + +// forgeRunCancelPathCouldBe reports whether an operand is a forge API path +// that cancels a workflow run (`…/actions/runs//cancel`, or +// `…/force-cancel`), or, written partly by a substitution, can still be one +// with its last segment fixed as `cancel` or `force-cancel` +// (`"$RUN_URL/cancel"`, `repos/$R/actions/runs/$ID/cancel`). Whatever the +// method: a read of the route cancels nothing, and nothing reads it. +func forgeRunCancelPathCouldBe(op string) bool { + p, segs := runCancelSegments(op) + if !isUnknown(p) { + return runCancelRouteRe.MatchString(p) + } + last := segs[len(segs)-1] + if isUnknown(last) || last != "cancel" && last != "force-cancel" { + return false + } + return runsSpelled(p) || runCancelCouldFit(segs) +} + +// runsSpelled reports whether a path's fixed text holds `actions/runs/`, so +// that it names a repository's runs whatever the line leaves unfixed before +// it: an owner or repository written with a variable may sit beside one +// named like a route (`repos/$O/pages/actions/runs/…`), which the route words +// must not rule out (forgeRefPathCouldBe holds `git/refs` the same way). +func runsSpelled(p string) bool { return strings.Contains(knownText(p), "actions/runs/") } + +// forgeRunCancelOpenPathCouldBe reports whether an operand's last segment is +// text the line does not fix, so that the path can still end in a run's cancel +// route (`"$EP"`, `"repos/$R/actions/runs/$ID"`), unless the segments before +// the first part it leaves unfixed cannot begin one (`repos/o/r/pulls/$N`). +// The entries that name this shape ask for a method that can be POST as +// well, as a read of such a path cancels nothing. +func forgeRunCancelOpenPathCouldBe(op string) bool { + p, segs := runCancelSegments(op) + if !isUnknown(p) || !isUnknown(segs[len(segs)-1]) { + return false + } + return runsSpelled(p) || runCancelCouldFit(segs) +} + // forgeRefWords are the words a path to a ref holds, whichever of them a // substitution leaves fixed. var forgeRefWords = map[string]bool{"git": true, "refs": true, "heads": true, "tags": true} @@ -480,6 +599,10 @@ const ( ShapeRefUpdateQuery = "graphql-ref-update" ShapeForceField = "graphql-force-field" ShapeRefForceField = "rest-ref-force-field" + // ShapeRESTBodyField is a field setting that is not a GraphQL query + // (`query=…`), or any `--input`: a REST call's body, which makes `gh api` + // send a POST where no method is written. + ShapeRESTBodyField = "rest-body-field" ) // ShapeSettingsUnchecked is a claude settings value that turns its permission @@ -498,6 +621,7 @@ var flagValueShapes = map[string]bool{ ShapeForceField: true, ShapeRefForceField: true, ShapeSettingsUnchecked: true, + ShapeRESTBodyField: true, } // flagValueShapeHolds reports whether a setting's fixed text has the shape. The @@ -523,6 +647,9 @@ func flagValueShapeHolds(shape, got string, glob bool) bool { key, value, ok := strings.Cut(text, "=") key = strings.ToLower(key) return ok && (key == "force" || strings.HasSuffix(key, "[force]")) && !gitBoolFalse(value) + case ShapeRESTBodyField: + key, _, _ := strings.Cut(got, "=") + return isUnknown(key) || key != "query" } return false } diff --git a/internal/core/guard/work_test.go b/internal/core/guard/work_test.go index 4f8c48ad1b..396f067618 100644 --- a/internal/core/guard/work_test.go +++ b/internal/core/guard/work_test.go @@ -42,11 +42,13 @@ const linearWorkBar = 6.0 // once the five branch- and worktree-deletion entries of iss-2610241239492159 // took theirs, about 62 once the twenty history-rewrite entries took theirs, and // about 64 once the two entries of the stop took theirs, about 70 once the -// update with a tag took one, and 72.0 once the two entries for setting the -// facilitator's mode took theirs (itd-2611252049031692). The bar sits at 76, -// which keeps those shapes under it with room for a few more entries and stays -// below the hundred a dropped bound costs. -const workPerByteBar = 76.0 +// update with a tag took one, 72.0 once the two entries for setting the +// facilitator's mode took theirs (itd-2611252049031692), and 76.0 once the +// four entries refusing a workflow run's cancel took theirs +// (iss-2612022221042267). The bar sits at 80, which keeps those shapes under +// it with room for a few more entries and stays below the hundred a dropped +// bound costs. +const workPerByteBar = 80.0 // checkWork runs one check over line against the bundled registry and returns // the work the guard counted doing it (tally in work.go): bytes tokenized, bytes diff --git a/internal/core/lint/devbinary_test.go b/internal/core/lint/devbinary_test.go index 4174d38d63..e795ba5f83 100644 --- a/internal/core/lint/devbinary_test.go +++ b/internal/core/lint/devbinary_test.go @@ -2,6 +2,7 @@ package lint_test import ( "bytes" + "fmt" "os" "os/exec" "path/filepath" @@ -10,8 +11,11 @@ import ( "strconv" "strings" "testing" + "time" "github.com/intentdriven/abcd/internal/abcdrepo" + "github.com/intentdriven/abcd/internal/gittest" + "github.com/intentdriven/abcd/internal/shellquote" ) // scripts/abcd.sh, the source checkout's own abcd (iss-2610241240133009), driven @@ -48,6 +52,13 @@ chmod +x "$5" printf 'bin-at-link-end=%s\n' "$(cat "$STUB_BIN" 2>/dev/null)" >> "$STUB_LOG" ` +// devBinaryStubGit stands in front of the real git: it records each call and +// runs the real one, so a test counts the git the script spends. +const devBinaryStubGit = `#!/bin/sh +printf 'git-args=%s\n' "$*" >> "$STUB_LOG" +exec @GIT@ "$@" +` + // devBinaryFake is the binary the stub writes, for a test that lays one down // as an earlier build's. func devBinaryFake(stubGo string) string { @@ -109,6 +120,9 @@ func runDevBinaryAs(t *testing.T, dir, path, root string, env []string, args ... t.Fatal(err) } writeExec(t, filepath.Join(stubBin, "go"), strings.ReplaceAll(devBinaryStubGo, "@MARK@", abcdrepo.CheckoutBuildEnv)) + if real, err := exec.LookPath("git"); err == nil { + writeExec(t, filepath.Join(stubBin, "git"), strings.ReplaceAll(devBinaryStubGit, "@GIT@", shellquote.Single(real))) + } logPath := filepath.Join(t.TempDir(), "calls.log") cmd := exec.Command(path, args...) @@ -390,3 +404,205 @@ func TestTheCheckoutsAbcdBuildsElsewhereWhenTheTierIsReadOnly(t *testing.T) { t.Errorf("the temporary build did not run unmarked with its arguments:\n%s", got.log) } } + +// behindFixture makes the checkout at root a repository on main, HEAD a +// commit ten days old, and lays a second line of history above it: one change +// landedAgo before now and one an hour ago. With origin set, that line is +// origin's default branch as last fetched (refs/remotes/origin/HEAD naming +// refs/remotes/origin/main), with no fetch possible: the remote's URL leads +// nowhere. It returns the git that ran each step, for a test that adds more. +func behindFixture(t *testing.T, root string, landedAgo time.Duration, origin bool) func(args ...string) string { + t.Helper() + env := gittest.Env(t) + now := time.Now() + at := now + git := func(args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", root, "-c", "user.email=fixture@example.invalid", + "-c", "user.name=Fixture", "-c", "commit.gpgsign=false"}, args...)...) + stamp := fmt.Sprintf("@%d +0000", at.Unix()) + cmd.Env = append(append([]string(nil), env...), "GIT_AUTHOR_DATE="+stamp, "GIT_COMMITTER_DATE="+stamp) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + if _, err := exec.LookPath("git"); err != nil { + t.Skip("no git here") + } + git("init", "--quiet", "--initial-branch=main") + git("add", "-A") + at = now.Add(-10 * 24 * time.Hour) + git("commit", "--quiet", "-m", "base") + head := git("rev-parse", "HEAD") + at = now.Add(-landedAgo) + git("commit", "--quiet", "--allow-empty", "-m", "landed first") + at = now.Add(-time.Hour) + git("commit", "--quiet", "--allow-empty", "-m", "landed since") + tip := git("rev-parse", "HEAD") + at = now + if origin { + git("remote", "add", "origin", "https://example.invalid/abcd.git") + git("update-ref", "refs/remotes/origin/main", tip) + git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + } + git("reset", "--quiet", "--hard", head) + return git +} + +// gitCalls lists the git calls a run's log records. +func gitCalls(log string) []string { + var calls []string + for _, line := range strings.Split(log, "\n") { + if c, ok := strings.CutPrefix(line, "git-args="); ok { + calls = append(calls, c) + } + } + return calls +} + +// iss-2612022220481334: the script builds the tree it lives in, so a tree far +// behind origin's default branch runs an abcd that old with nothing saying +// so. One line on stderr says how far behind it is, as last fetched, and where +// to run from instead; the verb still runs, its exit code arrives unchanged, +// and the check spends at most two git calls and never fetches. +func TestTheCheckoutsAbcdSaysWhenItsTreeIsBehind(t *testing.T) { + root := devBinaryCheckout(t) + behindFixture(t, root, 5*24*time.Hour, true) + for _, code := range []int{0, 2, 3} { + got := runDevBinary(t, root, []string{"FAKE_EXIT=" + strconv.Itoa(code)}, "reserve", "iss-1") + if got.code != code { + t.Errorf("the binary exited %d; scripts/abcd.sh exited %d, want the same code\nstderr:\n%s", code, got.code, got.stderr) + } + if !strings.Contains(got.log, "bin-arg=reserve\nbin-arg=iss-1\n") { + t.Errorf("the verb did not run:\n%s", got.log) + } + want := "scripts/abcd.sh: this tree is 5 days behind origin's default branch as last fetched (2 changes landed there that it lacks)" + if !strings.Contains(got.stderr, want) || !strings.Contains(got.stderr, "run scripts/abcd.sh from an up-to-date worktree") { + t.Errorf("stderr does not say how far behind the tree is and where to run from; want %q in:\n%s", want, got.stderr) + } + if n := strings.Count(got.stderr, "\n"); n != 1 { + t.Errorf("want one line on stderr, got %d:\n%s", n, got.stderr) + } + calls := gitCalls(got.log) + if len(calls) == 0 || len(calls) > 2 { + t.Errorf("the check spent %d git calls, want one or two: %q", len(calls), calls) + } + for _, c := range calls { + if strings.HasPrefix(c, "fetch") || strings.HasPrefix(c, "pull") || strings.Contains(c, "remote update") { + t.Errorf("the check asked the remote: git %s", c) + } + } + } +} + +// The line names the branch's own upstream when that is what the tree lacks, +// and it is said from a linked worktree too, whose .git is a file naming its +// admin folder in the repository. +func TestTheCheckoutsAbcdSaysWhenItsUpstreamIsAhead(t *testing.T) { + root := devBinaryCheckout(t) + git := behindFixture(t, root, 3*24*time.Hour, true) + // origin's default branch is where HEAD is; the upstream carries the two + // changes. + tip := git("rev-parse", "refs/remotes/origin/main") + git("update-ref", "refs/remotes/origin/main", "HEAD") + git("update-ref", "refs/remotes/origin/feature", tip) + git("branch", "--quiet", "--set-upstream-to=origin/feature", "main") + got := runDevBinary(t, root, nil, "status") + if want := "this tree is 3 days behind origin/feature as last fetched (2 changes landed there that it lacks)"; !strings.Contains(got.stderr, want) { + t.Errorf("want %q on stderr:\n%s", want, got.stderr) + } + + wt := filepath.Join(t.TempDir(), "wt") + git("worktree", "add", "--quiet", "--detach", wt, "HEAD") + wt, err := filepath.EvalSymlinks(wt) + if err != nil { + t.Fatal(err) + } + git("update-ref", "refs/remotes/origin/main", tip) + got = runDevBinaryAs(t, wt, filepath.Join(wt, "scripts", "abcd.sh"), wt, nil, "status") + if got.code != 0 || !strings.Contains(got.log, "bin-arg=status\n") { + t.Fatalf("from a linked worktree the verb did not run (exit %d):\n%s\nstderr:\n%s", got.code, got.log, got.stderr) + } + if want := "this tree is 3 days behind origin's default branch as last fetched"; !strings.Contains(got.stderr, want) { + t.Errorf("from a linked worktree, want %q on stderr:\n%s", want, got.stderr) + } + if calls := gitCalls(got.log); len(calls) > 2 { + t.Errorf("from a linked worktree the check spent %d git calls: %q", len(calls), calls) + } +} + +// With no origin/HEAD, as in a clone whose remote HEAD was never set, and no +// upstream, as on a branch `ahoy worktree add` cuts, the default branch is +// origin's main, else master, trunk or develop, as ahoy reads it; the refs +// may be packed. The log never verifies a signature, whatever +// log.showSignature says: a verifier per signed commit before every verb. +func TestTheCheckoutsAbcdReadsOriginsBranchWithNoOriginHEAD(t *testing.T) { + root := devBinaryCheckout(t) + git := behindFixture(t, root, 4*24*time.Hour, true) + git("symbolic-ref", "--delete", "refs/remotes/origin/HEAD") + git("config", "log.showSignature", "true") + got := runDevBinary(t, root, nil, "status") + if want := "this tree is 4 days behind origin/main as last fetched (2 changes landed there that it lacks)"; !strings.Contains(got.stderr, want) { + t.Errorf("no origin/HEAD: want %q on stderr:\n%s", want, got.stderr) + } + calls := gitCalls(got.log) + if len(calls) == 0 || len(calls) > 2 { + t.Errorf("no origin/HEAD: the check spent %d git calls, want one or two: %q", len(calls), calls) + } + for _, c := range calls { + if strings.HasPrefix(c, "log") && !strings.Contains(c, "--no-show-signature") { + t.Errorf("the log may verify signatures: git %s", c) + } + } + + // A local upstream is the branch config's text as written; one that is + // not a ref name is no upstream, never an option to git log. + out := filepath.Join(t.TempDir(), "written") + git("config", "branch.main.remote", ".") + git("config", "branch.main.merge", "--output="+out) + if got := runDevBinary(t, root, nil, "status"); got.code != 0 || !strings.Contains(got.stderr, "4 days behind origin/main") { + t.Errorf("an upstream that is not a ref name: exit %d, stderr:\n%s", got.code, got.stderr) + } + if _, err := os.Stat(out); err == nil { + t.Errorf("an upstream read as an option: git log wrote %s", out) + } + git("config", "--unset", "branch.main.remote") + git("config", "--unset", "branch.main.merge") + + tip := git("rev-parse", "refs/remotes/origin/main") + git("update-ref", "-d", "refs/remotes/origin/main") + git("update-ref", "refs/remotes/origin/master", tip) + git("pack-refs", "--all") + if want := "this tree is 4 days behind origin/master as last fetched"; !strings.Contains(runDevBinary(t, root, nil, "status").stderr, want) { + t.Errorf("only a packed origin/master: want %q on stderr", want) + } +} + +// A tree whose missing changes all landed within the day, or that lacks +// nothing, says nothing; a repository with no origin spends no git at all. +func TestTheCheckoutsAbcdIsQuietWhenItsTreeIsCurrent(t *testing.T) { + root := devBinaryCheckout(t) + git := behindFixture(t, root, 20*time.Hour, true) + if got := runDevBinary(t, root, nil, "status"); strings.Contains(got.stderr, "behind") || got.code != 0 { + t.Errorf("changes landed within the day: exit %d, stderr:\n%s", got.code, got.stderr) + } + git("reset", "--quiet", "--hard", "refs/remotes/origin/main") + if got := runDevBinary(t, root, nil, "status"); got.stderr != "" || got.code != 0 { + t.Errorf("a tree at origin's tip: exit %d, stderr:\n%s", got.code, got.stderr) + } + + lone := devBinaryCheckout(t) + behindFixture(t, lone, 5*24*time.Hour, false) + got := runDevBinary(t, lone, nil, "status") + if got.stderr != "" || got.code != 0 { + t.Errorf("no origin: exit %d, stderr:\n%s", got.code, got.stderr) + } + if calls := gitCalls(got.log); len(calls) != 0 { + t.Errorf("with no origin the check still ran git: %q", calls) + } + if calls := gitCalls(runDevBinary(t, devBinaryCheckout(t), nil, "status").log); len(calls) != 0 { + t.Errorf("outside any repository the check still ran git: %q", calls) + } +} diff --git a/internal/surface/cli/ahoy_main_checkout_behind_test.go b/internal/surface/cli/ahoy_main_checkout_behind_test.go new file mode 100644 index 0000000000..a51dafb500 --- /dev/null +++ b/internal/surface/cli/ahoy_main_checkout_behind_test.go @@ -0,0 +1,61 @@ +package cli + +import ( + "fmt" + "os/exec" + "strings" + "testing" + "time" + + "github.com/intentdriven/abcd/internal/gittest" +) + +// TestBareAhoyNamesAStaleMainCheckout (iss-2612022220481334): the gap is +// report-only, so the text board is where a person meets it, and its title +// alone would not say how far behind the checkout is or what to do. The +// board's `checkout:` line carries both. +func TestBareAhoyNamesAStaleMainCheckout(t *testing.T) { + hermeticEnv(t) + r := gittest.NewRepo(t) + r.Write("cmd/abcd/main.go", "package main\n") + r.Commit("base") + base := r.Git("rev-parse", "HEAD") + // Two changes land on origin's default branch three days ago, by their + // committer time, which is what the gap reads. + landed := fmt.Sprintf("@%d +0000", time.Now().Add(-3*24*time.Hour).Unix()) + for _, msg := range []string{"landed first", "landed since"} { + cmd := exec.Command("git", "-C", r.Root(), "-c", "user.email=fixture@example.invalid", "-c", "user.name=Fixture", + "-c", "commit.gpgsign=false", "commit", "--quiet", "--allow-empty", "-m", msg) + cmd.Env = append(gittest.Env(t), "GIT_AUTHOR_DATE="+landed, "GIT_COMMITTER_DATE="+landed) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git commit: %v\n%s", err, out) + } + } + r.Git("remote", "add", "origin", "https://example.invalid/abcd.git") + r.Git("update-ref", "refs/remotes/origin/main", r.Git("rev-parse", "HEAD")) + r.Git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + r.Git("reset", "--quiet", "--hard", base) + t.Chdir(r.Root()) + + out, err := runCLIErr(t, "ahoy") + if err != nil { + t.Fatalf("ahoy: %v\n%s", err, out) + } + var line string + for _, l := range strings.Split(string(out), "\n") { + if strings.HasPrefix(l, " checkout: ") { + line = l + } + } + if line == "" { + t.Fatalf("bare ahoy carries no checkout: line for a main checkout three days behind:\n%s", out) + } + for _, want := range []string{"is 3 days behind origin/main as last fetched", "2 changes landed there that it lacks", "scripts/abcd.sh ahoy worktree add", "abcd only reports it"} { + if !strings.Contains(line, want) { + t.Errorf("the checkout line lacks %q:\n%s", want, line) + } + } + if strings.Count(string(out), "abcd only reports it") != 1 { + t.Errorf("the gap's way on is printed more than once:\n%s", out) + } +} diff --git a/internal/surface/cli/cli.go b/internal/surface/cli/cli.go index 30199cfd02..28fcd9ec4f 100644 --- a/internal/surface/cli/cli.go +++ b/internal/surface/cli/cli.go @@ -4729,6 +4729,10 @@ func newAhoyCommand(asJSON *bool) *cobra.Command { // Report-only too: the check the file failed and its // repair (iss-2610091920437492). fmt.Fprintf(w, " filters: %s %s\n", termsafe.Sanitize(g.Detail), termsafe.Sanitize(g.FixHint)) + case ahoy.MainCheckoutBehindGapID: + // Report-only: how far behind the main checkout is, + // and the way on (iss-2612022220481334). + fmt.Fprintf(w, " checkout: %s %s\n", termsafe.Sanitize(g.Detail), termsafe.Sanitize(g.FixHint)) } } if res.FolderKind != ahoy.UnmanagedFolder { @@ -5112,7 +5116,7 @@ func unresolvableGapStep(g ahoy.Gap) string { func ahoyGapStepPrintedBelow(g ahoy.Gap) bool { switch g.ID { case ahoy.StatusLineUntrustedGapID, ahoy.StoreWorktreeUnlinkedGapID, - ahoy.FilterRootsIgnoredGapID, ahoy.ProviderAdapterGapID: + ahoy.FilterRootsIgnoredGapID, ahoy.ProviderAdapterGapID, ahoy.MainCheckoutBehindGapID: return true } return strings.HasPrefix(g.ID, ahoy.HarnessStrayHookGapPrefix+".") diff --git a/internal/surface/cli/hook_away.go b/internal/surface/cli/hook_away.go index 1167f9e4d9..a3cc00887d 100644 --- a/internal/surface/cli/hook_away.go +++ b/internal/surface/cli/hook_away.go @@ -44,6 +44,7 @@ func awayBlock(rec *autonomy.Record) string { b.WriteString("Never ask the person a question while they are away.\n") b.WriteString(autonomy.QuestionRoute() + "\n") b.WriteString("An intent's open planning question is never a reason to stop: settle it " + intent.OpenQuestionsAwayRoute + " (iss-2611260602175153).\n") + b.WriteString(autonomy.DeclinedCallLine() + "\n") b.WriteString("\nRun `abcd mode back` only on the person's word in this session.\n") return b.String() } diff --git a/internal/surface/cli/hook_away_test.go b/internal/surface/cli/hook_away_test.go index 2716b0eec8..09eff19f1d 100644 --- a/internal/surface/cli/hook_away_test.go +++ b/internal/surface/cli/hook_away_test.go @@ -80,6 +80,8 @@ func assertAwayBlock(t *testing.T, where, text string) { "spends money", // iss-2611260602175153: an intent's open question never stops the work. "An intent's open planning question is never a reason to stop", + // iss-2612022221066637: a declined call never stops the owed work. + "A declined tool call stays declined until the person says otherwise: do not reach that act another way; take other owed work, passing over any item that needs it.", "Run `abcd mode back` only on the person's word in this session", } { if !strings.Contains(text, want) { diff --git a/internal/surface/cli/hook_stop.go b/internal/surface/cli/hook_stop.go index 530e58a433..7731079e05 100644 --- a/internal/surface/cli/hook_stop.go +++ b/internal/surface/cli/hook_stop.go @@ -118,7 +118,8 @@ func newHookStopCommand() *cobra.Command { Long: `The Stop hook's front door onto the away mode's stop check. While the away record holds (abcd mode autonomous), a turn's end is blocked -while work is owed, naming the next item, and is allowed only with a +while work is owed, naming the next item and saying that a declined tool +call stays declined, the session taking other work; it is allowed only with a session cron whose latest fire time, the host's lateness included, falls before the deadline: within half an hour while work is owed (an hour when none is) and before the session's reservations need renewing. A wake diff --git a/scripts/abcd.sh b/scripts/abcd.sh index c531e2db2b..875cda04f6 100755 --- a/scripts/abcd.sh +++ b/scripts/abcd.sh @@ -26,6 +26,11 @@ # worktree of a repository reuses one compiled copy of each package rather than # adding its own to the build cache, and two trees that match link one binary. # +# The build is the tree as it stands, however old, so a tree more than a day +# behind origin's default branch or its own upstream, as last fetched, is named +# in one line on stderr first (iss-2612022220481334, behind_note below). It +# never fetches, never refuses and never touches the exit code. +# # Usage: scripts/abcd.sh [args...] from the checkout root, or by its path # (or a symlink to it) from anywhere; the verb runs in the caller's working # directory. A tree that does not build exits 2 and runs nothing, so a broken @@ -52,6 +57,88 @@ if [ ! -f "$root/cmd/abcd/main.go" ]; then exit 2 fi +# behind_note: one line on stderr when the tree lacks changes that landed on +# origin's default branch or on the branch's upstream, as last fetched, the +# oldest of them more than a day ago. origin's default branch is read as ahoy +# reads it: refs/remotes/origin/HEAD, else origin's main, master, trunk or +# develop, the first there is. A change is a commit on that branch's +# first-parent line, so the age is when the branch first moved past the tree, +# not when a merged branch's own commits were made. A repository whose config +# names no origin is passed over with no git spent: its config is read as a +# file, through the .git folder or a linked worktree's .git file and its +# commondir. Where there is an origin it costs two git calls, both local +# reads: one listing of the upstream and the candidate branches, and the +# first-parent log, which verifies no signature whatever log.showSignature +# says. Neither has a deadline: there is no portable one (macOS has no +# timeout), and dcn-2612022356262040 says why they go without. Any failure, +# and a session whose GIT_DIR points git elsewhere, says nothing. +behind_note() { + local dotgit="$root/.git" gitdir="" common="" line="" up="" out="" ct="" ref="" + local n=0 oldest="" where="" now="" days="" what="" branch="" refs="" def="" name="" ref_up="" + [ -z "${GIT_DIR:-}" ] || return 0 + if [ -d "$dotgit" ]; then + gitdir="$dotgit" + common="$dotgit" + elif [ -f "$dotgit" ]; then + IFS= read -r line <"$dotgit" || [ -n "$line" ] || return 0 + gitdir="${line#gitdir: }" + [ "$gitdir" != "$line" ] || return 0 + case $gitdir in /*) ;; *) gitdir="$root/$gitdir" ;; esac + common="$gitdir" + if [ -f "$gitdir/commondir" ]; then + line="" + IFS= read -r line <"$gitdir/commondir" || [ -n "$line" ] || return 0 + case $line in /*) common="$line" ;; *) common="$gitdir/$line" ;; esac + fi + else + return 0 + fi + grep -qs '^\[remote "origin"\]' "$common/config" || return 0 + line="" + IFS= read -r line <"$gitdir/HEAD" 2>/dev/null || true + case $line in "ref: refs/heads/"*) branch="${line#ref: }" ;; esac + refs="$(git -C "$root" for-each-ref --format='%(refname) %(upstream)' ${branch:+"$branch"} refs/remotes/origin/HEAD refs/remotes/origin/main refs/remotes/origin/master refs/remotes/origin/trunk refs/remotes/origin/develop 2>/dev/null)" || return 0 + while read -r ref ref_up; do + [ -z "$branch" ] || [ "$ref" != "$branch" ] || up="$ref_up" + done <<<"$refs" + # A local upstream is the branch config's text as written, so only a ref + # name is passed to git log, never what could read as an option. + case $up in refs/*) ;; *) up="" ;; esac + for name in HEAD main master trunk develop; do + while read -r ref ref_up; do + [ "$ref" != "refs/remotes/origin/$name" ] || def="$ref" + done <<<"$refs" + [ -z "$def" ] || break + done + [ -n "$def$up" ] || return 0 + out="$(git -C "$root" log --no-show-signature --ignore-missing --first-parent --format='%ct %S' '^HEAD' ${def:+"$def"} ${up:+"$up"} -- 2>/dev/null)" || return 0 + [ -n "$out" ] || return 0 + while read -r ct ref; do + case $ct in '' | *[!0-9]*) continue ;; esac + n=$((n + 1)) + if [ -z "$oldest" ] || [ "$ct" -lt "$oldest" ]; then + oldest="$ct" + where="$ref" + fi + done <<<"$out" + [ -n "$oldest" ] || return 0 + now="$(date +%s 2>/dev/null)" || return 0 + case $now in '' | *[!0-9]*) return 0 ;; esac + [ $((now - oldest)) -gt 86400 ] || return 0 + days=$(((now - oldest) / 86400)) + case $where in + refs/remotes/origin/HEAD) what="origin's default branch" ;; + refs/remotes/*) what="${where#refs/remotes/}" ;; + *) what="${where#refs/heads/}" ;; + esac + [ "$days" -eq 1 ] && days="1 day" || days="$days days" + [ "$n" -eq 1 ] && n="1 change" || n="$n changes" + # The backquotes are the line's own, around the command it names. + # shellcheck disable=SC2016 + printf 'scripts/abcd.sh: this tree is %s behind %s as last fetched (%s landed there that it lacks), and this abcd is built from it as it stands; run scripts/abcd.sh from an up-to-date worktree, such as one `scripts/abcd.sh ahoy worktree add ` makes\n' "$days" "$what" "$n" >&2 || true +} +behind_note || true + # build : link the tree to , or exit 2 having run nothing. build() { if ! (cd "$root" && go build -trimpath -buildvcs=false -o "$1" ./cmd/abcd); then