opencode-workflow-guard 1.20.1 → 1.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/policies.md CHANGED
@@ -16,6 +16,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
16
16
  - **Pre-edit Gate:** All file-editing tools (`edit`, `write`, `apply_patch`) are blocked while the session's effective todo list is known and contains no active task. On OpenCode 1.x the list comes from the native todo system (`todowrite`, persisted at `GET /session/:id/todo`). Before 2.1.0, the OpenCode 2.x builtin tool registry has no `todowrite`, and there is no todo endpoint. The list is then reconstructed from the newest applied `todowrite` tool call in the session history, which ACP agents may supply. OpenCode 2.1.x reintroduces a builtin `todowrite` behind the `experimental.todo` config key. The guard detects that capability by probing the host tool registry rather than inferring it from history. Verified on 2.1.3: `ctx.tool.list()` exposes `todowrite` when the flag is on, and omits it when off. The gate distinguishes a **definitively empty** list from an **undeterminable** one. A definitively empty list means the capability exists and reports no active task, which stays blocked. An undeterminable list means no todo capability, or the history cannot be read. The gate then fails open and records that once per session at warn level. This keeps builtin-only V2 sessions usable instead of deadlocking every edit forever.
17
17
  - **Flexible Task Execution:** Tasks can be completed in any order as work concludes without artificial sequential blockers, maintaining maximum pair-programming DX.
18
18
  - **No Silent Deletion:** Each `todowrite` update replaces the complete list. Active tasks must remain in subsequent updates until they are explicitly marked `completed` or `cancelled`.
19
+ - **Refinement, not deletion:** An active task may be reworded when its replacement keeps every word of the original and adds at least one more. That is the same work item sharpened, so the write passes and the task keeps its original mutation window. Two distinct words is the floor, so a one-word task always needs an exact match. Each replacement absorbs at most one removed task. Every accepted refinement is journaled as `todo_refined`. A reword that drops or substitutes a word is still a removal and blocks.
19
20
  - **Per-Task Completion Evidence (enforced):** Because a `todowrite` call replaces the whole list, a model can mark work `completed` without doing it. A task may therefore enter `completed` only when the session recorded at least one file mutation inside that task's active window. One mutation cannot vouch for several completions, so N completions require N mutations counted from the earliest of them. Mutations spent before a task became active never count toward it. A blocked write names the task and the remedy. The check also runs in simulation, so `guard_why` predicts the gate instead of reporting a falsely permissive verdict. A finished or dropped task releases its window, so reusing the same task text starts clean. Tasks are matched to their prior occurrences by count, so duplicate text cannot hide a new completion behind an already-completed item. The mutation counter records permitted mutation calls, not confirmed byte changes.
20
21
  - **Planned late:** a task first observed already `completed` has no window to judge, so it is scored against the session's mutation history instead. This is the deliberate path for an agent that did the work before writing the list. It stays bounded by the one-mutation-per-completion rule.
21
22
  - **Read-only escape:** A task whose text carries `[read-only]`, also `[read_only]` or `[read only]`, completes without a mutation. Review, investigation, and reading are legitimate work that changes no file. The marker is an annotation, not part of task identity, so it can be appended to an already-planned task without reading as a deletion. Every use is journaled as `todo_completed_read_only`, so relabeling real work as read-only stays visible in the audit trail. In a repository with no detectable verify command, that journal is the only counterweight. Work that was deliberately dropped uses `cancelled` instead.
@@ -79,12 +80,14 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
79
80
  - Quoted data spans are not shell syntax. Pattern matching runs on the quote-stripped residue, where redirect targets are honored quoted or not, and quote-concatenated paths keep normalizing. A quoted span containing a guarded path is never treated as a redirect or command verb. Unquoted redirects into guarded paths stay blocked.
80
81
  - Plan files under `.opencode/plans/` are exempt: opencode's plan mode writes agent-authored plan markdown there, and plans are content, not configuration. Everything else under `.opencode/` (including the directory itself) stays protected.
81
82
  - **Read-only access is allowed** (`cat`, `less`, `grep`, `head`, `tail` on config files) - only modification attempts trigger the guard.
82
- - **Live control-plane facts (`liveControlPlanePaths`, opt-in):** Declare the absolute paths of the live control plane in `.opencode/workflow-guard.json` or via `WORKFLOW_GUARD_LIVE_CONTROL_PLANE_PATHS` (comma-separated). Examples are `~/.config/opencode` and the guard's own install. When set, config-path protection classifies by runtime consumption instead of filename segments. Only targets that resolve under a live root are protected (symlink-aware). Copying **from** a config path into a sanctioned workspace draft is therefore no longer blocked, because the copy destination is what matters. Versioned drafts such as a project `.opencode/` or a dotfiles `.config/opencode` are editable. Roots must be absolute (`~`/`$HOME` are expanded). An unusable root rejects the whole set and falls back to the legacy fail-closed segment matching. Unset keeps the legacy behavior.
83
+ - **Live control-plane facts (`liveControlPlanePaths`, opt-in):** Declare the absolute paths of the live control plane in `.opencode/workflow-guard.json` or via `WORKFLOW_GUARD_LIVE_CONTROL_PLANE_PATHS` (comma-separated). Examples are `~/.config/opencode` and the guard's own install. When set, config-path protection classifies by runtime consumption instead of filename segments. Only targets that resolve under a live root are protected (symlink-aware). Copying **from** a config path into a sanctioned workspace draft is therefore no longer blocked, because the copy destination is what matters. Versioned drafts such as a project `.opencode/` or a dotfiles `.config/opencode` are editable. Roots must be absolute (`~`/`$HOME` are expanded). An unusable root rejects the whole set and falls back to the legacy segment matching. Unset keeps the legacy behavior.
84
+ - **Copy sources in legacy mode:** Without declared roots, a copy-like verb (`cp`, `ln`, `install`) is judged by its destination operand. That is the last operand, or the `-t`/`--target-directory` value. A guarded path used only as a source is a read, so `cp ~/.config/opencode/templates/x ./draft.md` is allowed. A guarded destination still blocks, including through `-t`, `--target-directory=`, and `install -d`, because that mode creates every directory it names. A hard link is not a read, because it is a second writable name for the same inode: `ln` without `-s`, and `cp -l`/`--link`, keep the broad match. `mv` keeps the broad any-operand match, because the move removes its source. Every other mutating verb, and any copy whose destination cannot be identified, keeps the fail-closed behavior.
83
85
 
