opencode-workflow-guard 1.20.3 → 1.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/policies.md CHANGED
@@ -113,9 +113,9 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
113
113
  ### 10. Evidence-Based Verification
114
114
  - When the agent attempts to mark **every** task completed (finalizing the request), the guard requires passing verification evidence.
115
115
  - Verification executes in an isolated environment with scrubbed credentials, output caps, token-efficient stdout/stderr snipping, and strict timeout protection. The command comes from the `WORKFLOW_GUARD_VERIFY` env, the project `verifyCommand`, or an auto-detected test or typecheck runner across ecosystems. Auto-detection covers `package.json` (`npm test`, `npm run typecheck`, `npm run check`, `npm run build`), `Cargo.toml` (`cargo test`), `go.mod` (`go test ./...`), `pytest.ini` or `pyproject.toml` (`pytest`), and `deno.json` (`deno test`). Environment configuration takes precedence over project configuration.
116
- - The verification timeout defaults to 30 seconds. Raise it per project with `verifyTimeoutMs` in `.opencode/workflow-guard.json`, or per environment with `WORKFLOW_GUARD_VERIFY_TIMEOUT_MS`, which wins over project config. Non-positive values are ignored and fall back to the default. Raise the timeout for suites that legitimately exceed the default, for example this repository's own unit suite.
117
- - A timeout is reported as `verification_timed_out`, not `verification_failed`. Both block finalization, because neither produced a passing result. They differ in what the agent is told: a timeout says the result is unknown and names the limit and the remedy, while a failure names the failing output. Calling a timeout a failure sent agents looking for an assertion that never ran, and the fix for a timeout is a longer limit rather than a code change.
118
- - Project `postEditValidators` can run faster targeted checks after a direct file edit actually changes the target. Each entry accepts a workspace-relative glob `pattern` with `*`, `**`, and `?` wildcards. Brace expansion and character classes are not supported. Each entry also accepts a non-empty `command` and an optional positive `timeoutMs`. Invalid entries are reported as advisory feedback rather than silently ignored. Matching commands run from the workspace root with the same scrubbed verification environment. Validator failures and timeouts are appended to the edit result as advisory feedback. They do not replace the blocking whole-project finalization verification. Multi-file `apply_patch` calls validate every changed target.
116
+ - The verification timeout defaults to 30 seconds. Raise it per project with `verifyTimeoutMs` in `.opencode/workflow-guard.json` (JSONC is also supported), or per environment with `WORKFLOW_GUARD_VERIFY_TIMEOUT_MS`, which wins over project config. Non-positive values are ignored and fall back to the default. Raise the timeout for suites that legitimately exceed the default, for example this repository's own unit suite.
117
+ - A timeout is reported as `verification_timed_out`, not `verification_failed`. Both block finalization, because neither produced a passing result. They differ in what the agent is told: a timeout says the result is unknown and names the limit and the remedy, while a failure names the failing output. Calling a timeout a failure sent agents looking for an assertion that never ran, and the fix for a timeout is a longer limit rather than a code change. The limit renders identically in the block reason and in the timed-out output tail, at the precision it was set (`50ms` stays `50ms`, never `0s`). A timed-out tail is snipped under its own `unknown` label, so it never claims the killed suite passed or failed.
118
+ - Project `postEditValidators` can run faster targeted checks after a direct file edit actually changes the target. Each entry accepts a workspace-relative glob `pattern` with `*`, `**`, and `?` wildcards. Brace expansion and character classes are not supported. Each entry also accepts a non-empty `command` and an optional positive `timeoutMs`. Invalid entries are reported as advisory feedback rather than silently ignored. Matching commands run from the workspace root with the same scrubbed verification environment. Validator failures and timeouts are appended to the edit result as advisory feedback, and a validator timeout names the limit rather than reporting a failed check. They do not replace the blocking whole-project finalization verification. Multi-file `apply_patch` calls validate every changed target.
119
119
  - With project `recoveryCheckpoints: true`, or the `autonomous` operation profile unless explicitly overridden, genuine root-session user runs capture a private Git checkpoint before agent work starts. Checkpoints preserve tracked and untracked state without using the user's stash list. Subagents and generated continuation prompts do not replace them. At the idle trigger (`session.status` with `status.type === "idle"`), the run's resulting workspace fingerprint is recorded before automatic continuation. `guard_recovery_restore` is provenance-bound to the same root session and refuses restoration after any intervening workspace change. Operation profiles only set optional workflow defaults and cannot weaken core safety policies.
120
120
  - Automatic continuation remains synthetic. By default, an eligible root session with unfinished owned todos briefly waits for OpenCode's native asynchronous title generation before that continuation is sent. The wait ends as soon as the delivered `session.renamed` event reports that the title committed, and falls back to the bounded poll interval on a host that does not emit it. The bounded wait never rewrites titles or provider and model parameters. Set `titleSettleWorkaround: false` to opt out.
121
121
  - **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.
