architecture-harness 0.18.0 → 0.18.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -45,6 +45,12 @@ export function decide(call, tmp = os.tmpdir()) {
45
45
  return withSignal(verdict, contextSignal(call, { swarm, count, budget, tmp }), call);
46
46
  }
47
47
 
48
+ /** The one note for an agent whose hook input names no transcript, and the state that keeps later calls quiet. */
49
+ function noTranscriptNote(file, state) {
50
+ writeState(file, { ...state, noTranscript: true });
51
+ return { note: "Context signal is off for this agent: the hook input names no transcript for it." };
52
+ }
53
+
48
54
  /** What the context signal adds to this call: `{ note }`, `{ stamp }`, or null. It never throws. */
49
55
  function contextSignal(call, { swarm, count, budget, tmp }) {
50
56
  let settings;
@@ -58,9 +64,9 @@ function contextSignal(call, { swarm, count, budget, tmp }) {
58
64
  if (!handback && count % settings.every !== 0) return null;
59
65
  try {
60
66
  const transcript = agentTranscriptOf(call);
61
- if (!transcript) return null;
62
67
  const file = stateFileOf(call.session_id ?? "session", call.agent_id, tmp);
63
68
  const state = readState(file);
69
+ if (!transcript) return handback || state.noTranscript ? null : noTranscriptNote(file, state);
64
70
  const first = state.first > 0 ? state.first : contextOf(firstUsage(transcript));
65
71
  if (!(first > 0)) return null;
66
72
  const estimate = "estimate" in state ? state.estimate : estimateOf(firstPromptOf(transcript));
@@ -151,11 +151,10 @@ test("a hand-back of a large agent gains a CONTEXT line through updatedInput", (
151
151
  assert.match(output.hookSpecificOutput.updatedInput.message, /^VERDICT: APPROVED abc1234\n\nCONTEXT: this agent ended at about 60K tokens per call/);
152
152
  });
153
153
 
154
- test("a small hand-back, a missing transcript, and `context: false` change nothing", (t) => {
154
+ test("a small hand-back and `context: false` change nothing", (t) => {
155
155
  const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
156
156
  const small = transcripts(ws, "a1", [10_000, 12_000]);
157
157
  assert.equal(runGuard(ws, signalCall(ws, small, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" })), null);
158
- assert.equal(runGuard(ws, signalCall(ws, path.join(ws.tmp, "none", "x.jsonl"))), null);
159
158
  const off = workspace(t, { toolCallBudget: 100, context: false });
160
159
  assert.equal(runGuard(off, signalCall(off, transcripts(off, "a1", [10_000, 60_000]))), null);
161
160
  });
@@ -199,3 +198,39 @@ test("a hand-back stamp replaces the budget reminder on the same call, because t
199
198
  assert.equal(noteOf(output), null);
200
199
  assert.doesNotMatch(JSON.stringify(output), /Tool-call budget/);
201
200
  });
201
+
202
+ const NO_TRANSCRIPT = /^Context signal is off for this agent: the hook input names no transcript for it\.$/;
203
+ const stateOf = (ws, agentId) => JSON.parse(readFileSync(path.join(ws.tmp, "architecture-kit", "context", `session-aaaa-${agentId}.json`), "utf8"));
204
+
205
+ test("a subagent call with no transcript gets the note once, and the next signal call gets none", (t) => {
206
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
207
+ const lost = signalCall(ws, path.join(ws.tmp, "none", "x.jsonl"));
208
+ assert.match(noteOf(runGuard(ws, lost)) ?? "", NO_TRANSCRIPT);
209
+ assert.equal(runGuard(ws, lost), null);
210
+ assert.equal(runGuard(ws, lost), null);
211
+ assert.equal(stateOf(ws, "a1").noTranscript, true, "the state file records that the note fired");
212
+ });
213
+
214
+ test("an agent_transcript_path to a missing file falls back to the subagents path, then to the note", (t) => {
215
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
216
+ const missing = path.join(ws.tmp, "none", "agent-a1.jsonl");
217
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
218
+ const found = { ...signalCall(ws, main), agent_transcript_path: missing };
219
+ assert.match(noteOf(runGuard(ws, found)) ?? "", /re-sends about 60K tokens/, "the subagents path is read");
220
+ const none = path.join(ws.tmp, "none", "x.jsonl");
221
+ assert.match(noteOf(runGuard(ws, { ...signalCall(ws, none), agent_transcript_path: missing })) ?? "", NO_TRANSCRIPT);
222
+ });
223
+
224
+ test("a hand-back with no transcript gets no stamp and no note, and leaves the note for a later signal call", (t) => {
225
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
226
+ const none = path.join(ws.tmp, "none", "x.jsonl");
227
+ assert.equal(runGuard(ws, signalCall(ws, none, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" })), null);
228
+ assert.match(noteOf(runGuard(ws, signalCall(ws, none))) ?? "", NO_TRANSCRIPT);
229
+ });
230
+
231
+ test("a main-session call with no transcript gets no note", (t) => {
232
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
233
+ const { agent_id: _id, agent_type: _type, ...main } = signalCall(ws, path.join(ws.tmp, "none", "x.jsonl"));
234
+ assert.equal(runGuard(ws, main), null);
235
+ assert.equal(runGuard(ws, main), null);
236
+ });
@@ -10,6 +10,7 @@ import { checkHandoffFile, handoffPathOf } from "./handoff-note.mjs";
10
10
  import { appendRecord, readLedger } from "./ledger.mjs";
11
11
  import { dropReport, keepReport, reportOf } from "./report-stash.mjs";
12
12
  import { commitLookup, firstUserText, resolveNamedWorktree, workflowOfRepo } from "./workflow-place.mjs";
13
+ import { agentTranscriptOf } from "./transcript-usage.mjs";
13
14
  import { workflowOf } from "./workflow-settings.mjs";
14
15
 
15
16
  const HANDBACK = "SubagentHandback";
@@ -69,8 +70,8 @@ const refusal = (role, problems) =>
69
70
  "Add it and send the report again.";
70
71
 
71
72
  /** A block already held this stop once, so it ends now, records nothing, and says what is still missing. */
72
- const held = (role, problems) => ({
73
- systemMessage: `${refusal(role, problems)} A block already held this stop once, so it ends now and the ledger records nothing.`,
73
+ const held = (role, problems, lost = null) => ({
74
+ systemMessage: `${refusal(role, problems)} A block already held this stop once, so it ends now and the ledger records nothing.${lost ? ` ${lost}` : ""}`,
74
75
  });
75
76
 
76
77
  const MAX_BRANCH_PROBES = 10;
@@ -122,7 +123,7 @@ function implementerPlace(records, worktree) {
122
123
  * @returns `{ workflow, named }`, `{ off }` for a repository with no workflow, or null; throws on a wrong config
123
124
  */
124
125
  function locate(call, tmp) {
125
- const text = firstUserText(call.agent_transcript_path);
126
+ const text = firstUserText(agentTranscriptOf(call));
126
127
  const place = text === null ? null : resolveNamedWorktree(text, call.cwd ?? process.cwd());
127
128
  const root = place?.found ? checkoutRootOf(place.abs) : null;
128
129
  if (root) {
@@ -139,6 +140,10 @@ function locate(call, tmp) {
139
140
  return workflow ? { workflow, named: null } : null;
140
141
  }
141
142
 
143
+ /** The line for a report the hook judges with no transcript to place the agent, so it cannot name the agent's worktree. */
144
+ const noTranscriptLine = (root) =>
145
+ `Workflow report: the hook input names no transcript for this agent, so the checks judge against the repository of the cwd or the session, ${root}.`;
146
+
142
147
  /** The note for an agent whose work is in a repository with no workflow, or null when the cwd's workflow does not track its type. */
143
148
  function offNote(call, root, event, tmp) {
144
149
  let own = null;
@@ -228,6 +233,10 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
228
233
  const handoff = spelled === null ? null : { spelled, ...checkHandoffFile(spelled, call.cwd ?? process.cwd()) };
229
234
  const lookup = verdict ? commit(worktree ?? workflow.root, verdict.sha) : null;
230
235
  const notes = [];
236
+ // A prior stop already placed a resumed agent, so only an agent with no worktree at all lacks a place.
237
+ const lost = worktree === null && agentTranscriptOf(call) === null ? noTranscriptLine(workflow.root) : null;
238
+ const withLost = (text) => (lost ? `${text} ${lost}` : text);
239
+ if (lost) notes.push(lost);
231
240
  if (lookup?.error) {
232
241
  notes.push(`Workflow report: git could not read ${verdict.sha} (${lookup.error}), so the verdict is not checked and is recorded as written.`);
233
242
  } else if (lookup?.unknown && !worktree) {
@@ -240,8 +249,9 @@ export function decide(call, tmp = os.tmpdir(), deps = {}) {
240
249
  }
241
250
  const problems = reportProblems(role, text, verdict, lookup, worktree !== null, handoff);
242
251
  if (problems.length > 0) {
243
- if (event === "PreToolUse") return deny(refusal(role, problems));
244
- return call.stop_hook_active === true ? held(role, problems) : block(refusal(role, problems));
252
+ if (event === "PreToolUse") return deny(withLost(refusal(role, problems)));
253
+ if (call.stop_hook_active !== true) return block(withLost(refusal(role, problems)));
254
+ return held(role, problems, lost);
245
255
  }
246
256
  if (event === "PreToolUse") return notes.length > 0 ? preContext(notes.join(" ")) : null;
247
257
  return recordStop({ workflow, call, session, agentId, role, worktree, verdict, lookup, text, tmp, records, notes, handoff });
@@ -37,7 +37,17 @@ function workspace(t) {
37
37
  return { on, plain, outside, tmp, head: git(on, "rev-parse", "HEAD"), ledger: path.join(on, ".git", "qc", "ledger.jsonl") };
38
38
  }
39
39
 
40
+ // A hook input as Claude Code sends it for a subagent: its own transcript path, whose file may name nothing.
41
+ const unread = (cwd) => {
42
+ const file = path.join(cwd, "unread.jsonl");
43
+ if (!existsSync(file)) writeFileSync(file, "");
44
+ return file;
45
+ };
46
+ /** The same call with no transcript path, the input the hook must say it cannot place. */
47
+ const bare = ({ agent_transcript_path: _, ...call }) => call;
48
+
40
49
  const handback = (cwd, agentType, message, event = "PreToolUse") => ({
50
+ agent_transcript_path: unread(cwd),
41
51
  session_id: "s",
42
52
  cwd,
43
53
  hook_event_name: event,
@@ -47,6 +57,7 @@ const handback = (cwd, agentType, message, event = "PreToolUse") => ({
47
57
  agent_type: agentType,
48
58
  });
49
59
  const stop = (cwd, agentType, last, extra = {}) => ({
60
+ agent_transcript_path: unread(cwd),
50
61
  session_id: "s",
51
62
  cwd,
52
63
  hook_event_name: "SubagentStop",
@@ -306,7 +317,7 @@ test("a resumed implementer keeps its worktree after another dispatch, and needs
306
317
  decide(stop(ws.on, IMPLEMENTER, REPORT, { agent_id: "agent-A", ...namesWorktree(ws, "ta", a.dir) }), ws.tmp);
307
318
  taskWorktree(ws, "wt-b", "feat/b-1");
308
319
  const fixed = commitMore(a.dir, "fix.txt");
309
- assert.equal(decide(stop(ws.on, IMPLEMENTER, REPORT, { agent_id: "agent-A" }), ws.tmp), null);
320
+ assert.equal(decide(bare(stop(ws.on, IMPLEMENTER, REPORT, { agent_id: "agent-A" })), ws.tmp), null);
310
321
  const second = stopsOf(ws).at(-1);
311
322
  assert.deepEqual([second.worktree, second.branch, second.head], [a.dir, "feat/a-1", fixed]);
312
323
  });
@@ -469,3 +480,64 @@ test("the implementer definition names the HANDOFF line and the resume from a no
469
480
  assert.match(body, /`HANDOFF: <note path>`/);
470
481
  assert.match(body, /git log --oneline <Head>\.\.HEAD/);
471
482
  });
483
+
484
+ /** The main transcript of a session and the subagent transcript Claude Code keeps beside it, which names `worktree`. */
485
+ function sessionTranscripts(ws, agentId, worktree) {
486
+ const dir = path.join(ws.tmp, "projects", "p");
487
+ const main = path.join(dir, "sess.jsonl");
488
+ mkdirSync(path.join(dir, "sess", "subagents"), { recursive: true });
489
+ writeFileSync(main, "");
490
+ const prompt = { type: "user", message: { role: "user", content: `Read the brief.\nWorktree: ${worktree}\nGo.` } };
491
+ writeFileSync(path.join(dir, "sess", "subagents", `agent-${agentId}.jsonl`), `${JSON.stringify(prompt)}\n`);
492
+ return main;
493
+ }
494
+
495
+ test("a hand-back with no agent_transcript_path finds its worktree in the subagent transcript beside the main one", (t) => {
496
+ const ws = workspace(t);
497
+ const message = "VERDICT: APPROVED deadbee\nRED-CHECKED: x";
498
+ const input = { ...bare(handback(ws.on, REVIEWER, message)), transcript_path: sessionTranscripts(ws, "agent-1", ws.on) };
499
+ assert.match(denied(decide(input, ws.tmp)) ?? "", /deadbee names no commit/);
500
+ assert.doesNotMatch(denied(decide(input, ws.tmp)) ?? "", /names no transcript/);
501
+ });
502
+
503
+ const LOST = /the hook input names no transcript for this agent, so the checks judge against the repository of the cwd or the session/;
504
+
505
+ test("an agent_transcript_path to a missing file falls back to the subagent transcript, and says so when that is missing too", (t) => {
506
+ const ws = workspace(t);
507
+ const message = "VERDICT: APPROVED deadbee\nRED-CHECKED: x";
508
+ const missing = { agent_transcript_path: path.join(ws.tmp, "gone", "agent-1.jsonl") };
509
+ const found = { ...handback(ws.on, REVIEWER, message), ...missing, transcript_path: sessionTranscripts(ws, "agent-1", ws.on) };
510
+ assert.match(denied(decide(found, ws.tmp)) ?? "", /deadbee names no commit/);
511
+ assert.doesNotMatch(denied(decide(found, ws.tmp)) ?? "", LOST);
512
+ const lost = decide({ ...handback(ws.on, REVIEWER, "Looks fine."), ...missing }, ws.tmp);
513
+ assert.match(denied(lost) ?? "", LOST, "the file named is missing, and no other transcript exists");
514
+ });
515
+
516
+ test("with no transcript that finds the agent, a hand-back or a stop says what it was judged against, and keeps its decision", (t) => {
517
+ const ws = workspace(t);
518
+ const refused = decide(bare(handback(ws.on, REVIEWER, "Looks fine.")), ws.tmp);
519
+ assert.match(denied(refused) ?? "", /VERDICT: APPROVED <sha>/, "a deny stays a deny");
520
+ assert.match(denied(refused) ?? "", LOST);
521
+ assert.ok((denied(refused) ?? "").includes(ws.on), "the line names the repository it judged against");
522
+ const message = `VERDICT: APPROVED ${ws.head.slice(0, 8)}\nRED-CHECKED: the test failed before the fix`;
523
+ const allowed = decide(bare(handback(ws.on, REVIEWER, message)), ws.tmp);
524
+ assert.equal(allowed.hookSpecificOutput.permissionDecision, undefined, "an allow stays an allow");
525
+ assert.match(allowed.hookSpecificOutput.additionalContext, LOST);
526
+ const blocked = decide(bare(stop(ws.on, REVIEWER, "All good.")), ws.tmp);
527
+ assert.equal(blocked.decision, "block");
528
+ assert.match(blocked.reason, LOST);
529
+ const held = decide(bare(stop(ws.on, REVIEWER, "All good.", { stop_hook_active: true })), ws.tmp);
530
+ assert.equal(held.decision, undefined);
531
+ assert.match(held.systemMessage, LOST);
532
+ decide(bare(handback(ws.on, REVIEWER, message, "PostToolUse")), ws.tmp);
533
+ const passed = decide(bare(stop(ws.on, REVIEWER, "Sent.")), ws.tmp);
534
+ assert.equal(passed.decision, undefined);
535
+ assert.match(passed.systemMessage, LOST);
536
+ assert.deepEqual(readLedger(ws.ledger).map((record) => record.type), ["stop", "verdict"], "the note leaves the record alone");
537
+ });
538
+
539
+ test("the no-transcript line is left off for an agent type the workflow does not track", (t) => {
540
+ const ws = workspace(t);
541
+ assert.equal(decide(bare(stop(ws.on, "Explore", "done")), ws.tmp), null);
542
+ assert.equal(decide(bare(handback(ws.on, "Explore", "done")), ws.tmp), null);
543
+ });
@@ -44,13 +44,25 @@ function workspace(t, installed) {
44
44
  stubHarness(cli, "installed", log, installed.codes, installed.withDoctor, installed.outputs);
45
45
  }
46
46
  const ran = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []);
47
- const run = (input = {}) =>
47
+ // Each workspace owns its temp folder, so the gate's memory of a block is shared with no other test.
48
+ const tmp = path.join(base, "tmp");
49
+ mkdirSync(tmp, { recursive: true });
50
+ const run = (input = {}, env = {}) =>
48
51
  spawnSync("bash", [HOOK], {
49
52
  input: JSON.stringify({ hook_event_name: "Stop", ...input }),
50
- env: { ...process.env, CLAUDE_PROJECT_DIR: repo, CLAUDE_PLUGIN_ROOT: pluginRoot, QC_STOP_EXTRA: "" },
53
+ env: {
54
+ ...process.env,
55
+ CLAUDE_PROJECT_DIR: repo,
56
+ CLAUDE_PLUGIN_ROOT: pluginRoot,
57
+ QC_STOP_EXTRA: "",
58
+ TMPDIR: tmp,
59
+ TEMP: tmp,
60
+ TMP: tmp,
61
+ ...env,
62
+ },
51
63
  encoding: "utf8",
52
64
  });
53
- return { ran, run };
65
+ return { ran, run, tmpDir: tmp, installedCli: installed ? path.join(repo, "node_modules", "architecture-harness", "src", "cli") : null };
54
66
  }
55
67
 
56
68
  test("an installed harness newer than the bundled one judges the repository, and the stop passes", (t) => {
@@ -111,3 +123,155 @@ test("hook drift beside a real gate failure still refuses a stop after a refused
111
123
  assert.equal(result.status, 2);
112
124
  assert.match(result.stderr, /citations: ADR-0099/);
113
125
  });
126
+
127
+ test("a failure text with backslashes reaches stderr byte for byte", (t) => {
128
+ const text = String.raw`FAIL C:\Users\x\AppData\Local\Temp\tmp.x\new a \t b \U c \n d`;
129
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: text } });
130
+ const result = ws.run();
131
+ assert.equal(result.status, 2);
132
+ assert.ok(result.stderr.includes(text), result.stderr);
133
+ assert.doesNotMatch(result.stderr, /printf/);
134
+ });
135
+
136
+ const SESSION_FAIL = "FAIL orders citations: ADR-0099 is cited but not defined";
137
+
138
+ test("a repeat stop with the same failure ends with a system message that names it", (t) => {
139
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
140
+ const first = ws.run({ session_id: "session-same" });
141
+ assert.equal(first.status, 2);
142
+ const repeat = ws.run({ session_id: "session-same", stop_hook_active: true });
143
+ assert.equal(repeat.status, 0, repeat.stderr);
144
+ const message = JSON.parse(repeat.stdout).systemMessage;
145
+ assert.match(message, /still fails/);
146
+ assert.ok(message.includes("ADR-0099 is cited but not defined"), message);
147
+ });
148
+
149
+ test("a repeat stop with a changed failure blocks again", (t) => {
150
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
151
+ assert.equal(ws.run({ session_id: "session-changed" }).status, 2);
152
+ writeFileSync(
153
+ path.join(ws.installedCli, "qc.mjs"),
154
+ `console.error(${JSON.stringify(SESSION_FAIL.replace("0099", "0100"))}); process.exit(1);`,
155
+ );
156
+ const repeat = ws.run({ session_id: "session-changed", stop_hook_active: true });
157
+ assert.equal(repeat.status, 2);
158
+ assert.match(repeat.stderr, /ADR-0100/);
159
+ const third = ws.run({ session_id: "session-changed", stop_hook_active: true });
160
+ assert.equal(third.status, 0, third.stderr);
161
+ });
162
+
163
+ test("a repeat stop with no session id blocks", (t) => {
164
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
165
+ assert.equal(ws.run().status, 2);
166
+ assert.equal(ws.run({ stop_hook_active: true }).status, 2);
167
+ });
168
+
169
+ test("a first stop with stop_hook_active set and no earlier block still blocks", (t) => {
170
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
171
+ assert.equal(ws.run({ session_id: "session-fresh", stop_hook_active: true }).status, 2);
172
+ });
173
+
174
+ test("a green gate forgets the last block, so the same failure later blocks again", (t) => {
175
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
176
+ assert.equal(ws.run({ session_id: "session-green" }).status, 2);
177
+ const qc = readFileSync(path.join(ws.installedCli, "qc.mjs"), "utf8");
178
+ writeFileSync(path.join(ws.installedCli, "qc.mjs"), "process.exit(0);");
179
+ assert.equal(ws.run({ session_id: "session-green" }).status, 0);
180
+ writeFileSync(path.join(ws.installedCli, "qc.mjs"), qc);
181
+ assert.equal(ws.run({ session_id: "session-green", stop_hook_active: true }).status, 2);
182
+ });
183
+
184
+ test("a session id with path characters cannot write outside the memory folder", (t) => {
185
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
186
+ assert.equal(ws.run({ session_id: "../../escape" }).status, 2);
187
+ assert.equal(existsSync(path.join(ws.tmpDir, "..", "escape.last")), false);
188
+ });
189
+
190
+ test("the same failure at a stop that follows no refusal blocks, because only a repeat block ends", (t) => {
191
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
192
+ assert.equal(ws.run({ session_id: "session-plain" }).status, 2);
193
+ assert.equal(ws.run({ session_id: "session-plain" }).status, 2);
194
+ });
195
+
196
+ test("a repeat stop names the first line of a failure that has no FAIL line", (t) => {
197
+ const text = ["error TS2322: Type 'string' is not assignable to type 'number'.", "src/a.ts(1,1): more"].join("\n");
198
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: text } });
199
+ assert.equal(ws.run({ session_id: "session-bare" }).status, 2);
200
+ const repeat = ws.run({ session_id: "session-bare", stop_hook_active: true });
201
+ assert.equal(repeat.status, 0, repeat.stderr);
202
+ const message = JSON.parse(repeat.stdout).systemMessage;
203
+ assert.ok(message.includes("error TS2322"), message);
204
+ assert.ok(!message.includes("structure failed:"), message);
205
+ });
206
+
207
+ test("a repeat stop names the FAIL line when other output comes before it", (t) => {
208
+ const text = ["OK orders structure", SESSION_FAIL].join("\n");
209
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: text } });
210
+ assert.equal(ws.run({ session_id: "session-later" }).status, 2);
211
+ const repeat = ws.run({ session_id: "session-later", stop_hook_active: true });
212
+ assert.equal(repeat.status, 0, repeat.stderr);
213
+ const message = JSON.parse(repeat.stdout).systemMessage;
214
+ assert.ok(message.includes("ADR-0099 is cited but not defined"), message);
215
+ assert.ok(!message.includes("OK orders"), message);
216
+ });
217
+
218
+ /** A stop gate whose only failing step is `QC_STOP_EXTRA`, which prints the file the test rewrites and fails. */
219
+ function extraWorkspace(t) {
220
+ const ws = workspace(t, { codes: {}, withDoctor: false });
221
+ const file = path.join(ws.tmpDir, "extra.txt");
222
+ const env = { QC_STOP_EXTRA: 'cat "$QC_TEST_EXTRA_FILE"; false', QC_TEST_EXTRA_FILE: file };
223
+ return { run: (input) => ws.run(input, env), set: (lines) => writeFileSync(file, lines.map((line) => `${line}\n`).join("")) };
224
+ }
225
+
226
+ test("a repeat stop blocks when only an early error line beyond the last 20 changed", (t) => {
227
+ const gate = extraWorkspace(t);
228
+ const tail = Array.from({ length: 24 }, (_, i) => `error TS2322: line ${i + 2}`);
229
+ gate.set(["error TS0001: first A", ...tail]);
230
+ assert.equal(gate.run({ session_id: "session-long" }).status, 2);
231
+ gate.set(["error TS0001: first B", ...tail]);
232
+ const repeat = gate.run({ session_id: "session-long", stop_hook_active: true });
233
+ assert.equal(repeat.status, 2, repeat.stdout);
234
+ assert.equal(gate.run({ session_id: "session-long", stop_hook_active: true }).status, 0, "the same text again ends the turn");
235
+ });
236
+
237
+ test("a repeat stop whose only change is a clock time and a duration ends the turn", (t) => {
238
+ const gate = extraWorkspace(t);
239
+ gate.set(["Start at 10:22:11", "FAIL orders citations: ADR-0099 is cited but not defined", "Duration 12.34s (transform 3ms)", " ✓ src/a.test.ts (3 tests) 12ms", "ℹ duration_ms 812.5"]);
240
+ assert.equal(gate.run({ session_id: "session-clock" }).status, 2);
241
+ gate.set(["Start at 10:23:45.678", "FAIL orders citations: ADR-0099 is cited but not defined", "Duration 9ms (transform 41ms)", " ✓ src/a.test.ts (3 tests) 9ms", "ℹ duration_ms 79.1"]);
242
+ const repeat = gate.run({ session_id: "session-clock", stop_hook_active: true });
243
+ assert.equal(repeat.status, 0, repeat.stderr);
244
+ assert.match(JSON.parse(repeat.stdout).systemMessage, /still fails/);
245
+ });
246
+
247
+ test("a repeat stop that changes a number beside a clock time and a duration still blocks", (t) => {
248
+ const gate = extraWorkspace(t);
249
+ gate.set(["Start at 10:22:11", "FAIL ADR-0099 is cited but not defined", "Duration 12.34s"]);
250
+ assert.equal(gate.run({ session_id: "session-digit" }).status, 2);
251
+ gate.set(["Start at 10:23:45", "FAIL ADR-0100 is cited but not defined", "Duration 1.5s"]);
252
+ assert.equal(gate.run({ session_id: "session-digit", stop_hook_active: true }).status, 2);
253
+ });
254
+
255
+ test("a repeat stop whose only change is a duration inside an assertion message still blocks", (t) => {
256
+ const gate = extraWorkspace(t);
257
+ gate.set([" ✓ src/a.test.ts (3 tests) 12ms", "AssertionError: expected 200ms, received 400ms"]);
258
+ assert.equal(gate.run({ session_id: "session-assert-ms" }).status, 2);
259
+ gate.set([" ✓ src/a.test.ts (3 tests) 9ms", "AssertionError: expected 200ms, received 100ms"]);
260
+ assert.equal(gate.run({ session_id: "session-assert-ms", stop_hook_active: true }).status, 2);
261
+ });
262
+
263
+ test("a repeat stop whose only change is a clock value inside an assertion message still blocks", (t) => {
264
+ const gate = extraWorkspace(t);
265
+ gate.set(["Start at 10:22:11", "AssertionError: expected 10:00:00, received 10:22:12"]);
266
+ assert.equal(gate.run({ session_id: "session-assert-clock" }).status, 2);
267
+ gate.set(["Start at 10:23:45", "AssertionError: expected 10:00:00, received 10:22:13"]);
268
+ assert.equal(gate.run({ session_id: "session-assert-clock", stop_hook_active: true }).status, 2);
269
+ });
270
+
271
+ test("the memory file holds a hash of the failure text, not the text", (t) => {
272
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: SESSION_FAIL } });
273
+ assert.equal(ws.run({ session_id: "session-hash" }).status, 2);
274
+ const stored = readFileSync(path.join(ws.tmpDir, "qc-stop-gate", "session-hash.last"), "utf8");
275
+ assert.match(stored.trim(), /^[0-9a-f]{64}$/);
276
+ assert.ok(!stored.includes("ADR-0099"));
277
+ });
@@ -1,7 +1,7 @@
1
1
  // `qc tokens`: what one session read and wrote, per agent type, from its transcripts. It also prices the
2
2
  // same requests at the one-hour cache lifetime, at API list prices, to show which lifetime fits.
3
3
 
4
- import { readdirSync, statSync } from "node:fs";
4
+ import { readdirSync, realpathSync, statSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { agentTypeOf, contextOf, readRequests } from "./transcript-usage.mjs";
@@ -139,8 +139,27 @@ export function summarizeSession({ main = [], agents = [] }, rates = RATES) {
139
139
 
140
140
  const UNKNOWN = "unknown";
141
141
 
142
- /** The folder name Claude Code gives a project: its path, with each character outside letters and digits a dash. */
143
- export const projectKeyOf = (dir) => path.resolve(dir).replace(/[^A-Za-z0-9]/g, "-");
142
+ /**
143
+ * A path in the form Claude Code keys it by: links followed, an 8.3 short name made long. A path
144
+ * that does not exist keeps its own tail, after its nearest existing ancestor is resolved.
145
+ */
146
+ function realPathOf(dir) {
147
+ const resolved = path.resolve(dir);
148
+ let ancestor = resolved;
149
+ for (;;) {
150
+ try {
151
+ const real = realpathSync.native(ancestor);
152
+ return ancestor === resolved ? real : path.join(real, path.relative(ancestor, resolved));
153
+ } catch {
154
+ const parent = path.dirname(ancestor);
155
+ if (parent === ancestor) return resolved;
156
+ ancestor = parent;
157
+ }
158
+ }
159
+ }
160
+
161
+ /** The folder name Claude Code gives a project: its real path, with each character outside letters and digits a dash. */
162
+ export const projectKeyOf = (dir) => realPathOf(dir).replace(/[^A-Za-z0-9]/g, "-");
144
163
 
145
164
  export const claudeDirOf = (env = process.env) => env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
146
165
 
@@ -1,5 +1,5 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { test } from "node:test";
@@ -204,6 +204,42 @@ test("the project key keeps a digit", () => {
204
204
  assert.match(projectKeyOf(path.join(os.tmpdir(), "repo2")), /repo2$/);
205
205
  });
206
206
 
207
+ test("the project key of a link to a folder is the key of the folder", (t) => {
208
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-tokens-link-")));
209
+ t.after(() => rmSync(base, { recursive: true, force: true }));
210
+ const target = path.join(base, "target");
211
+ mkdirSync(target);
212
+ const link = path.join(base, "link");
213
+ symlinkSync(target, link, "junction");
214
+ assert.equal(projectKeyOf(link), projectKeyOf(target));
215
+ });
216
+
217
+ test("the project key of a short 8.3 path is the key of its long path", () => {
218
+ assert.equal(projectKeyOf(os.tmpdir()), projectKeyOf(realpathSync.native(os.tmpdir())));
219
+ });
220
+
221
+ test("the project key of a missing child of a short 8.3 folder is the key of the same child of the long folder", () => {
222
+ const child = "qc-no-such-project";
223
+ assert.equal(projectKeyOf(path.join(os.tmpdir(), child)), projectKeyOf(path.join(realpathSync.native(os.tmpdir()), child)));
224
+ });
225
+
226
+ test("the project key of a missing child of a linked folder is the key of the same child of the target", (t) => {
227
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-tokens-linkmiss-")));
228
+ t.after(() => rmSync(base, { recursive: true, force: true }));
229
+ const target = path.join(base, "target");
230
+ mkdirSync(target);
231
+ const link = path.join(base, "link");
232
+ symlinkSync(target, link, "junction");
233
+ assert.equal(projectKeyOf(path.join(link, "a", "b")), projectKeyOf(path.join(target, "a", "b")));
234
+ });
235
+
236
+ test("the project key of a path that does not exist is built from the path as given", (t) => {
237
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-tokens-none-")));
238
+ t.after(() => rmSync(base, { recursive: true, force: true }));
239
+ const missing = path.join(base, "not-there");
240
+ assert.equal(projectKeyOf(missing), path.resolve(missing).replace(/[^A-Za-z0-9]/g, "-"));
241
+ });
242
+
207
243
  test("the Claude folder is the environment's, else the home folder's", () => {
208
244
  assert.equal(claudeDirOf({ CLAUDE_CONFIG_DIR: "/somewhere" }), "/somewhere");
209
245
  assert.equal(claudeDirOf({}), path.join(os.homedir(), ".claude"));
@@ -111,12 +111,12 @@ export function firstPromptOf(file, bytes = WINDOW_BYTES) {
111
111
  export const subagentTranscriptOf = (mainTranscript, agentId) =>
112
112
  path.join(path.dirname(mainTranscript), path.basename(mainTranscript, ".jsonl"), "subagents", `agent-${agentId}.jsonl`);
113
113
 
114
- /** The transcript of the subagent a hook call runs in, or null for the main session or a file not found. */
114
+ /** The transcript of the subagent a hook call runs in, or null for the main session or when no file exists. */
115
115
  export function agentTranscriptOf(call) {
116
116
  const agentId = call?.agent_id;
117
117
  if (typeof agentId !== "string" || agentId === "") return null;
118
118
  const own = call.agent_transcript_path;
119
- if (typeof own === "string" && own !== "") return own;
119
+ if (typeof own === "string" && own !== "" && existsSync(own)) return own;
120
120
  const main = call.transcript_path;
121
121
  if (typeof main !== "string" || main === "") return null;
122
122
  if (path.basename(main) === `agent-${agentId}.jsonl`) return main;
@@ -112,14 +112,23 @@ test("a subagent's transcript is found however the hook input names it", (t) =>
112
112
  write(own, [user("go")]);
113
113
  assert.equal(agentTranscriptOf({ agent_id: "a1", transcript_path: main }), own);
114
114
  assert.equal(agentTranscriptOf({ agent_id: "a1", transcript_path: own }), own);
115
- assert.equal(
116
- agentTranscriptOf({ agent_id: "a1", agent_transcript_path: "/x/agent-a1.jsonl", transcript_path: main }),
117
- "/x/agent-a1.jsonl",
118
- );
115
+ const named = write(path.join(base, "elsewhere", "agent-a1.jsonl"), [user("go")]);
116
+ assert.equal(agentTranscriptOf({ agent_id: "a1", agent_transcript_path: named, transcript_path: main }), named);
119
117
  assert.equal(agentTranscriptOf({ transcript_path: main }), null, "the main session has no agent id");
120
118
  assert.equal(agentTranscriptOf({ agent_id: "a1" }), null);
121
119
  });
122
120
 
121
+ test("an agent_transcript_path to a missing file falls back to the subagents path, and then to null", (t) => {
122
+ const base = folder(t);
123
+ const main = path.join(base, "proj", "sess.jsonl");
124
+ const missing = path.join(base, "proj", "gone", "agent-a1.jsonl");
125
+ write(main, [user("hi")]);
126
+ assert.equal(agentTranscriptOf({ agent_id: "a1", agent_transcript_path: missing, transcript_path: main }), null, "no file anywhere");
127
+ assert.equal(agentTranscriptOf({ agent_id: "a1", agent_transcript_path: missing }), null, "no main transcript either");
128
+ const own = write(subagentTranscriptOf(main, "a1"), [user("go")]);
129
+ assert.equal(agentTranscriptOf({ agent_id: "a1", agent_transcript_path: missing, transcript_path: main }), own);
130
+ });
131
+
123
132
  test("agentTypeOf reads the type from the meta file beside a transcript", (t) => {
124
133
  const base = folder(t);
125
134
  const file = write(path.join(base, "agent-a1.jsonl"), [user("go")]);