84
86
  ### 7. Feature-Branch Workflow
85
87
  - When the workspace git repository is on `main` or `master`, all file mutations and history-changing git commands are blocked. Those commands are `commit`, `merge`, `rebase`, `cherry-pick`, `revert`, `apply`, `am`, `reset`, `restore`, `stash pop`, `update-ref`, `filter-branch`, and `branch -D/-M`. A `pull` on the protected branch is blocked too, because with `pull.rebase` set it rewrites local commits.
86
88
  - **Sync exemption:** `git merge --ff-only [<ref>]`, `git rebase <ref>`, and `git pull --ff-only` are allowed on the protected branch when two facts hold. The target is a remote-tracking ref that is the branch's tracked upstream or the remote default (`origin/HEAD`). And `HEAD` is already an ancestor of that ref, so the branch carries no local commit to replay. A fast-forward adds no commit and rewrites none, so it cannot skip review; refusing it left a stale primary checkout with no way to sync (#145). `merge` without `--ff-only`, a bare `pull`, a local branch, another remote branch, a named remote and branch, and a diverged branch stay blocked. A `-c` override is accepted, because the command is judged by its subcommand and flags. Both `git -c pull.rebase=false pull --ff-only` and `git -c pull.rebase=true pull --ff-only` fast-forward a branch that is strictly behind. A `pull` derives its target from `@{u}`, and that derivation must still resolve to a remote-tracking ref, so a branch tracking a local branch stays blocked.
87
89
  - Git global flags are parsed, so `git -C /repo commit` is gated on `/repo`'s branch, not the workspace's.
90
+ - **Merged-branch cleanup exemption:** `git branch -d <branch>` and `git branch --delete <branch>` are allowed on the protected branch, provided no protected name is named and no `-D` or `--force` appears. Git itself refuses `-d` unless every named branch is fully merged, so the deletion cannot drop an unreviewed commit. `-D`, `--force`, and a protected name stay blocked. This is the local half of the cleanup a merged PR requires, which used to be impossible for the agent whenever the checkout sat on the branch that received the merge.
88
91
  - The agent is prompted to create a feature branch first (`git switch -c feat/my-feature`).
89
92
 
90
93
  ### 8. Workspace Boundary Guard
@@ -110,9 +113,9 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
110
113
  ### 10. Evidence-Based Verification
111
114
  - When the agent attempts to mark **every** task completed (finalizing the request), the guard requires passing verification evidence.
112
115
  - Verification executes in an isolated environment with scrubbed credentials, output caps, token-efficient stdout/stderr snipping, and strict timeout protection. The command comes from the `WORKFLOW_GUARD_VERIFY` env, the project `verifyCommand`, or an auto-detected test or typecheck runner across ecosystems. Auto-detection covers `package.json` (`npm test`, `npm run typecheck`, `npm run check`, `npm run build`), `Cargo.toml` (`cargo test`), `go.mod` (`go test ./...`), `pytest.ini` or `pyproject.toml` (`pytest`), and `deno.json` (`deno test`). Environment configuration takes precedence over project configuration.
113
- - The verification timeout defaults to 30 seconds. Raise it per project with `verifyTimeoutMs` in `.opencode/workflow-guard.json`, or per environment with `WORKFLOW_GUARD_VERIFY_TIMEOUT_MS`, which wins over project config. Non-positive values are ignored and fall back to the default. Raise the timeout for suites that legitimately exceed the default, for example this repository's own unit suite.
114
- - A timeout is reported as `verification_timed_out`, not `verification_failed`. Both block finalization, because neither produced a passing result. They differ in what the agent is told: a timeout says the result is unknown and names the limit and the remedy, while a failure names the failing output. Calling a timeout a failure sent agents looking for an assertion that never ran, and the fix for a timeout is a longer limit rather than a code change.
115
- - Project `postEditValidators` can run faster targeted checks after a direct file edit actually changes the target. Each entry accepts a workspace-relative glob `pattern` with `*`, `**`, and `?` wildcards. Brace expansion and character classes are not supported. Each entry also accepts a non-empty `command` and an optional positive `timeoutMs`. Invalid entries are reported as advisory feedback rather than silently ignored. Matching commands run from the workspace root with the same scrubbed verification environment. Validator failures and timeouts are appended to the edit result as advisory feedback. They do not replace the blocking whole-project finalization verification. Multi-file `apply_patch` calls validate every changed target.
116
+ - The verification timeout defaults to 30 seconds. Raise it per project with `verifyTimeoutMs` in `.opencode/workflow-guard.json` (JSONC is also supported), or per environment with `WORKFLOW_GUARD_VERIFY_TIMEOUT_MS`, which wins over project config. Non-positive values are ignored and fall back to the default. Raise the timeout for suites that legitimately exceed the default, for example this repository's own unit suite.
117
+ - A timeout is reported as `verification_timed_out`, not `verification_failed`. Both block finalization, because neither produced a passing result. They differ in what the agent is told: a timeout says the result is unknown and names the limit and the remedy, while a failure names the failing output. Calling a timeout a failure sent agents looking for an assertion that never ran, and the fix for a timeout is a longer limit rather than a code change. The limit renders identically in the block reason and in the timed-out output tail, at the precision it was set (`50ms` stays `50ms`, never `0s`). A timed-out tail is snipped under its own `unknown` label, so it never claims the killed suite passed or failed.
118
+ - Project `postEditValidators` can run faster targeted checks after a direct file edit actually changes the target. Each entry accepts a workspace-relative glob `pattern` with `*`, `**`, and `?` wildcards. Brace expansion and character classes are not supported. Each entry also accepts a non-empty `command` and an optional positive `timeoutMs`. Invalid entries are reported as advisory feedback rather than silently ignored. Matching commands run from the workspace root with the same scrubbed verification environment. Validator failures and timeouts are appended to the edit result as advisory feedback, and a validator timeout names the limit rather than reporting a failed check. They do not replace the blocking whole-project finalization verification. Multi-file `apply_patch` calls validate every changed target.
116
119
  - With project `recoveryCheckpoints: true`, or the `autonomous` operation profile unless explicitly overridden, genuine root-session user runs capture a private Git checkpoint before agent work starts. Checkpoints preserve tracked and untracked state without using the user's stash list. Subagents and generated continuation prompts do not replace them. At the idle trigger (`session.status` with `status.type === "idle"`), the run's resulting workspace fingerprint is recorded before automatic continuation. `guard_recovery_restore` is provenance-bound to the same root session and refuses restoration after any intervening workspace change. Operation profiles only set optional workflow defaults and cannot weaken core safety policies.
