opencode-workflow-guard 1.19.4 → 1.19.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/policies.md CHANGED
@@ -117,6 +117,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
117
117
  - **Git State & Snapshot Binding:** Verification evidence records the current git commit hash (`git rev-parse HEAD`) and working tree status. If unverified edits or index modifications occur after verification, fresh verification is enforced.
118
118
  - **Untracked Special Entries:** The worktree fingerprint binds untracked symlinks by their target string. It follows git semantics, so re-pointing a link moves the fingerprint and changing the link target's contents does not. FIFOs and sockets are bound by path and mode. Unopenable entries are skipped with a `worktree-fingerprint` warning in the audit trail instead of voiding the whole fingerprint. One unreadable scratch symlink or `chmod 000` file can no longer make review or verification evidence permanently unfresh. The PR preflight names the actual cause when an approval cannot be matched: no fingerprint binding, fingerprint mismatch, or uncomputable fingerprint. It no longer shows the generic "review approval required". Documented tradeoff: the contents of a skipped entry are excluded from the fingerprint. A file that stays unreadable to the guard's user across the entire window can therefore change contents without moving the fingerprint. Any readability transition is fingerprint-visible (fail-closed), and each skip is named in the durable audit trail.
119
119
  - **Durable Disk Cache:** Passing verification results (`~/.local/state/opencode/workflow-guard/last-verify.json`) and passing secondary review approvals (`~/.local/state/opencode/workflow-guard/last-review.json`) are cached to disk. Session restarts and multi-agent handoffs can therefore retain valid verification and review evidence without redundant test runs. Durable evidence is **workspace-bound**: a cached result is only accepted for the workspace that produced it. A passing run in one project can never satisfy finalization in another.
120
+ - **Evidence Visibility:** `guard_status.lastVerify` reports the command, pass state, freshness, evidence id, commit hash, observation timestamp, and duration, so a green gate leaves a record with a time and the commit it covered. `guard_status.lastReview` adds its observation timestamp plus `recorderSessionID`, `recorderRole` (`root` or `subagent`), and `targetSessionID`. With `requireSubagentReview` on, that lineage shows the approval came from a subagent rather than the root session it was recorded for.
120
121
  - If verification fails, finalization is blocked with a structured summary of error markers, stack traces, and failure output.
121
122
  - OpenCode's current `lsp.client.diagnostics` event identifies the server and path. It does not expose the diagnostics themselves. The guard therefore does not claim an LSP-clean finalization gate until the SDK provides a supported diagnostics source.
122
123
  - The verify command is **disabled** when `WORKFLOW_GUARD_VERIFY` is empty (`""`).
@@ -265,7 +266,7 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
265
266
  - **Priority-Ranked Review Gate:** Secondary review approval (`requireReview`) is enforced by default during PR preflight (`gh pr create` / `az repos pr create`). Before creating a pull request, a secondary reviewer subagent must evaluate the changes using `guard_review_rubric` and record approval with `record_review`. Approvals that include active P0 (blocker) or P1 (major defect) issues are rejected until blockers are resolved. Projects can opt out via `.opencode/workflow-guard.json` (`{ "requireReview": false }`) or environment variable `WORKFLOW_GUARD_REQUIRE_REVIEW=0`. Conversely, `WORKFLOW_GUARD_REQUIRE_REVIEW=1` forces the review requirement regardless of project config.
266
267
  - **Review binding is content, not session identity:** A recorded approval satisfies the PR preflight when its binding matches the tree the PR would publish. The binding covers the repository, the commit hash, and the tracked-content worktree fingerprint. Any session may record the verdict or create the PR. Reviewers record from subagent sessions, binding the verdict to their parent or their own directory. Sessions can move between directories (`session_move`), and subagents can spawn from other roots. Keying the gate on the PR-creating session's ID would make the documented flow impossible to satisfy from linked worktrees. Freshness is scoped to the reviewed diff, which is tracked content. Untracked scratch-file cleanup and mutations in sibling worktrees cannot invalidate an approval. Any tracked edit or new commit does.
