opencode-workflow-guard 1.19.4 → 1.19.6

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/README.md CHANGED
@@ -59,7 +59,7 @@ For complete policy specifications and override rules, see [docs/policies.md](do
59
59
  Enforcement is only half the surface. The plugin also registers first-class agent tools under the same names on OpenCode 1.x and 2.x, so disciplined workflow is the path of least resistance:
60
60
 
61
61
  * **Task Planning:** `guard_next_tasks` surfaces durable repository planning context at session start or during planning. It reads `TODO.md`, `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and plans under `docs/plans/`. `guard_status` reports active guardrails, branch protection, mutation counts, outstanding verification and review gates, a read-only git-hygiene snapshot, and the loaded `pluginVersion`.
62
- * **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform. The reviewer records its verdict with `record_review`, and approvals bind to the reviewed worktree content. An opt-in dogfood gate adds a recorded end-to-end run on real hardware with `record_dogfood`.
62
+ * **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform, and its first line names the workspace, base ref, and diff size it graded. When no listed base yields a diff the tool refuses and names what it tried instead of grading a substitute range. The calling session records the subagent's verdict with `record_review`, and approvals bind to the reviewed worktree content. An opt-in dogfood gate adds a recorded end-to-end run on real hardware with `record_dogfood`.
63
63
  * **Worktree Isolation:** `guard_worktree_create` and `guard_worktree_cleanup` give parallel subagents isolated linked worktrees, so concurrent mutations never collide.
64
64
  * **Technical Debt:** `guard_review_followups` lists open P2/P3 durable review follow-ups. `guard_review_followup_resolve` closes one after the underlying issue is fixed and verified.
65
65
  * **Policy Simulation:** `guard_why` returns the structured policy decision for a tool call or command without performing it. `guard_audit` shows recent audited policy entries.
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. 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.
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. A recognized shell writer is refused with the same reason when its target is claimed: redirection, `tee`, `sed -i`, `cp`/`mv`/`ln`, `rm`, `truncate`, `dd of=`, `git apply`, and `git am`. A `mv` source is checked too, because the move removes it. The check resolves a relative target against the tree the segment actually runs in, so a chained `cd` and a symlink alias are judged where the write lands. A shell write never acquires a claim, so it cannot strand one the edit path must later reclaim, and the provably stale rules release before the conflict is reported. Shell writers remain outside the write-observation and stale-write pre-check, 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
 
@@ -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 (`""`).
@@ -263,9 +264,11 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
263
264
  - `guard_status`, `guard_audit`, `guard_why`, `guard_review_rubric`, `record_review`, `guard_review_followups`, and `guard_review_followup_resolve` provide runtime introspection. They cover guardrail state, audit entries, block explanations, reviewer rubric definitions, reviewer decisions, and durable local review debt. `guard_status` also exposes the effective Ralph opt-in, its iteration budget, and the calling-session outcome when applicable. It reports a read-only `gitHygiene` snapshot (local branches already merged into the mainline, prunable worktree admin entries, and the current branch's base-behind distance). Hygiene itself stays manual: the guard reports, it never prunes or deletes branches. `guard_status` also reports `pluginVersion`, the version of the loaded guard package, so a stale installation is visible.
264
265
  - On OpenCode 2 the same report is also reachable as the server-side `/guard-status` command (`ctx.command.transform`). It delivers the JSON as a synthetic message with no model turn. That path needs no separately installed TUI companion.
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.
267
+ - **The rubric names what it graded:** `guard_review_rubric` prefixes the prompt with `Provenance: workspace=<abs root> base=<ref> diff=<n> bytes fallback=<none|HEAD~1>`. A session's own checkout and the checkout holding the change are not always the same tree, so the caller checks those three facts before trusting the prompt. Pass `directory` to grade another worktree and `base` to name another base. When no listed base yields a diff, the tool refuses with the workspace, every base it tried, and the remedy. It does not run `git diff HEAD~1` behind the caller's back, because that graded a substitute range and named nothing. `HEAD~1` is graded only when the caller passes `base: "HEAD~1"`, and the provenance line then says `base=HEAD~1 fallback=HEAD~1`.
268
+ - **The calling session records the verdict:** A reviewer agent is often configured with a toolset that omits `record_review`, so the injected guidance and both tool descriptions say the calling session records the subagent's verdict. `record_review` binds that verdict to the recorder's resolved directory or an explicit `directory`.
266
269
  - **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
270
  - **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.
271
+ - **`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
272
  - **`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
273
  - **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
274
  - **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
@@ -49,9 +49,11 @@ npm run test:all
49
49
  | **Policy 5: MCP Mutations** | Verifies GitHub/Azure mutating MCP tools are blocked while read-only tools pass. |
50
50
  | **Policy 6: Settings Tamper** | Verifies protection of `opencode.json`, `~/.config/opencode/*`, and `opencode auth`. |
51
51
  | **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. Also verifies the `/tmp/opencode` scratch allowance: a real session may write, redirect, patch, and run an interpreter payload there, while a session-less write, a sibling that shares the prefix, a `..` traversal out of it, and a symlink that leaves it stay blocked. |
52
- | **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. Also verifies `guard_status` names the project config file it read, and attributes the effective verify command to `project-config`, `auto-detected`, or neither. |
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
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. |
54
+ | **Shell Mutation Claim Conflicts** | Verifies a redirect into a claimed path is refused with the claim reason, `tee -a` with its flag parsed is refused, a symlink alias is refused, a chained `cd` is judged in the tree it lands in, a multi-operand mutation is refused when any operand is claimed, a `mv` source is refused because the move removes it, a subagent is refused on a path its parent claimed, `guard_why` reports the conflict as a shell mutation without acquiring a claim, an unclaimed path stays allowed, and the path is allowed once the owning edit releases its claim. |
55
+ | **Review Rubric Provenance** | Verifies the rubric names the workspace, base ref, and diff byte count it graded; grades a linked worktree named by `directory` rather than the caller's checkout; refuses when no base yields a diff, naming the workspace, every base tried, and the remedy, without emitting a rubric body over a substitute range; and honors an explicit `HEAD~1` base with `base=HEAD~1 fallback=HEAD~1`. Also verifies the injected workflow guidance names the calling session as the recorder rather than the subagent. |
56
+ | **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. |
55
57
  | **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
56
58
  | **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
57
59
  | **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.19.4",
3
+ "version": "1.19.6",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -44,7 +44,7 @@ import { todoEvidenceReport } from "../policies/todo.ts";
44
44
  import { existingProjectConfigPath, findGitRoot, loadProjectConfig, projectRootKey } from "./project-config.ts";
45
45
  import { detectVerifyCommand, getCurrentGitCommitHash, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint, verifyCommandSource } from "./verify.ts";
46
46
  import { evaluateDogfoodGate } from "./dogfood.ts";
47
- import { buildReviewRubric } from "./review.ts";
47
+ import { buildReviewRubric, type RubricProvenance } from "./review.ts";
48
48
  import { createGitWorktree, cleanupGitWorktree, validateHostWorktreeDirectory } from "./worktree.ts";
49
49
  import type { HostWorktreePort } from "./host-worktree.ts";
50
50
  import { branchHasDocumentationChange } from "../policies/docs.ts";
@@ -94,7 +94,7 @@ export function buildWorkflowGuardSystemGuidance(options: {
94
94
 
95
95
  if (!options.isReadOnly) {
96
96
  sections.push(
97
- "- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task` that records its verdict with `record_review`.",
97
+ "- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task`. The calling session records that subagent's verdict with `record_review`: a reviewer agent's own toolset may not carry the tool, so the caller owns the record.",
98
98
  "- Worktree Isolation: When orchestrating parallel subagent tasks with `task`, call `guard_worktree_create` to prevent concurrent file conflicts, and `guard_worktree_cleanup` when finished.",
99
99
  );
100
100
  }
@@ -346,13 +346,13 @@ export function createCustomTools(options: {
346
346
  }
347
347
  const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
348
348
  const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
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
+ 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);
350
350
  },
351
351
  }),
352
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) }),
353
353
  guard_why: tool({ description: "Simulate and return the structured policy decision for a specific tool call or command. Proactively use before executing questionable or complex commands to check if they would be blocked by guard policies.", args: { tool: tool.schema.string().describe("Tool name (e.g. bash, edit, write, read, apply_patch)"), input: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Tool input arguments") }, execute: async (args, toolContext) => JSON.stringify(await runWithRuntimeState(await resolveCallWorkspace(toolContext), client, () => guardToolCallImpl(args.tool, args.input ?? {}, { sessionID: toolContext.sessionID, worktree: toolContext.worktree, directory: toolContext.directory, simulate: true })), null, 2) }),
354
354
  record_review: tool({
355
- description: "Record a secondary reviewer agent's approval or critique of the current changes. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
355
+ description: "Record a secondary reviewer agent's approval or critique of the current changes. Call it from the session that owns the verdict: a reviewer subagent may not carry this tool at all, because host permissions decide an agent's toolset. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
356
356
  args: {
357
357
  reviewer: tool.schema.string().describe("Identifier/name of the reviewer subagent"),
358
358
  summary: tool.schema.string().describe("Review findings summary across the 5 core review axes"),
@@ -408,7 +408,7 @@ export function createCustomTools(options: {
408
408
  recorderRole: parentSessionID ? ("subagent" as const) : ("root" as const),
409
409
  targetSessionID: parentSessionID ?? toolContext.sessionID,
410
410
  };
411
- 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" });
412
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 });
413
413
  auditVerdict(args.passed ? "approved" : "changes_requested", args.passed ? "approved" : "changes_requested", binding);
414
414
  const recorderNote = parentSessionID
@@ -547,7 +547,7 @@ export function createCustomTools(options: {
547
547
  guard_review_followups: tool({ description: "List durable local P2/P3 review follow-ups (technical debt) for this project. Proactively check during planning or before final verification to address open findings.", args: {}, execute: async () => JSON.stringify(followupStore ? listReviewFollowups(followupStore) : [], null, 2) }),
548
548
  guard_review_followup_resolve: tool({ description: "Resolve a durable local review follow-up after the underlying issue has been fixed and verified.", args: { id: tool.schema.string() }, execute: async (args) => followupStore && resolveReviewFollowup(followupStore, args.id) ? `[workflow-guard] Review follow-up ${args.id} resolved.` : `[workflow-guard] Review follow-up ${args.id} was not open or was not found.` }),
549
549
  guard_review_rubric: tool({
550
- description: "Get the secondary-review rubric for the current branch diff across 5 core review axes (test integrity, task completeness, cleanliness, security, platform). The orchestrator should call this before finalizing work or creating a PR, then spawn a reviewer subagent with the rubric as the prompt, which records its verdict via record_review.",
550
+ description: "Get the secondary-review rubric for a branch diff across 5 core review axes (test integrity, task completeness, cleanliness, security, platform). The orchestrator should call this before finalizing work or creating a PR, then spawn a reviewer subagent with the rubric as the prompt. The calling session records that subagent's verdict with record_review. The rubric's first line names the workspace, base ref, and diff size it graded, so check those describe the change under review; pass directory and/or base when the change lives in another checkout.",
551
551
  args: {
552
552
  base: tool.schema.string().optional().describe("Base ref to diff against (default: origin/main, origin/master, main, master)"),
553
553
  directory: tool.schema.string().optional().describe("Target repository directory (defaults to active session directory or workspace root)"),
@@ -559,11 +559,24 @@ export function createCustomTools(options: {
559
559
  const bases = sanitizedBase ? [sanitizedBase] : ["origin/main", "origin/master", "main", "master"];
560
560
  const rubricWorkspace = await resolveCallWorkspace(toolContext, args?.directory);
561
561
  let diffText = "";
562
+ let usedBase: string | undefined;
562
563
  // Revision before the trailing `--` (LL-001) so the base ref is
563
564
  // always parsed as a revision, never as a pathspec.
564
- for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; break; } }
565
- if (!diffText) { const last = spawnSync("git", ["diff", "--no-ext-diff", "HEAD~1", "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); diffText = last.status === 0 ? last.stdout : "(no diff available)"; }
566
- return buildReviewRubric(diffText);
565
+ for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; usedBase = base; break; } }
566
+ // No listed base produced a diff. Grading a substitute range
567
+ // returned a rubric over the wrong change and named nothing, so
568
+ // refuse instead. HEAD~1 is graded only when the caller asks for
569
+ // it, and then the provenance line says which range was graded.
570
+ if (!diffText) {
571
+ return `[workflow-guard] No review diff found: workspace=${rubricWorkspace} bases=${bases.join(", ")} diff=0 bytes. No rubric was produced. Remedy: pass base: "<ref>" naming the base that holds the change (base: "HEAD~1" grades the last commit), and directory: "<absolute checkout>" when the change lives in another worktree.`;
572
+ }
573
+ const provenance: RubricProvenance = {
574
+ workspace: rubricWorkspace,
575
+ base: usedBase ?? null,
576
+ diffBytes: Buffer.byteLength(diffText, "utf8"),
577
+ fallback: usedBase === "HEAD~1" ? "HEAD~1" : "none",
578
+ };
579
+ return buildReviewRubric(diffText, undefined, provenance);
567
580
  },
568
581
  }),
569
582
  guard_worktree_create: tool({
package/src/lib/review.ts CHANGED
@@ -8,8 +8,32 @@ import {
8
8
 
9
9
  export { recordReviewResult, getLastReviewResult, resetReviewState, lastReview, sessionReviews };
10
10
 
11
- export function buildReviewRubric(diffText: string, taskPrompt?: string): string {
12
- return [
11
+ /**
12
+ * What a rubric actually graded. A session's own checkout and the checkout
13
+ * holding the change are not always the same tree, so the rubric must name the
14
+ * tree it read and the base it compared against.
15
+ */
16
+ export interface RubricProvenance {
17
+ /** Absolute workspace root the diff was taken from. */
18
+ workspace: string;
19
+ /** Base ref actually used, or null when the rubric was not produced. */
20
+ base: string | null;
21
+ /** Bytes in the diff the rubric grades, before its own truncation. */
22
+ diffBytes: number;
23
+ /**
24
+ * `HEAD~1` when the graded range is the last commit rather than a branch
25
+ * base. It says which range was graded, not who asked for it: an explicit
26
+ * `base: "HEAD~1"` marks it too, because the range is the same either way.
27
+ */
28
+ fallback: "none" | "HEAD~1";
29
+ }
30
+
31
+ export function rubricProvenanceLine(provenance: RubricProvenance): string {
32
+ return `Provenance: workspace=${provenance.workspace} base=${provenance.base ?? "none"} diff=${provenance.diffBytes} bytes fallback=${provenance.fallback}`;
33
+ }
34
+
35
+ export function buildReviewRubric(diffText: string, taskPrompt?: string, provenance?: RubricProvenance): string {
36
+ const lines = [
13
37
  "# Secondary Review Agent Quality Gate",
14
38
  "",
15
39
  "Evaluate this code change independently with fresh context across these 5 core axes:",
@@ -47,5 +71,7 @@ export function buildReviewRubric(diffText: string, taskPrompt?: string): string
47
71
  "```",
48
72
  "",
49
73
  "Provide your verdict: `[APPROVE]` or `[REQUEST_CHANGES]` with concise, actionable findings ranked by priority (P0-P3).",
50
- ].join("\n");
74
+ ];
75
+ if (provenance) lines.unshift(rubricProvenanceLine(provenance), "");
76
+ return lines.join("\n");
51
77
  }
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
@@ -137,6 +137,10 @@ export interface ReviewResult {
137
137
  summary: string;
138
138
  timestamp: number;
139
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";
140
144
  workspace?: string;
141
145
  commitHash?: string;
142
146
  gitStatus?: string;
@@ -12,7 +12,7 @@ import { isCollaborationInvocation, isProtectedPath, PROTECTED_PATH_REASON } fro
12
12
  import { isSecretPath, secretIn } from "./secrets.ts";
13
13
  import { isGitTreeWriteText, branchGuardReason, onProtectedBranch, parseGitInvocation } from "./git.ts";
14
14
  import { findGitRoot, isSameGitRepo, projectRootKey } from "../lib/project-config.ts";
15
- import { canonicalPath } from "./file-claims.ts";
15
+ import { canonicalPath, fileClaimConflictReason, releaseStaleFileClaims } from "./file-claims.ts";
16
16
  import {
17
17
  effectiveTodos,
18
18
  effectiveTodoOwnerSessionID,
@@ -798,6 +798,23 @@ export async function guardShellMutation(
798
798
  // that no command executes is prose, so its lines are not judged either.
799
799
  const masked = maskDataHeredocBodies(segment);
800
800
  const cleanSegment = isCollaborationInvocation(masked) ? stripQuotedSpans(masked) : masked;
801
+ // Claims are keyed by canonical absolute path, so a relative or
802
+ // `~`-relative target is resolved against the tree this segment runs in
803
+ // before comparing. A provably stale claim is released first, exactly as
804
+ // the edit path does, so the remedy in the conflict message is reachable
805
+ // from the shell too. Shell writes never acquire a claim.
806
+ const claimConflictForTarget = async (candidate: string): Promise<string | undefined> => {
807
+ if (!sessionID) return undefined;
808
+ const expanded = expandShellTargetPath(candidate);
809
+ if (expanded === null) return undefined;
810
+ const claimPath = resolve(runRoot, expanded);
811
+ let conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
812
+ if (conflict && record) {
813
+ await releaseStaleFileClaims([claimPath], sessionID, runRoot);
814
+ conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
815
+ }
816
+ return conflict;
817
+ };
801
818
  const secretSource = secretSourceInFilesystemCommand(cleanSegment);
802
819
  if (secretSource) {
803
820
  return `Blocked: shell command would copy, move, or link sensitive file '${secretSource}' under a non-secret name.`;
@@ -818,6 +835,10 @@ export async function guardShellMutation(
818
835
  }
819
836
  return `Blocked: mv would remove source '${source}' from outside the workspace root (${workspaceRoot}). File mutations must stay within the workspace.`;
820
837
  }
838
+ // A move removes its source, so a source another session is
839
+ // editing is a conflict even though the destination is fine.
840
+ const sourceConflict = await claimConflictForTarget(source);
841
+ if (sourceConflict) return sourceConflict;
821
842
  }
822
843
  }
823
844
  const simpleMutations = simpleFilesystemMutations(cleanSegment);
@@ -867,6 +888,13 @@ export async function guardShellMutation(
867
888
  if (onProtectedBranch(runRoot)) {
868
889
  return branchGuardReason();
869
890
  }
891
+ // A direct edit claims its target for the tool-call lifetime so two
892
+ // sessions cannot race it. A shell writer changes the same file, so
893
+ // the same conflict is refused here, with the same reason.
894
+ if (target) {
895
+ const claimConflict = await claimConflictForTarget(target);
896
+ if (claimConflict) return claimConflict;
897
+ }
870
898
  const todos = await effectiveTodos(sessionID);
871
899
  if (todos !== undefined && !hasActiveTodo(todos)) {
872
900
  return (
package/test/test.mts CHANGED
@@ -1197,6 +1197,70 @@ try {
1197
1197
  }
1198
1198
  check("blocked multi-target patch leaves no partial claims", !partialPatchClaim);
1199
1199
 
1200
+ // A shell write mutates the same path a direct edit claims, and the claim was
1201
+ // consulted only in the edit branch: `edit` was refused for a path while a
1202
+ // redirect to that same file was allowed at the same moment. A shell write is
1203
+ // a conflict check only (it never acquires a claim), so it cannot strand one.
1204
+ console.log("- Shell mutation claim conflicts -");
1205
+ writeFileSync(join(claimsDir, "shell-target.ts"), "before");
1206
+ writeFileSync(join(claimsDir, "shell-multi.ts"), "before");
1207
+ writeFileSync(join(claimsDir, "shell-multi2.ts"), "before");
1208
+ symlinkSync(join(claimsDir, "shell-target.ts"), join(claimsDir, "shell-target-link.ts"));
1209
+ await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-target.ts"), "claim-shell-read-target");
1210
+ await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner" }, { args: { filePath: join(claimsDir, "shell-target.ts"), content: "a" } });
1211
+ const shellBlockReason = async (command: string): Promise<string> => {
1212
+ try {
1213
+ await claimsBefore?.({ tool: "bash", sessionID: "s-claim-b", callID: "claim-shell-attempt" }, { args: { command } });
1214
+ return "";
1215
+ } catch (error) {
1216
+ return String(error);
1217
+ }
1218
+ };
1219
+ const shellRedirectReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
1220
+ check("a shell redirect into a claimed path is refused with the claim reason", shellRedirectReason.includes("is claimed by session") && shellRedirectReason.includes("Reclaim step"));
1221
+ const shellTeeReason = await shellBlockReason(`printf x | tee -a ${join(claimsDir, "shell-target.ts")}`);
1222
+ check("a tee append into a claimed path is refused, with the tee flag parsed", shellTeeReason.includes("is claimed by session"));
1223
+ const shellSymlinkReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target-link.ts")}`);
1224
+ check("a shell write through a symlink alias of a claimed path is refused", shellSymlinkReason.includes("is claimed by session"));
1225
+ const shellChainedReason = await shellBlockReason(`cd ${claimsDir} && echo x > shell-target.ts`);
1226
+ check("a chained shell write into a claimed path is judged in the tree it lands in", shellChainedReason.includes("is claimed by session"));
1227
+ await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-multi2.ts"), "claim-shell-read-multi");
1228
+ await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi" }, { args: { filePath: join(claimsDir, "shell-multi2.ts"), content: "a" } });
1229
+ const shellMultiReason = await shellBlockReason(`rm ${join(claimsDir, "shell-multi.ts")} ${join(claimsDir, "shell-multi2.ts")}`);
1230
+ check("a multi-operand shell mutation is refused when any operand is claimed", shellMultiReason.includes("is claimed by session") && shellMultiReason.includes("shell-multi2.ts"));
1231
+ const shellSubagentReason = await (async (): Promise<string> => {
1232
+ fakeParents.set("s-claim-subagent", "s-claim-a");
1233
+ try {
1234
+ await claimsBefore?.({ tool: "bash", sessionID: "s-claim-subagent", callID: "claim-shell-subagent" }, { args: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } });
1235
+ return "";
1236
+ } catch (error) {
1237
+ return String(error);
1238
+ }
1239
+ })();
1240
+ check("a subagent shell write into a path its parent claimed is refused", shellSubagentReason.includes("is claimed by session"));
1241
+ // mv removes its source, so a claimed source is a conflict even when the
1242
+ // destination is unclaimed.
1243
+ writeFileSync(join(claimsDir, "shell-move-source.ts"), "before");
1244
+ await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-move-source.ts"), "claim-shell-read-move");
1245
+ await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move" }, { args: { filePath: join(claimsDir, "shell-move-source.ts"), content: "a" } });
1246
+ const shellMoveSourceReason = await shellBlockReason(`mv ${join(claimsDir, "shell-move-source.ts")} ${join(claimsDir, "shell-moved-away.ts")}`);
1247
+ check("a mv of a claimed source is refused", shellMoveSourceReason.includes("is claimed by session") && shellMoveSourceReason.includes("shell-move-source.ts"));
1248
+ await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move", args: {} }, { title: "edit", output: "edited", metadata: {} });
1249
+ const shellWhy = JSON.parse(String(await claimsHooks.tool?.guard_why?.execute(
1250
+ { tool: "bash", input: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } },
1251
+ { sessionID: "s-claim-b", worktree: claimsDir, directory: claimsDir } as any,
1252
+ )));
1253
+ check(
1254
+ "guard_why reports a shell claim conflict as a shell mutation",
1255
+ shellWhy.code === "shell_mutation" && String(shellWhy.message).includes("is claimed by session"),
1256
+ );
1257
+ const shellUnclaimedReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-multi.ts")}`);
1258
+ check("a shell write to an unclaimed path stays allowed", shellUnclaimedReason === "");
1259
+ await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner", args: {} }, { title: "edit", output: "edited", metadata: {} });
1260
+ await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi", args: {} }, { title: "edit", output: "edited", metadata: {} });
1261
+ const shellAfterReleaseReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
1262
+ check("a shell write is allowed once the owning edit releases its claim", shellAfterReleaseReason === "");
1263
+
1200
1264
  // Stale claim takeover (missed idle release): a claim created BEFORE its
1201
1265
  // owner's last recorded idle timestamp cannot belong to an in-flight tool
1202
1266
  // call, so a leaked claim must not block another session forever. Owners that
@@ -2563,6 +2627,59 @@ writeFileSync(join(verifyRepo, "package.json"), JSON.stringify({ scripts: { test
2563
2627
  await call("bash", { command: "git restore git.ts" }, { sessionID: "s-verify-git" });
2564
2628
  check("git worktree mutation invalidates cached verification", blocked(await call("todowrite", { todos: [item("git work", "completed")] }, { sessionID: "s-verify-git" })));
2565
2629
 
2630
+ // G6: a configured verify command must leave visible evidence in guard_status,
2631
+ // not only an auto-detected command or an in-memory result. The package.json
2632
+ // test script deliberately fails, so a passing run proves the project config
2633
+ // wins over detection.
2634
+ console.log("- G6: configured verification evidence in guard_status -");
2635
+ const prevG6VerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
2636
+ delete process.env.WORKFLOW_GUARD_VERIFY;
2637
+ const g6Repo = mkdtempSync(join(tmpdir(), "wg-g6-verify-status-"));
2638
+ spawnSync("git", ["init", "-b", "feature/g6"], { cwd: g6Repo });
2639
+ spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: g6Repo });
2640
+ spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: g6Repo });
2641
+ writeFileSync(join(g6Repo, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(1)'" } }));
2642
+ writeFileSync(join(g6Repo, "code.ts"), "base\n");
2643
+ spawnSync("git", ["add", "."], { cwd: g6Repo });
2644
+ spawnSync("git", ["commit", "-m", "base"], { cwd: g6Repo });
2645
+ mkdirSync(join(g6Repo, ".opencode"), { recursive: true });
2646
+ writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(0)'" }));
2647
+ reloadProjectConfig(g6Repo);
2648
+ setWorkspaceRoot(g6Repo);
2649
+ resetVerifyState();
2650
+ todo("s-g6", item("g6 configured verification", "in_progress"));
2651
+ await call("edit", { filePath: join(g6Repo, "code-after.ts"), content: "after\n" }, { sessionID: "s-g6" });
2652
+ const g6Pass = await call("todowrite", { todos: [item("g6 configured verification", "completed")] }, { sessionID: "s-g6" });
2653
+ check("G6 configured command finalizes when it passes", !blocked(g6Pass));
2654
+ 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 });
2655
+ const g6Status = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
2656
+ check(
2657
+ "G6 guard_status reports the configured command and its source",
2658
+ g6Status.projectConfig.verifyCommand === "node -e 'process.exit(0)'" && g6Status.projectConfig.verifyCommandSource === "project-config",
2659
+ );
2660
+ check(
2661
+ "G6 guard_status reports lastVerify with a timestamp, duration, and commit hash",
2662
+ typeof g6Status.lastVerify?.timestamp === "number" && g6Status.lastVerify.timestamp > 0 &&
2663
+ typeof g6Status.lastVerify?.durationMs === "number" && g6Status.lastVerify.durationMs >= 0 &&
2664
+ typeof g6Status.lastVerify?.commitHash === "string" && g6Status.lastVerify.commitHash.length === 40 &&
2665
+ g6Status.lastVerify?.fresh === true,
2666
+ );
2667
+ await call("edit", { filePath: join(g6Repo, "code-stale.ts"), content: "stale\n" }, { sessionID: "s-g6" });
2668
+ const g6StaleStatus = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
2669
+ check("G6 lastVerify goes not-fresh after a later mutation", g6StaleStatus.lastVerify?.fresh === false);
2670
+ writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(1)'" }));
2671
+ reloadProjectConfig(g6Repo);
2672
+ resetVerifyState();
2673
+ todo("s-g6-fail", item("g6 failing verification", "in_progress"));
2674
+ await call("edit", { filePath: join(g6Repo, "code-fail.ts"), content: "fail\n" }, { sessionID: "s-g6-fail" });
2675
+ const g6Fail = await call("todowrite", { todos: [item("g6 failing verification", "completed")] }, { sessionID: "s-g6-fail" });
2676
+ check("G6 a deliberately failing configured command blocks finalization", blocked(g6Fail) && String(g6Fail).includes("verification"));
2677
+ if (prevG6VerifyEnv !== undefined) process.env.WORKFLOW_GUARD_VERIFY = prevG6VerifyEnv;
2678
+ rmSync(g6Repo, { recursive: true, force: true });
2679
+ reloadProjectConfig(verifyRepo);
2680
+ setWorkspaceRoot(verifyRepo);
2681
+ resetVerifyState();
2682
+
2566
2683
  // Ecosystem verification detection
2567
2684
  const rustRepo = mkdtempSync(join(tmpdir(), "wg-rust-"));
2568
2685
  writeFileSync(join(rustRepo, "Cargo.toml"), "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n");
@@ -3738,6 +3855,14 @@ check(
3738
3855
  autoDetectStatus.projectConfig.configPath === null && autoDetectStatus.projectConfig.verifyCommand === "npm test" && autoDetectStatus.projectConfig.verifyCommandSource === "auto-detected",
3739
3856
  );
3740
3857
  check("verifyCommandSource reports project config directly", verifyCommandSource(requirementsRoot) === "project-config" && verifyCommandSource(autoDetectRoot) === "auto-detected" && verifyCommandSource(noConfigRoot) === null);
3858
+ const prevStatusVerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
3859
+ process.env.WORKFLOW_GUARD_VERIFY = "node -e 'process.exit(0)'";
3860
+ check(
3861
+ "verify command resolution puts the environment ahead of project config and detection",
3862
+ verifyCommandSource(requirementsRoot) === "environment" && detectVerifyCommand(requirementsRoot) === "node -e 'process.exit(0)'",
3863
+ );
3864
+ if (prevStatusVerifyEnv === undefined) delete process.env.WORKFLOW_GUARD_VERIFY;
3865
+ else process.env.WORKFLOW_GUARD_VERIFY = prevStatusVerifyEnv;
3741
3866
  check("existingProjectConfigPath returns null-ish for a repo without config", existingProjectConfigPath(noConfigRoot) === undefined);
3742
3867
  rmSync(noConfigRoot, { recursive: true, force: true });
3743
3868
  rmSync(autoDetectRoot, { recursive: true, force: true });
@@ -3919,13 +4044,32 @@ check(
3919
4044
  typeof p0ReviewResult === "string" && p0ReviewResult.includes("P0 or P1 blockers"),
3920
4045
  );
3921
4046
 
3922
- // The rubric tool emits a real prompt with the current diff
4047
+ // The rubric tool emits a real prompt with a real diff. A fixture keeps this
4048
+ // independent of the checkout the suite runs in: once no base yields a diff the
4049
+ // tool now refuses instead of grading a substitute, so an ambient checkout with
4050
+ // nothing to review would assert the wrong thing.
3923
4051
  check("plugin registers guard_review_rubric tool", typeof customPlugin.tool?.guard_review_rubric?.execute === "function");
3924
- const rubricOut = await customPlugin.tool?.guard_review_rubric?.execute({}, {} as any);
4052
+ const rubricAxesRepo = join(root, "wg-review-rubric-axes");
4053
+ mkdirSync(rubricAxesRepo, { recursive: true });
4054
+ spawnSync("git", ["init", "-b", "main"], { cwd: rubricAxesRepo });
4055
+ spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricAxesRepo });
4056
+ spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricAxesRepo });
4057
+ writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\n");
4058
+ spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
4059
+ spawnSync("git", ["commit", "-m", "base"], { cwd: rubricAxesRepo });
4060
+ spawnSync("git", ["switch", "-c", "feature/rubric-axes"], { cwd: rubricAxesRepo });
4061
+ writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\nchange\n");
4062
+ spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
4063
+ spawnSync("git", ["commit", "-m", "change"], { cwd: rubricAxesRepo });
4064
+ const rubricOut = await customPlugin.tool?.guard_review_rubric?.execute(
4065
+ { base: "main", directory: rubricAxesRepo },
4066
+ { sessionID: "s-rubric-axes", worktree: rubricAxesRepo, directory: rubricAxesRepo } as any,
4067
+ );
3925
4068
  check(
3926
4069
  "guard_review_rubric returns the rubric with axes",
3927
4070
  typeof rubricOut === "string" && rubricOut.includes("Test Integrity") && rubricOut.includes("Code Diff Under Review"),
3928
4071
  );