117
120
  - Automatic continuation remains synthetic. By default, an eligible root session with unfinished owned todos briefly waits for OpenCode's native asynchronous title generation before that continuation is sent. The wait ends as soon as the delivered `session.renamed` event reports that the title committed, and falls back to the bounded poll interval on a host that does not emit it. The bounded wait never rewrites titles or provider and model parameters. Set `titleSettleWorkaround: false` to opt out.
118
121
  - **Git State & Snapshot Binding:** Verification evidence records the current git commit hash (`git rev-parse HEAD`) and working tree status. If unverified edits or index modifications occur after verification, fresh verification is enforced.
@@ -149,7 +152,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
149
152
  - Caps injected continuity context at 8,000 characters. Operational guard state is preserved first. The remaining budget holds active tasks, review follow-ups, and fresh local project memory.
150
153
  - Active `todowrite` tasks with status badges and subagent hierarchy attribution.
151
154
  - Active Git branch name and protected branch status.
152
- - Test verification status (passed/failed, test command, and commit hash).
155
+ - Test verification status (passed/failed/timed out, test command, and commit hash). A timed-out run is reported as `TIMED OUT within <limit> (result unknown, not a failing test)` rather than as a failure, naming the limit that was hit so the compacted context cannot restate the misattribution.
153
156
  - Secondary review verdicts (reviewer name and approval status).
154
157
  - Dogfood evidence state when Policy 27 is enabled, naming the deploy-matrix hosts still missing a passing run.
155
158
  - Uncommitted mutation counts.
@@ -177,6 +180,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
177
180
 
178
181
  ### 20. Merged Branch & Base Freshness Guard
179
182
  - Blocks pushing to branches already merged or associated with closed PRs in GitHub or Azure DevOps.
183
+ - **Merged-branch cleanup exemption:** A push that only deletes remote branches already merged into the remote default is allowed: `git push <remote> --delete <branch>` and the `:<branch>` or `:refs/heads/<branch>` refspec. Deleting a merged branch's remote ref publishes no commit, so it is the remote half of the cleanup a merged PR requires. Every named branch must resolve to a local `refs/heads/<branch>` or `refs/remotes/origin/<branch>` that is an ancestor of the remote default, so an unmerged branch keeps its commits reachable and an unknown branch stays blocked. A protected name is refused. Any ordinary refspec, a forced refspec, `--force`, `--prune`, and `--mirror` stay blocked, because each deletes or publishes more than the named branches. A fully-qualified refspec outside `refs/heads/` stays blocked, so tag deletion is unaffected.
180
184
  - Blocks creating feature branches (`git switch -c`, `git checkout -b`) from a stale base. Without an explicit start point, the current branch must be fresh against the remote default. An explicit start point that already contains the remote default (`origin/HEAD`) is accepted, because the new branch is fresh by construction. Start points that cannot be resolved fail closed. Block reasons name the branch actually checked. They also name remedies that work under the guard: rebase or ff-merge the branch, or branch from the remote default directly. Shell redirections attached to or following a branch creation are ignored when classifying the start point. Those redirections are stdout and stderr redirection and fd duplication such as `2>&1`. They never determine which commit the branch is created from.
181
185
  - Tag push refspecs are exempt. Publishing an existing tag (`git push origin v1.2.0`, `git push origin refs/tags/v1.2.0`) and creating tags (`git tag v1.2.0`, `git tag -a -m ...`) are release operations, not branch mutations. Only tag deletions (`git tag -d`, `git push origin :refs/tags/v1.2.0`, `--delete`) stay blocked.
182
186
 
@@ -185,7 +189,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
185
189
  - Only **README.md** (root or package level) and files under **`docs/`** count as documentation updates. Arbitrary markdown does not satisfy this gate. That includes `.changeset/*.md` fragments and `CHANGELOG.md`.
186
190
 
187
191
  ### 22. Non-Interactive Shell & TTY Hang Guard
188
- - Blocks commands that spawn interactive text editors (`nano`, `vim`, `emacs`), interactive pagers (`less`, `more`) including through common shell wrappers, and interactive monitors (`top`, `htop`). It also blocks interactive rebase and patch prompts (`git rebase -i`, `git add -p`), `sudo`, and package managers missing non-interactive confirmation flags (`npm init` without `-y`, `apt-get` without `-y`). Pager and monitor names appearing only as command arguments are not treated as pager or monitor execution. Examples are `az keyvault secret show --name top` and `echo top`. Monitors are only flagged in command position. That means after wrappers such as `sudo`/`env`/`timeout`, through `eval` and `sh -c`, and via `busybox`. `top` batch mode stays allowed. Indirection this does not model is a known limitation. It covers `watch`/`xargs`/`man`, `find -exec`/`su -c`, and shell loop bodies such as `while true; do top; done`.
192
+ - Blocks commands that spawn interactive text editors (`nano`, `vim`, `emacs`), interactive pagers (`less`, `more`) including through common shell wrappers, and interactive monitors (`top`, `htop`). It also blocks interactive rebase and patch prompts (`git rebase -i`, `git add -p`), `sudo`, and package managers missing non-interactive confirmation flags (`npm init` without `-y`, `apt-get` without `-y`). **Every one of those names is judged at command position.** A name that appears only as an argument is data, so `az keyvault secret show --name top`, `echo top`, `grep -n 'sudo'`, and `grep -n 'git rebase -i'` are all allowed. A command word is read after wrapper and assignment stripping (`env`, `timeout`, `command`, `exec`, `nice`, `nohup`, `stdbuf`, `time`), so `env FOO=1 sudo ls` and `timeout 5 sudo ls` still block. Control-flow prefixes (`then`, `else`, `elif`, `do`, `while`, `for`, `!`) are skipped, so a loop or conditional body is judged too. `eval` and shell `-c` payloads recurse, and `busybox` applets are matched. `top` batch mode stays allowed. Indirection this does not model is a known limitation. It covers `watch`/`xargs`/`man`, `find -exec`/`su -c`, shell loop bodies for monitors such as `while true; do top; done`, and a command name delivered to a shell as stdin data (`echo 'vim x' | sh`).
189
193
  - Prevents subshell agents from hanging indefinitely waiting for user stdin in background execution.
