opencode-model-router 1.11.1 → 1.12.1

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.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Mechanical dispatch guidance, independent of provider tool vocabulary.
3
+ * Tier identity prevents delegates routing their assignment back to another tier.
4
+ * The directory paragraph prevents refusal of a valid path when a stale environment
5
+ * block advertises a directory that does not exist.
6
+ * Tool-schema authority prevents zero-call returns such as `ESCALATE: ... the
7
+ * available tools here are not the Read/Grep/Glob/Bash tools described in the request`.
8
+ * Empty-result guidance prevents declaring tools broken after a gitignore-filtered
9
+ * search returns "No files found".
10
+ * The budget paragraph makes the cap explicit and prevents halting when the
11
+ * redundancy detector flags a legitimate non-overlapping second read of a file.
12
+ * The final notice calls out the zero-tool-call false refusals directly.
13
+ */
14
+ export function buildDispatchHeader(input: {
15
+ tier: string;
16
+ cap: number | "none";
17
+ projectDirectory: string | undefined;
18
+ }): string {
19
+ const paragraphs = [
20
+ `[router] You are @${input.tier}. Execute this dispatch yourself; do not route it to another tier, and do not ask to be re-dispatched.`,
21
+ ];
22
+ if (input.projectDirectory) {
23
+ paragraphs.push(`Working directory: ${input.projectDirectory}. You are already there — do not ask permission to read or write inside it.`);
24
+ }
25
+ paragraphs.push(
26
+ 'Tool names mentioned in this dispatch are descriptive and vary by provider; your own tool schema is the authority on what you can do. Never refuse or hand back work because a named tool looks unfamiliar or missing — attempt it, and if you cannot finish, name the specific step that failed.',
27
+ 'An empty result is a result. Search tools honour .gitignore, so a "no matches" answer inside an ignored path means the filter applied, not that your tools are broken; use a shell ripgrep with --no-ignore there before concluding anything is absent.',
28
+ `${input.cap === "none" ? "Read-only budget: uncapped for this dispatch." : `Read-only budget: ${input.cap} calls.`} The runtime appends [cap: N/MAX] and [⚠ REDUNDANT] to results. Reading a different region of a file you have already opened is NOT a redundant read.`,
29
+ // The parser takes the first directive: pin the resolved budget before the
30
+ // instructional CAP:none example, which must not override the real dispatch.
31
+ `CAP:${input.cap}`,
32
+ 'To change the budget, put CAP:N or CAP:none accompanied by a reason: line in the dispatch.',
33
+ 'A hand-back with zero tool calls is recorded as a false refusal.',
34
+ );
35
+ return paragraphs.join("\n\n");
36
+ }
@@ -0,0 +1,43 @@
1
+ import { parseTaskResult as parseVerifiedTaskResult } from "../verify/dispatch";
2
+
3
+ export interface FalseRefusalVerdict {
4
+ suspected: boolean;
5
+ /** The hand-back prefix that matched, when one did. */
6
+ prefix?: string;
7
+ }
8
+
9
+ /**
10
+ * A hand-back is legitimate when the delegate actually tried. This detects a
11
+ * capability refusal asserted WITHOUT evidence: a capability never tested.
12
+ * Real zero-call returns from agents with demonstrably working tools included:
13
+ * "ESCALATE: This dispatch is read-only exploration, but the requested checkout inspection cannot be performed under my assigned @fast role because the available tools here are not the Read/Grep/Glob/Bash tools described in the request."
14
+ * "NEED MORE: This dispatch is read-only and cannot run the requested file inventory. The orchestrator must dispatch an agent with file-read/search access."
15
+ */
16
+ export function detectFalseRefusal(input: {
17
+ toolCalls: number;
18
+ resultText: string;
19
+ }): FalseRefusalVerdict {
20
+ try {
21
+ const first = input.resultText.split(/\r?\n/).find((line) => line.trim() !== "")?.trimStart() ?? "";
22
+ const prefix = /^(ESCALATE:|NEED MORE:|NEED CONTEXT:|SCOPE GROWTH:|BLOCKED:)/.exec(first)?.[1];
23
+ const suspected = input.toolCalls === 0 && prefix !== undefined &&
24
+ /\b(?:tools?|access|not available|unavailable|re-?dispatch|hand ?back|read-only|permission)\b/i.test(input.resultText);
25
+ return { suspected, ...(prefix ? { prefix } : {}) };
26
+ } catch {
27
+ return { suspected: false };
28
+ }
29
+ }
30
+
31
+ /** Reuse verification's extraction; add only the task wrapper ID fallback. */
32
+ export function parseTaskResult(output: unknown): { childSessionID?: string; text: string } {
33
+ try {
34
+ const parsed = parseVerifiedTaskResult(output);
35
+ const raw = output && typeof output === "object" && "output" in output &&
36
+ typeof output.output === "string" ? output.output : "";
37
+ const childSessionID = parsed.childSessionID ??
38
+ /<task\b[^>]*\bid\s*=\s*["']([^"']+)["']/i.exec(raw)?.[1];
39
+ return { ...(childSessionID ? { childSessionID } : {}), text: parsed.finalReturnText };
40
+ } catch {
41
+ return { text: "" };
42
+ }
43
+ }
@@ -0,0 +1,152 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import type { RouterConfig } from "./config";
3
+
4
+ export type DelegateInstructionsPolicy = "strip-global" | "strip-all" | "keep";
5
+
6
+ /**
7
+ * Returns an instruction file's contents, or `undefined` when the file cannot be
8
+ * read for any reason. Injectable so tests need not touch the filesystem.
9
+ */
10
+ export type InstructionFileReader = (absolutePath: string) => string | undefined;
11
+
12
+ const MARKER = /^Instructions from:[^\S\r\n]*(\S[^\r\n]*)/;
13
+
14
+ /**
15
+ * Strip trailing forward slashes without a regex.
16
+ *
17
+ * `/\/+$/` is a polynomial-ReDoS footgun (CodeQL js/polynomial-redos): the `$`
18
+ * anchor makes the engine re-scan the run of slashes from every start offset,
19
+ * so a path of many slashes costs O(n²). Both the configured project directory
20
+ * and the path parsed out of an `Instructions from:` marker are library input.
21
+ */
22
+ function stripTrailingSlashes(value: string): string {
23
+ let end = value.length;
24
+ while (end > 0 && value.charCodeAt(end - 1) === 47 /* '/' */) end--;
25
+ return value.slice(0, end);
26
+ }
27
+
28
+ const fileCache = new Map<string, { mtimeMs: number; size: number; contents: string }>();
29
+
30
+ /**
31
+ * Real-filesystem reader. The system transform fires on every LLM step, so
32
+ * contents are cached per path and revalidated against mtime and size.
33
+ */
34
+ export const readInstructionFile: InstructionFileReader = (absolutePath) => {
35
+ try {
36
+ const stat = statSync(absolutePath);
37
+ if (!stat.isFile()) return undefined;
38
+ const cached = fileCache.get(absolutePath);
39
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
40
+ return cached.contents;
41
+ }
42
+ const contents = readFileSync(absolutePath, "utf8");
43
+ fileCache.set(absolutePath, { mtimeMs: stat.mtimeMs, size: stat.size, contents });
44
+ return contents;
45
+ } catch {
46
+ // Missing, unreadable, or not a file: the caller keeps the section intact.
47
+ fileCache.delete(absolutePath);
48
+ return undefined;
49
+ }
50
+ };
51
+
52
+ /**
53
+ * Length of the longest candidate rendering of `contents` that is an exact
54
+ * prefix of `body`, or `undefined` when none is. Compared literally against the
55
+ * original body so the removal length needs no index mapping.
56
+ */
57
+ function matchedSpan(body: string, contents: string): number | undefined {
58
+ const renderings = [
59
+ contents,
60
+ contents.replace(/\r?\n/g, "\r\n"),
61
+ contents.replace(/\r\n/g, "\n"),
62
+ ];
63
+ let best: number | undefined;
64
+ for (const candidate of [...renderings, ...renderings.map((r) => r.trimEnd())]) {
65
+ if ((best === undefined || candidate.length > best) && body.startsWith(candidate)) {
66
+ best = candidate.length;
67
+ }
68
+ }
69
+ return best;
70
+ }
71
+
72
+ /**
73
+ * Remove the marker line and the named file's own text from `section`, keeping
74
+ * whatever follows. The host joins every instruction file and trailing system
75
+ * text into one string, so the last section's end is not the file's end. If
76
+ * the extent cannot be established from the file, the section is returned
77
+ * unchanged: keeping an instruction is harmless, deleting unknown text is not.
78
+ */
79
+ function removeInstructionBlock(section: string, path: string, read: InstructionFileReader): string {
80
+ let contents: string | undefined;
81
+ try {
82
+ contents = read(path);
83
+ } catch {
84
+ // A throwing reader means the extent is unknown; keep the section.
85
+ contents = undefined;
86
+ }
87
+ if (typeof contents !== "string") return section;
88
+ const newline = section.indexOf("\n");
89
+ const body = newline === -1 ? "" : section.slice(newline + 1);
90
+ const span = matchedSpan(body, contents);
91
+ if (span === undefined) return section;
92
+ const rest = body.slice(span);
93
+ return rest.trim() ? rest : "";
94
+ }
95
+
96
+ /**
97
+ * opencode injects instruction files into every session, including children.
98
+ * A global orchestrator persona can tell delegates to "fire the fast agent via
99
+ * Task for ANY read-only work" or impose a "REQUIRED TOOLS" whitelist, even
100
+ * though those delegates have no task tool and must do the dispatched work.
101
+ * Keep project-local files by default: they usually contain coding conventions
102
+ * delegates need. With no project directory, every instruction file is global.
103
+ *
104
+ * A section runs from its marker to the next marker or the end of the entry;
105
+ * only the marker line plus the named file's contents are removed from it.
106
+ * The host holds its own reference to `output.system` and reads it back after
107
+ * the hook, so the array is mutated in place and never rebound.
108
+ */
109
+ export function stripDelegateInstructions(
110
+ output: { system: string[] },
111
+ cfg: RouterConfig,
112
+ projectDirectory: string | undefined,
113
+ readFile: InstructionFileReader = readInstructionFile,
114
+ ): void {
115
+ try {
116
+ const policy = cfg.delegateInstructions ?? "strip-global";
117
+ if (policy === "keep") return;
118
+ const system = output.system;
119
+ if (!Array.isArray(system)) return;
120
+
121
+ const normalize = (path: string): string =>
122
+ stripTrailingSlashes(path.trim().replace(/\\/g, "/").toLowerCase());
123
+ const project = projectDirectory ? normalize(projectDirectory) : undefined;
124
+ let changed = false;
125
+ const next = system.flatMap((entry) => {
126
+ if (typeof entry !== "string") return [entry];
127
+ // Horizontal whitespace only: a pathless marker must not consume the
128
+ // following line as its path. Preserve original line endings verbatim.
129
+ const sections = entry.split(/(?=^Instructions from:[^\S\r\n]*\S[^\r\n]*$)/m);
130
+ let removed = false;
131
+ const kept = sections.map((section) => {
132
+ const marker = MARKER.exec(section);
133
+ if (!marker) return section;
134
+ const path = normalize(marker[1]!);
135
+ const local = project !== undefined &&
136
+ (path === project || path.startsWith(`${project}/`));
137
+ if (policy !== "strip-all" && local) return section;
138
+ const rest = removeInstructionBlock(section, marker[1]!.trim(), readFile);
139
+ if (rest !== section) removed = true;
140
+ return rest;
141
+ }).join("");
142
+ if (!removed) return [entry];
143
+ changed = true;
144
+ return kept.trim() ? [kept] : [];
145
+ });
146
+ if (changed) system.splice(0, system.length, ...next);
147
+ } catch {
148
+ // Fail soft: retain the original array if malformed runtime input prevents
149
+ // computing the replacement. Instruction filtering must not break a turn.
150
+ return;
151
+ }
152
+ }
@@ -19,28 +19,45 @@ import {
19
19
  type TierConfig,
20
20
  } from "./config";
