opencode-workflow-guard 1.19.2 → 1.19.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/installation.md +16 -0
- package/docs/policies.md +5 -4
- package/docs/testing.md +6 -2
- package/docs/troubleshooting.md +3 -2
- package/package.json +6 -6
- package/src/lib/custom-tools.ts +32 -4
- package/src/lib/guard-dispatcher.ts +28 -14
- package/src/lib/project-config.ts +5 -0
- package/src/lib/types.ts +8 -0
- package/src/lib/v2-plugin.ts +44 -3
- package/src/lib/verify.ts +19 -0
- package/src/policies/boundary.ts +128 -7
- package/src/policies/continuation.ts +66 -2
- package/src/policies/file-claims.ts +61 -15
- package/src/policies/interpreter.ts +6 -2
- package/src/workflow-guard.ts +13 -1
- package/test/test-e2e.mts +20 -4
- package/test/test.mts +278 -17
package/docs/installation.md
CHANGED
|
@@ -231,6 +231,8 @@ Workflow Guard enforces secondary review approval (`requireReview`) by default d
|
|
|
231
231
|
|
|
232
232
|
The recorded verdict binds to the reviewed repository content: the commit hash and the tracked-content worktree fingerprint of the directory it was recorded against. The PR preflight accepts any approval whose binding matches the tree the PR would publish. A review recorded by a subagent rooted in a linked git worktree therefore satisfies a `pr create` run from that worktree. That holds even from a different session than the one that spawned the reviewer. Review freshness is scoped to tracked content. Deleting an untracked scratch file does not invalidate an approval, and any tracked edit or new commit does. Reviewer agents are frequently configured with read-only toolsets that exclude `record_review`. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's directory. The audit trail records who recorded it and where it is bound.
|
|
233
233
|
|
|
234
|
+
`record_review` is registered for every session, independent of `requireReview`. A host with a per-agent permission list can still withhold the call, and an agent that starts from a deny-all list must carry its own explicit allow for `record_review`. The guard cannot widen host permissions, so `guard_status` reporting the gate as required proves nothing about a given reviewer's toolset. Grant the tool in that agent's definition, or relay the verdict through a session that already has it.
|
|
235
|
+
|
|
234
236
|
To opt out of the PR secondary review gate for a project, set `requireReview: false` in `.opencode/workflow-guard.json`:
|
|
235
237
|
|
|
236
238
|
```json
|
|
@@ -245,6 +247,20 @@ For stricter environments, set `requireSubagentReview: true` in `.opencode/workf
|
|
|
245
247
|
|
|
246
248
|
---
|
|
247
249
|
|
|
250
|
+
## File-Claim Expiry
|
|
251
|
+
|
|
252
|
+
Direct edits claim each file for the tool-call lifetime so two sessions cannot race it. A leaked claim is reclaimed by two audited rules: the owner's recorded idle timestamp, and a claim TTL. The TTL covers a deleted session or a server restart, where the owner record cannot be read at all. It defaults to five minutes. Set `claimTtlMs` to raise or lower it:
|
|
253
|
+
|
|
254
|
+
```json
|
|
255
|
+
{
|
|
256
|
+
"claimTtlMs": 600000
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default, so a typo cannot disable expiry. A reclaim is journaled as `claim_ttl_expired` with the owner and claim age.
|
|
261
|
+
|
|
262
|
+
---
|
|
263
|
+
|
|
248
264
|
## Pre-Deployment Dogfood Gate
|
|
249
265
|
|
|
250
266
|
Policy 27 gates PR creation on a recorded run of the change on real hardware. It is **off by default**, because a gate is only meaningful once a repository has a runner that can produce a real run. Enable it after that runner exists:
|
package/docs/policies.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
On OpenCode 1.x those hooks are `tool.execute.before`, `experimental.session.compacting`, `shell.env`, `permission.ask`, and `event` journaling. On OpenCode 2.x they are `tool.hook("execute.before"/"execute.after")`, `session.hook("context"/"compaction"/"prompt")`, `command.transform`, `permission.hook("evaluate")`, `shell.hook("create.before")`, and `event.subscribe()`. V1 plugin implementations do not run on OpenCode 2. The two lists therefore describe separate entrypoints, not alternatives for the same host.
|
|
6
6
|
|
|
7
|
-
**A V2 event handler runs only if the host delivers its type.** `ctx.event.subscribe()` is served from `EventManifest.ServerDefinitions`. A type that appears in `EventManifest.Definitions` but not in `ServerDefinitions` is never delivered, so a handler for it is dead code even though it compiles and looks live. Check every `event.type` comparison against that manifest before relying on it. The test suite enforces
|
|
7
|
+
**A V2 event handler runs only if the host delivers its type.** `ctx.event.subscribe()` is served from `EventManifest.ServerDefinitions`. A type that appears in `EventManifest.Definitions` but not in `ServerDefinitions` is never delivered, so a handler for it is dead code even though it compiles and looks live. Check every `event.type` comparison against that manifest before relying on it. The subscription also passes the `types` filter, so only those types cross the stream at all. The test suite enforces both structurally: a scan of `src/lib/v2-plugin.ts` asserts every compared literal is delivered, and that `V2_EVENT_TYPES` matches the handler's comparisons in both directions.
|
|
8
8
|
|
|
9
9
|
This is a policy and enforcement layer, not an agent harness. Policies may constrain actions, record or explain decisions, and preserve bounded context. They do not plan, prioritize, delegate, or autonomously sequence work. Where Workflow Guard resumes an idle session, it only enforces already-owned todo lifecycle state. It does not choose what the agent works on next.
|
|
10
10
|
|
|
@@ -26,7 +26,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
26
26
|
- **Handoff Safety:** An idle subagent whose effective todos are inherited from its parent is not auto-continued. Inherited work belongs to the parent and can be handed back normally.
|
|
27
27
|
- **Durable Planning Context Discovery:** `guard_next_tasks` prefers a repository-root `TODO.md`. When it is absent, it reads conventional `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and Markdown files under `docs/plans/`. The tool exposes candidate planning context without selecting, prioritizing, or sequencing tasks. These files never replace OpenCode's native runtime todo state.
|
|
28
28
|
- **Subagent Mutation Budget:** Subagent sessions are protected by a mutation safety budget (`maxSubagentMutations` in project config or `WORKFLOW_GUARD_MAX_SUBAGENT_MUTATIONS` env, default 100). The budget terminates runaway edit loops deterministically.
|
|
29
|
-
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed.
|
|
29
|
+
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed. Two provable staleness rules reclaim a leaked claim, each audited, and both stay scoped to the contended paths so a long-running command elsewhere keeps its claim. The idle rule releases a claim created before its owner's last recorded idle timestamp, because that call finished before the turn ended. It writes a `stale_claim_takeover` entry. The TTL rule releases a claim older than the effective claim TTL, which covers a deleted session and a server restart where the owner record cannot be read at all. It writes a `claim_ttl_expired` entry with the owner and claim age. The TTL defaults to five minutes, is raised or lowered with `claimTtlMs` in `.opencode/workflow-guard.json`, and `WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default. Owners still mid-session within the TTL, clients without a session lookup, and failed lookups keep the block (fail-closed). The block names the owner, the claim age, and the reclaim step. `guard_why` stays read-only and still reports the conflict as blocked. Shell writers are not covered, and isolated worktrees remain the better choice for substantial parallel mutations.
|
|
30
30
|
- **Stale-Write Protection:** A successful `read` records a same-session fingerprint for an existing regular file from five fields. Those fields are canonical path, filesystem identity, size, nanosecond mtime, and SHA-256 content digest. A successful `edit`/`write` also records the resulting bytes, and only when the file actually changed. The session authored those bytes, so iterating on a just-created or just-modified file needs no redundant re-read. Before `edit` or `write` replaces an existing file, that fingerprint must exist and still match. Otherwise the call is blocked and must re-read. New-file creation is allowed without a prior read. Fingerprints are not inherited between parent and subagent sessions, and they are cleared on session idle or deletion. `apply_patch` and shell writers sit deliberately outside this bounded mechanism. An `apply_patch` result still seeds the session observation, but its clobbering itself is not pre-checked. The pre-execution comparison also cannot make external changes between the check and OpenCode's write atomic.
|
|
31
31
|
- **Shell-redirect seeding:** An allowed shell command that redirects into a workspace file (`cmd > file`, `cmd >> file`, fd forms) seeds the session's observation of the resulting bytes. It does so in the same change-gated way as direct edits. A file this session just created or rewrote via a shell redirect can therefore be edited without a redundant re-read. Redirects to `/dev/null`, the `/tmp/opencode` scratch directory, or outside the workspace seed nothing. An identical-byte (no-op) redirect does not seed. The not-read block message also suggests coordinating when another session may own the file. Shell writers themselves remain outside the bounded pre-check, so only the observation seeding applies.
|
|
32
32
|
|
|
@@ -89,7 +89,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
89
89
|
### 8. Workspace Boundary Guard
|
|
90
90
|
- File modification tools (`edit`, `write`, `apply_patch`) and recognized shell mutations are validated so detected targets cannot escape the current workspace root. The recognized shell mutations are redirection `>`, `>>`, `&>`, `>&`, `tee`, `sed -i`, `cp`/`mv`/`ln`, `touch`, `mkdir`, `rm`, `truncate`, `dd of=`, `git apply`, and `git am`. The check covers `../` traversal, symlinks, absolute paths, and shell expansions (`~`, `~user`, `$HOME`). Unresolvable `$VARIABLE` references fail closed. This is command-level enforcement, not filesystem sandboxing. Arbitrary programs and dynamically computed paths require the OS isolation described under Known Limits. Another user's home cannot be read portably, so `~user` is guessed as the name joined onto this home's parent. A workspace rooted at that parent therefore contains the guess. Keep the workspace below the home directory, which is the usual layout, and the guess stays outside it.
|
|
91
91
|
- **Unresolvable variable cause attribution:** A target containing an unresolvable `$VARIABLE` reference is indeterminate without executing shell semantics. Examples are `mkdir -p $D/sub` and `> $CACHE/out.txt`. The guard therefore treats it as outside the workspace. The block message says so ("contains an unresolvable variable reference … use a literal workspace-relative path") instead of showing the generic escape message. Deterministically expandable forms (`~`, `~user`, `$HOME`, `${HOME}`) keep the generic message. Cache-path and other literal destinations inside the workspace are unaffected. A git repository selection is judged the same way: `git -C $OTHER_REPO commit` stays a boundary block even when the shell's own workspace is a repository. The same-repository exemption that admits linked worktrees resolves the nearest existing ancestor, so an indeterminate value there would otherwise read as the workspace's own root, and the write would look local. Known limit: another user's home is not readable portably, so `~user` joins the name onto this home's parent. A workspace rooted at that parent therefore contains the guessed path, and a `~user`-relative mutation there is judged local. Keep the workspace root below the home directory, which is the normal layout, and this guess lands outside it.
|
|
92
|
-
- **Scratch-directory
|
|
92
|
+
- **Scratch-directory allowance:** `/tmp/opencode` is the environment's designated agent scratch space. A write there is allowed for a real session and only while the target's canonical location stays inside that exact directory. The root itself must be a real directory rather than a symlink. A symlink inside it that leaves the directory is refused with a message naming the scratch allowance, and a sibling that merely shares the prefix and a `..` traversal out of it stay blocked. A write with no session id is also blocked. The issue is a file-mutation allowance only. It does not change execution policy, task-completion evidence, or the feature-branch requirement, and it does not widen the workspace boundary anywhere else.
|
|
93
93
|
- **Symlink-alias acceptance:** A target whose lexical path falls outside the workspace root but whose canonical resolution is inside it is accepted. One example is `/home/<user>/...` on hosts where `/home` is a symlink into `/var/home` and the workspace root lives under `/var/home`. A target stays blocked whenever the canonical resolution is outside the canonicalized root. That includes symlinks inside the workspace that point outside, and not-yet-created files under them (nearest existing ancestor). When canonicalization is indeterminate, the lexical verdict stands (fail closed). A path is outside the workspace only when both its lexical and its canonical resolution are outside.
|
|
94
94
|
- `tee` flag parsing generically skips option flags (`-a`, `--append`, `-ai`, `--`) and validates all specified target files against the boundary.
|
|
95
95
|
- Embedded non-shell comparisons are not mutations. A bare `>` whose target is purely numeric (`WHERE count > 5`, awk `$3 > 100`) and `>=` or `==` operators are treated as comparison operands, not redirects. Real redirects are unaffected (`> src/a.ts`, `>>`, `&>`, `>&`, and fd targets like `/dev/null` still follow their existing rules).
|
|
@@ -113,7 +113,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
113
113
|
- 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.
|
|
114
114
|
- 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.
|
|
115
115
|
- 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.
|
|
116
|
-
- 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.
|
|
116
|
+
- 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.
|
|
117
117
|
- **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.
|
|
118
118
|
- **Untracked Special Entries:** The worktree fingerprint binds untracked symlinks by their target string. It follows git semantics, so re-pointing a link moves the fingerprint and changing the link target's contents does not. FIFOs and sockets are bound by path and mode. Unopenable entries are skipped with a `worktree-fingerprint` warning in the audit trail instead of voiding the whole fingerprint. One unreadable scratch symlink or `chmod 000` file can no longer make review or verification evidence permanently unfresh. The PR preflight names the actual cause when an approval cannot be matched: no fingerprint binding, fingerprint mismatch, or uncomputable fingerprint. It no longer shows the generic "review approval required". Documented tradeoff: the contents of a skipped entry are excluded from the fingerprint. A file that stays unreadable to the guard's user across the entire window can therefore change contents without moving the fingerprint. Any readability transition is fingerprint-visible (fail-closed), and each skip is named in the durable audit trail.
|
|
119
119
|
- **Durable Disk Cache:** Passing verification results (`~/.local/state/opencode/workflow-guard/last-verify.json`) and passing secondary review approvals (`~/.local/state/opencode/workflow-guard/last-review.json`) are cached to disk. Session restarts and multi-agent handoffs can therefore retain valid verification and review evidence without redundant test runs. Durable evidence is **workspace-bound**: a cached result is only accepted for the workspace that produced it. A passing run in one project can never satisfy finalization in another.
|
|
@@ -256,6 +256,7 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
|
|
|
256
256
|
|
|
257
257
|
### Hook-Context Safety
|
|
258
258
|
- All spawned git commands run with a sanitized environment. Inherited git context variables (`GIT_INDEX_FILE`, `GIT_DIR`, `GIT_WORK_TREE`, and others) are stripped, so the tools resolve the repository from their working directory alone. This makes them safe to invoke from inside git hooks, which export those variables.
|
|
259
|
+
- **Abort propagation:** The two hosts name the per-call abort signal differently. OpenCode 2's promise-layer tool context supplies `signal`, and OpenCode 1's supplies `abort`. The long-running guard tools that spawn subprocesses (`guard_worktree_create`, `guard_worktree_cleanup`, `guard_review_rubric`, `guard_recovery_restore`) read either one before starting work, so a call whose session was interrupted before it started returns a `Cancelled` result instead of running to its own timeout. The check runs before the work rather than during it, because `spawnSync` cannot observe an abort mid-flight. Short git-backed reads (`guard_status`, `record_review`, `record_dogfood`, `project_memory_record`) are deliberately out of scope: their subprocesses are bounded by a five-second timeout and cannot strand a session.
|
|
259
260
|
|
|
260
261
|
### Inspection Tools
|
|
261
262
|
### `guard_status`
|
package/docs/testing.md
CHANGED
|
@@ -26,6 +26,8 @@ WORKFLOW_GUARD_LIVE_E2E=1 npm run test:install # also run model-driven policy pr
|
|
|
26
26
|
```
|
|
27
27
|
Package and loader checks remain deterministic. Live probes explicitly select the first entry in OpenCode's persisted recent-model state (`${XDG_STATE_HOME:-~/.local/state}/opencode/model.json`). They never silently inherit the configured default model. Set `WORKFLOW_GUARD_LIVE_MODEL=provider/model` to override that selection. Provider credentials still come from the normal OpenCode environment. A provider may reject a live prompt before guard behavior can run. That happens when credits, rate limits, capacity, overload, or an unresolvable model make the provider unavailable. Such a case is reported as unavailable rather than as a guard failure. The classifier matches the host's literal `Model unavailable:` error line rather than the bare phrase, so model prose cannot mask a real guard regression. Other live-runtime failures still fail the suite.
|
|
28
28
|
|
|
29
|
+
The suite needs a temp directory with room for a full `node_modules` copy. On a host whose `os.tmpdir()` is a small tmpfs, a nearly full one fails `npm pack` and `npm install` with `Unknown system error -122` (`EDQUOT`). Point `TMPDIR` at a filesystem-backed directory in that case, for example `TMPDIR=/var/tmp npm run test:install`. The harness stops every managed service it starts before removing its temporary project, so a run no longer leaves a detached server writing into the directory it is deleting.
|
|
30
|
+
|
|
29
31
|
### 4. Full Verification Suite
|
|
30
32
|
Runs typecheck, unit tests, and live runtime installation tests in sequence:
|
|
31
33
|
```bash
|
|
@@ -46,8 +48,10 @@ npm run test:all
|
|
|
46
48
|
| **Policy 4: Live Commands** | Verifies destructive CLI command blocking across Kubernetes, Terraform, Helm, cloud CLIs, and databases, plus user-set `WORKFLOW_GUARD_ALLOW_LIVE=1` override. |
|
|
47
49
|
| **Policy 5: MCP Mutations** | Verifies GitHub/Azure mutating MCP tools are blocked while read-only tools pass. |
|
|
48
50
|
| **Policy 6: Settings Tamper** | Verifies protection of `opencode.json`, `~/.config/opencode/*`, and `opencode auth`. |
|
|
49
|
-
| **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. |
|
|
50
|
-
| **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. |
|
|
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, and attributes the effective verify command to `project-config`, `auto-detected`, or neither. |
|
|
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
|
+
| **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. |
|
|
51
55
|
| **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
|
|
52
56
|
| **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
|
|
53
57
|
| **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
|
package/docs/troubleshooting.md
CHANGED
|
@@ -112,7 +112,8 @@ After the command reports `Detected server + tui targets`, confirm it reports re
|
|
|
112
112
|
- **Diagnosis:** `guard_audit` records the binding key on every `record_review.verdict` entry. The key covers workspace, commit hash, fingerprint prefix, recorder session, and `recorderRole`. It also records a `pr-preflight.review-binding` entry when a PR preflight accepts a review. A verdict that cannot bind at all is rejected loudly with the reason instead of returning a success string. That case is a directory that is not a git repository.
|
|
113
113
|
- **Strict recorder mode rejects the approval:** Projects with `requireSubagentReview: true` (or `WORKFLOW_GUARD_REQUIRE_SUBAGENT_REVIEW=1`) reject `record_review` approval verdicts recorded by the root session. The message reads "this project requires approvals to be recorded from a subagent session", and the `guard_audit` entry carries reason `subagent_recorder_required`. Record the verdict from a subagent session (one with a parent session) instead, or disable the requirement in project config. Changes-requested verdicts remain relayable from any session. The knob is enforced when verdicts are recorded. An approval recorded by the root session before the requirement was enabled still satisfies the PR preflight until its content binding goes stale. That includes durable review-cache evidence recovered after a restart. Re-run the secondary review after adopting the knob to re-bind it.
|
|
114
114
|
- **Worktree creation failure leaving a branch behind:** `guard_worktree_create` failures previously surfaced only git's stderr. That output is often just checkout progress, and the failure could leave a half-created branch. Failures now report git's exit status, and the created branch is rolled back. Pre-existing branches are preserved. Stale worktree admin entries are pruned only for the newly-created path. A live registered worktree whose sanitized name collides with the requested branch is left fully intact, because rollback never removes pre-existing worktrees. Large checkouts that exceed the 15s timeout can raise it with `WORKFLOW_GUARD_WORKTREE_TIMEOUT_MS`.
|
|
115
|
-
- **Edit blocked by
|
|
115
|
+
- **Edit blocked by a file claim though no other session is working:** A missed `session.idle` release, a deleted session, or a server restart can leave a finished session's direct-edit claim behind. Two provable staleness rules reclaim it, each audited. A claim created before its owner's last recorded idle timestamp is provably stale and is released with a `stale_claim_takeover` entry in `guard_audit`. A claim older than the effective TTL is released even when the owner record cannot be read, with a `claim_ttl_expired` entry that names the owner and claim age. The TTL defaults to five minutes. Raise or lower it with `claimTtlMs` in `.opencode/workflow-guard.json`, or `WORKFLOW_GUARD_CLAIM_TTL_MS` (the environment wins). A non-positive or unparseable value falls back to the default. The block message names the owner, the claim age, and the reclaim step. Owners still mid-turn within the TTL keep their claim. The takeover fails closed without an SDK session lookup, and when the lookup fails. `guard_why` remains read-only and still reports the conflict.
|
|
116
116
|
- **You updated the plugin but the old version still loads:** A configured bare package name is resolved through Node's parent-directory lookup from OpenCode's configuration location. A copy in any parent `node_modules` (a pnpm-managed home directory or a manual install) shadows OpenCode's own plugin cache and a global `npm install -g`. OpenCode's own update check can then fail with only a server-log record (`NpmInstallFailedError`). Verify what actually loaded with `guard_status` (the `pluginVersion` field), the startup app-log line (`Workflow Guard v<version> plugin initialized ...`), or the server log's `loading plugin ... entrypoint=file:///...` record. Then update the resolved copy in place (for a pnpm-managed home directory: `cd ~ && pnpm add opencode-workflow-guard@<version>`). Run `opencode service restart`, because the plugin loads in the background service and restarting only the TUI does not reload it.
|
|
117
117
|
- **A benign-looking command with a shell variable is blocked as "outside the workspace":** A mutation or redirect target that contains an unresolvable `$VARIABLE` reference is indeterminate without executing shell semantics. Examples are `mkdir -p $D/sub`, `cp a.txt "$D/b.txt"`, and `> $CACHE/out.txt`. The boundary fails closed on indeterminate destinations. The block message names this cause: "contains an unresolvable variable reference … use a literal workspace-relative path". Deterministically expandable forms (`~`, `$HOME`) and literal paths inside the workspace are unaffected. Reads, including cache-path reads, are not gated. Replace the variable with a literal workspace-relative path in the command. Alternatively, assign it inside a script file within the workspace that the boundary has already validated. Resolving the variable would need shell execution, which the boundary deliberately avoids.
|
|
118
|
-
- **A scratch write to `/tmp/opencode` is blocked:**
|
|
118
|
+
- **A scratch write to `/tmp/opencode` is blocked:** A write there is allowed for a real session when the target's canonical location stays inside that exact directory. The root must be a real directory, not a symlink. A symlink inside it that leaves the directory is refused, and so is a sibling path that merely shares the prefix or a `..` traversal out of it. A write with no session id is also blocked. Use a real path under `/tmp/opencode` or an untracked file inside the workspace, for example `.tmp-notes.md`. The allowance is a file-mutation allowance only, and the boundary has no override for anything outside it.
|
|
119
|
+
- **A reviewer agent cannot call `record_review`:** The guard registers `record_review` for every session, independent of `requireReview`. A host with a per-agent permission list can still withhold the call, and a reviewer agent that starts from a deny-all list (`action: "*"`, `resource: "*"`, `effect: deny`) does exactly that. The guard cannot inject the tool past host permissions, so grant it in that agent's own frontmatter with an explicit allow rule for `record_review`, or relay the verdict through a session that already has the tool. `guard_status` reporting the review gate as required proves nothing about the reviewer's toolset. This is a permission grant in the agent definition, not a guard policy change.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-workflow-guard",
|
|
3
|
-
"version": "1.19.
|
|
3
|
+
"version": "1.19.4",
|
|
4
4
|
"description": "Deterministic workflow and safety policy enforcement for OpenCode",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -50,15 +50,15 @@
|
|
|
50
50
|
"prepublishOnly": "npm run typecheck"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@opencode-ai/plugin": "1.19.
|
|
54
|
-
"@opencode/ai": "2.2.
|
|
55
|
-
"@opencode/plugin": "2.2.
|
|
56
|
-
"@opentui/solid": "0.
|
|
53
|
+
"@opencode-ai/plugin": "1.19.5",
|
|
54
|
+
"@opencode/ai": "2.2.5",
|
|
55
|
+
"@opencode/plugin": "2.2.5",
|
|
56
|
+
"@opentui/solid": "0.8.1",
|
|
57
57
|
"jsonc-parser": "3.3.1"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@changesets/cli": "3.0.3",
|
|
61
|
-
"@types/node": "26.6.
|
|
61
|
+
"@types/node": "26.6.6",
|
|
62
62
|
"typescript": "7.0.2"
|
|
63
63
|
},
|
|
64
64
|
"overrides": {
|
package/src/lib/custom-tools.ts
CHANGED
|
@@ -41,8 +41,8 @@ import {
|
|
|
41
41
|
} from "./state.ts";
|
|
42
42
|
import { getRalphOutcome } from "../policies/continuation.ts";
|
|
43
43
|
import { todoEvidenceReport } from "../policies/todo.ts";
|
|
44
|
-
import { findGitRoot, loadProjectConfig, projectRootKey } from "./project-config.ts";
|
|
45
|
-
import { detectVerifyCommand, getCurrentGitCommitHash, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint } from "./verify.ts";
|
|
44
|
+
import { existingProjectConfigPath, findGitRoot, loadProjectConfig, projectRootKey } from "./project-config.ts";
|
|
45
|
+
import { detectVerifyCommand, getCurrentGitCommitHash, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint, verifyCommandSource } from "./verify.ts";
|
|
46
46
|
import { evaluateDogfoodGate } from "./dogfood.ts";
|
|
47
47
|
import { buildReviewRubric } from "./review.ts";
|
|
48
48
|
import { createGitWorktree, cleanupGitWorktree, validateHostWorktreeDirectory } from "./worktree.ts";
|
|
@@ -132,6 +132,25 @@ export function buildWorkflowGuardSystemGuidance(options: {
|
|
|
132
132
|
return sections.join("\n");
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
/** Message a tool returns when its session was interrupted mid-call. */
|
|
136
|
+
const ABORTED_MESSAGE = "[workflow-guard] Cancelled: the session was interrupted before this tool finished.";
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Stop before starting cancellable work when the session is gone.
|
|
140
|
+
*
|
|
141
|
+
* The two hosts name the abort signal differently. OpenCode 2's promise-layer
|
|
142
|
+
* `ToolContext` adds `signal`, and OpenCode 1's `ToolContext` carries `abort`,
|
|
143
|
+
* so both are read and either one cancels the call. A subprocess spawned with
|
|
144
|
+
* `spawnSync` cannot observe an abort mid-flight, so the check is placed before
|
|
145
|
+
* the work rather than during it: a call that has not started yet is cancelled,
|
|
146
|
+
* and one already running finishes and reports normally.
|
|
147
|
+
*/
|
|
148
|
+
function abortedMessage(toolContext: unknown): string | undefined {
|
|
149
|
+
const signals = toolContext as { signal?: AbortSignal; abort?: AbortSignal } | undefined;
|
|
150
|
+
const aborted = signals?.signal?.aborted || signals?.abort?.aborted;
|
|
151
|
+
return aborted ? ABORTED_MESSAGE : undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
135
154
|
export function createCustomTools(options: {
|
|
136
155
|
effectiveRoot: string;
|
|
137
156
|
projectMemoryEnabled: boolean;
|
|
@@ -168,7 +187,7 @@ export function createCustomTools(options: {
|
|
|
168
187
|
// an instance-derived root must never re-anchor another session's tool
|
|
169
188
|
// execution.
|
|
170
189
|
const resolveCallWorkspace = async (
|
|
171
|
-
toolContext: { sessionID?: string; worktree?: string; directory?: string } | undefined,
|
|
190
|
+
toolContext: { sessionID?: string; worktree?: string; directory?: string; signal?: AbortSignal } | undefined,
|
|
172
191
|
explicitDirectory?: string,
|
|
173
192
|
): Promise<string> => {
|
|
174
193
|
if (explicitDirectory) {
|
|
@@ -187,6 +206,8 @@ export function createCustomTools(options: {
|
|
|
187
206
|
description: "Restore this root session's workspace to its pre-run recovery checkpoint. Refuses if the run has not gone idle or if the workspace changed after that boundary.",
|
|
188
207
|
args: { run: tool.schema.number() },
|
|
189
208
|
execute: async (args, toolContext) => {
|
|
209
|
+
const cancelled = abortedMessage(toolContext);
|
|
210
|
+
if (cancelled) return cancelled;
|
|
190
211
|
if (!Number.isInteger(args.run) || args.run < 1) return "[workflow-guard] Recovery rejected: run must be a positive integer.";
|
|
191
212
|
const parent = await fetchParentSession(toolContext.sessionID);
|
|
192
213
|
if (!parent.ok) return "[workflow-guard] Recovery rejected: could not confirm this is a root session.";
|
|
@@ -280,6 +301,7 @@ export function createCustomTools(options: {
|
|
|
280
301
|
const verifyEvidence = lastV ? verificationEvidence(lastV) : undefined;
|
|
281
302
|
const reviewEvidenceRecord = lastR ? reviewEvidence(lastR) : undefined;
|
|
282
303
|
const verifyCommand = detectVerifyCommand(root);
|
|
304
|
+
const verifySource = verifyCommandSource(root);
|
|
283
305
|
const verifyFresh = Boolean(lastV && verifyEvidence && lastV.passed && lastV.command === verifyCommand && isEvidenceFresh(verifyEvidence, subject, lastMut));
|
|
284
306
|
const reviewRequired = isReviewRequired(root);
|
|
285
307
|
// Review freshness is content-scoped, matching the PR preflight:
|
|
@@ -324,7 +346,7 @@ export function createCustomTools(options: {
|
|
|
324
346
|
}
|
|
325
347
|
const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
|
|
326
348
|
const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
|
|
327
|
-
return JSON.stringify({ pluginVersion: loadedPluginVersion() ?? null, qualifiedHostVersion: qualifiedHostVersion() ?? null, hostVersion: hostVersion?.() ?? null, workspaceRoot: root, branch, onProtectedBranch: isProtected, todoCapability: todoCapability ? todoCapability() : "available", taskEvidence, outstandingRequirements, recommendedActions, lastMutationTimestamp: lastMut, mutationCount: getWorkspaceMutationCount(root), lastVerify: lastV && verifyEvidence ? { command: lastV.command, passed: lastV.passed, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash } : null, lastReview: lastR && reviewEvidenceRecord ? { reviewer: lastR.reviewer, passed: lastR.passed, summary: lastR.summary, fresh: reviewFresh, evidenceId: reviewEvidenceRecord.id } : null, lastDogfood: lastD && lastDogfoodEvidence ? { scenarioId: lastD.scenarioId, verdict: lastD.verdict, host: lastD.host.label, taxonomyClass: lastD.taxonomyClass ?? null, runCount: lastD.runCount, fresh: dogfoodGate.required ? dogfoodFresh : null, evidenceId: lastDogfoodEvidence.id, missingHosts: dogfoodGate.missingHosts, coveredHosts: (dogfoodGate.matchedRecords ?? []).map((record) => record.host.label) } : null, ralph: { enabled: isRalphModeEnabled(root), maxIterations: getRalphMaxIterations(root), outcome: ralphOutcome ?? null }, projectConfig: { profile: getOperationProfile(root), protectedBranches: cfg.protectedBranches ?? ["main", "master"], verifyCommand: verifyCommand ?? null, requireReview: reviewRequired, requireDocumentation: documentationRequired, requireSubagentReview: isSubagentReviewRequired(root), requireDogfood: dogfoodGate.required, dogfoodDeployMatrix: dogfoodGate.required ? getDogfoodDeployMatrix(root) : [], recoveryCheckpoints: isRecoveryCheckpointsEnabled(root) }, gitHygiene: gitHygieneSnapshot(root) ?? null }, null, 2);
|
|
349
|
+
return JSON.stringify({ pluginVersion: loadedPluginVersion() ?? null, qualifiedHostVersion: qualifiedHostVersion() ?? null, hostVersion: hostVersion?.() ?? null, workspaceRoot: root, branch, onProtectedBranch: isProtected, todoCapability: todoCapability ? todoCapability() : "available", taskEvidence, outstandingRequirements, recommendedActions, lastMutationTimestamp: lastMut, mutationCount: getWorkspaceMutationCount(root), lastVerify: lastV && verifyEvidence ? { command: lastV.command, passed: lastV.passed, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash } : null, lastReview: lastR && reviewEvidenceRecord ? { reviewer: lastR.reviewer, passed: lastR.passed, summary: lastR.summary, fresh: reviewFresh, evidenceId: reviewEvidenceRecord.id } : null, lastDogfood: lastD && lastDogfoodEvidence ? { scenarioId: lastD.scenarioId, verdict: lastD.verdict, host: lastD.host.label, taxonomyClass: lastD.taxonomyClass ?? null, runCount: lastD.runCount, fresh: dogfoodGate.required ? dogfoodFresh : null, evidenceId: lastDogfoodEvidence.id, missingHosts: dogfoodGate.missingHosts, coveredHosts: (dogfoodGate.matchedRecords ?? []).map((record) => record.host.label) } : null, ralph: { enabled: isRalphModeEnabled(root), maxIterations: getRalphMaxIterations(root), outcome: ralphOutcome ?? null }, projectConfig: { configPath: existingProjectConfigPath(root) ?? null, profile: getOperationProfile(root), protectedBranches: cfg.protectedBranches ?? ["main", "master"], verifyCommand: verifyCommand ?? null, verifyCommandSource: verifySource, requireReview: reviewRequired, requireDocumentation: documentationRequired, requireSubagentReview: isSubagentReviewRequired(root), requireDogfood: dogfoodGate.required, dogfoodDeployMatrix: dogfoodGate.required ? getDogfoodDeployMatrix(root) : [], recoveryCheckpoints: isRecoveryCheckpointsEnabled(root) }, gitHygiene: gitHygieneSnapshot(root) ?? null }, null, 2);
|
|
328
350
|
},
|
|
329
351
|
}),
|
|
330
352
|
guard_audit: tool({ description: "View recent audit entries recorded by opencode-workflow-guard. Use to diagnose policy decisions, blocked commands, or outcome telemetry.", args: { limit: tool.schema.number().optional().describe("Maximum entries to return (default 10)") }, execute: async (args) => JSON.stringify(getRecentAuditEntries(typeof args?.limit === "number" ? Math.min(args.limit, 50) : 10), null, 2) }),
|
|
@@ -531,6 +553,8 @@ export function createCustomTools(options: {
|
|
|
531
553
|
directory: tool.schema.string().optional().describe("Target repository directory (defaults to active session directory or workspace root)"),
|
|
532
554
|
},
|
|
533
555
|
execute: async (args, toolContext) => {
|
|
556
|
+
const cancelled = abortedMessage(toolContext);
|
|
557
|
+
if (cancelled) return cancelled;
|
|
534
558
|
const sanitizedBase = typeof args.base === "string" && !args.base.startsWith("-") && !/[\s;'"\0]/.test(args.base) ? args.base : undefined;
|
|
535
559
|
const bases = sanitizedBase ? [sanitizedBase] : ["origin/main", "origin/master", "main", "master"];
|
|
536
560
|
const rubricWorkspace = await resolveCallWorkspace(toolContext, args?.directory);
|
|
@@ -545,6 +569,8 @@ export function createCustomTools(options: {
|
|
|
545
569
|
guard_worktree_create: tool({
|
|
546
570
|
description: "Create an isolated git worktree directory for concurrent subagent execution. Proactively call when launching parallel tasks/subagents to prevent file collision and maintain branch isolation.", args: { branch: tool.schema.string().describe("Branch name for the isolated worktree (e.g. 'feat/subagent-task')"), baseBranch: tool.schema.string().optional().describe("Base branch to branch off of (defaults to HEAD)") },
|
|
547
571
|
execute: async (args, toolContext) => {
|
|
572
|
+
const cancelled = abortedMessage(toolContext);
|
|
573
|
+
if (cancelled) return cancelled;
|
|
548
574
|
const todos = await effectiveTodos(toolContext.sessionID); if (todos !== undefined && !hasActiveTodo(todos)) return "[workflow-guard] Blocked: worktree creation with no active todo item. Break the request down with todowrite first, then create worktrees.";
|
|
549
575
|
const toolRoot = await resolveCallWorkspace(toolContext);
|
|
550
576
|
// Host first: it honors the operator's configured worktree directory
|
|
@@ -586,6 +612,8 @@ export function createCustomTools(options: {
|
|
|
586
612
|
guard_worktree_cleanup: tool({
|
|
587
613
|
description: "Commit a final snapshot and remove an isolated git worktree directory. Call to clean up worktrees created with guard_worktree_create after subagent tasks complete.", args: { worktreePath: tool.schema.string().describe("Path of the worktree directory to clean up") },
|
|
588
614
|
execute: async (args, toolContext) => {
|
|
615
|
+
const cancelled = abortedMessage(toolContext);
|
|
616
|
+
if (cancelled) return cancelled;
|
|
589
617
|
const todos = await effectiveTodos(toolContext.sessionID); if (todos !== undefined && !hasActiveTodo(todos)) return "[workflow-guard] Blocked: worktree cleanup with no active todo item. Break the request down with todowrite first, then clean up worktrees.";
|
|
590
618
|
const toolRoot = await resolveCallWorkspace(toolContext);
|
|
591
619
|
// Removal never delegates to the host: its `remove` takes a `force`
|
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
resolveVerifyTimeoutMs,
|
|
45
45
|
snipVerifyOutput,
|
|
46
46
|
} from "./verify.ts";
|
|
47
|
-
import { detectShellMutation, extractPatchPaths, foreignSegmentMutationReason, guardShellMutation, hasUnresolvableVariable, isEnvironmentScratchTarget, isPathOutsideWorkspace, nestedPayloadMutationReason, OPENCODE_SCRATCH_DIR } from "../policies/boundary.ts";
|
|
47
|
+
import { detectShellMutation, extractPatchPaths, foreignSegmentMutationReason, guardShellMutation, hasUnresolvableVariable, isAllowedScratchTarget, isEnvironmentScratchTarget, isPathOutsideWorkspace, linkedWorktreeMismatchReason, nestedPayloadMutationReason, OPENCODE_SCRATCH_DIR } from "../policies/boundary.ts";
|
|
48
48
|
import { branchHasChangelogChange, checkLockfileSync, hasPrCreateInvocation, prBodyHasLiteralLineBreakEscapes, prBodyIncludesChangelog } from "../policies/changelog.ts";
|
|
49
49
|
import { extractEditContent, liveMutationIn } from "../policies/destructive.ts";
|
|
50
50
|
import { branchHasDocumentationChange } from "../policies/docs.ts";
|
|
@@ -334,6 +334,7 @@ export async function guardToolCallImpl(
|
|
|
334
334
|
logPolicyBlock(`[workflow-guard] blocked apply_patch: secret file path ${patchPath}`);
|
|
335
335
|
return block("secrets", "secret_write", `Blocked: modifying secret file '${patchPath}' directly is not permitted.`);
|
|
336
336
|
}
|
|
337
|
+
if (isAllowedScratchTarget(patchPath, currentRoot, context?.sessionID)) continue;
|
|
337
338
|
if (isPathOutsideWorkspace(patchPath, currentRoot)) {
|
|
338
339
|
logPolicyBlock(`[workflow-guard] blocked apply_patch: patch target escapes workspace: ${patchPath}`);
|
|
339
340
|
return block(
|
|
@@ -342,22 +343,27 @@ export async function guardToolCallImpl(
|
|
|
342
343
|
hasUnresolvableVariable(patchPath)
|
|
343
344
|
? `Blocked: patch targets file '${patchPath}', which contains an unresolvable variable reference; indeterminate destinations are treated as outside the workspace root (${currentRoot}). Use a literal workspace-relative path.`
|
|
344
345
|
: isEnvironmentScratchTarget(patchPath, currentRoot)
|
|
345
|
-
?
|
|
346
|
+
? context?.sessionID
|
|
347
|
+
? `Blocked: patch targets file '${patchPath}' is under ${OPENCODE_SCRATCH_DIR} but does not resolve inside it (a symlink leaves the directory, or the root is not a real directory), so the scratch allowance does not cover it. Use a real path inside that directory or inside the workspace root (${currentRoot}).`
|
|
348
|
+
: `Blocked: patch targets file '${patchPath}' under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover without a session; write scratch as an untracked file inside the workspace root (${currentRoot}) instead (for example .tmp-notes.md).`
|
|
346
349
|
: `Blocked: patch targets file '${patchPath}' outside workspace root (${currentRoot}).`,
|
|
347
350
|
);
|
|
348
351
|
}
|
|
349
352
|
}
|
|
350
353
|
}
|
|
351
|
-
if (target && isPathOutsideWorkspace(target, currentRoot)) {
|
|
354
|
+
if (target && isPathOutsideWorkspace(target, currentRoot) && !isAllowedScratchTarget(target, currentRoot, context?.sessionID)) {
|
|
352
355
|
logPolicyBlock(`[workflow-guard] blocked ${toolName}: path escapes workspace: ${target}`);
|
|
356
|
+
const mismatch = linkedWorktreeMismatchReason(target, currentRoot);
|
|
353
357
|
return block(
|
|
354
358
|
"boundary",
|
|
355
359
|
"workspace_escape",
|
|
356
360
|
hasUnresolvableVariable(target)
|
|
357
361
|
? `Blocked: file path '${target}' contains an unresolvable variable reference, so the boundary treats it as outside the workspace root (${currentRoot}). Use a literal workspace-relative path; all changes must stay within the workspace.`
|
|
358
362
|
: isEnvironmentScratchTarget(target, currentRoot)
|
|
359
|
-
?
|
|
360
|
-
|
|
363
|
+
? context?.sessionID
|
|
364
|
+
? `Blocked: file path '${target}' is under ${OPENCODE_SCRATCH_DIR} but does not resolve inside it (a symlink leaves the directory, or the root is not a real directory), so the scratch allowance does not cover it. Use a real path inside that directory or inside the workspace root (${currentRoot}).`
|
|
365
|
+
: `Blocked: file path '${target}' is under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover without a session; write scratch as an untracked file inside the workspace root (${currentRoot}) instead (for example .tmp-notes.md).`
|
|
366
|
+
: mismatch ?? `Blocked: file path '${target}' escapes workspace root (${currentRoot}). All changes must stay within the workspace.`,
|
|
361
367
|
);
|
|
362
368
|
}
|
|
363
369
|
for (const content of extractEditContent(input)) {
|
|
@@ -413,9 +419,14 @@ export async function guardToolCallImpl(
|
|
|
413
419
|
return block("todo", "mutation_budget", reason);
|
|
414
420
|
}
|
|
415
421
|
}
|
|
422
|
+
const editPaths = editTargets(input, currentRoot);
|
|
423
|
+
// Scratch writes are sanctioned but are not repository mutations: they
|
|
424
|
+
// must not need a prior read, claim a file against another session, or
|
|
425
|
+
// count toward task completion evidence.
|
|
426
|
+
const trackedPaths = editPaths.filter((path) => !isAllowedScratchTarget(path, currentRoot, context?.sessionID));
|
|
416
427
|
if (context?.sessionID) {
|
|
417
428
|
if (toolName === "edit" || toolName === "write") {
|
|
418
|
-
for (const path of
|
|
429
|
+
for (const path of trackedPaths) {
|
|
419
430
|
const staleReason = staleWriteReason(path, context.sessionID);
|
|
420
431
|
if (staleReason) {
|
|
421
432
|
logPolicyBlock(`[workflow-guard] ${staleReason}`);
|
|
@@ -423,22 +434,22 @@ export async function guardToolCallImpl(
|
|
|
423
434
|
}
|
|
424
435
|
}
|
|
425
436
|
}
|
|
426
|
-
const targets =
|
|
437
|
+
const targets = trackedPaths;
|
|
427
438
|
if (!context.simulate) {
|
|
428
439
|
// A missed idle release can leave a finished session's claims
|
|
429
440
|
// behind; release provably stale ones before claiming. The
|
|
430
441
|
// simulate path (guard_why) stays read-only.
|
|
431
|
-
await releaseStaleFileClaims(targets, context.sessionID);
|
|
442
|
+
await releaseStaleFileClaims(targets, context.sessionID, currentRoot);
|
|
432
443
|
}
|
|
433
444
|
const claimReason = context.simulate
|
|
434
|
-
? fileClaimConflictReason(targets, context.sessionID)
|
|
445
|
+
? fileClaimConflictReason(targets, context.sessionID, currentRoot)
|
|
435
446
|
: context.callID ? claimFiles(targets, context.sessionID, context.callID) : undefined;
|
|
436
447
|
if (claimReason) {
|
|
437
448
|
logPolicyBlock(`[workflow-guard] ${claimReason}`);
|
|
438
449
|
return block("file-claims", "file_claim_conflict", claimReason);
|
|
439
450
|
}
|
|
440
451
|
}
|
|
441
|
-
if (!context?.simulate) recordMutation(await effectiveTodoOwnerSessionID(context?.sessionID), context?.sessionID);
|
|
452
|
+
if (!context?.simulate && trackedPaths.length > 0) recordMutation(await effectiveTodoOwnerSessionID(context?.sessionID), context?.sessionID);
|
|
442
453
|
return allow();
|
|
443
454
|
}
|
|
444
455
|
|
|
@@ -506,7 +517,7 @@ export async function guardToolCallImpl(
|
|
|
506
517
|
`Blocked: the shell's workdir '${requestedShellRoot}' is outside workspace root (${currentRoot}) and is not a linked worktree of this repository, so relative targets cannot be validated against the tree the command would actually change. Run the command from inside the workspace instead.`,
|
|
507
518
|
);
|
|
508
519
|
}
|
|
509
|
-
const foreignSegmentReason = foreignSegmentMutationReason(segmentPlan, currentRoot);
|
|
520
|
+
const foreignSegmentReason = foreignSegmentMutationReason(segmentPlan, currentRoot, context?.sessionID);
|
|
510
521
|
if (foreignSegmentReason) {
|
|
511
522
|
logPolicyBlock(`[workflow-guard] blocked mutation in a directory outside workspace: ${command.slice(0, 120)}`);
|
|
512
523
|
return block("boundary", "workspace_escape", foreignSegmentReason);
|
|
@@ -584,13 +595,13 @@ export async function guardToolCallImpl(
|
|
|
584
595
|
// sees one word, so the top-level walk above cannot see it. Plan from
|
|
585
596
|
// `raw` for the same reason the top-level walk does: a heredoc body's
|
|
586
597
|
// own lines are real commands to the shell that consumes it.
|
|
587
|
-
const nestedTreeReason = nestedPayloadMutationReason(extractInterpreterPayload, writePathsInPayload, raw, shellRoot, currentRoot);
|
|
598
|
+
const nestedTreeReason = nestedPayloadMutationReason(extractInterpreterPayload, writePathsInPayload, raw, shellRoot, currentRoot, context?.sessionID);
|
|
588
599
|
if (nestedTreeReason) {
|
|
589
600
|
logPolicyBlock(`[workflow-guard] blocked nested interpreter mutation outside workspace: ${command.slice(0, 120)}`);
|
|
590
601
|
return block("boundary", "workspace_escape", nestedTreeReason);
|
|
591
602
|
}
|
|
592
603
|
for (const payload of extractInterpreterPayload(raw)) {
|
|
593
|
-
const outsidePath = outsideWritePathInPayload(payload, currentRoot);
|
|
604
|
+
const outsidePath = outsideWritePathInPayload(payload, currentRoot, (candidate) => isAllowedScratchTarget(candidate, currentRoot, context?.sessionID));
|
|
594
605
|
if (outsidePath) {
|
|
595
606
|
logPolicyBlock(`[workflow-guard] blocked interpreter payload writing outside workspace: ${outsidePath}`);
|
|
596
607
|
return block(
|
|
@@ -601,7 +612,10 @@ export async function guardToolCallImpl(
|
|
|
601
612
|
: `Blocked: inline interpreter script targets file '${outsidePath}' outside workspace root (${currentRoot}). All changes must stay within the workspace.`,
|
|
602
613
|
);
|
|
603
614
|
}
|
|
604
|
-
|
|
615
|
+
// A scratch write is sanctioned, so it does not need an active todo,
|
|
616
|
+
// a feature branch, or a mutation record. Repository writes in the
|
|
617
|
+
// same payload still do.
|
|
618
|
+
const writePaths = writePathsInPayload(payload).filter((path) => !isAllowedScratchTarget(path, currentRoot, context?.sessionID));
|
|
605
619
|
if (writePaths.length > 0) {
|
|
606
620
|
if (context?.agent && isReadOnlyRole(context.agent)) return block("subagent-role", "read_only_role", `Blocked: subagent with read-only role '${context.agent}' cannot perform shell file mutations.`);
|
|
607
621
|
for (const path of writePaths) if (isProtectedPath(path)) return block("tamper", "protected_path", PROTECTED_PATH_REASON);
|
|
@@ -76,6 +76,11 @@ export function projectConfigPath(root: string): string {
|
|
|
76
76
|
return candidates.find(existsSync) ?? candidates[0]!;
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
/** The project config file actually read for `root`, or undefined when none exists. */
|
|
80
|
+
export function existingProjectConfigPath(root: string): string | undefined {
|
|
81
|
+
return projectConfigCandidates(root).find(existsSync);
|
|
82
|
+
}
|
|
83
|
+
|
|
79
84
|
/** Strip JSONC comments and trailing commas without altering string literals. */
|
|
80
85
|
export function stripJsonComments(jsonc: string): string {
|
|
81
86
|
let insideString = false;
|
package/src/lib/types.ts
CHANGED
|
@@ -41,6 +41,12 @@ export interface ProjectConfig {
|
|
|
41
41
|
protectedBranches?: string[];
|
|
42
42
|
verifyCommand?: string;
|
|
43
43
|
verifyTimeoutMs?: number;
|
|
44
|
+
/**
|
|
45
|
+
* File-claim expiry. A claim older than this cannot belong to an in-flight
|
|
46
|
+
* tool call, so a leaked claim from an ended session is released and audited
|
|
47
|
+
* instead of blocking every other session. Defaults to 5 minutes.
|
|
48
|
+
*/
|
|
49
|
+
claimTtlMs?: number;
|
|
44
50
|
postEditValidators?: Array<{
|
|
45
51
|
pattern: string;
|
|
46
52
|
command: string;
|
|
@@ -222,6 +228,8 @@ export interface AuditEntry {
|
|
|
222
228
|
targetPath?: string;
|
|
223
229
|
/** Owner of a released stale file claim (stale_claim_takeover audits). */
|
|
224
230
|
claimOwnerSessionID?: string;
|
|
231
|
+
/** Age of a TTL-expired file claim, in milliseconds (claim_ttl_expired audits). */
|
|
232
|
+
claimAgeMs?: number;
|
|
225
233
|
verification?: {
|
|
226
234
|
command: string;
|
|
227
235
|
passed: boolean;
|
package/src/lib/v2-plugin.ts
CHANGED
|
@@ -74,7 +74,7 @@ import { expandShellTargetPath, isPathOutsideWorkspace, OPENCODE_SCRATCH_DIR, re
|
|
|
74
74
|
import { audit, summarizeInput } from "./audit.ts";
|
|
75
75
|
import { asRecord, isSensitiveEnvKey } from "./utils.ts";
|
|
76
76
|
import { loadedPluginVersion } from "./version.ts";
|
|
77
|
-
import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, markInterrupted, recordUserMessage } from "../policies/continuation.ts";
|
|
77
|
+
import { clearContinuationState, continueUnfinishedSession, isGeneratedContinuationMessage, markInterrupted, notifySessionRenamed, recordUserMessage } from "../policies/continuation.ts";
|
|
78
78
|
import { createRecoveryCheckpoint, finalizeRecoveryCheckpoint, nextRecoveryRun } from "./checkpoint.ts";
|
|
79
79
|
import { buildCompactionContext, guardToolCall } from "./guard-api.ts";
|
|
80
80
|
import { evaluateDogfoodGate } from "./dogfood.ts";
|
|
@@ -258,15 +258,20 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
258
258
|
// definition.args is a V1 zod raw shape (plain object of zod fields);
|
|
259
259
|
// wrap it so the V2 registry receives a real StandardSchemaV1.
|
|
260
260
|
input: z.object(definition.args as unknown as z.ZodRawShape),
|
|
261
|
-
execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string }) => {
|
|
261
|
+
execute: async (rawInput: unknown, toolContext: { sessionID: string; id: string; signal?: AbortSignal }) => {
|
|
262
262
|
// Only a session-bound workspace counts as the tool's own
|
|
263
263
|
// context; an unbound entry is a plugin-instance bootstrap
|
|
264
264
|
// and must not be presented to the tools as one.
|
|
265
265
|
const boundWorktree = getSessionBoundWorkspace(toolContext.sessionID);
|
|
266
|
+
// `signal` aborts when the session is interrupted. Guard tools
|
|
267
|
+
// pass it to cancellable work so an interrupt stops them
|
|
268
|
+
// instead of waiting out their own timeouts. V1's tool
|
|
269
|
+
// context supplies no signal, so the checks there are no-ops.
|
|
266
270
|
const result = await (definition.execute as (input: unknown, context: unknown) => Promise<unknown>)(rawInput, {
|
|
267
271
|
sessionID: toolContext.sessionID,
|
|
268
272
|
...(boundWorktree ? { worktree: boundWorktree } : {}),
|
|
269
273
|
directory: boundWorktree ?? effectiveRoot,
|
|
274
|
+
...(toolContext.signal ? { signal: toolContext.signal } : {}),
|
|
270
275
|
});
|
|
271
276
|
const text = typeof result === "string" ? result : (result as { output?: string } | undefined)?.output;
|
|
272
277
|
return {
|
|
@@ -710,10 +715,14 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
|
|
|
710
715
|
} catch {}
|
|
711
716
|
|
|
712
717
|
// ── Event stream ──
|
|
718
|
+
// `types` is a host-side filter, so unrelated events never cross the stream
|
|
719
|
+
// or reach the handler. It must list every literal `handleV2Event` acts on:
|
|
720
|
+
// the test suite asserts this set matches the handler's comparisons, because
|
|
721
|
+
// a missing type silently disables its feature instead of failing loudly.
|
|
713
722
|
const controller = new AbortController();
|
|
714
723
|
void (async () => {
|
|
715
724
|
try {
|
|
716
|
-
for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
|
|
725
|
+
for await (const raw of ctx.event.subscribe({ types: V2_EVENT_TYPES, signal: controller.signal })) {
|
|
717
726
|
const event = raw as { type?: string; data?: unknown };
|
|
718
727
|
try {
|
|
719
728
|
await handleV2Event(event, {
|
|
@@ -831,6 +840,30 @@ function recordV2ToolOutcome(
|
|
|
831
840
|
|
|
832
841
|
// ── Event handling ────────────────────────────────────────────────────────────
|
|
833
842
|
|
|
843
|
+
/**
|
|
844
|
+
* Every event type `handleV2Event` acts on.
|
|
845
|
+
*
|
|
846
|
+
* The subscription passes this as the host-side `types` filter. Each entry is a
|
|
847
|
+
* literal the handler compares against, so the two lists must stay identical: a
|
|
848
|
+
* type missing here is never delivered, and its feature becomes dead code that
|
|
849
|
+
* still type-checks. The suite asserts the match in both directions.
|
|
850
|
+
*
|
|
851
|
+
* Both idle triggers are listed because which one the host publishes is not
|
|
852
|
+
* settled, and `session.idle` is deprecated but still delivered.
|
|
853
|
+
*/
|
|
854
|
+
export const V2_EVENT_TYPES = [
|
|
855
|
+
"mcp.status.changed",
|
|
856
|
+
"session.text.ended",
|
|
857
|
+
"session.moved",
|
|
858
|
+
"session.renamed",
|
|
859
|
+
"session.execution.interrupted",
|
|
860
|
+
"session.status",
|
|
861
|
+
"session.idle",
|
|
862
|
+
"session.deleted",
|
|
863
|
+
"permission.asked",
|
|
864
|
+
"permission.replied",
|
|
865
|
+
] as const;
|
|
866
|
+
|
|
834
867
|
export interface V2EventState {
|
|
835
868
|
effectiveRoot: string;
|
|
836
869
|
client: unknown;
|
|
@@ -892,6 +925,14 @@ export async function handleV2Event(
|
|
|
892
925
|
return;
|
|
893
926
|
}
|
|
894
927
|
|
|
928
|
+
if (event.type === "session.renamed") {
|
|
929
|
+
// The async title write landed. A pending continuation waits on this
|
|
930
|
+
// instead of polling for the full settle interval.
|
|
931
|
+
const data = event.data as { sessionID?: unknown } | undefined;
|
|
932
|
+
if (typeof data?.sessionID === "string") notifySessionRenamed(data.sessionID);
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
|
|
895
936
|
if (event.type === "session.moved") {
|
|
896
937
|
// `session_move` relocates a session between checkouts, and the host
|
|
897
938
|
// announces it. On the pinned 2.2.0 SDK the V2 union carries
|
package/src/lib/verify.ts
CHANGED
|
@@ -53,6 +53,25 @@ export function detectVerifyCommand(root: string): string | undefined {
|
|
|
53
53
|
return undefined;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
export type VerifyCommandSource = "environment" | "project-config" | "auto-detected" | null;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Where `detectVerifyCommand` got its answer.
|
|
60
|
+
*
|
|
61
|
+
* The effective command alone cannot tell an operator which lever to move. A
|
|
62
|
+
* project that reports `verifyCommand` with no project config is running the
|
|
63
|
+
* auto-detected command, and a null means no command is configured or
|
|
64
|
+
* detectable at all.
|
|
65
|
+
*/
|
|
66
|
+
export function verifyCommandSource(root: string): VerifyCommandSource {
|
|
67
|
+
if (process.env.WORKFLOW_GUARD_VERIFY !== undefined) {
|
|
68
|
+
return process.env.WORKFLOW_GUARD_VERIFY.trim() ? "environment" : null;
|
|
69
|
+
}
|
|
70
|
+
const configured = getProjectConfig(root).verifyCommand;
|
|
71
|
+
if (typeof configured === "string" && configured.trim()) return "project-config";
|
|
72
|
+
return detectVerifyCommand(root) ? "auto-detected" : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
56
75
|
/**
|
|
57
76
|
* Truncates and snips verification stdout/stderr for token efficiency.
|
|
58
77
|
* When a test suite or compiler passes, verbose log lines are trimmed to a
|