267
268
  - **Commit before you verify and review:** Both evidence gates bind to the HEAD commit hash, so a commit after either one invalidates it. Finish every tracked change first, then run verification, then record the review, then open the PR. That order satisfies both gates in one pass. Any other order costs a re-run. A review recorded before its change is committed keeps the same tracked fingerprint. The preflight then names the commit drift specifically and asks for the review again at the current commit.
268
- - **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`). Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
269
+ - **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`), and `guard_status.lastReview` reports the same lineage beside the parent it was recorded for. Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
269
270
  - **`requireSubagentReview` strict recorder mode (opt-in):** Projects that cannot tolerate root-session self-approval can set `requireSubagentReview: true` in `.opencode/workflow-guard.json`. They can also set `WORKFLOW_GUARD_REQUIRE_SUBAGENT_REVIEW=1` in the environment. In that mode `record_review` rejects APPROVALS recorded by the root session itself, which is a session with no parent. The rejection carries an actionable message and a `subagent_recorder_required` audit entry. The verdict is not recorded and the review gate stays unsatisfied. Changes-requested verdicts remain relayable from any session. `WORKFLOW_GUARD_REQUIRE_SUBAGENT_REVIEW=0` disables the requirement even when project config enables it. The default keeps the documented relay flow for read-only reviewer toolsets.
270
271
  - **Durable Lower-Priority Follow-ups:** Accepted review summaries containing a P2 or P3 finding are persisted in the project's local Workflow Guard SQLite database. Open findings are included in compacted agent context. They remain open across sessions until explicitly resolved with `guard_review_followup_resolve`, and they are not silently discarded with the review session.
271
272
  - **Privacy-Safe Local Telemetry:** Guard decisions remain in the local audit JSONL. Tool after-hook observations add `callID` and duration records for local diagnosis and performance analysis. The current hook API does not distinguish success from every failure path, so these records do not claim a success outcome. Command and patch bodies are never written to the journal. Only their byte count and SHA-256 fingerprint are retained for correlation.
package/docs/testing.md CHANGED
@@ -49,9 +49,9 @@ 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
+ | **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
55
  | **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
56
56
  | **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
57
57
  | **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.19.4",