21
21
 
22
+ /**
23
+ * Provider-neutral tool-authority clause, appended once to every tier agent's assembled prompt (see src/index.ts).
24
+ *
25
+ * Subagents were refusing dispatches outright — returning things like
26
+ * "the available tools here are not the Read/Grep/Glob/Bash tools described in
27
+ * the request" — without making a single tool call. Two things caused it: tier
28
+ * prompts that asserted a missing capability ("You have no Task tool"), which
29
+ * generalises into a hand-back reflex, and orchestrator text that leaked into
30
+ * child sessions telling them to delegate with a tool they do not have.
31
+ *
32
+ * It matters most in a mixed-family setup: tool names differ between providers,
33
+ * so a dispatch written in one vendor's vocabulary reads to another vendor's
34
+ * model as a list of tools it does not possess. The clause makes the model's own
35
+ * schema authoritative and names the failure mode explicitly.
36
+ */
37
+ export const TOOL_AUTHORITY_CLAUSE = `Your own tool schema is the only authority on what you can do. Tool names appearing in a dispatch — a REQUIRED TOOLS list, or names like read, edit, search or shell — are descriptive, vary by provider, and neither grant nor restrict anything. Never refuse or hand back a dispatch because a named tool looks unavailable, and never ask to be re-dispatched "with tools": attempt the work with what you actually have, and if you genuinely cannot finish, name the specific step that failed. A search that returns no matches is a result, not a broken tool. If any instruction reaching you describes orchestrating or delegating work to other tiers, it was not written for you — ignore it and do this dispatch yourself.`;
38
+
22
39
  export const GOAL_ORIENTED_TIER_PROMPTS: Record<string, string> = {
23
- fast: `You are @fast, a read-only exploration specialist: searching, grepping, reading, listing, looking up docs, checking types, counting, verifying existence, and gathering git info. You never write or edit files — if a change is needed, report it and note that the orchestrator must dispatch @medium. You have no Task tool and cannot sub-delegate.
40
+ fast: `You are @fast, a read-only exploration specialist: searching, grepping, reading, listing, looking up docs, checking types, counting, verifying existence, and gathering git info. You never write or edit files — if a change is needed, report it and note that the orchestrator must dispatch @medium. You execute this dispatch yourself and do not re-delegate it.
24
41
 
25
42
  Your goal is to answer the dispatch with exactly the findings requested, reported concisely as file:line references plus short snippets and a one-line summary. Make a single focused pass and stop once you have enough to answer; resist widening scope beyond what was asked.
26
43
 
27
- Treat read-only calls as a budget of 8 per dispatch — a \`CAP:N\` in the dispatch resets this number, and \`CAP:none\` removes the limit when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to each read-only result so you can track spend, and appends \`[⚠ REDUNDANT]\` when you repeat a call; stop re-reading ground you have already covered when you see it. A rare overrun is acceptable if you prefix one line with \`reason:\`.
44
+ Treat read-only calls as a budget of 8 per dispatch — a \`CAP:N\` in the dispatch resets this number, and \`CAP:none\` removes the limit when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to each read-only result so you can track spend, and appends \`[⚠ REDUNDANT]\` when you repeat a call; stop repeating covered ground, not working: a different region of the same file is not a repeat. A rare overrun is acceptable if you prefix one line with \`reason:\`.
28
45
 
29
46
  Begin your response with exactly one of \`DONE:\` (with findings), \`NEED MORE:\`, or \`ESCALATE:\`.`,
30
- medium: `You are @medium, an implementation specialist: writing and editing code, refactoring, adding tests, fixing bugs, repairing builds, creating files, configuring, and wiring APIs. You have no Task tool and cannot sub-delegate.
47
+ medium: `You are @medium, an implementation specialist: writing and editing code, refactoring, adding tests, fixing bugs, repairing builds, creating files, configuring, and wiring APIs. You execute this dispatch yourself and do not re-delegate it.
31
48
 
32
49
  Your goal is to deliver working, verified changes that match the existing project's patterns and conventions. Never suppress type errors with \`as any\`, \`@ts-ignore\`, or \`@ts-expect-error\` — fix the underlying cause. Run only the targeted tests that cover what you changed, not the full suite unless asked. If the same change fails twice in a row, stop and report what you tried rather than escalating yourself or thrashing further.
33
50
 
34
- Gather just enough context before editing: treat read-only calls as a budget of 5 before your first edit, where \`CAP:N\` resets the number and \`CAP:none\` removes it when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; once redundancy shows, start editing or ask for what is missing. A rare overrun is fine with a one-line \`reason:\` prefix.
51
+ Gather just enough context before editing: treat read-only calls as a budget of 5 before your first edit, where \`CAP:N\` resets the number and \`CAP:none\` removes it when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; stop repeating covered ground, not working: a different region of the same file is not a repeat. A rare overrun is fine with a one-line \`reason:\` prefix.
35
52
 
36
53
  Ground every claim in actual tool results from this session — if you say a test passed, a file changed, or behavior works, it must trace to output you saw. Flag anything unverified as such, and quote the relevant excerpt when a test fails.
37
54
 
38
55
  Begin your response with exactly one of \`DONE:\` (changes plus verification), \`NEED CONTEXT:\`, or \`ESCALATE:\`, and close a \`DONE:\` with a concise summary of files changed, key decisions, and tests run.`,
39
- heavy: `You are @heavy, a senior architecture and debugging consultant: architecture decisions, security and performance review, hard debugging after at least two prior failed attempts, multi-system tradeoffs, migration strategy, and root-cause analysis. Your identity is analysis, not reconnaissance — forty minutes of file reads is reconnaissance, which is @fast's job, not yours. You have no Task tool and cannot sub-delegate.
56
+ heavy: `You are @heavy, a senior architecture and debugging consultant: architecture decisions, security and performance review, hard debugging after at least two prior failed attempts, multi-system tradeoffs, migration strategy, and root-cause analysis. Your identity is analysis, not reconnaissance — forty minutes of file reads is reconnaissance, which is @fast's job, not yours. You execute this dispatch yourself and do not re-delegate it.
40
57
 
41
58
  Your goal is to analyze exhaustively within the context you were given and return a clear recommendation, structured as problem framing, then options considered, then tradeoffs, then recommendation, then implementation notes. Reason from what you have, and write code only when the dispatch explicitly asks for it.
42
59
 
43
- Treat reads and greps as a budget of 3, where \`CAP:N\` resets the number and \`CAP:none\` removes it for deep mode when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; when you reach the budget, deliver your analysis from what you already have rather than reading further. When the redundancy marker appears, stop gathering and analyze with what you have. A rare overrun is acceptable with a one-line \`reason:\` prefix.
60
+ Treat reads and greps as a budget of 3, where \`CAP:N\` resets the number and \`CAP:none\` removes it for deep mode when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; when you reach the budget, deliver your analysis from what you already have rather than reading further. When the redundancy marker appears, stop repeating covered ground, not working: a different region of the same file is not a repeat. A rare overrun is acceptable with a one-line \`reason:\` prefix.
44
61
 
45
62
  Ground every claim in a tool result or the context you were given; flag anything unverified explicitly, and quote the relevant excerpt when you cite a failure.
46
63
 
@@ -254,12 +254,13 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
254
254
  "check: testsPass",
255
255
  "check: buildPasses",
256
256
  "check: fileExists path=src/foo.ts",
257
- "check: run command=\"node -e ...\" expect=OK",
257
+ "check: run command=\"node verify.js\" expect=OK",
258
258
  "criteria: <plain-language success condition>",
259
259
  "deliverable: <path or short description>",
260
260
  "[/acceptance]",
261
261
  "",
262
262
  "- check kinds: testsPass | buildPasses | lintClean | fileExists path=\u2026 | schemaMatch path=\u2026 schema=\u2026 | run command=\"\u2026\" expect=\u2026",
263
+ "- Command allowlist (first-token basename): npm, npx, pnpm, yarn, bun, node, tsc, tsx, vitest, jest, eslint, prettier. No shell chaining, redirection, substitution or newlines; interpreter inline-eval/print flags are forbidden. buildPasses probes a build script, then root tsconfig.json (npx tsc --noEmit). Unavailable checks produce acceptance caveats, not producer escalation; strictUnverifiable restores rejection.",
263
264
  "- " + omitLine,
264
265
  "- A failing DoD causes the result to be rejected and retried/escalated, not silently accepted.",
265
266
  ].join("\n");
@@ -399,6 +399,26 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
399
399
  touch(sessionID);
400
400
  },
401
401
 
402
+ /**
403
+ * Mark a session as a child (subagent) session without assigning a tier or
404
+ * cap state. This is the agent-name-INDEPENDENT classifier: opencode reports
405
+ * every child session — a `general`/`explore` dispatch, a markdown-defined
406
+ * agent, an agent repointed through `subagentTiers`, or a plugin-created
407
+ * grader — with a `parentID`, whereas `registerFromChatMessage` only ever
408
+ * recognises a name that is literally an active tier.
409
+ *
410
+ * Deliberately sets NO cap state. Cap/redundancy banners are a tier-scoped
411
+ * feature and `recordToolCall` early-returns without it, so an untiered
412
+ * child keeps byte-identical tool output. The only thing this changes is
413
+ * `isSubagent`, which is what suppresses the orchestrator delegation
414
+ * protocol in the system.transform hook.
415
+ */
416
+ markChildSession(sessionID: string): void {
417
+ if (!sessionID) return;
418
+ subagentSessionIDs.add(sessionID);
419
+ touch(sessionID);
420
+ },
421
+
402
422
  /** Remove a session from tracking (used to clean up delegate producer sessions). */
403
423
  unregister(sessionID: string): void {
404
424
  evict(sessionID);
@@ -444,13 +464,18 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
444
464
  cfg: RouterConfig,
445
465
  tierNames: string[],
446
466
  ): RegisterResult {
447
- if (!input.agent || !tierNames.includes(input.agent)) {
467
+ if (!input.agent) return { registered: false, resumed: false };
468
+ // Tier names map to themselves; pre-existing agents use subagentTiers.
469
+ // resolveSubagentOverrides skips tier-name collisions, keeping these disjoint.
470
+ const tierName = tierNames.includes(input.agent)
471
+ ? input.agent
472
+ : cfg.subagentTiers?.[input.agent];
473
+ if (!tierName || !tierNames.includes(tierName)) {
448
474
  return { registered: false, resumed: false };
449
475
  }
450
476
 
451
477
  subagentSessionIDs.add(input.sessionID);
452
478
 
453
- const tierName = input.agent;
454
479
  const dispatchText = extractDispatchText(output);
455
480
  // CAP:none is honored only when the dispatch carries a justification
456
481
  // (a `reason:` line). An unjustified CAP:none falls back to the tier
@@ -19,6 +19,7 @@ export interface TrajectoryState {
19
19
  sessionID: string;
20
20
  tier: string | null;
21
21
  toolCallCount: number;
22
+ falseRefusalCount: number;
22
23
  readCount: number;
23
24
  execCount: number;
24
25
  selfScriptCount: number;
@@ -48,6 +49,7 @@ export function createTrajectory(
48
49
  sessionID,
49
50
  tier: tier ?? null,
50
51
  toolCallCount: 0,
52
+ falseRefusalCount: 0,
51
53
  readCount: 0,
52
54
  execCount: 0,
53
55
  selfScriptCount: 0,
@@ -188,6 +190,14 @@ export function createTrajectoryStore(options: TrajectoryStoreOptions = {}) {
188
190
  recordToolEvent(s, event);
189
191
  },
190
192
 
193
+ toolCallCount(sessionID: string): number {
194
+ return store.get(sessionID)?.toolCallCount ?? 0;
195
+ },
196
+
197
+ recordFalseRefusal(sessionID: string): void {
198
+ ensureState(sessionID).falseRefusalCount += 1;
199
+ },
200
+
191
201
  /**
192
202
  * Record a resumed dispatch into an existing session. Creates state when
193
203
  * absent so a resume that outlived an idle-TTL sweep still reports a
@@ -0,0 +1,78 @@
1
+ // Runner-independent comparison with opportunistic text/JSON adapters.
2
+ import type { ExecResult } from "./types";
3
+
4
+ export interface TestObservation {
5
+ code: number;
6
+ failures: string[];
7
+ count?: number;
8
+ complete: boolean;
9
+ }
10
+
11
+ export interface TestBaseline {
12
+ observation: TestObservation;
13
+ dirty: boolean;
14
+ }
15
+
16
+ export function observeTests(result: ExecResult): TestObservation {
17
+ const text = (result.stdout + "\n" + result.stderr).replace(/\x1b\[[0-9;]*m/g, "");
18
+ const failures = new Set<string>();
19
+ let count: number | undefined;
20
+ // Counts are only test counts, never file/suite counts. Unknown formats remain
21
+ // useful at the exit-code floor; they must not throw or invent identities.
22
+ for (const line of text.split(/\r?\n/)) {
23
+ const trimmed = line.trim();
24
+ const summary = /^(?:Tests:|Tests\s|=+\s|\d+\s+(?:passing|passed))/.test(trimmed)
25
+ || /^\d+\s+(?:failed|failing)\b/.test(trimmed);
26
+ const n = summary ? /\b(\d+)\s+(?:failed|failing)\b/.exec(trimmed) : null;
27
+ if (n) count = Math.max(count ?? 0, Number(n[1]));
28
+ const id = /^FAILED\s+(\S+)(?:\s+-|$)/.exec(trimmed)?.[1]
29
+ ?? /^FAIL\s+(.+\s+>\s+.+)$/.exec(trimmed)?.[1]
30
+ ?? /^--- FAIL:\s+(.+?)\s+\([\d.]+s\)$/.exec(trimmed)?.[1];
31
+ if (id) failures.add(id);
32
+ }
33
+ // Jest's JSON reporter (also used by compatible runners). Only complete
34
+ // assertion inventories count as identity evidence, not suite-level FAILs.
35
+ try {
36
+ const json: unknown = JSON.parse(result.stdout);
37
+ if (json && typeof json === "object" && "testResults" in json && Array.isArray(json.testResults)) {
38
+ for (const suite of json.testResults) {
39
+ if (!suite || typeof suite !== "object" || !Array.isArray(suite.assertionResults)) continue;
40
+ for (const test of suite.assertionResults) {
41
+ if (test?.status === "failed" && typeof test.fullName === "string") {
42
+ failures.add(`${String(suite.name ?? "")} > ${test.fullName}`);
43
+ }
44
+ }
45
+ }
46
+ if ("numFailedTests" in json && typeof json.numFailedTests === "number") count = json.numFailedTests;
47
+ }
48
+ } catch {
49
+ // Not a JSON reporter; the text observations above still apply.
50
+ }
51
+ return {
52
+ code: result.code, failures: [...failures].sort(), count,
53
+ complete: result.code === 0 || (count !== undefined && count > 0 && count === failures.size),
54
+ };
55
+ }
56
+
57
+ export function compareTests(after: TestObservation, baseline?: TestBaseline): {
58
+ ok: boolean; unverifiable?: boolean; reason?: string; evidence?: string; note?: string;
59
+ } {
60
+ const observed = `observed failures: ${after.failures.join(", ") || "(identities unavailable)"}; count=${after.count ?? "unknown"}; exit=${after.code}`;
61
+ const unavailable = (why: string) => ({ ok: false, unverifiable: true, reason: `testsPass: ${why}; ${observed}` });
62
+ if (!baseline) return unavailable("no usable dispatch-time baseline");
63
+ const before = baseline.observation;
64
+ if (after.code === 0) return { ok: true, evidence: "testsPass: suite is green (exit 0)" };
65
+ const added = after.failures.filter(id => !before.failures.includes(id));
66
+ if (before.code === 0 || (before.complete && added.length > 0) ||
67
+ (before.count !== undefined && after.count !== undefined && after.count > before.count)) {
68
+ const named = before.code === 0 || before.complete ? added : [];
69
+ return { ok: false, reason: `testsPass: introduced failures: ${named.join(", ") || `failure count ${before.count ?? 0} -> ${after.count ?? "unknown"}, exit ${after.code}`}` };
70
+ }
71
+ if (before.complete && after.complete && added.length === 0) {
72
+ const note = `testsPass: no worse than before; pre-existing failures: ${after.failures.join(", ")}; suite is NOT green; baseline tree was ${baseline.dirty ? "dirty" : "clean"}`;
73
+ return { ok: true, evidence: note, note };
74
+ }
75
+ // Equal counts or equal non-zero exits cannot prove that the identities are
76
+ // unchanged. Under-excuse rather than silently replace an old failure by a new one.
77
+ return unavailable(`baseline exit=${before.code}, count=${before.count ?? "unknown"}; cannot prove failures predate dispatch`);
78
+ }
@@ -15,6 +15,7 @@ import { scrubText } from "../guard/scrub";
15
15
  export interface ArtefactView {
16
16
  finalReturnText: string;
17
17
  changedFiles: { path: string; status: string }[];
18
+ changeBaseline?: "available" | "unavailable";
18
19
  declaredOutputs: string[];
19
20
  }
20
21
 
@@ -131,6 +132,9 @@ export function buildGradingPrompt(input: CheckerInput): { system: string; promp
131
132
  lines.push(scrubText(input.artefact.finalReturnText) || "(empty)");
132
133
 
133
134
  lines.push("");
135
+ lines.push(input.artefact.changeBaseline === "available"
136
+ ? "Producer delta only: child editing-tool paths union newly changed paths since dispatch. Files outside this delta predate the dispatch and are not the producer's work. An empty delta is valid for a read-only task; require edits only if an acceptance criterion requires them."
137
+ : "Dispatch-time changed-file snapshot unavailable (or current tree unavailable). Listed files are child editing-tool observations only, NOT an unqualified dirty tree. Do not attribute other dirty files to the producer or infer failure from an empty edit log for a read-only task.");
134
138
  lines.push("### Changed files");
135
139
  if (input.artefact.changedFiles.length > 0) {
136
140
  for (const f of input.artefact.changedFiles) {
@@ -231,6 +235,7 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
231
235
  } catch (err) {
232
236
  return {
233
237
  pass: false,
238
+ outcome: "unverifiable",
234
239
  method: "checker",
235
240
  reasons: [scrubText("grader dispatch failed: " + String(err))],
236
241
  };
@@ -263,6 +268,7 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
263
268
  // 7. Return verdict
264
269
  return {
265
270
  pass: parsed.pass === true,
271
+ outcome: parsed.pass ? "pass" : "fail",
266
272
  method: "checker",
267
273
  reasons: parsed.reasons.map(scrubText),
268
274
  evidence: scrubText("grader=" + graderTier),
@@ -8,6 +8,7 @@ import type { Verdict, DeterministicDeps, MutexRegistry, ExecResult } from "./ty
8
8
  import { scrubText } from "../guard/scrub";
9
9
  import { resolveAgainst } from "./paths";
10
10
  import { isAbsolute } from "node:path";
11
+ import { compareTests, observeTests } from "./baseline";
11
12
 
12
13
  // ---------------------------------------------------------------------------
13
14
  // MutexRegistry — per-key serialization via promise-chaining
@@ -105,6 +106,8 @@ export function shapeMismatch(
105
106
 
106
107
  interface CheckResult {
107
108
  ok: boolean;
109
+ note?: string;
110
+ unverifiable?: boolean;
108
111
  reason?: string;
109
112
  evidence?: string;
110
113
  }
@@ -116,6 +119,7 @@ interface CheckResult {
116
119
  async function runFileExists(check: Check, deps: DeterministicDeps): Promise<CheckResult> {
117
120
  try {
118
121
  if (!check.path) return { ok: false, reason: "fileExists check missing 'path'" };
122
+ if (!deps.cwd && !isAbsolute(check.path)) return { ok: false, unverifiable: true, reason: `fileExists path cannot be resolved without a declared working directory: ${check.path}` };
119
123
  const resolved = resolveAgainst(deps.cwd, check.path);
120
124
  const ok = await deps.fs.fileExists(resolved);
121
125
  if (ok) return { ok: true, evidence: `exists: ${check.path}` };
@@ -138,7 +142,7 @@ async function runRun(
138
142
  try {
139
143
  if (!check.command) return { ok: false, reason: "run check missing 'command'" };
140
144
  if (!isCommandAllowed(check.command, allowlist)) {
141
- return { ok: false, reason: `command not allowlisted: ${check.command}` };
145
+ return { ok: false, unverifiable: true, reason: `command not allowlisted: ${check.command}` };
142
146
  }
143
147
  const r: ExecResult = await deps.exec(check.command, { cwd: deps.cwd, timeoutMs });
144
148
  if (r.timedOut) {
@@ -166,7 +170,7 @@ async function runRun(
166
170
  }
167
171
  }
168
172
 
169
- function resolveRepoCommand(
173
+ export function resolveRepoCommand(
170
174
  check: Check,
171
175
  kind: "testsPass" | "buildPasses" | "lintClean",
172
176
  defaults: DeterministicDeps["defaults"],
@@ -184,17 +188,41 @@ async function runCommandCheck(
184
188
  allowlist: string[],
185
189
  timeoutMs: number,
186
190
  ): Promise<CheckResult> {
187
- const command = resolveRepoCommand(check, kind, deps.defaults);
191
+ let command = resolveRepoCommand(check, kind, deps.defaults);
192
+ if (kind === "buildPasses" && !check.command && !deps.defaults?.buildCommand) {
193
+ try {
194
+ const packagePath = resolveAgainst(deps.cwd, "package.json");
195
+ let hasBuild = false;
196
+ if (await deps.fs.fileExists(packagePath)) {
197
+ const pkg: unknown = JSON.parse(await deps.fs.readFile(packagePath));
198
+ if (pkg && typeof pkg === "object" && "scripts" in pkg) {
199
+ const scripts = pkg.scripts;
200
+ hasBuild = !!(scripts && typeof scripts === "object" && "build" in scripts && typeof scripts.build === "string" && scripts.build.trim());
201
+ }
202
+ }
203
+ if (hasBuild) command = "npm run build";
204
+ else if (await deps.fs.fileExists(resolveAgainst(deps.cwd, "tsconfig.json"))) command = "npx tsc --noEmit";
205
+ else return { ok: false, unverifiable: true, reason: "buildPasses: no build script or root tsconfig.json" };
206
+ } catch (err) {
207
+ return { ok: false, unverifiable: true, reason: `buildPasses probe failed: ${scrubText(String(err))}` };
208
+ }
209
+ }
188
210
 
189
211
  const fn = async (): Promise<CheckResult> => {
190
212
  try {
191
213
  if (!isCommandAllowed(command, allowlist)) {
192
- return { ok: false, reason: `command not allowlisted: ${command}` };
214
+ return { ok: false, unverifiable: true, reason: `command not allowlisted: ${command}` };
193
215
  }
216
+ const baseline = kind === "testsPass" ? await deps.testBaseline?.(command) : undefined;
194
217
  const r: ExecResult = await deps.exec(command, { cwd: deps.cwd, timeoutMs });
195
218
  if (r.timedOut) {
219
+ if (kind === "testsPass") {
220
+ const observed = compareTests(observeTests(r));
221
+ return { ...observed, reason: `${kind} timed out after ${timeoutMs}ms: ${command}; ${observed.reason}` };
222
+ }
196
223
  return { ok: false, reason: `${kind} timed out after ${timeoutMs}ms: ${command}` };
197
224
  }
225
+ if (kind === "testsPass") return compareTests(observeTests(r), baseline);
198
226
  const out = r.stdout + "\n" + r.stderr;
199
227
  const ok = r.code === 0;
200
228
  if (!ok) {
@@ -206,7 +234,7 @@ async function runCommandCheck(
206
234
  }
207
235
  return { ok: true, evidence: `exit 0: ${command}` };
208
236
  } catch (err) {
209
- return { ok: false, reason: `${kind} check errored: ${scrubText(String(err))}` };
237
+ return { ok: false, ...(kind === "testsPass" ? { unverifiable: true } : {}), reason: `${kind} check errored: ${scrubText(String(err))}` };
210
238
  }
211
239
  };
212
240
 
@@ -221,6 +249,9 @@ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<Ch
221
249
  if (!check.path || !check.schema) {
222
250
  return { ok: false, reason: "schemaMatch requires 'path' and 'schema'" };
223
251
  }
252
+ if (!deps.cwd && (!isAbsolute(check.path) || (!check.schema.trim().startsWith("{") && !isAbsolute(check.schema)))) {
253
+ return { ok: false, unverifiable: true, reason: "schemaMatch path cannot be resolved without a declared working directory" };
254
+ }
224
255
 
225
256
  const targetRaw = await deps.fs.readFile(resolveAgainst(deps.cwd, check.path));
226
257
  let targetVal: unknown;
@@ -304,9 +335,15 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
304
335
  }
305
336
 
306
337
  results.push(result);
338
+ if (!result.ok && !result.unverifiable) {
339
+ deps.onFailure?.(scrubText(result.reason ?? "check failed"));
340
+ }
307
341
  }
308
342
 
309
343
  const allPass = results.every(r => r.ok);
344
+ const failed = results.some(r => !r.ok && !r.unverifiable);
345
+ const caveats = results.filter(r => r.unverifiable).map(r => scrubText(r.reason ?? "check unavailable"));
346
+ const notes = results.flatMap(r => r.note ? [scrubText(r.note)] : []);
310
347
 
311
348
  const reasons: string[] = allPass
312
349
  ? [`all ${checks.length} deterministic checks passed`]
@@ -320,6 +357,9 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
320
357
 
321
358
  return {
322
359
  pass: allPass,
360
+ outcome: failed ? "fail" : allPass ? "pass" : "unverifiable",
361
+ ...(caveats.length ? { caveats } : {}),
362
+ ...(notes.length ? { notes } : {}),
323
363
  method: "deterministic",
324
364
  reasons,
325
365
  ...(evidence !== undefined ? { evidence } : {}),