4072
+ rmSync(rubricAxesRepo, { recursive: true, force: true });
3929
4073
  const rubricOptionFlag = await customPlugin.tool?.guard_review_rubric?.execute({ base: "--output=injected" }, {} as any);
3930
4074
  check("guard_review_rubric sanitizes option flags in base ref", typeof rubricOptionFlag === "string" && !existsSync(join(root, "injected")));
3931
4075
 
@@ -3984,6 +4128,94 @@ check(
3984
4128
  );
3985
4129
  rmSync(rubricNoOrigin, { recursive: true, force: true });
3986
4130
 
4131
+ // Provenance: the rubric must name the tree it graded. A session whose own
4132
+ // checkout holds unrelated work must be able to grade a linked worktree, and
4133
+ // the rubric must say which workspace and base it read. Before this fix the
4134
+ // tool returned a rubric over whichever tree it happened to resolve and named
4135
+ // neither, so a real review was graded against the wrong diff.
4136
+ const rubricWtPrimary = join(root, "wg-rubric-wt-primary");
4137
+ mkdirSync(rubricWtPrimary, { recursive: true });
4138
+ spawnSync("git", ["init", "-b", "main"], { cwd: rubricWtPrimary });
4139
+ spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricWtPrimary });
4140
+ spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricWtPrimary });
4141
+ writeFileSync(join(rubricWtPrimary, "seed.txt"), "base\n");
4142
+ spawnSync("git", ["add", "seed.txt"], { cwd: rubricWtPrimary });
4143
+ spawnSync("git", ["commit", "-m", "base"], { cwd: rubricWtPrimary });
4144
+ // The session's own checkout carries unrelated work. Judging THIS tree would
4145
+ // put primaryOnlyMarker in the rubric instead of the worktree's change.
4146
+ spawnSync("git", ["switch", "-c", "feature/primary-unrelated"], { cwd: rubricWtPrimary });
4147
+ writeFileSync(join(rubricWtPrimary, "primary-only.txt"), "primaryOnlyMarker\n");
4148
+ spawnSync("git", ["add", "primary-only.txt"], { cwd: rubricWtPrimary });
4149
+ spawnSync("git", ["commit", "-m", "unrelated primary work"], { cwd: rubricWtPrimary });
4150
+ const rubricWtLinked = join(root, "wg-rubric-wt-linked");
4151
+ spawnSync("git", ["worktree", "add", "-q", "-b", "feature/wt-under-review", rubricWtLinked, "main"], { cwd: rubricWtPrimary });
4152
+ writeFileSync(join(rubricWtLinked, "worktree-change.txt"), "worktreeOnlyMarker\n");
4153
+ spawnSync("git", ["add", "worktree-change.txt"], { cwd: rubricWtLinked });
4154
+ spawnSync("git", ["commit", "-m", "worktree change under review"], { cwd: rubricWtLinked });
4155
+ const rubricWtRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout).trim();
4156
+ const rubricWtDiff = String(spawnSync("git", ["diff", "--no-ext-diff", "main...HEAD", "--"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout);
4157
+ const rubricWtOut = await customPlugin.tool?.guard_review_rubric?.execute(
4158
+ { directory: rubricWtLinked },
4159
+ { sessionID: "s-rubric-wt", worktree: rubricWtPrimary, directory: rubricWtPrimary } as any,
4160
+ );
4161
+ check(
4162
+ "guard_review_rubric grades the requested worktree and names it in the provenance line",
4163
+ typeof rubricWtOut === "string" &&
4164
+ rubricWtOut.includes(`Provenance: workspace=${rubricWtRoot} base=main `) &&
4165
+ rubricWtOut.includes(`diff=${Buffer.byteLength(rubricWtDiff, "utf8")} bytes`) &&
4166
+ rubricWtOut.includes("worktreeOnlyMarker") &&
4167
+ !rubricWtOut.includes("primaryOnlyMarker"),
4168
+ );
4169
+
4170
+ // No matching base: refuse. The old code ran `git diff HEAD~1` and printed a
4171
+ // rubric over that substitute, so the caller got a confident review of the
4172
+ // wrong range with no indication that its base was never found.
4173
+ const rubricNoBase = join(root, "wg-rubric-no-base");
4174
+ mkdirSync(rubricNoBase, { recursive: true });
4175
+ spawnSync("git", ["init", "-b", "main"], { cwd: rubricNoBase });
4176
+ spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricNoBase });
4177
+ spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricNoBase });
4178
+ writeFileSync(join(rubricNoBase, "seed.txt"), "base\n");
4179
+ spawnSync("git", ["add", "seed.txt"], { cwd: rubricNoBase });
4180
+ spawnSync("git", ["commit", "-m", "base"], { cwd: rubricNoBase });
4181
+ writeFileSync(join(rubricNoBase, "last-commit.txt"), "substituteMarker\n");
4182
+ spawnSync("git", ["add", "last-commit.txt"], { cwd: rubricNoBase });
4183
+ spawnSync("git", ["commit", "-m", "last commit"], { cwd: rubricNoBase });
4184
+ const rubricNoBaseRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricNoBase, encoding: "utf8" }).stdout).trim();
4185
+ const rubricNoBaseOut = await customPlugin.tool?.guard_review_rubric?.execute(
4186
+ { directory: rubricNoBase },
4187
+ { sessionID: "s-rubric-no-base", worktree: rubricNoBase, directory: rubricNoBase } as any,
4188
+ );
4189
+ check(
4190
+ "guard_review_rubric refuses when no base yields a diff instead of grading a substitute",
4191
+ typeof rubricNoBaseOut === "string" &&
4192
+ rubricNoBaseOut.includes("No review diff found") &&
4193
+ rubricNoBaseOut.includes(`workspace=${rubricNoBaseRoot}`) &&
4194
+ rubricNoBaseOut.includes("bases=origin/main, origin/master, main, master") &&
4195
+ rubricNoBaseOut.includes("Remedy") &&
4196
+ !rubricNoBaseOut.includes("substituteMarker") &&
4197
+ !rubricNoBaseOut.includes("Code Diff Under Review"),
4198
+ );
4199
+
4200
+ // HEAD~1 is graded only when the caller asks for it, and the provenance line
4201
+ // says which range was graded so a reader can tell it is the last commit.
4202
+ const rubricHead1Out = await customPlugin.tool?.guard_review_rubric?.execute(
4203
+ { base: "HEAD~1", directory: rubricNoBase },
4204
+ { sessionID: "s-rubric-head1", worktree: rubricNoBase, directory: rubricNoBase } as any,
4205
+ );
4206
+ check(
4207
+ "an explicit HEAD~1 base is honored and named in the provenance line",
4208
+ typeof rubricHead1Out === "string" &&
4209
+ rubricHead1Out.includes("base=HEAD~1") &&
4210
+ rubricHead1Out.includes("fallback=HEAD~1") &&
4211
+ rubricHead1Out.includes("substituteMarker") &&
4212
+ rubricHead1Out.includes("Code Diff Under Review"),
4213
+ );
4214
+ rmSync(rubricNoBase, { recursive: true, force: true });
4215
+ spawnSync("git", ["worktree", "remove", "--force", rubricWtLinked], { cwd: rubricWtPrimary });
4216
+ rmSync(rubricWtLinked, { recursive: true, force: true });
4217
+ rmSync(rubricWtPrimary, { recursive: true, force: true });
4218
+
3987
4219
  // Reviewer-type agents often lack record_review in their toolset entirely, so