3
+ "version": "1.19.5",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -346,7 +346,7 @@ 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) }),
@@ -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
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;
package/test/test.mts CHANGED
@@ -2563,6 +2563,59 @@ writeFileSync(join(verifyRepo, "package.json"), JSON.stringify({ scripts: { test
2563
2563
  await call("bash", { command: "git restore git.ts" }, { sessionID: "s-verify-git" });
2564
2564
  check("git worktree mutation invalidates cached verification", blocked(await call("todowrite", { todos: [item("git work", "completed")] }, { sessionID: "s-verify-git" })));
2565
2565
 
2566
+ // G6: a configured verify command must leave visible evidence in guard_status,
2567
+ // not only an auto-detected command or an in-memory result. The package.json
2568
+ // test script deliberately fails, so a passing run proves the project config
2569
+ // wins over detection.
2570
+ console.log("- G6: configured verification evidence in guard_status -");
2571
+ const prevG6VerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
2572
+ delete process.env.WORKFLOW_GUARD_VERIFY;
2573
+ const g6Repo = mkdtempSync(join(tmpdir(), "wg-g6-verify-status-"));
2574
+ spawnSync("git", ["init", "-b", "feature/g6"], { cwd: g6Repo });
2575
+ spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: g6Repo });
2576
+ spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: g6Repo });
2577
+ writeFileSync(join(g6Repo, "package.json"), JSON.stringify({ scripts: { test: "node -e 'process.exit(1)'" } }));
2578
+ writeFileSync(join(g6Repo, "code.ts"), "base\n");
2579
+ spawnSync("git", ["add", "."], { cwd: g6Repo });
2580
+ spawnSync("git", ["commit", "-m", "base"], { cwd: g6Repo });
2581
+ mkdirSync(join(g6Repo, ".opencode"), { recursive: true });
2582
+ writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(0)'" }));
2583
+ reloadProjectConfig(g6Repo);
2584
+ setWorkspaceRoot(g6Repo);
2585
+ resetVerifyState();
2586
+ todo("s-g6", item("g6 configured verification", "in_progress"));
2587
+ await call("edit", { filePath: join(g6Repo, "code-after.ts"), content: "after\n" }, { sessionID: "s-g6" });
2588
+ const g6Pass = await call("todowrite", { todos: [item("g6 configured verification", "completed")] }, { sessionID: "s-g6" });
2589
+ check("G6 configured command finalizes when it passes", !blocked(g6Pass));
2590
+ const g6Plugin = await (defaultExport?.server ?? WorkflowGuard)({ directory: g6Repo, worktree: g6Repo, client: fakeClient as any, project: {} as any, experimental_workspace: {} as any, serverUrl: new URL("http://localhost:4096"), $: undefined as any });
2591
+ const g6Status = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
2592
+ check(
2593
+ "G6 guard_status reports the configured command and its source",
2594
+ g6Status.projectConfig.verifyCommand === "node -e 'process.exit(0)'" && g6Status.projectConfig.verifyCommandSource === "project-config",
2595
+ );
2596
+ check(
2597
+ "G6 guard_status reports lastVerify with a timestamp, duration, and commit hash",
2598
+ typeof g6Status.lastVerify?.timestamp === "number" && g6Status.lastVerify.timestamp > 0 &&
2599
+ typeof g6Status.lastVerify?.durationMs === "number" && g6Status.lastVerify.durationMs >= 0 &&
2600
+ typeof g6Status.lastVerify?.commitHash === "string" && g6Status.lastVerify.commitHash.length === 40 &&
2601
+ g6Status.lastVerify?.fresh === true,
2602
+ );
2603
+ await call("edit", { filePath: join(g6Repo, "code-stale.ts"), content: "stale\n" }, { sessionID: "s-g6" });
2604
+ const g6StaleStatus = JSON.parse(String(await g6Plugin.tool?.guard_status?.execute({}, { sessionID: "s-g6", worktree: g6Repo, directory: g6Repo } as any)));
2605
+ check("G6 lastVerify goes not-fresh after a later mutation", g6StaleStatus.lastVerify?.fresh === false);
2606
+ writeFileSync(join(g6Repo, ".opencode", "workflow-guard.json"), JSON.stringify({ verifyCommand: "node -e 'process.exit(1)'" }));
2607
+ reloadProjectConfig(g6Repo);
2608
+ resetVerifyState();
2609
+ todo("s-g6-fail", item("g6 failing verification", "in_progress"));
2610
+ await call("edit", { filePath: join(g6Repo, "code-fail.ts"), content: "fail\n" }, { sessionID: "s-g6-fail" });
2611
+ const g6Fail = await call("todowrite", { todos: [item("g6 failing verification", "completed")] }, { sessionID: "s-g6-fail" });
2612
+ check("G6 a deliberately failing configured command blocks finalization", blocked(g6Fail) && String(g6Fail).includes("verification"));
2613
+ if (prevG6VerifyEnv !== undefined) process.env.WORKFLOW_GUARD_VERIFY = prevG6VerifyEnv;
2614
+ rmSync(g6Repo, { recursive: true, force: true });
2615
+ reloadProjectConfig(verifyRepo);
2616
+ setWorkspaceRoot(verifyRepo);
2617
+ resetVerifyState();
2618
+
2566
2619
  // Ecosystem verification detection
2567
2620
  const rustRepo = mkdtempSync(join(tmpdir(), "wg-rust-"));
2568
2621
  writeFileSync(join(rustRepo, "Cargo.toml"), "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n");
@@ -3738,6 +3791,14 @@ check(
3738
3791
  autoDetectStatus.projectConfig.configPath === null && autoDetectStatus.projectConfig.verifyCommand === "npm test" && autoDetectStatus.projectConfig.verifyCommandSource === "auto-detected",
3739
3792
  );
