opencode-workflow-guard 1.19.3 → 1.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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. A claim created before its owner's last recorded idle timestamp cannot belong to an in-flight tool call. When another session hits such a conflict, the stale claim is released with an audited `stale_claim_takeover` entry. Owners still mid-session (no idle timestamp), clients without a session lookup, and failed lookups keep the block (fail-closed). `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.
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 cause attribution:** `/tmp/opencode` is the environment's designated agent scratch space, but the workspace boundary is workspace-absolute and does not cover it. Writes there stay blocked. The block message names the directory and points to the remedy instead of reading as a guard bug. The remedy is an untracked scratch file inside the workspace, for example `.tmp-notes.md`. The enforcement decision is unchanged.
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).
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, and attributes the effective verify command to `project-config`, `auto-detected`, or neither. |
53
+ | **File-Claim TTL Reclaim** | Verifies a claim within the TTL blocks and names the reclaim step, an expired claim is reclaimed for the next claimant, the reclaim writes a `claim_ttl_expired` audit with the owner and age, the environment override wins, and project config `claimTtlMs` is honored. |
54
+ | **record_review Registration** | Verifies `record_review` stays registered when the review gate is disabled, so a reviewer agent's host permission list, not project config, is what can withhold the call. |
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. |
@@ -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 "claimed by another active session" though no other session is working:** A missed `session.idle` release can leave a finished session's direct-edit claim behind. Claims have no expiry. Every other session is blocked from that path until the owning session is deleted or the service restarts. On a real (non-simulated) call the takeover resolves it. A claim created before its owner's last recorded idle timestamp is provably stale and is released. `guard_audit` records a `file-claims` entry with reason `stale_claim_takeover`. Sessions still mid-turn (no idle timestamp) 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.
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:** The environment designates that directory as agent scratch space. The workspace boundary is workspace-absolute, though, and does not cover it. Writes there stay blocked, and the block message names both the directory and the remedy. Write scratch as an untracked file inside the workspace instead, for example `.tmp-notes.md`. The boundary has no override for it, and this attribution does not change the enforcement decision.
118
+ - **A scratch write to `/tmp/opencode` is blocked:** A write there is allowed for a real session when the target's canonical location stays inside that exact directory. The root must be a real directory, not a symlink. A symlink inside it that leaves the directory is refused, and so is a sibling path that merely shares the prefix or a `..` traversal out of it. A write with no session id is also blocked. Use a real path under `/tmp/opencode` or an untracked file inside the workspace, for example `.tmp-notes.md`. The allowance is a file-mutation allowance only, and the boundary has no override for anything outside it.
119
+ - **A reviewer agent cannot call `record_review`:** The guard registers `record_review` for every session, independent of `requireReview`. A host with a per-agent permission list can still withhold the call, and a reviewer agent that starts from a deny-all list (`action: "*"`, `resource: "*"`, `effect: deny`) does exactly that. The guard cannot inject the tool past host permissions, so grant it in that agent's own frontmatter with an explicit allow rule for `record_review`, or relay the verdict through a session that already has the tool. `guard_status` reporting the review gate as required proves nothing about the reviewer's toolset. This is a permission grant in the agent definition, not a guard policy change.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.19.3",
3
+ "version": "1.19.4",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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 } : null, lastReview: lastR && reviewEvidenceRecord ? { reviewer: lastR.reviewer, passed: lastR.passed, summary: lastR.summary, fresh: reviewFresh, evidenceId: reviewEvidenceRecord.id } : null, lastDogfood: lastD && lastDogfoodEvidence ? { scenarioId: lastD.scenarioId, verdict: lastD.verdict, host: lastD.host.label, taxonomyClass: lastD.taxonomyClass ?? null, runCount: lastD.runCount, fresh: dogfoodGate.required ? dogfoodFresh : null, evidenceId: lastDogfoodEvidence.id, missingHosts: dogfoodGate.missingHosts, coveredHosts: (dogfoodGate.matchedRecords ?? []).map((record) => record.host.label) } : null, ralph: { enabled: isRalphModeEnabled(root), maxIterations: getRalphMaxIterations(root), outcome: ralphOutcome ?? null }, projectConfig: { configPath: existingProjectConfigPath(root) ?? null, profile: getOperationProfile(root), protectedBranches: cfg.protectedBranches ?? ["main", "master"], verifyCommand: verifyCommand ?? null, verifyCommandSource: verifySource, requireReview: reviewRequired, requireDocumentation: documentationRequired, requireSubagentReview: isSubagentReviewRequired(root), requireDogfood: dogfoodGate.required, dogfoodDeployMatrix: dogfoodGate.required ? getDogfoodDeployMatrix(root) : [], recoveryCheckpoints: isRecoveryCheckpointsEnabled(root) }, gitHygiene: gitHygieneSnapshot(root) ?? null }, null, 2);
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) }),
@@ -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
- ? `Blocked: patch targets file '${patchPath}' under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover; write scratch as an untracked file inside the workspace root (${currentRoot}) instead (for example .tmp-notes.md).`
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
- ? `Blocked: file path '${target}' is under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover; write scratch as an untracked file inside the workspace root (${currentRoot}) instead (for example .tmp-notes.md).`
360
- : `Blocked: file path '${target}' escapes workspace root (${currentRoot}). All changes must stay within the workspace.`,
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 editTargets(input, currentRoot)) {
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 = editTargets(input, currentRoot);
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
- const writePaths = writePathsInPayload(payload);
615
+ // A scratch write is sanctioned, so it does not need an active todo,
616
+ // a feature branch, or a mutation record. Repository writes in the
617
+ // same payload still do.
618
+ const writePaths = writePathsInPayload(payload).filter((path) => !isAllowedScratchTarget(path, currentRoot, context?.sessionID));
605
619
  if (writePaths.length > 0) {
606
620
  if (context?.agent && isReadOnlyRole(context.agent)) return block("subagent-role", "read_only_role", `Blocked: subagent with read-only role '${context.agent}' cannot perform shell file mutations.`);
607
621
  for (const path of writePaths) if (isProtectedPath(path)) return block("tamper", "protected_path", PROTECTED_PATH_REASON);
@@ -76,6 +76,11 @@ export function projectConfigPath(root: string): string {
76
76
  return candidates.find(existsSync) ?? candidates[0]!;
77
77
  }
78
78
 
79
+ /** The project config file actually read for `root`, or undefined when none exists. */
80
+ export function existingProjectConfigPath(root: string): string | undefined {
81
+ return projectConfigCandidates(root).find(existsSync);
82
+ }
83
+
79
84
  /** Strip JSONC comments and trailing commas without altering string literals. */
80
85
  export function stripJsonComments(jsonc: string): string {
81
86
  let insideString = false;
package/src/lib/types.ts CHANGED
@@ -41,6 +41,12 @@ export interface ProjectConfig {
41
41
  protectedBranches?: string[];
42
42
  verifyCommand?: string;
43
43
  verifyTimeoutMs?: number;
44
+ /**
45
+ * File-claim expiry. A claim older than this cannot belong to an in-flight
46
+ * tool call, so a leaked claim from an ended session is released and audited
47
+ * instead of blocking every other session. Defaults to 5 minutes.
48
+ */
49
+ claimTtlMs?: number;
44
50
  postEditValidators?: Array<{
45
51
  pattern: string;
46
52
  command: string;
@@ -222,6 +228,8 @@ export interface AuditEntry {
222
228
  targetPath?: string;
223
229
  /** Owner of a released stale file claim (stale_claim_takeover audits). */
224
230
  claimOwnerSessionID?: string;
231
+ /** Age of a TTL-expired file claim, in milliseconds (claim_ttl_expired audits). */
232
+ claimAgeMs?: number;
225
233
  verification?: {
226
234
  command: string;
227
235
  passed: boolean;
package/src/lib/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
@@ -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 `Blocked: shell mutation '${mutation.what}' targets '${target}' under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover; write scratch as an untracked file inside the workspace root (${workspaceRoot}) instead (for example .tmp-notes.md).`;
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
- return `Blocked: file '${path}' is claimed by another active session ('${existing.sessionID}'). Wait for that edit to finish or use an isolated worktree.`;
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. A claim created
71
- * BEFORE its owner's last recorded idle timestamp cannot belong to an
72
- * in-flight tool call — that call finished before the turn ended — so it is
73
- * provably stale and is released with an audited takeover. Without an SDK
74
- * client, or when the owner record cannot be read, nothing is released:
75
- * fail-closed keeps live two-session protection intact. Clock skew between
76
- * this process and the server is not expected for a local (same-host)
77
- * service: negative skew fails closed; forward skew could make fresh claims
78
- * look stale and is accepted for that deployment. Concurrent claimants can
79
- * emit duplicate takeover audits (append-only, harmless). Release is
80
- * per-claim: only claims whose ts is provably stale are dropped, re-read
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(payload: string, root: string): string | undefined {
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
  }
@@ -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 cause attribution: /tmp/opencode is the environment's
920
- // designated scratch space, but the workspace boundary is workspace-absolute
921
- // and does not cover it; the message explains that instead of reading as a
922
- // guard bug (6 of the device audit's boundary blocks were this class).
923
- const scratchWrite = await call("write", { filePath: "/tmp/opencode/scratch.txt", content: "x" }, { sessionID: "s-active" });
924
- check("scratch-dir write attributes the environment scratch cause", blocked(scratchWrite) && String(scratchWrite).includes("environment scratch directory") && String(scratchWrite).includes("/tmp/opencode") && !String(scratchWrite).includes("unresolvable variable reference"));
925
- const scratchRedirect = await call("bash", { command: "echo x > /tmp/opencode/out.md" }, { sessionID: "s-active" });
926
- check("scratch-dir redirect attributes the environment scratch cause", blocked(scratchRedirect) && String(scratchRedirect).includes("environment scratch directory"));
927
- const scratchPatch = await call("apply_patch", { patchText: "*** Add File: /tmp/opencode/scratch.ts\n+scratch\n" }, { sessionID: "s-active" });
928
- check("scratch-dir apply_patch attributes the environment scratch cause", blocked(scratchPatch) && String(scratchPatch).includes("environment scratch directory"));
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 another active session");
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 another active session");
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 another active session");
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 another active session");
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 another active session");
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 another active session");
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 another active session");
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
 
@@ -3606,6 +3681,17 @@ check("plugin registers guard_audit tool", typeof customPlugin.tool?.guard_audit
3606
3681
  check("plugin registers guard_why tool", typeof customPlugin.tool?.guard_why?.execute === "function");
3607
3682
  check("plugin registers record_review tool", typeof customPlugin.tool?.record_review?.execute === "function");
3608
3683
 
3684
+ // G2 regression: record_review is offered to every session regardless of the
3685
+ // review gate, so the only thing that can withhold it is the host's per-agent
3686
+ // permission list. A reviewer agent with a deny-all list must be granted it in
3687
+ // its own frontmatter; the guard cannot inject it past host permissions.
3688
+ const noReviewRoot = mkdtempSync(join(tmpdir(), "wg-record-review-gate-off-"));
3689
+ mkdirSync(join(noReviewRoot, ".opencode"), { recursive: true });
3690
+ writeFileSync(join(noReviewRoot, ".opencode", "workflow-guard.json"), JSON.stringify({ requireReview: false }));
3691
+ 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 });
3692
+ 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");
3693
+ rmSync(noReviewRoot, { recursive: true, force: true });
3694
+
3609
3695
  const statusResult = await customPlugin.tool?.guard_status?.execute({}, {} as any);
3610
3696
  check("guard_status executes and returns JSON string", typeof statusResult === "string" && statusResult.includes("workspaceRoot"));
3611
3697
  const parsedStatus = JSON.parse(statusResult as string);
@@ -3625,6 +3711,37 @@ const requirementsPlugin = await (defaultExport?.server ?? WorkflowGuard)({ dire
3625
3711
  setWorkspaceRoot(root);
3626
3712
  const requirementsStatus = JSON.parse(String(await requirementsPlugin.tool?.guard_status?.execute({}, {} as any)));
3627
3713
  check("guard_status reports configured unsatisfied requirements directly", requirementsStatus.workspaceRoot === requirementsRoot && ["verification", "review", "documentation"].every((requirement) => requirementsStatus.outstandingRequirements.includes(requirement)));
3714
+ check(
3715
+ "guard_status names the project config file it read",
3716
+ typeof requirementsStatus.projectConfig.configPath === "string" &&
3717
+ requirementsStatus.projectConfig.configPath.endsWith("/.opencode/workflow-guard.json") &&
3718
+ requirementsStatus.projectConfig.verifyCommand === "node -e 'process.exit(0)'" &&
3719
+ requirementsStatus.projectConfig.verifyCommandSource === "project-config",
3720
+ );
3721
+
3722
+ const noConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-no-config-"));
3723
+ spawnSync("git", ["init", "-b", "feature/no-config"], { cwd: noConfigRoot });
3724
+ 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 });
3725
+ const noConfigStatus = JSON.parse(String(await noConfigPlugin.tool?.guard_status?.execute({}, {} as any)));
3726
+ check(
3727
+ "guard_status distinguishes no config and no detectable verify command",
3728
+ noConfigStatus.projectConfig.configPath === null && noConfigStatus.projectConfig.verifyCommand === null && noConfigStatus.projectConfig.verifyCommandSource === null,
3729
+ );
3730
+
3731
+ const autoDetectRoot = mkdtempSync(join(tmpdir(), "wg-status-autodetect-"));
3732
+ spawnSync("git", ["init", "-b", "feature/autodetect"], { cwd: autoDetectRoot });
3733
+ writeFileSync(join(autoDetectRoot, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(0)'" } }));
3734
+ 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 });
3735
+ const autoDetectStatus = JSON.parse(String(await autoDetectPlugin.tool?.guard_status?.execute({}, {} as any)));
3736
+ check(
3737
+ "guard_status attributes an auto-detected verify command to detection, not config",
3738
+ autoDetectStatus.projectConfig.configPath === null && autoDetectStatus.projectConfig.verifyCommand === "npm test" && autoDetectStatus.projectConfig.verifyCommandSource === "auto-detected",
3739
+ );
3740
+ check("verifyCommandSource reports project config directly", verifyCommandSource(requirementsRoot) === "project-config" && verifyCommandSource(autoDetectRoot) === "auto-detected" && verifyCommandSource(noConfigRoot) === null);
3741
+ check("existingProjectConfigPath returns null-ish for a repo without config", existingProjectConfigPath(noConfigRoot) === undefined);
3742
+ rmSync(noConfigRoot, { recursive: true, force: true });
3743
+ rmSync(autoDetectRoot, { recursive: true, force: true });
3744
+ reloadProjectConfig(root);
3628
3745
 
3629
3746
  const conflictingConfigRoot = mkdtempSync(join(tmpdir(), "wg-status-conflicting-config-"));
3630
3747
  mkdirSync(join(conflictingConfigRoot, ".opencode"), { recursive: true });
@@ -4582,6 +4699,16 @@ const linkedAbsoluteWrite = await call("bash", { command: `echo x > ${join(wtRep
4582
4699
  check("an absolute target in the primary checkout stays allowed from a linked worktree", !blocked(linkedAbsoluteWrite));
4583
4700
  const linkedOutsideWrite = await call("bash", { command: `echo x > ${join(foreignWtRepo, "outside.txt")}`, workdir: wtLinked }, { sessionID: "s-wt-foreign", worktree: wtRepo, directory: wtRepo });
4584
4701
  check("an absolute target outside both checkouts is still blocked from a linked worktree", blocked(linkedOutsideWrite));
4702
+ // A session bound to the primary checkout must not silently edit into a sibling
4703
+ // worktree. The mutation still stays refused (a tool-call path never re-anchors
4704
+ // the boundary), but the block names the mismatch and the host move, or the
4705
+ // agent works around the guard through the shell.
4706
+ todo("s-wt-mismatch", item("edit in the linked worktree", "in_progress"));
4707
+ const mismatchWrite = await call("write", { filePath: join(wtLinked, "mismatch.ts"), content: "x" }, { sessionID: "s-wt-mismatch", worktree: wtRepo, directory: wtRepo });
4708
+ check(
4709
+ "an edit into a linked worktree names the worktree mismatch and the move",
4710
+ blocked(mismatchWrite) && String(mismatchWrite).includes(wtLinked) && String(mismatchWrite).includes("session_move"),
4711
+ );
4585
4712
 
4586
4713
  // An in-command `cd` moves the tree later segments run in, so the walk has to
4587
4714
  // follow it. Judging every segment against the shell's initial `workdir` let