@@ -152,7 +152,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
152
152
  - Caps injected continuity context at 8,000 characters. Operational guard state is preserved first. The remaining budget holds active tasks, review follow-ups, and fresh local project memory.
153
153
  - Active `todowrite` tasks with status badges and subagent hierarchy attribution.
154
154
  - Active Git branch name and protected branch status.
155
- - Test verification status (passed/failed, test command, and commit hash).
155
+ - Test verification status (passed/failed/timed out, test command, and commit hash). A timed-out run is reported as `TIMED OUT within <limit> (result unknown, not a failing test)` rather than as a failure, naming the limit that was hit so the compacted context cannot restate the misattribution.
156
156
  - Secondary review verdicts (reviewer name and approval status).
157
157
  - Dogfood evidence state when Policy 27 is enabled, naming the deploy-matrix hosts still missing a passing run.
158
158
  - Uncommitted mutation counts.
@@ -202,7 +202,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
202
202
 
203
203
  ### 24. Completion Claims vs Evidence (Observability)
204
204
  - When the assistant's final response text asserts completion or passing verification, the guard compares the claim against recorded verification evidence for that session. The trigger phrases are "all tests pass", "work is done", and "verified".
205
- - Mismatches are journaled to the audit trail and logged at info level. A mismatch means failing verification, stale evidence due to mutations after the verify run, or no evidence at all. This is **observability, not gating**. The response is never blocked, but a confident wrap-up cannot silently contradict a failing or absent verification state.
205
+ - Mismatches are journaled to the audit trail and logged at info level. A mismatch means failing verification, a timed-out verification, stale evidence due to mutations after the verify run, or no evidence at all. This is **observability, not gating**. The response is never blocked, but a confident wrap-up cannot silently contradict a failing or absent verification state. A timed-out run gets its own `timed-out` evidence state rather than being filed as `failing`, so the journal names the limit that was hit instead of implying an assertion broke.
206
206
  - Uses the `experimental.text.complete` hook. Claim detection is a conservative phrase heuristic to avoid false positives on casual wording.
207
207
 
208
208
  ### 25. Live-Documentation Research Floor