3740
3793
  check("verifyCommandSource reports project config directly", verifyCommandSource(requirementsRoot) === "project-config" && verifyCommandSource(autoDetectRoot) === "auto-detected" && verifyCommandSource(noConfigRoot) === null);
3794
+ const prevStatusVerifyEnv = process.env.WORKFLOW_GUARD_VERIFY;
3795
+ process.env.WORKFLOW_GUARD_VERIFY = "node -e 'process.exit(0)'";
3796
+ check(
3797
+ "verify command resolution puts the environment ahead of project config and detection",
3798
+ verifyCommandSource(requirementsRoot) === "environment" && detectVerifyCommand(requirementsRoot) === "node -e 'process.exit(0)'",
3799
+ );
3800
+ if (prevStatusVerifyEnv === undefined) delete process.env.WORKFLOW_GUARD_VERIFY;
3801
+ else process.env.WORKFLOW_GUARD_VERIFY = prevStatusVerifyEnv;
3741
3802
  check("existingProjectConfigPath returns null-ish for a repo without config", existingProjectConfigPath(noConfigRoot) === undefined);
3742
3803
  rmSync(noConfigRoot, { recursive: true, force: true });
3743
3804
  rmSync(autoDetectRoot, { recursive: true, force: true });
@@ -4291,6 +4352,14 @@ const strictSubagentResult = await strictPlugin.tool?.record_review?.execute(
4291
4352
  check("strict mode: subagent recorder records the approval", typeof strictSubagentResult === "string" && strictSubagentResult.includes("APPROVED"));
4292
4353
  const strictStatusAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_status?.execute({ directory: strictRepo }, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
4293
4354
  check("strict mode: subagent approval satisfies the review gate", !strictStatusAfterSubagent.outstandingRequirements.includes("review") && strictStatusAfterSubagent.lastReview?.fresh === true);
4355
+ check(
4356
+ "strict mode: guard_status attributes the approval to the subagent recorder, not its parent",
4357
+ strictStatusAfterSubagent.lastReview?.recorderRole === "subagent" &&
4358
+ strictStatusAfterSubagent.lastReview?.recorderSessionID === "s-strict-reviewer" &&
4359
+ strictStatusAfterSubagent.lastReview?.targetSessionID === "s-strict-root" &&
4360
+ strictStatusAfterSubagent.lastReview?.recorderSessionID !== strictStatusAfterSubagent.lastReview?.targetSessionID &&
4361
+ typeof strictStatusAfterSubagent.lastReview?.timestamp === "number",
4362
+ );
4294
4363
  const strictPrAfterSubagent = JSON.parse(String(await strictPlugin.tool?.guard_why?.execute(strictPrProbe, { sessionID: "s-strict-root", worktree: strictRepo, directory: strictRepo } as any)));
4295
4364
  check("strict mode: PR preflight passes after subagent-recorded approval", strictPrAfterSubagent.status !== "blocked" && (strictPrAfterSubagent.status === "allowed" || strictPrAfterSubagent.code === "remote_state_unchecked"));
4296
4365
  if (strictPrAfterSubagent.status === "blocked") console.log(" blocked:", strictPrAfterSubagent.message);
@@ -4707,7 +4776,7 @@ todo("s-wt-mismatch", item("edit in the linked worktree", "in_progress"));
4707
4776
  const mismatchWrite = await call("write", { filePath: join(wtLinked, "mismatch.ts"), content: "x" }, { sessionID: "s-wt-mismatch", worktree: wtRepo, directory: wtRepo });
4708
4777
  check(
4709
4778
  "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"),
4779
+ blocked(mismatchWrite) && String(mismatchWrite).includes(wtLinked) && String(mismatchWrite).includes(wtRepo) && String(mismatchWrite).includes("session_move"),
4711
4780
  );
4712
4781
 
4713
4782
  // An in-command `cd` moves the tree later segments run in, so the walk has to