190
194
  - **Desktop Notifications:** Emits native OS notifications when a policy blocks a command or when verification runs finish. The backends are Linux `notify-send` and macOS `osascript`. This keeps developers informed when their terminal is backgrounded. Configure it via `WORKFLOW_GUARD_NOTIFY=0`.
191
195
 
@@ -198,7 +202,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
198
202
 
199
203
  ### 24. Completion Claims vs Evidence (Observability)
200
204
  - When the assistant's final response text asserts completion or passing verification, the guard compares the claim against recorded verification evidence for that session. The trigger phrases are "all tests pass", "work is done", and "verified".
201
- - Mismatches are journaled to the audit trail and logged at info level. A mismatch means failing verification, stale evidence due to mutations after the verify run, or no evidence at all. This is **observability, not gating**. The response is never blocked, but a confident wrap-up cannot silently contradict a failing or absent verification state.
205
+ - Mismatches are journaled to the audit trail and logged at info level. A mismatch means failing verification, a timed-out verification, stale evidence due to mutations after the verify run, or no evidence at all. This is **observability, not gating**. The response is never blocked, but a confident wrap-up cannot silently contradict a failing or absent verification state. A timed-out run gets its own `timed-out` evidence state rather than being filed as `failing`, so the journal names the limit that was hit instead of implying an assertion broke.
202
206
  - Uses the `experimental.text.complete` hook. Claim detection is a conservative phrase heuristic to avoid false positives on casual wording.
203
207
 
204
208
  ### 25. Live-Documentation Research Floor
package/docs/testing.md CHANGED
@@ -49,14 +49,14 @@ npm run test:all
49
49
  | **Policy 5: MCP Mutations** | Verifies GitHub/Azure mutating MCP tools are blocked while read-only tools pass. |
50
50
  | **Policy 6: Settings Tamper** | Verifies protection of `opencode.json`, `~/.config/opencode/*`, `opencode auth`, and the plugin and MCP mutating verbs (`plugin add/remove`, `mcp add`), including a global-flag form, while `plugin list` and `mcp list` stay allowed. |
51
51
  | **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. Also verifies the `/tmp/opencode` scratch allowance: a real session may write, redirect, patch, and run an interpreter payload there, while a session-less write, a sibling that shares the prefix, a `..` traversal out of it, and a symlink that leaves it stay blocked. |
52
- | **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. Also verifies `guard_status` names the project config file it read, attributes the effective verify command to `project-config`, `auto-detected`, or neither, and puts the environment ahead of both. A configured command that passes leaves `lastVerify` with a timestamp, a `durationMs`, and a commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
52
+ | **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. The timed-out output tail renders the same limit at the same precision and is snipped under its own `unknown` label, so a killed suite is never reported as passing or failed, and the compaction summary reports the timeout rather than a failure. Also verifies `guard_status` names the project config file it read, attributes the effective verify command to `project-config`, `auto-detected`, or neither, and puts the environment ahead of both. A configured command that passes leaves `lastVerify` with a timestamp, a `durationMs`, and a commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
53
53
  | **File-Claim TTL Reclaim** | Verifies a claim within the TTL blocks and names the reclaim step, an expired claim is reclaimed for the next claimant, the reclaim writes a `claim_ttl_expired` audit with the owner and age, the environment override wins, and project config `claimTtlMs` is honored. |
54
54
  | **Shell Mutation Claim Conflicts** | Verifies a redirect into a claimed path is refused with the claim reason, `tee -a` with its flag parsed is refused, a symlink alias is refused, a chained `cd` is judged in the tree it lands in, a multi-operand mutation is refused when any operand is claimed, a `mv` source is refused because the move removes it, a subagent is refused on a path its parent claimed, `guard_why` reports the conflict as a shell mutation without acquiring a claim, an unclaimed path stays allowed, and the path is allowed once the owning edit releases its claim. |
55
55
  | **Review Rubric Provenance** | Verifies the rubric names the workspace, base ref, and diff byte count it graded; grades a linked worktree named by `directory` rather than the caller's checkout; refuses when no base yields a diff, naming the workspace, every base tried, and the remedy, without emitting a rubric body over a substitute range; and honors an explicit `HEAD~1` base with `base=HEAD~1 fallback=HEAD~1`. Also verifies the injected workflow guidance names the calling session as the recorder rather than the subagent. |
56
56
  | **record_review Registration** | Verifies `record_review` stays registered when the review gate is disabled, so a reviewer agent's host permission list, not project config, is what can withhold the call. Under `requireSubagentReview`, verifies a root approval is rejected and `guard_status.lastReview` names the subagent recorder and its parent separately. |
57
57
  | **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
58
58
  | **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
59
- | **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
59
+ | **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/timed-out/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
60
60
  | **Compaction & TUI Feedback** | Verifies active task injection in `experimental.session.compacting`, the static TUI badge, guard block warning toasts, and clean error propagation. |
61
61
  | **Runtime Instance Isolation** | Verifies concurrent plugin instances keep workspace root and SDK client state isolated via `runWithRuntimeState`. |
62
62
  | **V2 Permission Seat Abstention** | Verifies the simulated seat denies a real finding, abstains on a decision it cannot make instead of denying, never upgrades a configured `ask`, and journals the abstention as `deferred_to_execute_before` with the preserved decision. Covers both the remote-probe deferral (`remote_state_unchecked`) and the cwd-dependent deferral (`repository_unidentified`). |
@@ -44,6 +44,8 @@ Common issues, root causes, and solutions when using `opencode-workflow-guard`.
44
44
 
45
45
  A checkout that is only behind its remote is not blocked. `git merge --ff-only <upstream>`, `git rebase <upstream>`, and `git pull --ff-only` are allowed on the protected branch when the ref is the branch's tracked upstream or the remote default, and `HEAD` is already an ancestor of it. That adds no commit and rewrites none, so a stale primary checkout can sync without a feature branch. `git merge` without `--ff-only`, a bare `git pull`, a local branch target, a different remote branch, a named remote and branch, and a branch with its own commits stay blocked. On a host where `pull.rebase` is set, run `git -c pull.rebase=false pull --ff-only`; the guard accepts that form.
46
46
 
47
+ The cleanup a merged PR requires is also allowed on the protected branch. `git branch -d <branch>` and `git branch --delete <branch>` pass, because git itself refuses them unless the branch is fully merged. A remote branch that is already merged can be deleted with `git push origin --delete <branch>` or `git push origin :<branch>`. A forced deletion, `git branch -D`, a protected branch name, an unmerged branch, and the options that delete more than the named branches (`--prune`, `--mirror`) stay blocked.
48
+
47
49
  ---