package/docs/testing.md CHANGED
@@ -49,14 +49,14 @@ 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/*`, `opencode auth`, and the plugin and MCP mutating verbs (`plugin add/remove`, `mcp add`), including a global-flag form, while `plugin list` and `mcp list` stay allowed. |
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, 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, a `durationMs`, and a commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
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. The timed-out output tail renders the same limit at the same precision and is snipped under its own `unknown` label, so a killed suite is never reported as passing or failed, and the compaction summary reports the timeout rather than a failure. 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, a `durationMs`, and a 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
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
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
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. |
57
57
  | **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
58
58
  | **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
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. |
59
+ | **Completion Claims & Tool Honesty** | Verifies the claims-vs-evidence detector (missing/failing/timed-out/stale/fresh states), `experimental.text.complete` journaling, and `tool.definition` enrichment idempotence. |
60
60
  | **Compaction & TUI Feedback** | Verifies active task injection in `experimental.session.compacting`, the static TUI badge, guard block warning toasts, and clean error propagation. |
61
61
  | **Runtime Instance Isolation** | Verifies concurrent plugin instances keep workspace root and SDK client state isolated via `runWithRuntimeState`. |
62
62
  | **V2 Permission Seat Abstention** | Verifies the simulated seat denies a real finding, abstains on a decision it cannot make instead of denying, never upgrades a configured `ask`, and journals the abstention as `deferred_to_execute_before` with the preserved decision. Covers both the remote-probe deferral (`remote_state_unchecked`) and the cwd-dependent deferral (`repository_unidentified`). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-workflow-guard",
3
- "version": "1.20.3",
3
+ "version": "1.20.4",
4
4
  "description": "Deterministic workflow and safety policy enforcement for OpenCode",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -50,10 +50,10 @@
50
50
  "prepublishOnly": "npm run typecheck"
51
51
  },
52
52
  "dependencies": {
53
- "@opencode-ai/plugin": "1.19.5",
54
- "@opencode/ai": "2.3.0",
55
- "@opencode/plugin": "2.3.0",
56
- "@opentui/solid": "0.9.2",
53
+ "@opencode-ai/plugin": "1.19.6",
54
+ "@opencode/ai": "2.4.1",
55
+ "@opencode/plugin": "2.4.1",
56
+ "@opentui/solid": "0.9.9",
57
57
  "jsonc-parser": "3.3.1"
58
58
  },
59
59
  "devDependencies": {
@@ -347,7 +347,7 @@ export function createCustomTools(options: {
347
347
  const ralphOutcome = runWithRuntimeState(root, client, () => getRalphOutcome(toolContext.sessionID));
348
348
  const taskEvidence = await runWithRuntimeState(root, client, () => todoEvidenceReport(toolContext.sessionID));
349
349
  const verifySnapshot = lastV && verifyEvidence
350
- ? { command: lastV.command, passed: lastV.passed, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null }
350
+ ? { command: lastV.command, passed: lastV.passed, timedOut: lastV.timedOut === true, fresh: verifyFresh, evidenceId: verifyEvidence.id, commitHash: lastV.commitHash, timestamp: lastV.timestamp, durationMs: lastV.durationMs ?? null }
351
351
  : null;
352
352
  const reviewSnapshot = lastR && reviewEvidenceRecord
353
353
  ? { 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 }
@@ -54,6 +54,7 @@ export async function guardToolCall(
54
54
  ? {
55
55
  command: lastVerify.command,
56
56
  passed: lastVerify.passed,
57
+ timedOut: lastVerify.timedOut === true,
57
58
  fresh: lastVerify.timestamp >= lastMutationTimestamp,
58
59
  durationMs: lastVerify.durationMs,
59
60
  }
@@ -43,6 +43,7 @@ import {
43
43
  runVerify,
44
44
  resolveVerifyTimeoutMs,
45
45
  snipVerifyOutput,
46
+ formatTimeoutLimit,
46
47
  } from "./verify.ts";
47
48
  import { detectShellMutation, extractPatchPaths, foreignSegmentMutationReason, guardShellMutation, hasUnresolvableVariable, isAllowedScratchTarget, isEnvironmentScratchTarget, isPathOutsideWorkspace, linkedWorktreeMismatchReason, nestedPayloadMutationReason, OPENCODE_SCRATCH_DIR } from "../policies/boundary.ts";
48
49
  import { branchHasChangelogChange, checkLockfileSync, hasPrCreateInvocation, prBodyHasLiteralLineBreakEscapes, prBodyIncludesChangelog } from "../policies/changelog.ts";
@@ -164,17 +165,6 @@ function logBlock(message: string, simulate = false): void {
164
165
  } catch {}
165
166
  }
166
167
 
167
- /**
168
- * Render a verification timeout limit for the block reason.
169
- *
170
- * Sub-second limits are exercised by tests, and a bare `Math.round(ms/1000)`
171
- * reports those as "0s", which reads as no limit at all.
172
- */
173
- function formatTimeoutLimit(timeoutMs: number | undefined): string {
174
- if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return "the verification timeout";
175
- return timeoutMs < 1000 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1000)}s`;
176
- }
177
-
178
168
  export async function guardToolCallImpl(
179
169
  toolName: string,
180
170
  input: unknown,
@@ -282,11 +272,12 @@ export async function guardToolCallImpl(
282
272
  // finalization, but naming a failure sends the
283
273
  // agent chasing an assertion that never ran, and
284
274
  // the remedy is a longer limit rather than a code
285
- // change. The tail is snipped as passing output on
286
- // that path, because snipVerifyOutput labels a
287
- // failing run with a "Verification Failed" header
288
- // that would restate the misattribution.
289
- const tail = snipVerifyOutput(result.output, result.timedOut === true).slice(-500);
275
+ // change. A timed-out tail is snipped as `unknown`:
276
+ // neither label is honest, because the run neither
277
+ // passed nor failed. `unknown` also keeps the
278
+ // "Verification Failed" header off a run that did
279
+ // not report one.
280
+ const tail = snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : "failed").slice(-500);
290
281
  const reason = result.timedOut
291
282
  ? `Blocked todowrite: verification did not finish within ${formatTimeoutLimit(result.timeoutMs)} so the result is unknown rather than failing (${command}). Only the user can raise the limit, in the project .opencode/workflow-guard.json or .jsonc (verifyTimeoutMs) or with WORKFLOW_GUARD_VERIFY_TIMEOUT_MS set before the guard starts; ask them, then complete the tasks again. Output tail: ${tail}`
292
283
  : `Blocked todowrite: all tasks marked done but verification is failing (${command}). Fix the failure before finishing; output tail: ${tail}`;
package/src/lib/state.ts CHANGED
@@ -4,6 +4,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { audit, getDogfoodCacheFilePath, getReviewCacheFilePath, loadDogfoodCache, loadReviewCache, persistDogfoodCache, persistReviewCache, persistVerifyCache, persistVerifyHistory } from "./audit.ts";
5
5
  import { findGitRoot, getCachedProjectConfig, isSameGitRepo, loadProjectConfig, projectRootKey } from "./project-config.ts";
6
6
  import { snipVerifyOutput, getCurrentGitCommitHash, getGitStatusSummary, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint } from "./verify.ts";
7
+ import type { VerifyOutcomeFields } from "./verify.ts";
7
8
  import { normalizeLiveControlPlaneRoots } from "./live-control-plane.ts";
8
9
  import type {
9
10
  TodoSdkClient,
@@ -417,16 +418,18 @@ export function getLastVerifyResultForWorkspace(root: string): typeof lastVerify
417
418
 
418
419
  export function recordVerifyResult(
419
420
  command: string,
420
- result: { passed: boolean; output: string; durationMs?: number },
421
+ result: VerifyOutcomeFields,
421
422
  sessionID?: string,
422
423
  root = getWorkspaceRoot(),
423
424
  ): void {
424
425
  lastVerify = {
425
426
  command,
426
427
  passed: result.passed,
427
- output: snipVerifyOutput(result.output, result.passed),
428
+ output: snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : result.passed ? "passed" : "failed"),
428
429
  timestamp: Date.now(),
429
430
  durationMs: result.durationMs,
431
+ timedOut: result.timedOut === true,
432
+ timeoutMs: result.timeoutMs,
430
433
  commitHash: getCurrentGitCommitHash(root),
431
434
  gitStatus: getGitStatusSummary(root),
432
435
  workspaceRoot: projectRootKey(root),
package/src/lib/types.ts CHANGED
@@ -125,6 +125,14 @@ export interface VerifyResult {
125
125
  output: string;
126
126
  timestamp: number;
127
127
  durationMs?: number;
128
+ /**
129
+ * Set when the run was killed at its limit. The result is neither a pass nor
130
+ * a fail, so any human-readable summary of it must say "timed out" rather
131
+ * than claim a failing test.
132
+ */
133
+ timedOut?: boolean;
134
+ /** The limit that was hit, so a summary can name it at the precision it was set. */
135
+ timeoutMs?: number;
128
136
  commitHash?: string;
129
137
  gitStatus?: string;
130
138
  workspaceRoot?: string;
@@ -237,6 +245,8 @@ export interface AuditEntry {
237
245
  verification?: {
238
246
  command: string;
239
247
  passed: boolean;
248
+ /** A timed-out run is neither a pass nor a fail; the audit must not imply one. */
249
+ timedOut?: boolean;
240
250
  fresh: boolean;
241
251
  durationMs?: number;
242
252
  };
@@ -59,6 +59,7 @@ import {
59
59
  import { secretIn } from "../policies/secrets.ts";
60
60
  import { createCustomTools, buildWorkflowGuardSystemGuidance } from "./custom-tools.ts";
61
61
  import { isMutatingSurfaceTool, isReadOnlyRole, SHELL_TOOL_NAMES } from "./guard-dispatcher.ts";
62
+ import { formatTimeoutLimit } from "./verify.ts";
62
63
  import { ToolInvocationLifecycle } from "./tool-lifecycle.ts";
63
64
  import { ToolOutcomeTracker } from "./tool-outcomes.ts";
64
65
  import { EDIT_TOOL_NAMES, fetchParentSession, fetchParentSessionID, effectiveTodos } from "../policies/todo.ts";
@@ -535,7 +536,7 @@ export const WorkflowGuardV2 = async (ctx: V2Context) => {
535
536
  ];
536
537
  if (lastV) {
537
538
  stateLines.push(
538
- `- Test Verification: ${lastV.passed ? "PASSED" : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
539
+ `- Test Verification: ${lastV.passed ? "PASSED" : lastV.timedOut ? `TIMED OUT within ${formatTimeoutLimit(lastV.timeoutMs)} (result unknown, not a failing test)` : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
539
540
  );
540
541
  }
541
542
  if (lastR) {
package/src/lib/verify.ts CHANGED
@@ -72,23 +72,39 @@ export function verifyCommandSource(root: string): VerifyCommandSource {
72
72
  return detectVerifyCommand(root) ? "auto-detected" : null;
73
73
  }
74
74
 
75
+ /**
76
+ * What a verification run proved. `unknown` is the timeout outcome: the command
77
+ * never finished, so it is evidence of neither passing nor failing work.
78
+ */
79
+ export type VerifyOutcome = "passed" | "failed" | "unknown";
80
+
75
81
  /**
76
82
  * Truncates and snips verification stdout/stderr for token efficiency.
77
83
  * When a test suite or compiler passes, verbose log lines are trimmed to a
78
84
  * concise summary. When it fails, failure context, error markers, and stack
79
85
  * traces are prioritized.
86
+ *
87
+ * A timed-out run gets its own label. Borrowing the passing label told the agent
88
+ * "all tests passing" about a suite that never finished, and borrowing the
89
+ * failing one invented a failure that does not exist.
80
90
  */
81
- export function snipVerifyOutput(output: string, passed: boolean, maxLines = 40): string {
91
+ export function snipVerifyOutput(output: string, outcome: VerifyOutcome, maxLines = 40): string {
82
92
  if (!output) return "(no output)";
83
93
  const lines = output.trim().split("\n");
84
94
  if (lines.length <= maxLines) return output.trim();
85
95
 
86
- if (passed) {
87
- const head = lines.slice(0, 5).join("\n");
96
+ const head = lines.slice(0, 5).join("\n");
97
+
98
+ if (outcome === "passed") {
88
99
  const tail = lines.slice(-15).join("\n");
89
100
  return `${head}\n... [${lines.length - 20} lines omitted - all tests passing] ...\n${tail}`;
90
101
  }
91
102
 
103
+ if (outcome === "unknown") {
104
+ const tail = lines.slice(-20).join("\n");
105
+ return `${head}\n... [${lines.length - 25} lines omitted - outcome unknown, the run did not finish] ...\n${tail}`;
106
+ }
107
+
92
108
  const errorLines: string[] = [];
93
109
  for (const line of lines) {
94
110
  if (/(?:fail|error|exception|panic|assert|reject|expected|received|err:)/i.test(line)) {
@@ -96,7 +112,6 @@ export function snipVerifyOutput(output: string, passed: boolean, maxLines = 40)
96
112
  }
97
113
  }
98
114
 
99
- const head = lines.slice(0, 5).join("\n");
100
115
  const tail = lines.slice(-20).join("\n");
101
116
  const errorSummary = errorLines.slice(-15).join("\n");
102
117
 
@@ -250,6 +265,22 @@ export function resolveVerifyTimeoutMs(root: string): number {
250
265
  return typeof configured === "number" && Number.isFinite(configured) && configured > 0 ? configured : 30_000;
251
266
  }
252
267
 
268
+ /**
269
+ * Render a verification timeout limit for anything the agent reads.
270
+ *
271
+ * Sub-second limits are exercised by tests, and a bare `Math.round(ms/1000)`
272
+ * reports those as "0s", which reads as no limit at all. Both the block reason
273
+ * and the timed-out output tail render through here so they cannot disagree.
274
+ *
275
+ * The non-finite fallback is defensive only: `timedOut`/`timeoutMs` are set in
276
+ * one place, from the same argument Node coerced into a valid timer delay, so a
277
+ * real timeout always carries a finite positive value here.
278
+ */
279
+ export function formatTimeoutLimit(timeoutMs: number | undefined): string {
280
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return "the verification timeout";
281
+ return timeoutMs < 1000 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1000)}s`;
282
+ }
283
+
253
284
  export interface VerifyRun {
254
285
  passed: boolean;
255
286
  output: string;
@@ -265,6 +296,13 @@ export interface VerifyRun {
265
296
  timeoutMs?: number;
266
297
  }
267
298
 
299
+ /**
300
+ * The part of a verification run that gets recorded as evidence. `timeoutMs`
301
+ * travels with `timedOut` so a summary can name the limit at its own precision
302
+ * instead of guessing at it.
303
+ */
304
+ export type VerifyOutcomeFields = Pick<VerifyRun, "passed" | "output" | "timedOut" | "timeoutMs"> & { durationMs?: number };
305
+
268
306
  export async function runVerify(
269
307
  command: string,
270
308
  root: string,
@@ -326,7 +364,7 @@ export async function runVerify(
326
364
  void terminateProcessTree(child.pid, () => child.kill("SIGKILL")).finally(() => {
327
365
  resolve({
328
366
  passed: false,
329
- output: output + `\n(Verification timed out after ${Math.round(timeoutMs / 1000)}s)`,
367
+ output: output + `\n(Verification timed out after ${formatTimeoutLimit(timeoutMs)})`,
330
368
  durationMs: Date.now() - start,
331
369
  timedOut: true,
332
370
  timeoutMs,
@@ -2,7 +2,7 @@ import { isEvidenceFresh, verificationEvidence } from "../lib/evidence.ts";
2
2
  import { projectRootKey } from "../lib/project-config.ts";
3
3
  import { getWorkspaceRoot, sessionVerifyResults, lastVerify, sessionMutationTimestamps, lastMutationTimestamp } from "../lib/state.ts";
4
4
  import type { VerifyResult } from "../lib/types.ts";
5
- import { getCurrentGitCommitHash, getGitWorktreeFingerprint } from "../lib/verify.ts";
5
+ import { getCurrentGitCommitHash, formatTimeoutLimit, getGitWorktreeFingerprint } from "../lib/verify.ts";
6
6
 
7
7
  /**
8
8
  * Claims-vs-evidence check (Policy 24): when the assistant's final text
@@ -26,7 +26,7 @@ const VERIFICATION_FRESH_WINDOW_MS = 120_000;
26
26
  export interface CompletionClaimCheck {
27
27
  claimsCompletion: boolean;
28
28
  claim?: string;
29
- evidenceState?: "fresh-pass" | "stale-pass" | "failing" | "missing";
29
+ evidenceState?: "fresh-pass" | "stale-pass" | "failing" | "timed-out" | "missing";
30
30
  reason?: string;
31
31
  }
32
32
 
@@ -61,7 +61,10 @@ export function checkCompletionClaims(
61
61
  evidenceState =
62
62
  context?.sessionID && mutationTimestamp > 0 ? "stale-pass" : "missing";
63
63
  } else if (!verifyResult.passed) {
64
- evidenceState = "failing";
64
+ // A timed-out run proved nothing. Filing it under "failing" tells the
65
+ // reader an assertion broke, which is the misattribution Policy 10 now
66
+ // avoids everywhere else.
67
+ evidenceState = verifyResult.timedOut === true ? "timed-out" : "failing";
65
68
  } else if (
66
69
  !isEvidenceFresh(verificationEvidence(verifyResult, context?.sessionID), {
67
70
  workspace: projectRootKey(getWorkspaceRoot()),
@@ -84,6 +87,7 @@ export function checkCompletionClaims(
84
87
  missing:
85
88
  "the response asserts completion/verification, but no verification evidence has been recorded in this session.",
86
89
  failing: `the response asserts completion, but the latest verification (${verifyResult?.command}) FAILED.`,
90
+ "timed-out": `the response asserts completion, but the latest verification (${verifyResult?.command}) did not finish within ${formatTimeoutLimit(verifyResult?.timeoutMs)}, so its result is unknown rather than failing.`,
87
91
  "stale-pass":
88
92
  "the response asserts completion, but the last passing verification is stale - mutations were recorded after it.",
89
93
  "fresh-pass": "",
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { isAbsolute, relative, resolve } from "node:path";
4
4
  import { getProjectConfig } from "../lib/state.ts";
5
- import { runVerify, snipVerifyOutput } from "../lib/verify.ts";
5
+ import { formatTimeoutLimit, runVerify, snipVerifyOutput } from "../lib/verify.ts";
6
6
  import { extractPatchPaths } from "./boundary.ts";
7
7
 
8
8
  export interface FileSnapshot {
@@ -69,7 +69,12 @@ export async function runPostEditValidators(root: string, before: FileSnapshot):
69
69
  const timeoutMs = validator.timeoutMs ?? 30_000;
70
70
  const result = await runVerify(validator.command, root, timeoutMs);
71
71
  if (!result.passed) {
72
- failures.push(`[workflow-guard] Post-edit validator failed for ${relativePath}: ${validator.command}\n${snipVerifyOutput(result.output, false)}`);
72
+ // A validator that never finished is not a failed validator. Say
73
+ // which one happened, or the agent debugs a check that never ran.
74
+ const outcome = result.timedOut === true
75
+ ? `did not finish within ${formatTimeoutLimit(result.timeoutMs)}`
76
+ : "failed";
77
+ failures.push(`[workflow-guard] Post-edit validator ${outcome} for ${relativePath}: ${validator.command}\n${snipVerifyOutput(result.output, result.timedOut === true ? "unknown" : "failed")}`);
73
78
  }
74
79
  }
75
80
  return failures.length ? failures.join("\n\n") : undefined;
@@ -245,6 +245,7 @@ import {
245
245
  resolveVerifyTimeoutMs,
246
246
  runVerify,
247
247
  snipVerifyOutput,
248
+ formatTimeoutLimit,
248
249
  getCurrentGitCommitHash,
249
250
  getGitStatusSummary,
250
251
  getGitWorktreeFingerprint,
@@ -257,6 +258,7 @@ export {
257
258
  resolveVerifyTimeoutMs,
258
259
  runVerify,
259
260
  snipVerifyOutput,
261
+ formatTimeoutLimit,
260
262
  getCurrentGitCommitHash,
261
263
  getGitStatusSummary,
262
264
  getGitWorktreeFingerprint,
@@ -679,7 +681,7 @@ export const WorkflowGuard: V1Plugin = async (ctx: Parameters<V1Plugin>[0]) => {
679
681
  ];
680
682
  if (lastV) {
681
683
  stateLines.push(
682
- `- Test Verification: ${lastV.passed ? "PASSED" : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
684
+ `- Test Verification: ${lastV.passed ? "PASSED" : lastV.timedOut ? `TIMED OUT within ${formatTimeoutLimit(lastV.timeoutMs)} (result unknown, not a failing test)` : "FAILED"} (${lastV.command})${lastV.commitHash ? ` at commit ${lastV.commitHash.slice(0, 7)}` : ""}`,
683
685
  );
684
686
  }
685
687
  if (lastR) {
package/test/test.mts CHANGED
@@ -1968,6 +1968,20 @@ writeFileSync(timeoutArgs.filePath, "after");
1968
1968
  const timeoutOutput = { title: "edit", output: "edited", metadata: {} };
1969
1969
  await validatorAfter?.({ tool: "edit", sessionID: "s-validator", callID: "validator-4", args: timeoutArgs }, timeoutOutput);
1970
1970
  check("post-edit validator timeout is bounded and reported", timeoutOutput.output.includes("timed out"));
1971
+ // A validator killed at its limit did not fail. Naming it a failure sends the
1972
+ // agent debugging a check that never reached an assertion, and the fix is a
1973
+ // longer validator timeout. Both validators match timeout.ts, so the genuine
1974
+ // `**/*.ts` failure appears in the same message; assert on the timed-out
1975
+ // validator's own line rather than on the message as a whole.
1976
+ const timeoutValidatorLine = timeoutOutput.output
1977
+ .split("\n")
1978
+ .find((line) => line.includes("Post-edit validator") && line.includes("setTimeout"));
1979
+ check(
1980
+ "post-edit validator timeout names the limit instead of claiming a failed check",
1981
+ Boolean(timeoutValidatorLine) &&
1982
+ timeoutValidatorLine!.includes("did not finish within 25ms") &&
1983
+ !timeoutValidatorLine!.includes("failed"),
1984
+ );
1971
1985
 
1972
1986
  writeFileSync(join(validatorDir, "patched-a.ts"), "before");
1973
1987
  writeFileSync(join(validatorDir, "patched-b.ts"), "before");
@@ -2795,6 +2809,24 @@ check(
2795
2809
  "verification timeout names the user as the actor for a limit the agent cannot raise",
2796
2810
  String(timeoutFinalRes).includes("Only the user can raise the limit") && String(timeoutFinalRes).includes(".jsonc"),
2797
2811
  );
2812
+ // The tail is rendered by the verify engine, the reason by the dispatcher.
2813
+ // Two formatters meant the reason said 50ms while the tail said "after 0s",
2814
+ // which reads as no limit at all. One formatter, asserted at both ends.
2815
+ check(
2816
+ "a timed-out tail names the same limit at the same precision as the reason",
2817
+ String(timeoutFinalRes).includes("Verification timed out after 50ms") &&
2818
+ !String(timeoutFinalRes).includes("timed out after 0s"),
2819
+ );
2820
+ // The tail is also snipped, and the snipper used to label it "all tests
2821
+ // passing" because a timeout was routed down the pass branch. A killed suite
2822
+ // is not a passing suite, and this is the same message the agent reads. The
2823
+ // omission marker only appears once the snipper has more lines than its budget,
2824
+ // so the positive label is pinned by the snip unit check above; here the
2825
+ // invariant is that no claim of passing can appear on this path at all.
2826
+ check(
2827
+ "a timed-out tail never claims the killed suite passed",
2828
+ !String(timeoutFinalRes).includes("all tests passing"),
2829
+ );
2798
2830
  // Machine consumers (audit, evidence, the V2 seat) branch on the code, not the
2799
2831
  // prose, so pin the timeout's own code rather than only its message.
2800
2832
  const timeoutDecision = await guardToolDecision(
@@ -4028,6 +4060,15 @@ const statusResult = await customPlugin.tool?.guard_status?.execute({}, {} as an
4028
4060
  check("guard_status executes and returns JSON string", typeof statusResult === "string" && statusResult.includes("workspaceRoot"));
4029
4061
  const parsedStatus = JSON.parse(statusResult as string);
4030
4062
  check("guard_status exposes subject-bound evidence references", parsedStatus.lastVerify === null || (typeof parsedStatus.lastVerify.evidenceId === "string" && typeof parsedStatus.lastVerify.fresh === "boolean"));
4063
+ // guard_status is the machine-readable half the agent reads before finalizing.
4064
+ // A timed-out run must not read as a failing one there either.
4065
+ recordVerifyResult("npm test", { passed: false, output: "killed", durationMs: 50, timedOut: true }, undefined, root);
4066
+ const timeoutStatus = JSON.parse(String(await customPlugin.tool?.guard_status?.execute({}, {} as any)));
4067
+ check(
4068
+ "guard_status marks a timed-out verification as timedOut rather than a failure",
4069
+ timeoutStatus.lastVerify?.timedOut === true && timeoutStatus.lastVerify?.passed === false,
4070
+ );
4071
+ resetVerifyState();
4031
4072
  check("guard_status exposes effective operation profile without TUI state", parsedStatus.projectConfig.profile === "interactive" && typeof parsedStatus.projectConfig.recoveryCheckpoints === "boolean");
4032
4073
  check("guard_status exposes disabled-by-default Ralph accountability state", parsedStatus.ralph?.enabled === false && parsedStatus.ralph?.maxIterations === 10 && parsedStatus.ralph?.outcome === null);
4033
4074
  check("guard_status exposes bounded outstanding requirements", Array.isArray(parsedStatus.outstandingRequirements) && parsedStatus.outstandingRequirements.every((requirement: unknown) => ["verification", "review", "documentation"].includes(String(requirement))));
@@ -5864,12 +5905,22 @@ check("read on .env file returns blocked message with masked variable schema hin
5864
5905
 
5865
5906
  // Feature 2: Verification output snipping
5866
5907
  const verbosePassingLogs = Array.from({ length: 100 }, (_, i) => `PASS: test #${i} passed successfully`).join("\n");
5867
- const snippedPass = snipVerifyOutput(verbosePassingLogs, true, 20);
5908
+ const snippedPass = snipVerifyOutput(verbosePassingLogs, "passed", 20);
5868
5909
  check("snipVerifyOutput truncates verbose passing logs", snippedPass.includes("lines omitted") && snippedPass.split("\n").length < 30);
5869
5910
 
5870
5911
  const verboseFailingLogs = Array.from({ length: 80 }, (_, i) => i === 40 ? "FAIL: AssertionError: expected true to be false\n at Object.<anonymous> (test.ts:42:1)" : `info log line ${i}`).join("\n");
5871
- const snippedFail = snipVerifyOutput(verboseFailingLogs, false, 20);
5912
+ const snippedFail = snipVerifyOutput(verboseFailingLogs, "failed", 20);
5872
5913
  check("snipVerifyOutput preserves failure keywords on fail", snippedFail.includes("AssertionError") || snippedFail.includes("FAIL:"));
5914
+ // A run that never finished proved nothing. Snipping it as passing printed
5915
+ // "all tests passing" about a suite that was killed; snipping it as failing
5916
+ // printed a "Verification Failed" header nobody observed. Both are false
5917
+ // statements about the same evidence, so the third outcome is its own label.
5918
+ const verboseTimedOutLogs = Array.from({ length: 100 }, (_, i) => `info log line ${i}`).join("\n");
5919
+ const snippedTimeout = snipVerifyOutput(verboseTimedOutLogs, "unknown", 20);
5920
+ check(
5921
+ "snipVerifyOutput does not claim a timed-out run passed or failed",
5922
+ !snippedTimeout.includes("all tests passing") && !snippedTimeout.includes("Verification Failed") && snippedTimeout.includes("outcome unknown"),
5923
+ );
5873
5924
 
5874
5925
  // Feature 3: Git snapshot & mutation counts
5875
5926
  check("getCurrentGitCommitHash returns commit string in git repo", typeof getCurrentGitCommitHash(conflictRepo) === "string");
@@ -5894,6 +5945,26 @@ check("compaction context includes subagent session & parent attribution", compa
5894
5945
  check("compaction context includes Operational Guard State header", compactText.includes("Operational Guard State"));
5895
5946
  check("compaction context includes Git Branch status", compactText.includes("Git Branch:"));
5896
5947
  check("compaction context includes Test Verification status", compactText.includes("Test Verification:"));
5948
+ // A timed-out run is not a failing run in the compacted context either. The
5949
+ // summary is what a post-compaction agent reads first, so "FAILED" there sends
5950
+ // it hunting for an assertion that never ran.
5951
+ recordVerifyResult("npm test", { passed: false, output: "killed", durationMs: 50, timedOut: true, timeoutMs: 50 }, "s-active");
5952
+ const timeoutCompactingContext: { context: string[] } = { context: [] };
5953
+ if (typeof compactSubagentFn === "function") {
5954
+ await compactSubagentFn({ sessionID: "s-active" } as any, timeoutCompactingContext as any);
5955
+ }
5956
+ const timeoutCompactText = timeoutCompactingContext.context[0] ?? "";
5957
+ check(
5958
+ "compaction context reports a timed-out verification as unknown, not failed",
5959
+ timeoutCompactText.includes("Test Verification: TIMED OUT") && !timeoutCompactText.includes("Test Verification: FAILED"),
5960
+ );
5961
+ // The limit travels with the outcome, so the summary names it at the precision
5962
+ // it was set rather than rounding a sub-second limit to "0s".
5963
+ check(
5964
+ "compaction context names the limit that was hit at its own precision",
5965
+ timeoutCompactText.includes("TIMED OUT within 50ms"),
5966
+ );
5967
+ recordVerifyResult("npm test", { passed: true, output: "ok" }, "s-active");
5897
5968
  check("compaction context includes Secondary Review status", compactText.includes("Secondary Review:"));
5898
5969
  const unrelatedCompactingContext: { context: string[] } = { context: [] };
5899
5970
  if (typeof compactSubagentFn === "function") {
@@ -6923,6 +6994,19 @@ recordVerifyResult("npm test", { passed: false, output: "1 failed" }, "s-claim-f
6923
6994
  const failCheck = checkCompletionClaims("All tests pass.", { sessionID: "s-claim-fail" });
6924
6995
  check("failing verification contradicts the claim", failCheck.evidenceState === "failing" && typeof failCheck.reason === "string");
6925
6996
 
6997
+ // A timed-out run proved nothing, so it must not be filed as a failure. The
6998
+ // audit trail is where this surfaces: a timeout journaled as "failing" tells a
6999
+ // reader an assertion broke when nothing ran to completion.
7000
+ resetVerifyState();
7001
+ recordVerifyResult("npm test", { passed: false, output: "killed", durationMs: 50, timedOut: true, timeoutMs: 50 }, "s-claim-timeout");
7002
+ const timeoutClaimCheck = checkCompletionClaims("All tests pass.", { sessionID: "s-claim-timeout" });
7003
+ check(
7004
+ "a timed-out verification is not filed as a failing one",
7005
+ timeoutClaimCheck.evidenceState === "timed-out" &&
7006
+ String(timeoutClaimCheck.reason).includes("did not finish within 50ms") &&
7007
+ !String(timeoutClaimCheck.reason).includes("FAILED"),
7008
+ );
7009
+
6926
7010
  // Stale evidence: passing verification, then a mutation, then claim -> stale-pass
6927
7011
  resetVerifyState();
6928
7012
  recordVerifyResult("npm test", { passed: true, output: "ok" }, "s-claim-stale");