opencode-workflow-guard 1.19.3 → 1.19.5
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 +4 -3
- package/docs/testing.md +4 -2
- package/docs/troubleshooting.md +3 -2
- package/package.json +1 -1
- package/src/lib/custom-tools.ts +5 -4
- package/src/lib/guard-dispatcher.ts +28 -14
- package/src/lib/project-config.ts +5 -0
- package/src/lib/state.ts +3 -0
- package/src/lib/types.ts +12 -0
- package/src/lib/verify.ts +19 -0
- package/src/policies/boundary.ts +128 -7
- 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.mts +213 -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
|
@@ -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).
|
|
@@ -117,6 +117,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
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.
|
|
120
|
+
- **Evidence Visibility:** `guard_status.lastVerify` reports the command, pass state, freshness, evidence id, commit hash, observation timestamp, and duration, so a green gate leaves a record with a time and the commit it covered. `guard_status.lastReview` adds its observation timestamp plus `recorderSessionID`, `recorderRole` (`root` or `subagent`), and `targetSessionID`. With `requireSubagentReview` on, that lineage shows the approval came from a subagent rather than the root session it was recorded for.
|
|
120
121
|
- If verification fails, finalization is blocked with a structured summary of error markers, stack traces, and failure output.
|
|
121
122
|
- OpenCode's current `lsp.client.diagnostics` event identifies the server and path. It does not expose the diagnostics themselves. The guard therefore does not claim an LSP-clean finalization gate until the SDK provides a supported diagnostics source.
|
|
122
123
|
- The verify command is **disabled** when `WORKFLOW_GUARD_VERIFY` is empty (`""`).
|
|
@@ -265,7 +266,7 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
|
|
|
265
266
|
- **Priority-Ranked Review Gate:** Secondary review approval (`requireReview`) is enforced by default during PR preflight (`gh pr create` / `az repos pr create`). Before creating a pull request, a secondary reviewer subagent must evaluate the changes using `guard_review_rubric` and record approval with `record_review`. Approvals that include active P0 (blocker) or P1 (major defect) issues are rejected until blockers are resolved. Projects can opt out via `.opencode/workflow-guard.json` (`{ "requireReview": false }`) or environment variable `WORKFLOW_GUARD_REQUIRE_REVIEW=0`. Conversely, `WORKFLOW_GUARD_REQUIRE_REVIEW=1` forces the review requirement regardless of project config.
|
|
266
267
|
- **Review binding is content, not session identity:** A recorded approval satisfies the PR preflight when its binding matches the tree the PR would publish. The binding covers the repository, the commit hash, and the tracked-content worktree fingerprint. Any session may record the verdict or create the PR. Reviewers record from subagent sessions, binding the verdict to their parent or their own directory. Sessions can move between directories (`session_move`), and subagents can spawn from other roots. Keying the gate on the PR-creating session's ID would make the documented flow impossible to satisfy from linked worktrees. Freshness is scoped to the reviewed diff, which is tracked content. Untracked scratch-file cleanup and mutations in sibling worktrees cannot invalidate an approval. Any tracked edit or new commit does.
|
|
267
268
|
- **Commit before you verify and review:** Both evidence gates bind to the HEAD commit hash, so a commit after either one invalidates it. Finish every tracked change first, then run verification, then record the review, then open the PR. That order satisfies both gates in one pass. Any other order costs a re-run. A review recorded before its change is committed keeps the same tracked fingerprint. The preflight then names the commit drift specifically and asks for the review again at the current commit.
|
|
268
|
-
- **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`). Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
|
|
269
|
+
- **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`), and `guard_status.lastReview` reports the same lineage beside the parent it was recorded for. Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
|
|
269
270
|
- **`requireSubagentReview` strict recorder mode (opt-in):** Projects that cannot tolerate root-session self-approval can set `requireSubagentReview: true` in `.opencode/workflow-guard.json`. They can also set `WORKFLOW_GUARD_REQUIRE_SUBAGENT_REVIEW=1` in the environment. In that mode `record_review` rejects APPROVALS recorded by the root session itself, which is a session with no parent. The rejection carries an actionable message and a `subagent_recorder_required` audit entry. The verdict is not recorded and the review gate stays unsatisfied. Changes-requested verdicts remain relayable from any session. `WORKFLOW_GUARD_REQUIRE_SUBAGENT_REVIEW=0` disables the requirement even when project config enables it. The default keeps the documented relay flow for read-only reviewer toolsets.
|
|
270
271
|
- **Durable Lower-Priority Follow-ups:** Accepted review summaries containing a P2 or P3 finding are persisted in the project's local Workflow Guard SQLite database. Open findings are included in compacted agent context. They remain open across sessions until explicitly resolved with `guard_review_followup_resolve`, and they are not silently discarded with the review session.
|
|
271
272
|
- **Privacy-Safe Local Telemetry:** Guard decisions remain in the local audit JSONL. Tool after-hook observations add `callID` and duration records for local diagnosis and performance analysis. The current hook API does not distinguish success from every failure path, so these records do not claim a success outcome. Command and patch bodies are never written to the journal. Only their byte count and SHA-256 fingerprint are retained for correlation.
|
package/docs/testing.md
CHANGED
|
@@ -48,8 +48,10 @@ npm run test:all
|
|
|
48
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. |
|
|
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/*`, and `opencode auth`. |
|
|
51
|
-
| **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. |
|
|
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. |
|
|
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 and commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
|
|
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. Under `requireSubagentReview`, verifies a root approval is rejected and `guard_status.lastReview` names the subagent recorder and its parent separately. |
|
|
53
55
|
| **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
|
|
54
56
|
| **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
|
|
55
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
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";
|
|
@@ -301,6 +301,7 @@ export function createCustomTools(options: {
|
|
|
301
301
|
const verifyEvidence = lastV ? verificationEvidence(lastV) : undefined;
|
|
302
302
|
const reviewEvidenceRecord = lastR ? reviewEvidence(lastR) : undefined;
|
|
303
303
|
const verifyCommand = detectVerifyCommand(root);
|
|
304
|
+
const verifySource = verifyCommandSource(root);
|
|
304
305
|
const verifyFresh = Boolean(lastV && verifyEvidence && lastV.passed && lastV.command === verifyCommand && isEvidenceFresh(verifyEvidence, subject, lastMut));
|
|
305
306
|
const reviewRequired = isReviewRequired(root);
|
|
306
307
|
// Review freshness is content-scoped, matching the PR preflight:
|
|
@@ -345,7 +346,7 @@ export function createCustomTools(options: {
|
|
|
345
346
|
}
|
|
346
347
|
const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
|
|
347
348
|
const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
|
|
348
|
-
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, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null } : null, lastReview: lastR && reviewEvidenceRecord ? { 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 } : 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);
|
|
349
350
|
},
|
|
350
351
|
}),
|
|
351
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) }),
|
|
@@ -407,7 +408,7 @@ export function createCustomTools(options: {
|
|
|
407
408
|
recorderRole: parentSessionID ? ("subagent" as const) : ("root" as const),
|
|
408
409
|
targetSessionID: parentSessionID ?? toolContext.sessionID,
|
|
409
410
|
};
|
|
410
|
-
recordReviewResult(args.reviewer, args.summary, args.passed, parentSessionID ?? toolContext.sessionID, reviewWorkspace);
|
|
411
|
+
recordReviewResult(args.reviewer, args.summary, args.passed, parentSessionID ?? toolContext.sessionID, reviewWorkspace, { sessionID: toolContext.sessionID, role: parentSessionID ? "subagent" : "root" });
|
|
411
412
|
if (followupStore && !secretIn(args.summary)) for (const finding of extractReviewFollowups(args.summary)) recordReviewFollowup(followupStore, { severity: finding.severity, summary: finding.summary, reviewer: args.reviewer, sessionID: toolContext.sessionID, commit: bindingCommitHash });
|
|
412
413
|
auditVerdict(args.passed ? "approved" : "changes_requested", args.passed ? "approved" : "changes_requested", binding);
|
|
413
414
|
const recorderNote = parentSessionID
|
|
@@ -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/state.ts
CHANGED
|
@@ -461,6 +461,7 @@ export function recordReviewResult(
|
|
|
461
461
|
passed: boolean,
|
|
462
462
|
targetSessionID?: string,
|
|
463
463
|
workspace?: string,
|
|
464
|
+
recorder?: { sessionID?: string; role?: "root" | "subagent" },
|
|
464
465
|
): ReviewResult {
|
|
465
466
|
const root = projectRootKey(workspace ?? getWorkspaceRoot());
|
|
466
467
|
lastReview = {
|
|
@@ -469,6 +470,8 @@ export function recordReviewResult(
|
|
|
469
470
|
passed,
|
|
470
471
|
timestamp: Date.now(),
|
|
471
472
|
targetSessionID,
|
|
473
|
+
recorderSessionID: recorder?.sessionID,
|
|
474
|
+
recorderRole: recorder?.role,
|
|
472
475
|
workspace: root,
|
|
473
476
|
commitHash: getCurrentGitCommitHash(root),
|
|
474
477
|
gitStatus: getGitStatusSummary(root),
|
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;
|
|
@@ -131,6 +137,10 @@ export interface ReviewResult {
|
|
|
131
137
|
summary: string;
|
|
132
138
|
timestamp: number;
|
|
133
139
|
targetSessionID?: string;
|
|
140
|
+
/** Session that actually called record_review, which may be a relay subagent. */
|
|
141
|
+
recorderSessionID?: string;
|
|
142
|
+
/** Lineage of the recorder, so guard_status can show a subagent approval. */
|
|
143
|
+
recorderRole?: "root" | "subagent";
|
|
134
144
|
workspace?: string;
|
|
135
145
|
commitHash?: string;
|
|
136
146
|
gitStatus?: string;
|
|
@@ -222,6 +232,8 @@ export interface AuditEntry {
|
|
|
222
232
|
targetPath?: string;
|
|
223
233
|
/** Owner of a released stale file claim (stale_claim_takeover audits). */
|
|
224
234
|
claimOwnerSessionID?: string;
|
|
235
|
+
/** Age of a TTL-expired file claim, in milliseconds (claim_ttl_expired audits). */
|
|
236
|
+
claimAgeMs?: number;
|
|
225
237
|
verification?: {
|
|
226
238
|
command: string;
|
|
227
239
|
passed: boolean;
|
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
|
package/src/policies/boundary.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { realpathSync } from "node:fs";
|
|
1
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import type { ShellMutation } from "../lib/types.ts";
|
|
@@ -11,7 +11,8 @@ import { isLeadingEvalSegment, maskDataHeredocBodies, prepareRedirectResidue, pl
|
|
|
11
11
|
import { isCollaborationInvocation, isProtectedPath, PROTECTED_PATH_REASON } from "./tamper.ts";
|
|
12
12
|
import { isSecretPath, secretIn } from "./secrets.ts";
|
|
13
13
|
import { isGitTreeWriteText, branchGuardReason, onProtectedBranch, parseGitInvocation } from "./git.ts";
|
|
14
|
-
import { isSameGitRepo } from "../lib/project-config.ts";
|
|
14
|
+
import { findGitRoot, isSameGitRepo, projectRootKey } from "../lib/project-config.ts";
|
|
15
|
+
import { canonicalPath } from "./file-claims.ts";
|
|
15
16
|
import {
|
|
16
17
|
effectiveTodos,
|
|
17
18
|
effectiveTodoOwnerSessionID,
|
|
@@ -81,6 +82,61 @@ export function isEnvironmentScratchTarget(targetPath: string, root: string): bo
|
|
|
81
82
|
return resolved === OPENCODE_SCRATCH_DIR || resolved.startsWith(OPENCODE_SCRATCH_DIR + "/");
|
|
82
83
|
}
|
|
83
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Real path of the scratch root, or undefined when it is missing or a symlink.
|
|
87
|
+
*
|
|
88
|
+
* The scratch allowance is scoped to one real directory. A symlinked root
|
|
89
|
+
* would make `/tmp/opencode -> /etc` a write grant over `/etc`, so the root
|
|
90
|
+
* itself must be a real directory; symlinks *inside* it are resolved and
|
|
91
|
+
* refused below when they leave.
|
|
92
|
+
*/
|
|
93
|
+
function scratchRealRoot(scratchRoot: string): string | undefined {
|
|
94
|
+
try {
|
|
95
|
+
const stat = lstatSync(scratchRoot);
|
|
96
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) return undefined;
|
|
97
|
+
return realpathSync(scratchRoot);
|
|
98
|
+
} catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Whether a resolved path is a sanctioned scratch write.
|
|
105
|
+
*
|
|
106
|
+
* Writes are allowed only under the exact pre-created scratch directory, only
|
|
107
|
+
* for a real session (the session id gates the allowance), and only when the
|
|
108
|
+
* target's canonical location stays inside that directory. Symlinks that
|
|
109
|
+
* leave it are refused. This is a write allowance only: it does not make the
|
|
110
|
+
* directory an execution surface and it does not widen the workspace boundary
|
|
111
|
+
* anywhere else.
|
|
112
|
+
*/
|
|
113
|
+
export function isAllowedScratchPath(
|
|
114
|
+
resolvedPath: string,
|
|
115
|
+
sessionID: string | undefined,
|
|
116
|
+
scratchRoot = OPENCODE_SCRATCH_DIR,
|
|
117
|
+
): boolean {
|
|
118
|
+
if (!sessionID || !resolvedPath) return false;
|
|
119
|
+
const scratch = resolve(scratchRoot);
|
|
120
|
+
if (resolvedPath !== scratch && !resolvedPath.startsWith(scratch + "/")) return false;
|
|
121
|
+
const realScratch = scratchRealRoot(scratchRoot);
|
|
122
|
+
if (!realScratch) return false;
|
|
123
|
+
const canonical = canonicalPath(resolvedPath);
|
|
124
|
+
return canonical === realScratch || canonical.startsWith(realScratch + "/");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Resolve a command's target against its run root, then judge scratch scope. */
|
|
128
|
+
export function isAllowedScratchTarget(
|
|
129
|
+
targetPath: string,
|
|
130
|
+
root: string,
|
|
131
|
+
sessionID: string | undefined,
|
|
132
|
+
scratchRoot = OPENCODE_SCRATCH_DIR,
|
|
133
|
+
): boolean {
|
|
134
|
+
if (!sessionID || !targetPath) return false;
|
|
135
|
+
const expanded = expandShellTargetPath(targetPath);
|
|
136
|
+
if (expanded === null) return false;
|
|
137
|
+
return isAllowedScratchPath(resolve(root, expanded), sessionID, scratchRoot);
|
|
138
|
+
}
|
|
139
|
+
|
|
84
140
|
export function isPathOutsideWorkspace(targetPath: string, root: string): boolean {
|
|
85
141
|
if (!targetPath) return false;
|
|
86
142
|
const expanded = expandShellTargetPath(targetPath);
|
|
@@ -136,6 +192,42 @@ export function isPathOutsideWorkspace(targetPath: string, root: string): boolea
|
|
|
136
192
|
return lexicallyOutside && !canonicallyInside;
|
|
137
193
|
}
|
|
138
194
|
|
|
195
|
+
/**
|
|
196
|
+
* The linked worktree a target belongs to when the session is bound elsewhere.
|
|
197
|
+
*
|
|
198
|
+
* A subagent's workspace is the directory its session opened in, not the
|
|
199
|
+
* worktree named in its brief. The mutation is still refused (a tool-call path
|
|
200
|
+
* never re-anchors the boundary), but the block must name the mismatch and the
|
|
201
|
+
* move, or the agent works around the guard through the shell.
|
|
202
|
+
*/
|
|
203
|
+
export function linkedWorktreeMismatch(targetPath: string, root: string, boundRoot = root): string | undefined {
|
|
204
|
+
const expanded = expandShellTargetPath(targetPath);
|
|
205
|
+
if (expanded === null) return undefined;
|
|
206
|
+
const resolved = resolve(root, expanded);
|
|
207
|
+
if (!isPathOutsideWorkspace(resolved, boundRoot)) return undefined;
|
|
208
|
+
let ancestor = resolved;
|
|
209
|
+
while (true) {
|
|
210
|
+
try {
|
|
211
|
+
const stat = lstatSync(ancestor);
|
|
212
|
+
if (stat.isDirectory() || stat.isFile()) break;
|
|
213
|
+
} catch {}
|
|
214
|
+
const parent = dirname(ancestor);
|
|
215
|
+
if (parent === ancestor) return undefined;
|
|
216
|
+
ancestor = parent;
|
|
217
|
+
}
|
|
218
|
+
const worktreeRoot = findGitRoot(ancestor);
|
|
219
|
+
if (!worktreeRoot) return undefined;
|
|
220
|
+
if (projectRootKey(worktreeRoot) === projectRootKey(boundRoot)) return undefined;
|
|
221
|
+
if (!isSameGitRepo(worktreeRoot, boundRoot)) return undefined;
|
|
222
|
+
return worktreeRoot;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function linkedWorktreeMismatchReason(targetPath: string, root: string, boundRoot = root): string | undefined {
|
|
226
|
+
const worktreeRoot = linkedWorktreeMismatch(targetPath, root, boundRoot);
|
|
227
|
+
if (!worktreeRoot) return undefined;
|
|
228
|
+
return `Blocked: file path '${targetPath}' is inside the linked worktree '${worktreeRoot}', but this session is bound to '${boundRoot}'. Move the session with the OpenCode session_move tool (directory: '${worktreeRoot}'), or start the subagent in that worktree, before editing.`;
|
|
229
|
+
}
|
|
230
|
+
|
|
139
231
|
export function extractPatchPaths(patchText: string): string[] {
|
|
140
232
|
const paths: string[] = [];
|
|
141
233
|
const markerRe =
|
|
@@ -386,6 +478,7 @@ function stripQuotedSpans(segment: string): string {
|
|
|
386
478
|
export function foreignSegmentMutationReason(
|
|
387
479
|
segments: ShellSegmentPlan[],
|
|
388
480
|
workspaceRoot: string,
|
|
481
|
+
sessionID?: string,
|
|
389
482
|
): string | undefined {
|
|
390
483
|
for (const { segment, root } of segments) {
|
|
391
484
|
const mutation = detectShellMutation(segment);
|
|
@@ -394,6 +487,17 @@ export function foreignSegmentMutationReason(
|
|
|
394
487
|
if (root === undefined) {
|
|
395
488
|
return `Blocked: the command changes directory to a target that cannot be determined without executing shell expansion, then runs a mutation (${mutation?.what ?? "git write"}). Indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal directory inside the workspace.`;
|
|
396
489
|
}
|
|
490
|
+
// A directory change into the sanctioned scratch root is not a foreign
|
|
491
|
+
// tree. A file mutation there is judged by its target in the per-segment
|
|
492
|
+
// loop, so a target that leaves the directory gets the right cause. A git
|
|
493
|
+
// write gets none of that, and scratch is not a repository this session
|
|
494
|
+
// may mutate.
|
|
495
|
+
if (isAllowedScratchPath(root, sessionID)) {
|
|
496
|
+
if (gitWrite) {
|
|
497
|
+
return `Blocked: a git write runs in ${OPENCODE_SCRATCH_DIR}, the scratch directory, which is not a repository this session may mutate. Run git from the workspace checkout instead.`;
|
|
498
|
+
}
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
397
501
|
if (!isPathOutsideWorkspace(root, workspaceRoot) || isSameGitRepo(root, workspaceRoot)) continue;
|
|
398
502
|
return `Blocked: the command changes into '${root}' and mutates it (${mutation?.what ?? "git write"}), but that directory is outside workspace root (${workspaceRoot}) and is not a linked worktree of this repository. Relative targets there cannot be validated against the tree the command would actually change. Run the command from inside the workspace instead.`;
|
|
399
503
|
}
|
|
@@ -575,6 +679,7 @@ export function nestedPayloadMutationReason(
|
|
|
575
679
|
command: string,
|
|
576
680
|
baseDir: string,
|
|
577
681
|
workspaceRoot: string,
|
|
682
|
+
sessionID?: string,
|
|
578
683
|
depth = 0,
|
|
579
684
|
): string | undefined {
|
|
580
685
|
// Nesting deeper than this is not modelled. A launcher chain that deep is
|
|
@@ -608,12 +713,12 @@ export function nestedPayloadMutationReason(
|
|
|
608
713
|
if (foreignRepo) {
|
|
609
714
|
return `Blocked: the inline interpreter script runs a git write against '${foreignRepo}', outside workspace root (${workspaceRoot}) and not a linked worktree of this repository. Run the command from inside the workspace instead.`;
|
|
610
715
|
}
|
|
611
|
-
const nested = foreignSegmentMutationReason(planShellSegments(payload, launcherRoot), workspaceRoot);
|
|
716
|
+
const nested = foreignSegmentMutationReason(planShellSegments(payload, launcherRoot), workspaceRoot, sessionID);
|
|
612
717
|
if (nested) return nested;
|
|
613
718
|
// A payload can launch another interpreter: `bash -c "bash -c 'cd
|
|
614
719
|
// <other> && git commit'"` only extracts its own quoted body. Re-plan
|
|
615
720
|
// each payload until the nesting bottoms out.
|
|
616
|
-
const inner = nestedPayloadMutationReason(extractPayloads, writesIn, payload, launcherRoot, workspaceRoot, depth + 1);
|
|
721
|
+
const inner = nestedPayloadMutationReason(extractPayloads, writesIn, payload, launcherRoot, workspaceRoot, sessionID, depth + 1);
|
|
617
722
|
if (inner) return inner;
|
|
618
723
|
const declared = payloadWorkingRoot(payload);
|
|
619
724
|
if (declared.status === "none") continue;
|
|
@@ -622,6 +727,13 @@ export function nestedPayloadMutationReason(
|
|
|
622
727
|
return `Blocked: the inline interpreter script runs a mutating command in a working directory that cannot be determined without executing the script (${declared.raw}). Indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal directory inside the workspace.`;
|
|
623
728
|
}
|
|
624
729
|
const targetRoot = resolve(launcherRoot, declared.root);
|
|
730
|
+
// A payload whose declared working directory and every detected
|
|
731
|
+
// write stay inside the sanctioned scratch root is a scratch write,
|
|
732
|
+
// not a foreign-tree mutation.
|
|
733
|
+
if (isAllowedScratchPath(targetRoot, sessionID) && !isGitTreeWriteText(payload)) {
|
|
734
|
+
const scratchWrites = writesIn(payload);
|
|
735
|
+
if (scratchWrites.length > 0 && scratchWrites.every((write) => isAllowedScratchTarget(write, targetRoot, sessionID))) continue;
|
|
736
|
+
}
|
|
625
737
|
if (!isPathOutsideWorkspace(targetRoot, workspaceRoot) || isSameGitRepo(targetRoot, workspaceRoot)) continue;
|
|
626
738
|
return `Blocked: the inline interpreter script runs a mutating command in '${targetRoot}', outside workspace root (${workspaceRoot}) and not a linked worktree of this repository. Relative targets there cannot be validated against the tree the command would actually change. Run the command from inside the workspace instead.`;
|
|
627
739
|
}
|
|
@@ -667,7 +779,7 @@ export async function guardShellMutation(
|
|
|
667
779
|
// The foreign-tree gate runs here too, so this function is safe when called
|
|
668
780
|
// on its own: an indeterminate or foreign `cd` is refused instead of silently
|
|
669
781
|
// falling back to judging relative targets against the wrong tree.
|
|
670
|
-
const foreignReason = foreignSegmentMutationReason(plan, workspaceRoot);
|
|
782
|
+
const foreignReason = foreignSegmentMutationReason(plan, workspaceRoot, sessionID);
|
|
671
783
|
if (foreignReason) return foreignReason;
|
|
672
784
|
let hasMutation = false;
|
|
673
785
|
for (const { segment, root: segmentRoot } of plan) {
|
|
@@ -722,7 +834,6 @@ export async function guardShellMutation(
|
|
|
722
834
|
if (fallbackMutation) mutations.push(fallbackMutation);
|
|
723
835
|
}
|
|
724
836
|
for (const mutation of mutations) {
|
|
725
|
-
hasMutation = true;
|
|
726
837
|
const secret = secretIn(cleanSegment);
|
|
727
838
|
if (secret) {
|
|
728
839
|
return `Blocked: shell file mutation payload appears to contain a ${secret}. Secrets must not be written to disk from agent commands.`;
|
|
@@ -731,6 +842,12 @@ export async function guardShellMutation(
|
|
|
731
842
|
if (target && isProtectedPath(target)) {
|
|
732
843
|
return PROTECTED_PATH_REASON;
|
|
733
844
|
}
|
|
845
|
+
// A scratch write is sanctioned only for a real session and only
|
|
846
|
+
// while its canonical target stays inside the pre-created root. It
|
|
847
|
+
// is not a repository mutation, so it does not advance task evidence
|
|
848
|
+
// or the feature-branch requirement.
|
|
849
|
+
if (isAllowedScratchTarget(target, runRoot, sessionID)) continue;
|
|
850
|
+
hasMutation = true;
|
|
734
851
|
if (target && outsideWorkspace(target)) {
|
|
735
852
|
// The workspace boundary has no override: a write outside the
|
|
736
853
|
// workspace is out of bounds even with WORKFLOW_GUARD_ALLOW_LIVE
|
|
@@ -739,8 +856,12 @@ export async function guardShellMutation(
|
|
|
739
856
|
return `Blocked: shell mutation '${mutation.what}' targets '${target}', which contains an unresolvable variable reference; indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal workspace-relative path.`;
|
|
740
857
|
}
|
|
741
858
|
if (isEnvironmentScratchTarget(target, runRoot)) {
|
|
742
|
-
return
|
|
859
|
+
return sessionID
|
|
860
|
+
? `Blocked: shell mutation '${mutation.what}' targets '${target}', which 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 (${workspaceRoot}).`
|
|
861
|
+
: `Blocked: shell mutation '${mutation.what}' targets '${target}' 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 (${workspaceRoot}) instead (for example .tmp-notes.md).`;
|
|
743
862
|
}
|
|
863
|
+
const mismatch = linkedWorktreeMismatchReason(target, runRoot, workspaceRoot);
|
|
864
|
+
if (mismatch) return mismatch;
|
|
744
865
|
return `Blocked: shell mutation '${mutation.what}' targets a path outside the workspace root (${workspaceRoot}). All changes must stay within the workspace.`;
|
|
745
866
|
}
|
|
746
867
|
if (onProtectedBranch(runRoot)) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readlinkSync, realpathSync } from "node:fs";
|
|
2
2
|
import { dirname, relative, resolve } from "node:path";
|
|
3
3
|
import { audit } from "../lib/audit.ts";
|
|
4
|
-
import { getSdkClient } from "../lib/state.ts";
|
|
4
|
+
import { getProjectConfig, getSdkClient, getWorkspaceRoot } from "../lib/state.ts";
|
|
5
5
|
|
|
6
6
|
interface FileClaim {
|
|
7
7
|
sessionID: string;
|
|
@@ -12,6 +12,21 @@ interface FileClaim {
|
|
|
12
12
|
|
|
13
13
|
const claims = new Map<string, FileClaim>();
|
|
14
14
|
|
|
15
|
+
/** Default claim TTL: a claim this old is leaked, because a tool call is not that long. */
|
|
16
|
+
export const DEFAULT_FILE_CLAIM_TTL_MS = 5 * 60_000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Effective claim TTL: `WORKFLOW_GUARD_CLAIM_TTL_MS` wins, then project config
|
|
20
|
+
* `claimTtlMs`, then the 5-minute default. Non-positive or unparseable values
|
|
21
|
+
* fall back to the default so a typo cannot disable expiry.
|
|
22
|
+
*/
|
|
23
|
+
export function fileClaimTtlMs(root: string = getWorkspaceRoot()): number {
|
|
24
|
+
const envValue = Number(process.env.WORKFLOW_GUARD_CLAIM_TTL_MS);
|
|
25
|
+
if (Number.isFinite(envValue) && envValue > 0) return envValue;
|
|
26
|
+
const configured = getProjectConfig(root).claimTtlMs;
|
|
27
|
+
return typeof configured === "number" && Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_FILE_CLAIM_TTL_MS;
|
|
28
|
+
}
|
|
29
|
+
|
|
15
30
|
export function canonicalPath(path: string, seen = new Set<string>()): string {
|
|
16
31
|
const resolved = resolve(path);
|
|
17
32
|
if (seen.has(resolved)) return resolved;
|
|
@@ -53,12 +68,15 @@ export function claimFiles(paths: string[], sessionID: string, callID: string):
|
|
|
53
68
|
return undefined;
|
|
54
69
|
}
|
|
55
70
|
|
|
56
|
-
export function fileClaimConflictReason(paths: string[], sessionID: string): string | undefined {
|
|
71
|
+
export function fileClaimConflictReason(paths: string[], sessionID: string, root: string = getWorkspaceRoot()): string | undefined {
|
|
57
72
|
const canonical = [...new Set(paths.map((path) => canonicalPath(path)))];
|
|
73
|
+
const ttlMs = fileClaimTtlMs(root);
|
|
58
74
|
for (const path of canonical) {
|
|
59
75
|
const existing = claims.get(path);
|
|
60
76
|
if (existing && existing.sessionID !== sessionID) {
|
|
61
|
-
|
|
77
|
+
const ageMs = Math.max(0, Date.now() - existing.ts);
|
|
78
|
+
const remainingSec = Math.max(1, Math.ceil((ttlMs - ageMs) / 1000));
|
|
79
|
+
return `Blocked: file '${path}' is claimed by session '${existing.sessionID}' (claimed ${Math.round(ageMs / 1000)}s ago). Reclaim step: retry after the claim TTL (${remainingSec}s remaining), when the guard releases and audits a stale claim. Otherwise wait for that session's edit to finish, or use an isolated worktree.`;
|
|
62
80
|
}
|
|
63
81
|
}
|
|
64
82
|
return undefined;
|
|
@@ -67,22 +85,50 @@ export function fileClaimConflictReason(paths: string[], sessionID: string): str
|
|
|
67
85
|
/**
|
|
68
86
|
* A claim is normally released by its owning tool call (after-hook) or by the
|
|
69
87
|
* owner's session.idle/session.deleted events. When an idle release is missed,
|
|
70
|
-
* the claim would otherwise block every other session forever.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
88
|
+
* the claim would otherwise block every other session forever. Two provable
|
|
89
|
+
* staleness rules reclaim it, each audited:
|
|
90
|
+
*
|
|
91
|
+
* - TTL: a claim older than `claimTtlMs` cannot belong to an in-flight tool
|
|
92
|
+
* call. It is released even when the owner's session record cannot be read,
|
|
93
|
+
* which covers a deleted session and a server restart.
|
|
94
|
+
* - Idle: a claim created BEFORE its owner's last recorded idle timestamp
|
|
95
|
+
* finished before the turn ended. Without an SDK client, or when the owner
|
|
96
|
+
* record cannot be read, this rule releases nothing: fail-closed keeps live
|
|
97
|
+
* two-session protection intact.
|
|
98
|
+
*
|
|
99
|
+
* Clock skew between this process and the server is not expected for a local
|
|
100
|
+
* (same-host) service: negative skew fails closed; forward skew could make
|
|
101
|
+
* fresh claims look stale and is accepted for that deployment. Concurrent
|
|
102
|
+
* claimants can emit duplicate reclaim audits (append-only, harmless). Release
|
|
103
|
+
* is per-claim: only claims whose ts is provably stale are dropped, re-read
|
|
81
104
|
* AFTER the lookup round-trip so an owner that re-claimed (and refreshed) a
|
|
82
105
|
* path meanwhile keeps its live claim.
|
|
83
106
|
*/
|
|
84
|
-
export async function releaseStaleFileClaims(paths: string[], claimantSessionID: string): Promise<void> {
|
|
107
|
+
export async function releaseStaleFileClaims(paths: string[], claimantSessionID: string, root: string = getWorkspaceRoot()): Promise<void> {
|
|
85
108
|
const canonical = [...new Set(paths.map((path) => canonicalPath(path)))];
|
|
109
|
+
// A claim older than the TTL cannot belong to an in-flight tool call, so it
|
|
110
|
+
// is a leak from a session that ended without an idle/deleted release. It
|
|
111
|
+
// is released even when the owner's record cannot be read (a deleted
|
|
112
|
+
// session, a missing SDK lookup, a server restart), with an audited
|
|
113
|
+
// reclaim. Only the contended paths are examined, so a long-running command
|
|
114
|
+
// elsewhere keeps its claim.
|
|
115
|
+
const ttlMs = fileClaimTtlMs(root);
|
|
116
|
+
const now = Date.now();
|
|
117
|
+
for (const claimPath of canonical) {
|
|
118
|
+
const claim = claims.get(claimPath);
|
|
119
|
+
if (!claim || claim.sessionID === claimantSessionID) continue;
|
|
120
|
+
if (now - claim.ts < ttlMs) continue;
|
|
121
|
+
claims.delete(claimPath);
|
|
122
|
+
audit({
|
|
123
|
+
ts: new Date().toISOString(),
|
|
124
|
+
sessionID: claimantSessionID,
|
|
125
|
+
tool: "file-claims",
|
|
126
|
+
decision: "allow",
|
|
127
|
+
phase: "event",
|
|
128
|
+
reason: "claim_ttl_expired",
|
|
129
|
+
evidence: { mutation: false, targetPath: claimPath, claimOwnerSessionID: claim.sessionID, claimAgeMs: now - claim.ts },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
86
132
|
const staleOwners = new Map<string, string>();
|
|
87
133
|
for (const path of canonical) {
|
|
88
134
|
const existing = claims.get(path);
|
|
@@ -154,7 +154,11 @@ const WRITE_TARGET_PATTERNS: RegExp[] = [
|
|
|
154
154
|
* workspace root) initiated from inline interpreter payloads. Extracts destination
|
|
155
155
|
* file arguments from file-writing APIs and shell redirects.
|
|
156
156
|
*/
|
|
157
|
-
export function outsideWritePathInPayload(
|
|
157
|
+
export function outsideWritePathInPayload(
|
|
158
|
+
payload: string,
|
|
159
|
+
root: string,
|
|
160
|
+
isAllowed: (candidate: string) => boolean = () => false,
|
|
161
|
+
): string | undefined {
|
|
158
162
|
const candidates = new Set<string>();
|
|
159
163
|
|
|
160
164
|
for (const pattern of WRITE_TARGET_PATTERNS) {
|
|
@@ -166,7 +170,7 @@ export function outsideWritePathInPayload(payload: string, root: string): string
|
|
|
166
170
|
|
|
167
171
|
for (const candidate of candidates) {
|
|
168
172
|
if (/^\/dev\/(?:null|stdout|stderr|tty|fd\/\d+)$/.test(candidate)) continue;
|
|
169
|
-
if (isPathOutsideWorkspace(candidate, root)) {
|
|
173
|
+
if (isPathOutsideWorkspace(candidate, root) && !isAllowed(candidate)) {
|
|
170
174
|
return candidate;
|
|
171
175
|
}
|
|
172
176
|
}
|
package/src/workflow-guard.ts
CHANGED
|
@@ -107,7 +107,9 @@ import {
|
|
|
107
107
|
resolveSessionBoundWorkspace,
|
|
108
108
|
resolveEffectiveWorkspace,
|
|
109
109
|
} from "./lib/state.ts";
|
|
110
|
-
import { findGitRoot, isSameGitRepo, loadProjectConfig, reloadProjectConfig, stripJsonComments } from "./lib/project-config.ts";
|
|
110
|
+
import { existingProjectConfigPath, findGitRoot, isSameGitRepo, loadProjectConfig, reloadProjectConfig, stripJsonComments } from "./lib/project-config.ts";
|
|
111
|
+
|
|
112
|
+
export { existingProjectConfigPath };
|
|
111
113
|
|
|
112
114
|
export {
|
|
113
115
|
setWorkspaceRoot,
|
|
@@ -247,6 +249,7 @@ import {
|
|
|
247
249
|
getGitStatusSummary,
|
|
248
250
|
getGitWorktreeFingerprint,
|
|
249
251
|
getTrackedWorktreeFingerprint,
|
|
252
|
+
verifyCommandSource,
|
|
250
253
|
} from "./lib/verify.ts";
|
|
251
254
|
|
|
252
255
|
export {
|
|
@@ -258,6 +261,7 @@ export {
|
|
|
258
261
|
getGitStatusSummary,
|
|
259
262
|
getGitWorktreeFingerprint,
|
|
260
263
|
getTrackedWorktreeFingerprint,
|
|
264
|
+
verifyCommandSource,
|
|
261
265
|
};
|
|
262
266
|
export type { VerifyRun } from "./lib/verify.ts";
|
|
263
267
|
|
|
@@ -349,6 +353,14 @@ import { isSecretPath, secretIn, isEnvFilePath, generateMaskedEnvSchema } from "
|
|
|
349
353
|
|
|
350
354
|
export { isSecretPath, isEnvFilePath, generateMaskedEnvSchema };
|
|
351
355
|
|
|
356
|
+
import { isAllowedScratchTarget } from "./policies/boundary.ts";
|
|
357
|
+
|
|
358
|
+
export { isAllowedScratchTarget, OPENCODE_SCRATCH_DIR };
|
|
359
|
+
|
|
360
|
+
import { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs } from "./policies/file-claims.ts";
|
|
361
|
+
|
|
362
|
+
export { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs };
|
|
363
|
+
|
|
352
364
|
import {
|
|
353
365
|
extractInterpreterPayload,
|
|
354
366
|
secretPathInPayload,
|
package/test/test.mts
CHANGED
|
@@ -172,6 +172,10 @@ import { createHostWorktreePort } from "../src/lib/host-worktree.ts";
|
|
|
172
172
|
import { validateHostWorktreeDirectory } from "../src/lib/worktree.ts";
|
|
173
173
|
import { guardedTokensFromServerName, listHostMcpServerNames, recordHostMcpServers } from "../src/lib/mcp-inventory.ts";
|
|
174
174
|
import { addGuardedMcpTokens, guardedMcpServers, mcpMutationTool, resetGuardedMcpTokensForTesting } from "../src/policies/mcp.ts";
|
|
175
|
+
import { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs } from "../src/policies/file-claims.ts";
|
|
176
|
+
import { OPENCODE_SCRATCH_DIR, isAllowedScratchTarget } from "../src/policies/boundary.ts";
|
|
177
|
+
import { existingProjectConfigPath } from "../src/lib/project-config.ts";
|
|
178
|
+
import { verifyCommandSource } from "../src/lib/verify.ts";
|
|
175
179
|
|
|
176
180
|
let pass = 0;
|
|
177
181
|
let fail = 0;
|
|
@@ -916,16 +920,34 @@ const unresolvableMv = await call("bash", { command: "mv $D/foo.txt ./bar.txt" }
|
|
|
916
920
|
check("mv source with unresolvable $VAR names the variable cause", blocked(unresolvableMv) && String(unresolvableMv).includes("unresolvable variable reference"));
|
|
917
921
|
const unresolvableGit = await call("bash", { command: "git -C $OTHER_REPO commit -m x" }, { sessionID: "s-active" });
|
|
918
922
|
check("git repoDir with unresolvable $VAR names the variable cause", blocked(unresolvableGit) && String(unresolvableGit).includes("unresolvable variable reference"));
|
|
919
|
-
// Scratch-directory
|
|
920
|
-
//
|
|
921
|
-
//
|
|
922
|
-
//
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
const
|
|
926
|
-
|
|
927
|
-
const
|
|
928
|
-
|
|
923
|
+
// Scratch-directory allowance: /tmp/opencode is the environment's designated
|
|
924
|
+
// agent scratch space. Writes there are sanctioned for a real session and only
|
|
925
|
+
// while the canonical target stays inside that exact directory; a symlink that
|
|
926
|
+
// leaves it, a sibling with a shared prefix, and a traversal out of it are all
|
|
927
|
+
// still boundary escapes. Execution itself is unchanged.
|
|
928
|
+
mkdirSync(OPENCODE_SCRATCH_DIR, { recursive: true });
|
|
929
|
+
const scratchTag = `wg-scratch-${process.pid}-${String(Date.now())}`;
|
|
930
|
+
todo("s-scratch", item("write scratch notes", "in_progress"));
|
|
931
|
+
const scratchFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.txt`);
|
|
932
|
+
const scratchPatchFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.ts`);
|
|
933
|
+
const scratchRedirectFile = join(OPENCODE_SCRATCH_DIR, `${scratchTag}.md`);
|
|
934
|
+
check("scratch-dir write is allowed for a session", allowed(await call("write", { filePath: scratchFile, content: "x" }, { sessionID: "s-scratch" })));
|
|
935
|
+
check("scratch-dir redirect is allowed for a session", allowed(await call("bash", { command: `echo x > ${scratchRedirectFile}` }, { sessionID: "s-scratch" })));
|
|
936
|
+
check("scratch-dir apply_patch is allowed for a session", allowed(await call("apply_patch", { patchText: `*** Add File: ${scratchPatchFile}\n+scratch\n` }, { sessionID: "s-scratch" })));
|
|
937
|
+
check("scratch-dir interpreter payload write is allowed", allowed(await call("bash", { command: `python3 -c "open('${scratchFile}', 'w').write('x')"` }, { sessionID: "s-scratch" })));
|
|
938
|
+
check("scratch-dir cd redirect is allowed", allowed(await call("bash", { command: `cd ${OPENCODE_SCRATCH_DIR} && echo x > ${scratchTag}-cd.md` }, { sessionID: "s-scratch" })));
|
|
939
|
+
const sessionlessScratch = await call("write", { filePath: scratchFile, content: "x" });
|
|
940
|
+
check("scratch-dir write needs a session id", blocked(sessionlessScratch) && String(sessionlessScratch).includes("environment scratch directory"));
|
|
941
|
+
const scratchPrefixPeer = await call("write", { filePath: `${OPENCODE_SCRATCH_DIR}-evil/out.txt`, content: "x" }, { sessionID: "s-scratch" });
|
|
942
|
+
check("a sibling sharing the scratch prefix is still blocked", blocked(scratchPrefixPeer) && String(scratchPrefixPeer).includes("escapes workspace root"));
|
|
943
|
+
const scratchTraversal = await call("write", { filePath: `${OPENCODE_SCRATCH_DIR}/../wg-escape.txt`, content: "x" }, { sessionID: "s-scratch" });
|
|
944
|
+
check("a traversal out of the scratch dir is blocked", blocked(scratchTraversal) && String(scratchTraversal).includes("escapes workspace root"));
|
|
945
|
+
const scratchEscapeDir = mkdtempSync(join(tmpdir(), "wg-scratch-escape-"));
|
|
946
|
+
symlinkSync(scratchEscapeDir, join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`), "dir");
|
|
947
|
+
const symlinkScratch = await call("write", { filePath: join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`, "out.txt"), content: "x" }, { sessionID: "s-scratch" });
|
|
948
|
+
check("a symlink out of the scratch dir is blocked", blocked(symlinkScratch) && String(symlinkScratch).includes("scratch allowance does not cover it"));
|
|
949
|
+
rmSync(join(OPENCODE_SCRATCH_DIR, `${scratchTag}-link`), { force: true });
|
|
950
|
+
rmSync(scratchEscapeDir, { recursive: true, force: true });
|
|
929
951
|
const otherOutsideWrite = await call("write", { filePath: "/var/tmp/elsewhere.txt", content: "x" }, { sessionID: "s-active" });
|
|
930
952
|
check("non-scratch outside path keeps the generic escape message", blocked(otherOutsideWrite) && String(otherOutsideWrite).includes("escapes workspace root") && !String(otherOutsideWrite).includes("scratch directory"));
|
|
931
953
|
check("allow apply_patch within workspace", !(await call("apply_patch", { patchText: "*** Update File: src/app.ts\n" }, { sessionID: "s-active" })));
|
|
@@ -1112,7 +1134,7 @@ let claimConflict = false;
|
|
|
1112
1134
|
try {
|
|
1113
1135
|
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-b", callID: "claim-b" }, { args: { filePath: join(claimsDir, "shared-link.ts"), content: "b" } });
|
|
1114
1136
|
} catch (error) {
|
|
1115
|
-
claimConflict = String(error).includes("claimed by
|
|
1137
|
+
claimConflict = String(error).includes("is claimed by session");
|
|
1116
1138
|
}
|
|
1117
1139
|
check("concurrent file claims block another session through a symlink alias", claimConflict);
|
|
1118
1140
|
const whyClaimConflict = JSON.parse(String(await claimsHooks.tool?.guard_why?.execute(
|
|
@@ -1143,7 +1165,7 @@ let danglingConflict = false;
|
|
|
1143
1165
|
try {
|
|
1144
1166
|
await claimsBefore?.({ tool: "write", sessionID: "s-claim-b", callID: "claim-dangling-alias" }, { args: { filePath: join(claimsDir, "future-link.ts"), content: "b" } });
|
|
1145
1167
|
} catch (error) {
|
|
1146
|
-
danglingConflict = String(error).includes("claimed by
|
|
1168
|
+
danglingConflict = String(error).includes("is claimed by session");
|
|
1147
1169
|
}
|
|
1148
1170
|
check("concurrent file claims canonicalize dangling final symlinks", danglingConflict);
|
|
1149
1171
|
await claimsHooks.event?.({ event: { type: "session.idle", properties: { sessionID: "s-claim-a" } } } as any);
|
|
@@ -1162,7 +1184,7 @@ let patchConflict = false;
|
|
|
1162
1184
|
try {
|
|
1163
1185
|
await claimsBefore?.({ tool: "apply_patch", sessionID: "s-claim-b", callID: "claim-patch" }, { args: { patchText: "*** Begin Patch\n*** Update File: other.ts\n-old\n+new\n*** Update File: shared.ts\n-old\n+new\n*** End Patch" } });
|
|
1164
1186
|
} catch (error) {
|
|
1165
|
-
patchConflict = String(error).includes("claimed by
|
|
1187
|
+
patchConflict = String(error).includes("is claimed by session");
|
|
1166
1188
|
}
|
|
1167
1189
|
check("apply_patch claims all targets atomically when one target conflicts", patchConflict);
|
|
1168
1190
|
todo("s-claim-c", item("edit unclaimed file", "in_progress"));
|
|
@@ -1237,7 +1259,7 @@ let liveClaimBlocked = false;
|
|
|
1237
1259
|
try {
|
|
1238
1260
|
await takeoverBefore?.({ tool: "edit", sessionID: "s-claimant", callID: "live-blocked" }, { args: { filePath: join(takeoverDir, "live.ts"), content: "c" } });
|
|
1239
1261
|
} catch (error) {
|
|
1240
|
-
liveClaimBlocked = String(error).includes("claimed by
|
|
1262
|
+
liveClaimBlocked = String(error).includes("is claimed by session");
|
|
1241
1263
|
}
|
|
1242
1264
|
check("a live owner without an idle timestamp keeps its claim", liveClaimBlocked);
|
|
1243
1265
|
await takeoverAfter?.({ tool: "edit", sessionID: "s-live-owner", callID: "live-claim", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
@@ -1256,7 +1278,7 @@ let refreshClaimBlocked = false;
|
|
|
1256
1278
|
try {
|
|
1257
1279
|
await takeoverBefore?.({ tool: "edit", sessionID: "s-claimant", callID: "refresh-conflict" }, { args: { filePath: join(takeoverDir, "refresh.ts"), content: "f" } });
|
|
1258
1280
|
} catch (error) {
|
|
1259
|
-
refreshClaimBlocked = String(error).includes("claimed by
|
|
1281
|
+
refreshClaimBlocked = String(error).includes("is claimed by session");
|
|
1260
1282
|
}
|
|
1261
1283
|
check("a same-session re-claim refreshes past the owner's idle so it is not taken over mid-turn", refreshClaimBlocked);
|
|
1262
1284
|
await takeoverAfter?.({ tool: "edit", sessionID: "s-stale-owner", callID: "refresh-claim-2", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
@@ -1301,6 +1323,59 @@ await takeoverAfter?.({ tool: "edit", sessionID: "s-claimant", callID: "multi-ta
|
|
|
1301
1323
|
const takeoverAudits = getRecentAuditEntries(30).filter((entry) => entry.reason === "stale_claim_takeover" && typeof entry.evidence?.targetPath === "string" && entry.evidence.targetPath.includes("multi-"));
|
|
1302
1324
|
check("each released stale path has its own audited takeover entry", takeoverAudits.length === 2 && takeoverAudits.every((entry) => entry.evidence?.claimOwnerSessionID === "s-stale-owner"));
|
|
1303
1325
|
|
|
1326
|
+
// File-claim TTL reclaim (missed idle release with no readable owner record):
|
|
1327
|
+
// a claim older than the effective TTL cannot belong to an in-flight call, so
|
|
1328
|
+
// it is released with an audited reclaim. A fresh claim still blocks and the
|
|
1329
|
+
// block advertises the reclaim step.
|
|
1330
|
+
console.log("- File-claim TTL reclaim -");
|
|
1331
|
+
const ttlDir = mkdtempSync(join(tmpdir(), "wg-claim-ttl-"));
|
|
1332
|
+
writeFileSync(join(ttlDir, "ttl.ts"), "before");
|
|
1333
|
+
const ttlHooks = await pluginFn({
|
|
1334
|
+
directory: ttlDir,
|
|
1335
|
+
client: fakeClient as any,
|
|
1336
|
+
project: {} as any,
|
|
1337
|
+
worktree: ttlDir,
|
|
1338
|
+
experimental_workspace: {} as any,
|
|
1339
|
+
serverUrl: new URL("http://localhost:4096"),
|
|
1340
|
+
$: undefined as any,
|
|
1341
|
+
});
|
|
1342
|
+
const ttlBefore = ttlHooks["tool.execute.before"];
|
|
1343
|
+
const ttlAfter = ttlHooks["tool.execute.after"];
|
|
1344
|
+
todo("s-ttl-owner", item("edit ttl file", "in_progress"));
|
|
1345
|
+
todo("s-ttl-claimant", item("take over ttl claim", "in_progress"));
|
|
1346
|
+
await recordRead(ttlBefore, ttlAfter, "s-ttl-owner", join(ttlDir, "ttl.ts"), "ttl-read-owner");
|
|
1347
|
+
await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-owner", callID: "ttl-claim" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "a" } });
|
|
1348
|
+
const previousClaimTtl = process.env.WORKFLOW_GUARD_CLAIM_TTL_MS;
|
|
1349
|
+
process.env.WORKFLOW_GUARD_CLAIM_TTL_MS = "25";
|
|
1350
|
+
check("claim TTL honours the environment override", fileClaimTtlMs(ttlDir) === 25);
|
|
1351
|
+
await recordRead(ttlBefore, ttlAfter, "s-ttl-claimant", join(ttlDir, "ttl.ts"), "ttl-read-claimant");
|
|
1352
|
+
let freshTtlBlocked = false;
|
|
1353
|
+
try {
|
|
1354
|
+
await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-blocked" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "b" } });
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
freshTtlBlocked = String(error).includes("is claimed by session") && String(error).includes("Reclaim step");
|
|
1357
|
+
}
|
|
1358
|
+
check("a claim within the TTL still blocks and names the reclaim step", freshTtlBlocked);
|
|
1359
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
1360
|
+
let expiredTtlAllowed = true;
|
|
1361
|
+
try {
|
|
1362
|
+
await ttlBefore?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-reclaimed" }, { args: { filePath: join(ttlDir, "ttl.ts"), content: "c" } });
|
|
1363
|
+
} catch {
|
|
1364
|
+
expiredTtlAllowed = false;
|
|
1365
|
+
}
|
|
1366
|
+
check("an expired claim is reclaimed for the next claimant", expiredTtlAllowed);
|
|
1367
|
+
const ttlAudit = getRecentAuditEntries(40).find((entry) => entry.reason === "claim_ttl_expired" && typeof entry.evidence?.targetPath === "string" && entry.evidence.targetPath.endsWith("ttl.ts"));
|
|
1368
|
+
check("TTL reclaim is audited with the released path, owner, and age", ttlAudit?.decision === "allow" && ttlAudit.evidence?.claimOwnerSessionID === "s-ttl-owner" && typeof ttlAudit.evidence?.claimAgeMs === "number" && ttlAudit.evidence.claimAgeMs >= 25);
|
|
1369
|
+
await ttlAfter?.({ tool: "edit", sessionID: "s-ttl-claimant", callID: "ttl-reclaimed", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1370
|
+
if (previousClaimTtl === undefined) delete process.env.WORKFLOW_GUARD_CLAIM_TTL_MS;
|
|
1371
|
+
else process.env.WORKFLOW_GUARD_CLAIM_TTL_MS = previousClaimTtl;
|
|
1372
|
+
const ttlConfigDir = mkdtempSync(join(tmpdir(), "wg-claim-ttl-cfg-"));
|
|
1373
|
+
mkdirSync(join(ttlConfigDir, ".opencode"), { recursive: true });
|
|
1374
|
+
writeFileSync(join(ttlConfigDir, ".opencode", "workflow-guard.json"), JSON.stringify({ claimTtlMs: 1234 }));
|
|
1375
|
+
reloadProjectConfig(ttlConfigDir);
|
|
1376
|
+
check("project config claimTtlMs sets the claim TTL", fileClaimTtlMs(ttlConfigDir) === 1234);
|
|
1377
|
+
check("default claim TTL is five minutes", DEFAULT_FILE_CLAIM_TTL_MS === 300_000);
|
|
1378
|
+
|
|
1304
1379
|
// Fail-closed: no session lookup on the client, and a lookup that throws.
|
|
1305
1380
|
const noLookupDir = mkdtempSync(join(tmpdir(), "wg-claim-nolookup-"));
|
|
1306
1381
|
writeFileSync(join(noLookupDir, "file.ts"), "before");
|
|
@@ -1316,7 +1391,7 @@ let noLookupBlocked = false;
|
|
|
1316
1391
|
try {
|
|
1317
1392
|
await noLookupBefore?.({ tool: "edit", sessionID: "s-nolookup-claimant", callID: "nolookup-claimant" }, { args: { filePath: join(noLookupDir, "file.ts"), content: "b" } });
|
|
1318
1393
|
} catch (error) {
|
|
1319
|
-
noLookupBlocked = String(error).includes("claimed by
|
|
1394
|
+
noLookupBlocked = String(error).includes("is claimed by session");
|
|
1320
1395
|
}
|
|
1321
1396
|
check("stale takeover fails closed when the client has no session lookup", noLookupBlocked);
|
|
1322
1397
|
|
|
@@ -1334,7 +1409,7 @@ let throwLookupBlocked = false;
|
|
|
1334
1409
|
try {
|
|
1335
1410
|
await throwLookupBefore?.({ tool: "edit", sessionID: "s-throwlookup-claimant", callID: "throwlookup-claimant" }, { args: { filePath: join(throwLookupDir, "file.ts"), content: "b" } });
|
|
1336
1411
|
} catch (error) {
|
|
1337
|
-
throwLookupBlocked = String(error).includes("claimed by
|
|
1412
|
+
throwLookupBlocked = String(error).includes("is claimed by session");
|
|
1338
1413
|
}
|
|
1339
1414
|
check("stale takeover fails closed when the session lookup throws", throwLookupBlocked);
|
|
1340
1415
|
|
|
@@ -2488,6 +2563,59 @@ writeFileSync(join(verifyRepo, "package.json"), JSON.stringify({ scripts: { test
|
|
|
2488
2563
|
await call("bash", { command: "git restore git.ts" }, { sessionID: "s-verify-git" });
|
|
2489
2564
|
check("git worktree mutation invalidates cached verification", blocked(await call("todowrite", { todos: [item("git work", "completed")] }, { sessionID: "s-verify-git" })));
|
|
2490
2565
|
|
|
2566
|
+
// G6: a configured verify command must leave visible evidence in guard_status,
|
|
2567
|
+
// not only an auto-detected command or an in-memory result. The package.json
|
|
2568
|
+
// test script deliberately fails, so a passing run proves the project config
|
|
2569
|
+
// wins over detection.
|
|
2570
|
+
console.log("- G6: configured verification evidence in guard_status -");
|
|
2571
|
+
const prevG6VerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
|
|
2572
|
+
delete process.env.WORKFLOW_GUARD_VERIFY;
|
|
2573
|
+
const g6Repo = mkdtempSync(join(tmpdir(), "wg-g6-verify-status-"));
|
|
2574
|
+
spawnSync("git", ["init", "-b", "feature/g6"], { cwd: g6Repo });
|
|
2575
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: g6Repo });
|
|
2576
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: g6Repo });
|
|
2577
|
+
writeFileSync(join(g6Repo, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(1)'" } }));
|
|
2578
|
+
writeFileSync(join(g6Repo, "code.ts"), "base\n");
|
|
2579
|
+
spawnSync("git", ["add", "."], { cwd: g6Repo });
|
|
2580
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: g6Repo });
|
|
2581
|
+
mkdirSync(join(g6Repo, ".opencode"), { recursive: true });
|
|
2582
|
+
writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(0)'" }));
|
|
2583
|
+
reloadProjectConfig(g6Repo);
|
|
2584
|
+
setWorkspaceRoot(g6Repo);
|
|
2585
|
+
resetVerifyState();
|
|
2586
|
+
todo("s-g6", item("g6 configured verification", "in_progress"));
|
|
2587
|
+
await call("edit", { filePath: join(g6Repo, "code-after.ts"), content: "after\n" }, { sessionID: "s-g6" });
|
|
2588
|
+
const g6Pass = await call("todowrite", { todos: [item("g6 configured verification", "completed")] }, { sessionID: "s-g6" });
|
|
2589
|
+
check("G6 configured command finalizes when it passes", !blocked(g6Pass));
|
|
2590
|
+
const g6Plugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: g6Repo, worktree: g6Repo, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
|
|
2591
|
+
const g6Status = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
|
|
2592
|
+
check(
|
|
2593
|
+
"G6 guard_status reports the configured command and its source",
|
|
2594
|
+
g6Status.projectConfig.verifyCommand === "node -e 'process.exit(0)'" && g6Status.projectConfig.verifyCommandSource === "project-config",
|
|
2595
|
+
);
|
|
2596
|
+
check(
|
|
2597
|
+
"G6 guard_status reports lastVerify with a timestamp, duration, and commit hash",
|
|
2598
|
+
typeof g6Status.lastVerify?.timestamp === "number" && g6Status.lastVerify.timestamp > 0 &&
|
|
2599
|
+
typeof g6Status.lastVerify?.durationMs === "number" && g6Status.lastVerify.durationMs >= 0 &&
|
|
2600
|
+
typeof g6Status.lastVerify?.commitHash === "string" && g6Status.lastVerify.commitHash.length === 40 &&
|
|
2601
|
+
g6Status.lastVerify?.fresh === true,
|
|
2602
|
+
);
|
|
2603
|
+
await call("edit", { filePath: join(g6Repo, "code-stale.ts"), content: "stale\n" }, { sessionID: "s-g6" });
|
|
2604
|
+
const g6StaleStatus = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
|
|
2605
|
+
check("G6 lastVerify goes not-fresh after a later mutation", g6StaleStatus.lastVerify?.fresh === false);
|
|
2606
|
+
writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(1)'" }));
|
|
2607
|
+
reloadProjectConfig(g6Repo);
|
|
2608
|
+
resetVerifyState();
|
|
2609
|
+
todo("s-g6-fail", item("g6 failing verification", "in_progress"));
|
|
2610
|
+
await call("edit", { filePath: join(g6Repo, "code-fail.ts"), content: "fail\n" }, { sessionID: "s-g6-fail" });
|
|
2611
|
+
const g6Fail = await call("todowrite", { todos: [item("g6 failing verification", "completed")] }, { sessionID: "s-g6-fail" });
|
|
2612
|
+
check("G6 a deliberately failing configured command blocks finalization", blocked(g6Fail) && String(g6Fail).includes("verification"));
|
|
2613
|
+
if (prevG6VerifyEnv !== undefined) process.env.WORKFLOW_GUARD_VERIFY = prevG6VerifyEnv;
|
|
2614
|
+
rmSync(g6Repo, { recursive: true, force: true });
|
|
2615
|
+
reloadProjectConfig(verifyRepo);
|
|
2616
|
+
setWorkspaceRoot(verifyRepo);
|
|
2617
|
+
resetVerifyState();
|
|
2618
|
+
|
|
2491
2619
|
// Ecosystem verification detection
|
|
2492
2620
|
const rustRepo = mkdtempSync(join(tmpdir(), "wg-rust-"));
|
|
2493
2621
|
writeFileSync(join(rustRepo, "Cargo.toml"), "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n");
|
|
@@ -3606,6 +3734,17 @@ check("plugin registers guard_audit tool", typeof customPlugin.tool?.guard_audit
|
|
|
3606
3734
|
check("plugin registers guard_why tool", typeof customPlugin.tool?.guard_why?.execute === "function");
|
|
3607
3735
|
check("plugin registers record_review tool", typeof customPlugin.tool?.record_review?.execute === "function");
|
|
3608
3736
|
|
|
3737
|
+
// G2 regression: record_review is offered to every session regardless of the
|
|
3738
|
+
// review gate, so the only thing that can withhold it is the host's per-agent
|
|
3739
|
+
// permission list. A reviewer agent with a deny-all list must be granted it in
|
|
3740
|
+
// its own frontmatter; the guard cannot inject it past host permissions.
|
|
3741
|
+
const noReviewRoot = mkdtempSync(join(tmpdir(), "wg-record-review-gate-off-"));
|
|
3742
|
+
mkdirSync(join(noReviewRoot, ".opencode"), { recursive: true });
|
|
3743
|
+
writeFileSync(join(noReviewRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ requireReview: false }));
|
|
3744
|
+
const noReviewPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: noReviewRoot, worktree: noReviewRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
|
|
3745
|
+
check("record_review stays registered with the review gate off, so only host permissions gate the call", typeof noReviewPlugin.tool?.record_review?.execute === "function" && typeof noReviewPlugin.tool?.record_review?.description === "string");
|
|
3746
|
+
rmSync(noReviewRoot, { recursive: true, force: true });
|
|
3747
|
+
|
|
3609
3748
|
const statusResult = await customPlugin.tool?.guard_status?.execute({}, {} as any);
|
|
3610
3749
|
check("guard_status executes and returns JSON string", typeof statusResult === "string" && statusResult.includes("workspaceRoot"));
|
|
3611
3750
|
const parsedStatus = JSON.parse(statusResult as string);
|
|
@@ -3625,6 +3764,45 @@ const requirementsPlugin = await (defaultExport?.server ?? WorkflowGuard)({ dire
|
|
|
3625
3764
|
setWorkspaceRoot(root);
|
|
3626
3765
|
const requirementsStatus = JSON.parse(String(await requirementsPlugin.tool?.guard_status?.execute({}, {} as any)));
|
|
3627
3766
|
check("guard_status reports configured unsatisfied requirements directly", requirementsStatus.workspaceRoot === requirementsRoot && ["verification", "review", "documentation"].every((requirement) => requirementsStatus.outstandingRequirements.includes(requirement)));
|
|
3767
|
+
check(
|
|
3768
|
+
"guard_status names the project config file it read",
|
|
3769
|
+
typeof requirementsStatus.projectConfig.configPath === "string" &&
|
|
3770
|
+
requirementsStatus.projectConfig.configPath.endsWith("/.opencode/workflow-guard.json") &&
|
|
3771
|
+
requirementsStatus.projectConfig.verifyCommand === "node -e 'process.exit(0)'" &&
|
|
3772
|
+
requirementsStatus.projectConfig.verifyCommandSource === "project-config",
|
|
3773
|
+
);
|
|
3774
|
+
|
|
3775
|
+
const noConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-no-config-"));
|
|
3776
|
+
spawnSync("git", ["init", "-b", "feature/no-config"], { cwd: noConfigRoot });
|
|
3777
|
+
const noConfigPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: noConfigRoot, worktree: noConfigRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
|
|
3778
|
+
const noConfigStatus = JSON.parse(String(await noConfigPlugin.tool?.guard_status?.execute({}, {} as any)));
|
|
3779
|
+
check(
|
|
3780
|
+
"guard_status distinguishes no config and no detectable verify command",
|
|
3781
|
+
noConfigStatus.projectConfig.configPath === null && noConfigStatus.projectConfig.verifyCommand === null && noConfigStatus.projectConfig.verifyCommandSource === null,
|
|
3782
|
+
);
|
|
3783
|
+
|
|
3784
|
+
const autoDetectRoot = mkdtempSync(join(tmpdir(), "wg-status-autodetect-"));
|
|
3785
|
+
spawnSync("git", ["init", "-b", "feature/autodetect"], { cwd: autoDetectRoot });
|
|
3786
|
+
writeFileSync(join(autoDetectRoot, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(0)'" } }));
|
|
3787
|
+
const autoDetectPlugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: autoDetectRoot, worktree: autoDetectRoot, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
|
|
3788
|
+
const autoDetectStatus = JSON.parse(String(await autoDetectPlugin.tool?.guard_status?.execute({}, {} as any)));
|
|
3789
|
+
check(
|
|
3790
|
+
"guard_status attributes an auto-detected verify command to detection, not config",
|
|
3791
|
+
autoDetectStatus.projectConfig.configPath === null && autoDetectStatus.projectConfig.verifyCommand === "npm test" && autoDetectStatus.projectConfig.verifyCommandSource === "auto-detected",
|
|
3792
|
+
);
|
|
3793
|
+
check("verifyCommandSource reports project config directly", verifyCommandSource(requirementsRoot) === "project-config" && verifyCommandSource(autoDetectRoot) === "auto-detected" && verifyCommandSource(noConfigRoot) === null);
|
|
3794
|
+
const prevStatusVerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
|
|
3795
|
+
process.env.WORKFLOW_GUARD_VERIFY = "node -e 'process.exit(0)'";
|
|
3796
|
+
check(
|
|
3797
|
+
"verify command resolution puts the environment ahead of project config and detection",
|
|
3798
|
+
verifyCommandSource(requirementsRoot) === "environment" && detectVerifyCommand(requirementsRoot) === "node -e 'process.exit(0)'",
|
|
3799
|
+
);
|
|
3800
|
+
if (prevStatusVerifyEnv === undefined) delete process.env.WORKFLOW_GUARD_VERIFY;
|
|
3801
|
+
else process.env.WORKFLOW_GUARD_VERIFY = prevStatusVerifyEnv;
|
|
3802
|
+
check("existingProjectConfigPath returns null-ish for a repo without config", existingProjectConfigPath(noConfigRoot) === undefined);
|
|
3803
|
+
rmSync(noConfigRoot, { recursive: true, force: true });
|
|
3804
|
+
rmSync(autoDetectRoot, { recursive: true, force: true });
|
|
3805
|
+
reloadProjectConfig(root);
|
|
3628
3806
|
|
|
3629
3807
|
const conflictingConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-conflicting-config-"));
|
|
3630
3808
|
mkdirSync(join(conflictingConfigRoot, ".opencode"), { recursive: true });
|
|
@@ -4174,6 +4352,14 @@ const strictSubagentResult = await strictPlugin.tool?.record_review?.execute(
|
|
|
4174
4352
|
check("strict mode: subagent recorder records the approval", typeof strictSubagentResult === "string" && strictSubagentResult.includes("APPROVED"));
|
|
4175
4353
|
const strictStatusAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_status?.execute({ directory: strictRepo }, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
|
|
4176
4354
|
check("strict mode: subagent approval satisfies the review gate", !strictStatusAfterSubagent.outstandingRequirements.includes("review") && strictStatusAfterSubagent.lastReview?.fresh === true);
|
|
4355
|
+
check(
|
|
4356
|
+
"strict mode: guard_status attributes the approval to the subagent recorder, not its parent",
|
|
4357
|
+
strictStatusAfterSubagent.lastReview?.recorderRole === "subagent" &&
|
|
4358
|
+
strictStatusAfterSubagent.lastReview?.recorderSessionID === "s-strict-reviewer" &&
|
|
4359
|
+
strictStatusAfterSubagent.lastReview?.targetSessionID === "s-strict-root" &&
|
|
4360
|
+
strictStatusAfterSubagent.lastReview?.recorderSessionID !== strictStatusAfterSubagent.lastReview?.targetSessionID &&
|
|
4361
|
+
typeof strictStatusAfterSubagent.lastReview?.timestamp === "number",
|
|
4362
|
+
);
|
|
4177
4363
|
const strictPrAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_why?.execute(strictPrProbe, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
|
|
4178
4364
|
check("strict mode: PR preflight passes after subagent-recorded approval", strictPrAfterSubagent.status !== "blocked" && (strictPrAfterSubagent.status === "allowed" || strictPrAfterSubagent.code === "remote_state_unchecked"));
|
|
4179
4365
|
if (strictPrAfterSubagent.status === "blocked") console.log(" blocked:", strictPrAfterSubagent.message);
|
|
@@ -4582,6 +4768,16 @@ const linkedAbsoluteWrite = await call("bash", { command: `echo x > ${join(wtRep
|
|
|
4582
4768
|
check("an absolute target in the primary checkout stays allowed from a linked worktree", !blocked(linkedAbsoluteWrite));
|
|
4583
4769
|
const linkedOutsideWrite = await call("bash", { command: `echo x > ${join(foreignWtRepo, "outside.txt")}`, workdir: wtLinked }, { sessionID: "s-wt-foreign", worktree: wtRepo, directory: wtRepo });
|
|
4584
4770
|
check("an absolute target outside both checkouts is still blocked from a linked worktree", blocked(linkedOutsideWrite));
|
|
4771
|
+
// A session bound to the primary checkout must not silently edit into a sibling
|
|
4772
|
+
// worktree. The mutation still stays refused (a tool-call path never re-anchors
|
|
4773
|
+
// the boundary), but the block names the mismatch and the host move, or the
|
|
4774
|
+
// agent works around the guard through the shell.
|
|
4775
|
+
todo("s-wt-mismatch", item("edit in the linked worktree", "in_progress"));
|
|
4776
|
+
const mismatchWrite = await call("write", { filePath: join(wtLinked, "mismatch.ts"), content: "x" }, { sessionID: "s-wt-mismatch", worktree: wtRepo, directory: wtRepo });
|
|
4777
|
+
check(
|
|
4778
|
+
"an edit into a linked worktree names the worktree mismatch and the move",
|
|
4779
|
+
blocked(mismatchWrite) && String(mismatchWrite).includes(wtLinked) && String(mismatchWrite).includes(wtRepo) && String(mismatchWrite).includes("session_move"),
|
|
4780
|
+
);
|
|
4585
4781
|
|
|
4586
4782
|
// An in-command `cd` moves the tree later segments run in, so the walk has to
|
|
4587
4783
|
// follow it. Judging every segment against the shell's initial `workdir` let
|