48
50
 
49
51
  ### 6. Edits Blocked: `Blocked: file path '...' escapes workspace root`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.20.1",
3
+ "version": "1.20.4",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -50,10 +50,10 @@
50
50
  "prepublishOnly": "npm run typecheck"
51
51
  },
52
52
  "dependencies": {
53
- "@opencode-ai/plugin": "1.19.5",
54
- "@opencode/ai": "2.3.0",
55
- "@opencode/plugin": "2.3.0",
56
- "@opentui/solid": "0.9.2",
53
+ "@opencode-ai/plugin": "1.19.6",
54
+ "@opencode/ai": "2.4.1",
55
+ "@opencode/plugin": "2.4.1",
56
+ "@opentui/solid": "0.9.9",
57
57
  "jsonc-parser": "3.3.1"
58
58
  },
59
59
  "devDependencies": {
@@ -347,7 +347,7 @@ export function createCustomTools(options: {
347
347
  const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
348
348
  const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
349
349
  const verifySnapshot = lastV && verifyEvidence
350
- ? { command: lastV.command, passed: lastV.passed, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null }
350
+ ? { command: lastV.command, passed: lastV.passed, timedOut: lastV.timedOut === true, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null }
351
351
  : null;
352
352
  const reviewSnapshot = lastR && reviewEvidenceRecord
353
353
  ? { reviewer: lastR.reviewer, passed: lastR.passed, summary: lastR.summary, fresh: reviewFresh, evidenceId: reviewEvidenceRecord.id, timestamp: lastR.timestamp, targetSessionID: lastR.targetSessionID ?? null, recorderSessionID: lastR.recorderSessionID ?? null, recorderRole: lastR.recorderRole ?? null }
@@ -54,6 +54,7 @@ export async function guardToolCall(
54
54
  ? {
55
55
  command: lastVerify.command,
56
56
  passed: lastVerify.passed,
57
+ timedOut: lastVerify.timedOut === true,
57
58
  fresh: lastVerify.timestamp >= lastMutationTimestamp,
58
59
  durationMs: lastVerify.durationMs,
59
60
  }
@@ -43,6 +43,7 @@ import {
43
43
  runVerify,
44
44
  resolveVerifyTimeoutMs,
45
45
  snipVerifyOutput,
46
+ formatTimeoutLimit,
46
47
  } from "./verify.ts";
47
48
  import { detectShellMutation, extractPatchPaths, foreignSegmentMutationReason, guardShellMutation, hasUnresolvableVariable, isAllowedScratchTarget, isEnvironmentScratchTarget, isPathOutsideWorkspace, linkedWorktreeMismatchReason, nestedPayloadMutationReason, OPENCODE_SCRATCH_DIR } from "../policies/boundary.ts";
48
49
  import { branchHasChangelogChange, checkLockfileSync, hasPrCreateInvocation, prBodyHasLiteralLineBreakEscapes, prBodyIncludesChangelog } from "../policies/changelog.ts";
@@ -63,11 +64,13 @@ import {
63
64
  hasUnsafeGitAlias,
64
65
  isBranchAlreadyMergedOrClosed,
65
66
  isGitTreeWriteText,
67
+ isMergedLocalBranchDeletion,
66
68
  isProtectedBranchFastForward,
67
69
  normalizeGitCommands,
68
70
  onProtectedBranch,
69
71
  parseGitInvocation,
70
72
  prSourceBranch,
73
+ purgesMergedRemoteBranches,
71
74
  pushedProtectedBranchIn,
72
75
  tagRefspecIn,
73
76
  } from "../policies/git.ts";
@@ -85,12 +88,12 @@ import {
85
88
  effectiveTodos,
86
89
  fetchSessionTodos,
87
90
  hasActiveTodo,
91
+ inspectTodoLifecycle,
88
92
  readOnlyTodoCompletions,
89
93
  recordTodoTaskStarts,
90
94
  subagentMutationBudgetReason,
91
95
  todoCompletionBlockReason,
92
96
  unverifiedTodoCompletions,
93
- validateTodoLifecycle,
94
97
  } from "../policies/todo.ts";
95
98
  import { recordedTodoCapability, reportTodoGateFailOpen } from "./v2-todo.ts";
96
99
 
@@ -162,17 +165,6 @@ function logBlock(message: string, simulate = false): void {
162
165
  } catch {}
163
166
  }
164
167
 
165
- /**
166
- * Render a verification timeout limit for the block reason.
167
- *
168
- * Sub-second limits are exercised by tests, and a bare `Math.round(ms/1000)`
169
- * reports those as "0s", which reads as no limit at all.
170
- */
171
- function formatTimeoutLimit(timeoutMs: number | undefined): string {
172
- if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return "the verification timeout";
173
- return timeoutMs < 1000 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1000)}s`;
174
- }
175
-
176
168
  export async function guardToolCallImpl(
177
169
  toolName: string,
178
170
  input: unknown,
@@ -228,10 +220,10 @@ export async function guardToolCallImpl(
228
220
  if (Array.isArray(rawTodos)) {
229
221
  const newTodos = rawTodos;
230
222
  const existingTodos = context?.sessionID ? await fetchSessionTodos(context.sessionID) : undefined;
231
- const err = validateTodoLifecycle(newTodos, existingTodos);
232
- if (err) {
233
- logPolicyBlock(`[workflow-guard] ${err}`);
234
- return block("todo", "todo_lifecycle", err);
223
+ const lifecycle = inspectTodoLifecycle(newTodos, existingTodos);
224
+ if (lifecycle.error) {
225
+ logPolicyBlock(`[workflow-guard] ${lifecycle.error}`);
226
+ return block("todo", "todo_lifecycle", lifecycle.error);
235
227
  }
236
228
  // Per-task completion evidence. Every task may enter `completed`
237
229
  // only after the session mutated inside that task's window. The
@@ -241,7 +233,7 @@ export async function guardToolCallImpl(
241
233
  if (context?.sessionID) {
242
234
  const starts = todoTaskStarts(context.sessionID);
243
235
  const total = getSessionMutationCount(context.sessionID);
244
- const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total);
236
+ const unverified = unverifiedTodoCompletions(existingTodos, newTodos, starts, total, lifecycle.refinements);
245
237
  if (unverified.length > 0) {
246
238
  const reason = todoCompletionBlockReason(unverified);
247
239
  logPolicyBlock(`[workflow-guard] ${reason}`);
@@ -280,11 +272,12 @@ export async function guardToolCallImpl(
280
272
  // finalization, but naming a failure sends the
281
273
  // agent chasing an assertion that never ran, and
282
274
  // the remedy is a longer limit rather than a code
283
- // change. The tail is snipped as passing output on
284
- // that path, because snipVerifyOutput labels a
285
- // failing run with a "Verification Failed" header
286
- // that would restate the misattribution.
287
- const tail = snipVerifyOutput(result.output, result.timedOut === true).slice(-500);
275
+ // change. A timed-out tail is snipped as `unknown`:
276
+ // neither label is honest, because the run neither
277
+ // passed nor failed. `unknown` also keeps the
278
+ // "Verification Failed" header off a run that did
279
+ // not report one.
280
+ const tail = snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : "failed").slice(-500);
288
281
  const reason = result.timedOut
289
282
  ? `Blocked todowrite: verification did not finish within ${formatTimeoutLimit(result.timeoutMs)} so the result is unknown rather than failing (${command}). Only the user can raise the limit, in the project .opencode/workflow-guard.json or .jsonc (verifyTimeoutMs) or with WORKFLOW_GUARD_VERIFY_TIMEOUT_MS set before the guard starts; ask them, then complete the tasks again. Output tail: ${tail}`
290
283
  : `Blocked todowrite: all tasks marked done but verification is failing (${command}). Fix the failure before finishing; output tail: ${tail}`;
@@ -297,7 +290,18 @@ export async function guardToolCallImpl(
297
290
  // Only an accepted write becomes the task list, so task windows move
298
291
  // and read-only marker use is journaled after every gate has passed.
299
292
  if (context?.sessionID && !context.simulate) {
300
- recordTodoTaskStarts(todoTaskStarts(context.sessionID), existingTodos, newTodos, getSessionMutationCount(context.sessionID));
293
+ recordTodoTaskStarts(todoTaskStarts(context.sessionID), existingTodos, newTodos, getSessionMutationCount(context.sessionID), lifecycle.refinements);
294
+ if (lifecycle.refinements.length > 0) {
295
+ audit({
296
+ ts: new Date().toISOString(),
297
+ sessionID: context.sessionID,
298
+ tool: "todowrite",
299
+ decision: "allow",
300
+ phase: "event",
301
+ reason: "todo_refined",
302
+ input: { refinements: lifecycle.refinements.map(({ from, to }) => ({ from, to })) },
303
+ });
304
+ }
301
305
  if (readOnlyCompleted.length > 0) {
302
306
  audit({
303
307
  ts: new Date().toISOString(),
@@ -561,7 +565,7 @@ export async function guardToolCallImpl(
561
565
  // to sync (#145).
562
566
  const gitText = `git ${invocation.rest}`;
563
567
  const protectedWrite = GIT_WRITE_RE.test(gitText) || GIT_PULL_RE.test(gitText);
564
- if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir)) {
568
+ if (protectedWrite && onProtectedBranch(invocation.repoDir) && !isProtectedBranchFastForward(gitText, invocation.repoDir) && !isMergedLocalBranchDeletion(gitText, invocation.repoDir)) {
565
569
  logPolicyBlock(`[workflow-guard] blocked git write on protected branch: ${command.slice(0, 120)}`);
566
570
  return block("git", "protected_branch", branchGuardReason());
567
571
  }
@@ -687,8 +691,16 @@ export async function guardToolCallImpl(
687
691
  }
688
692
  }
689
693
  for (const invocation of gitInvocations) {
690
- if (!/\bgit\s+push\b/.test(`git ${invocation.rest}`)) continue;
691
- if (tagRefspecIn(`git ${invocation.rest}`, invocation.repoDir)) continue;
694
+ const pushText = `git ${invocation.rest}`;
695
+ if (!/\bgit\s+push\b/.test(pushText)) continue;
696
+ if (tagRefspecIn(pushText, invocation.repoDir)) continue;
697
+ // A push that only deletes remote branches already merged into the
698
+ // remote default publishes no commit. That is the remote half of the
699
+ // cleanup a merged PR requires, so neither the protected checkout nor
700
+ // the merged-current-branch rule has anything to protect. Every other
701
+ // push, including --prune, --mirror, a forced refspec, and an unmerged
702
+ // branch, stays blocked below.
703
+ if (purgesMergedRemoteBranches(pushText, invocation.repoDir)) continue;
692
704
  if (onProtectedBranch(invocation.repoDir)) {
693
705
  logPolicyBlock(`[workflow-guard] blocked push from protected branch: ${command}`);
694
706
  return block("git", "protected_branch", branchGuardReason());
package/src/lib/shell.ts CHANGED
@@ -545,7 +545,7 @@ export function splitShellSegments(command: string): string[] {
545
545
  return segments;
546
546
  }
547
547
 
548
- function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: boolean; cwdTarget?: string; assignments: string[] } {
548
+ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: boolean; cwdTarget?: string; assignments: string[]; sudo: boolean } {
549
549
  let cleanCmd = decodeShellEscapes(command.trim());
550
550
  // Strip outer grouping parentheses/braces if present e.g. ( git commit ) or { git commit; }
551
551
  while (
@@ -569,6 +569,9 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
569
569
  // assignment, and treating it as one would claim a repository that the
570
570
  // invocation never named.
571
571
  const assignments: string[] = [];
572
+ // A `sudo` wrapper is stripped before the command word, so a caller that
573
+ // needs to know the command runs privileged asks for it here.
574
+ let sudo = false;
572
575
  while (i < words.length) {
573
576
  const rawWord = words[i]!;
574
577
  const word = rawWord.replace(/^[\({]+/, "").replace(/[\)};]+$/, "");
@@ -635,6 +638,7 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
635
638
  continue;
636
639
  }
637
640
  if (word === "sudo" || word === "doas") {
641
+ if (word === "sudo") sudo = true;
638
642
  i++;
639
643
  const valueOptions = new Set([
640
644
  "-u",
@@ -747,13 +751,18 @@ function unwrapShellWordsImpl(command: string): { words: string[]; changesCwd: b
747
751
  return { words: words
748
752
  .slice(i)
749
753
  .map((w) => w.replace(/^[\({]+/, "").replace(/[\)};]+$/, ""))
750
- .filter(Boolean), changesCwd, cwdTarget, assignments };
754
+ .filter(Boolean), changesCwd, cwdTarget, assignments, sudo };
751
755
  }
752
756
 
753
757
  export function unwrapShellWords(command: string): string[] {
754
758
  return unwrapShellWordsImpl(command).words;
755
759
  }
756
760
 
761
+ /** True when a `sudo` wrapper was stripped ahead of the command word. */
762
+ export function shellHasSudoWrapper(command: string): boolean {
763
+ return unwrapShellWordsImpl(command).sudo;
764
+ }
765
+
757
766
  /**
758
767
  * The directory a wrapper (`env -C`, `sudo -D`) runs its command in, if it
759
768
  * names one. The target is left unexpanded: the caller knows the directory it
@@ -826,7 +835,7 @@ export function expandCwdTarget(target: string): string | undefined {
826
835
  }
827
836
 
828
837
  /** Words that carry no directory of their own; a control-flow body follows them. */
829
- const TRANSPARENT_PREFIX = new Set([
838
+ export const TRANSPARENT_PREFIX = new Set([
830
839
  "builtin",
831
840
  "command",
832
841
  "then",
package/src/lib/state.ts CHANGED
@@ -4,6 +4,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { audit, getDogfoodCacheFilePath, getReviewCacheFilePath, loadDogfoodCache, loadReviewCache, persistDogfoodCache, persistReviewCache, persistVerifyCache, persistVerifyHistory } from "./audit.ts";
5
5
  import { findGitRoot, getCachedProjectConfig, isSameGitRepo, loadProjectConfig, projectRootKey } from "./project-config.ts";
6
6
  import { snipVerifyOutput, getCurrentGitCommitHash, getGitStatusSummary, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint } from "./verify.ts";
7
+ import type { VerifyOutcomeFields } from "./verify.ts";
7
8
  import { normalizeLiveControlPlaneRoots } from "./live-control-plane.ts";
8
9
  import type {
9
10
  TodoSdkClient,
@@ -417,16 +418,18 @@ export function getLastVerifyResultForWorkspace(root: string): typeof lastVerify
417
418
 
418
419
  export function recordVerifyResult(
419
420
  command: string,
420
- result: { passed: boolean; output: string; durationMs?: number },
421
+ result: VerifyOutcomeFields,
421
422
  sessionID?: string,
422
423
  root = getWorkspaceRoot(),
423
424
  ): void {
424
425
  lastVerify = {
425
426
  command,
426
427
  passed: result.passed,
427
- output: snipVerifyOutput(result.output, result.passed),
428
+ output: snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : result.passed ? "passed" : "failed"),
428
429
  timestamp: Date.now(),
429
430
  durationMs: result.durationMs,
431
+ timedOut: result.timedOut === true,
432
+ timeoutMs: result.timeoutMs,
430
433
  commitHash: getCurrentGitCommitHash(root),
431
434
  gitStatus: getGitStatusSummary(root),
432
435
  workspaceRoot: projectRootKey(root),
package/src/lib/types.ts CHANGED
@@ -125,6 +125,14 @@ export interface VerifyResult {
125
125
  output: string;
126
126
  timestamp: number;
127
127
  durationMs?: number;
128
+ /**
129
+ * Set when the run was killed at its limit. The result is neither a pass nor
130
+ * a fail, so any human-readable summary of it must say "timed out" rather
131
+ * than claim a failing test.
132
+ */
133
+ timedOut?: boolean;
134
+ /** The limit that was hit, so a summary can name it at the precision it was set. */
135
+ timeoutMs?: number;
128
136
  commitHash?: string;
129
137
  gitStatus?: string;
130
138
  workspaceRoot?: string;
@@ -237,6 +245,8 @@ export interface AuditEntry {
237
245
  verification?: {
238
246
  command: string;
239
247
  passed: boolean;
248
+ /** A timed-out run is neither a pass nor a fail; the audit must not imply one. */
249
+ timedOut?: boolean;
240
250
  fresh: boolean;
241
251
  durationMs?: number;
242
252
  };
@@ -59,6 +59,7 @@ import {
59
59
  import { secretIn } from "../policies/secrets.ts";
60
60
  import { createCustomTools, buildWorkflowGuardSystemGuidance } from "./custom-tools.ts";
61
61
  import { isMutatingSurfaceTool, isReadOnlyRole, SHELL_TOOL_NAMES } from "./guard-dispatcher.ts";
62
+ import { formatTimeoutLimit } from "./verify.ts";
62
63
  import { ToolInvocationLifecycle } from "./tool-lifecycle.ts";
63
64
  import { ToolOutcomeTracker } from "./tool-outcomes.ts";
64
65
  import { EDIT_TOOL_NAMES, fetchParentSession, fetchParentSessionID, effectiveTodos } from "../policies/todo.ts";
@@ -535,7 +536,7 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
535
536
  ];
536
537
  if (lastV) {
537
538
  stateLines.push(
538
- `- Test Verification: ${lastV.passed ? "PASSED" : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
539
+ `- Test Verification: ${lastV.passed ? "PASSED" : lastV.timedOut ? `TIMED OUT within ${formatTimeoutLimit(lastV.timeoutMs)} (result unknown, not a failing test)` : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
539
540
  );
540
541
  }
541
542
  if (lastR) {
package/src/lib/verify.ts CHANGED
@@ -72,23 +72,39 @@ export function verifyCommandSource(root: string): VerifyCommandSource {
72
72
  return detectVerifyCommand(root) ? "auto-detected" : null;
73
73
  }
74
74
 
75
+ /**
76
+ * What a verification run proved. `unknown` is the timeout outcome: the command
77
+ * never finished, so it is evidence of neither passing nor failing work.
78
+ */
79
+ export type VerifyOutcome = "passed" | "failed" | "unknown";
80
+
75
81
  /**
76
82
  * Truncates and snips verification stdout/stderr for token efficiency.
77
83
  * When a test suite or compiler passes, verbose log lines are trimmed to a
78
84
  * concise summary. When it fails, failure context, error markers, and stack
79
85
  * traces are prioritized.
86
+ *
87
+ * A timed-out run gets its own label. Borrowing the passing label told the agent
88
+ * "all tests passing" about a suite that never finished, and borrowing the
89
+ * failing one invented a failure that does not exist.
80
90
  */
81
- export function snipVerifyOutput(output: string, passed: boolean, maxLines = 40): string {
91
+ export function snipVerifyOutput(output: string, outcome: VerifyOutcome, maxLines = 40): string {
82
92
  if (!output) return "(no output)";
83
93
  const lines = output.trim().split("\n");
84
94
  if (lines.length <= maxLines) return output.trim();
85
95
 
86
- if (passed) {
87
- const head = lines.slice(0, 5).join("\n");
96
+ const head = lines.slice(0, 5).join("\n");
97
+
98
+ if (outcome === "passed") {
88
99
  const tail = lines.slice(-15).join("\n");
89
100
  return `${head}\n... [${lines.length - 20} lines omitted - all tests passing] ...\n${tail}`;
90
101
  }
91
102
 
103
+ if (outcome === "unknown") {
104
+ const tail = lines.slice(-20).join("\n");
105
+ return `${head}\n... [${lines.length - 25} lines omitted - outcome unknown, the run did not finish] ...\n${tail}`;
106
+ }
107
+
92
108
  const errorLines: string[] = [];
93
109
  for (const line of lines) {
94
110
  if (/(?:fail|error|exception|panic|assert|reject|expected|received|err:)/i.test(line)) {
@@ -96,7 +112,6 @@ export function snipVerifyOutput(output: string, passed: boolean, maxLines = 40)
96
112
  }
97
113
  }
98
114
 
99
- const head = lines.slice(0, 5).join("\n");
100
115
  const tail = lines.slice(-20).join("\n");
101
116
  const errorSummary = errorLines.slice(-15).join("\n");
102
117
 
@@ -250,6 +265,22 @@ export function resolveVerifyTimeoutMs(root: string): number {
250
265
  return typeof configured === "number" && Number.isFinite(configured) && configured > 0 ? configured : 30_000;
251
266
  }
252
267
 
268
+ /**
269
+ * Render a verification timeout limit for anything the agent reads.
270
+ *
271
+ * Sub-second limits are exercised by tests, and a bare `Math.round(ms/1000)`
272
+ * reports those as "0s", which reads as no limit at all. Both the block reason
273
+ * and the timed-out output tail render through here so they cannot disagree.
274
+ *
275
+ * The non-finite fallback is defensive only: `timedOut`/`timeoutMs` are set in
276
+ * one place, from the same argument Node coerced into a valid timer delay, so a
277
+ * real timeout always carries a finite positive value here.
278
+ */
279
+ export function formatTimeoutLimit(timeoutMs: number | undefined): string {
280
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return "the verification timeout";
281
+ return timeoutMs < 1000 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1000)}s`;
282
+ }
283
+
253
284
  export interface VerifyRun {
254
285
  passed: boolean;
255
286
  output: string;
@@ -265,6 +296,13 @@ export interface VerifyRun {
265
296
  timeoutMs?: number;
266
297
  }
267
298
 
299
+ /**
300
+ * The part of a verification run that gets recorded as evidence. `timeoutMs`
301
+ * travels with `timedOut` so a summary can name the limit at its own precision
302
+ * instead of guessing at it.
303
+ */
304
+ export type VerifyOutcomeFields = Pick<VerifyRun, "passed" | "output" | "timedOut" | "timeoutMs"> & { durationMs?: number };
305
+
268
306
  export async function runVerify(
269
307
  command: string,
270
308
  root: string,
@@ -326,7 +364,7 @@ export async function runVerify(
326
364
  void terminateProcessTree(child.pid, () => child.kill("SIGKILL")).finally(() => {
327
365
  resolve({
328
366
  passed: false,
329
- output: output + `\n(Verification timed out after ${Math.round(timeoutMs / 1000)}s)`,
367
+ output: output + `\n(Verification timed out after ${formatTimeoutLimit(timeoutMs)})`,
330
368
  durationMs: Date.now() - start,
331
369
  timedOut: true,
332
370
  timeoutMs,
@@ -2,7 +2,7 @@ import { isEvidenceFresh, verificationEvidence } from "../lib/evidence.ts";
2
2
  import { projectRootKey } from "../lib/project-config.ts";
3
3
  import { getWorkspaceRoot, sessionVerifyResults, lastVerify, sessionMutationTimestamps, lastMutationTimestamp } from "../lib/state.ts";
4
4
  import type { VerifyResult } from "../lib/types.ts";
5
- import { getCurrentGitCommitHash, getGitWorktreeFingerprint } from "../lib/verify.ts";
5
+ import { getCurrentGitCommitHash, formatTimeoutLimit, getGitWorktreeFingerprint } from "../lib/verify.ts";
6
6
 
7
7
  /**
8
8
  * Claims-vs-evidence check (Policy 24): when the assistant's final text
@@ -26,7 +26,7 @@ const VERIFICATION_FRESH_WINDOW_MS = 120_000;
26
26
  export interface CompletionClaimCheck {
27
27
  claimsCompletion: boolean;
28
28
  claim?: string;
29
- evidenceState?: "fresh-pass" | "stale-pass" | "failing" | "missing";
29
+ evidenceState?: "fresh-pass" | "stale-pass" | "failing" | "timed-out" | "missing";
30
30
  reason?: string;
31
31
  }
32
32
 
@@ -61,7 +61,10 @@ export function checkCompletionClaims(
61
61
  evidenceState =
62
62
  context?.sessionID && mutationTimestamp > 0 ? "stale-pass" : "missing";
63
63
  } else if (!verifyResult.passed) {
64
- evidenceState = "failing";
64
+ // A timed-out run proved nothing. Filing it under "failing" tells the
65
+ // reader an assertion broke, which is the misattribution Policy 10 now
66
+ // avoids everywhere else.
67
+ evidenceState = verifyResult.timedOut === true ? "timed-out" : "failing";
65
68
  } else if (
66
69
  !isEvidenceFresh(verificationEvidence(verifyResult, context?.sessionID), {
67
70
  workspace: projectRootKey(getWorkspaceRoot()),
@@ -84,6 +87,7 @@ export function checkCompletionClaims(
84
87
  missing:
85
88
  "the response asserts completion/verification, but no verification evidence has been recorded in this session.",
86
89
  failing: `the response asserts completion, but the latest verification (${verifyResult?.command}) FAILED.`,
90
+ "timed-out": `the response asserts completion, but the latest verification (${verifyResult?.command}) did not finish within ${formatTimeoutLimit(verifyResult?.timeoutMs)}, so its result is unknown rather than failing.`,
87
91
  "stale-pass":
88
92
  "the response asserts completion, but the last passing verification is stale - mutations were recorded after it.",
89
93
  "fresh-pass": "",