3988
4220
  // the tool accepts recorders of any session type: the verdict binds to the
3989
4221
  // recording session's directory and the audit trail captures the recorder
@@ -4291,6 +4523,14 @@ const strictSubagentResult = await strictPlugin.tool?.record_review?.execute(
4291
4523
  check("strict mode: subagent recorder records the approval", typeof strictSubagentResult === "string" && strictSubagentResult.includes("APPROVED"));
4292
4524
  const strictStatusAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_status?.execute({ directory: strictRepo }, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
4293
4525
  check("strict mode: subagent approval satisfies the review gate", !strictStatusAfterSubagent.outstandingRequirements.includes("review") && strictStatusAfterSubagent.lastReview?.fresh === true);
4526
+ check(
4527
+ "strict mode: guard_status attributes the approval to the subagent recorder, not its parent",
4528
+ strictStatusAfterSubagent.lastReview?.recorderRole === "subagent" &&
4529
+ strictStatusAfterSubagent.lastReview?.recorderSessionID === "s-strict-reviewer" &&
4530
+ strictStatusAfterSubagent.lastReview?.targetSessionID === "s-strict-root" &&
4531
+ strictStatusAfterSubagent.lastReview?.recorderSessionID !== strictStatusAfterSubagent.lastReview?.targetSessionID &&
4532
+ typeof strictStatusAfterSubagent.lastReview?.timestamp === "number",
4533
+ );
4294
4534
  const strictPrAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_why?.execute(strictPrProbe, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
4295
4535
  check("strict mode: PR preflight passes after subagent-recorded approval", strictPrAfterSubagent.status !== "blocked" && (strictPrAfterSubagent.status === "allowed" || strictPrAfterSubagent.code === "remote_state_unchecked"));
4296
4536
  if (strictPrAfterSubagent.status === "blocked") console.log(" blocked:", strictPrAfterSubagent.message);
@@ -4707,7 +4947,7 @@ todo("s-wt-mismatch", item("edit in the linked worktree", "in_progress"));
4707
4947
  const mismatchWrite = await call("write", { filePath: join(wtLinked, "mismatch.ts"), content: "x" }, { sessionID: "s-wt-mismatch", worktree: wtRepo, directory: wtRepo });
4708
4948
  check(
4709
4949
  "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"),
4950
+ blocked(mismatchWrite) && String(mismatchWrite).includes(wtLinked) && String(mismatchWrite).includes(wtRepo) && String(mismatchWrite).includes("session_move"),
4711
4951
  );
4712
4952
 
4713
4953
  // An in-command `cd` moves the tree later segments run in, so the walk has to
@@ -6511,6 +6751,16 @@ check("tool.definition todowrite enriches with planning and status guidance", to
6511
6751
  const systemOutput = { system: ["Base system prompt"] };
6512
6752
  await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutput);
6513
6753
  check("experimental.chat.system.transform adds workflow guard guidance", systemOutput.system.length === 2 && systemOutput.system[1].includes("## Workflow Guard & Operational Tools") && systemOutput.system[1].includes("guard_next_tasks") && systemOutput.system[1].includes("guard_review_rubric"));
6754
+ // A reviewer agent that denies every action does not carry record_review, so
6755
+ // the injected instruction must name the calling session as the recorder. The
6756
+ // old text told the subagent to record its own verdict, which the fleet
6757
+ // reviewer could not do.
6758
+ check(
6759
+ "injected guidance names the calling session as the review recorder",
6760
+ systemOutput.system[1].includes("The calling session records that subagent's verdict") &&
6761
+ systemOutput.system[1].includes("may not carry the tool") &&
6762
+ !systemOutput.system[1].includes("that records its verdict with `record_review`"),
6763
+ );
6514
6764
  const systemOutputIdem = { system: [...systemOutput.system] };
6515
6765
  await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutputIdem);
6516
6766
  check("experimental.chat.system.transform is idempotent", systemOutputIdem.system.length === 2);