architecture-harness 0.17.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.17.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",
@@ -19,11 +19,9 @@ function readCount(file) {
19
19
  }
20
20
  }
21
21
 
22
- /** Adds one to the count and writes it through a rename. @returns the new count; throws on a write error. */
23
- export function bumpCount(file, now = Date.now()) {
24
- const count = readCount(file) + 1;
22
+ /** Writes one small JSON payload through a rename; throws on a write error. */
23
+ function writeJson(file, payload) {
25
24
  const temp = `${file}.${process.pid}.tmp`;
26
- const payload = JSON.stringify({ count, updatedAt: new Date(now).toISOString() });
27
25
  try {
28
26
  writeFileSync(temp, payload);
29
27
  } catch {
@@ -36,5 +34,28 @@ export function bumpCount(file, now = Date.now()) {
36
34
  rmSync(temp, { force: true });
37
35
  throw error;
38
36
  }
37
+ }
38
+
39
+ /** Adds one to the count and writes it through a rename. @returns the new count; throws on a write error. */
40
+ export function bumpCount(file, now = Date.now()) {
41
+ const count = readCount(file) + 1;
42
+ writeJson(file, JSON.stringify({ count, updatedAt: new Date(now).toISOString() }));
39
43
  return count;
40
44
  }
45
+
46
+ /** The file that holds one agent's context-signal state: its first context, its estimate, and the last note. */
47
+ export const stateFileOf = (sessionId, agentId, tmp) =>
48
+ path.join(tmp, "architecture-kit", "context", `${fileSafe(sessionId)}-${fileSafe(agentId)}.json`);
49
+
50
+ /** @returns the state, or {} for a missing or unreadable file. */
51
+ export function readState(file) {
52
+ try {
53
+ const state = JSON.parse(readFileSync(file, "utf8"));
54
+ return state !== null && typeof state === "object" && !Array.isArray(state) ? state : {};
55
+ } catch {
56
+ return {};
57
+ }
58
+ }
59
+
60
+ /** Writes the state through a rename; throws on a write error. */
61
+ export const writeState = (file, state) => writeJson(file, JSON.stringify(state));
@@ -6,10 +6,14 @@ import { existsSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { CONFIG_FILE, load } from "../config.mjs";
9
+ import { CONFIG_FILE, contextDefaults, load } from "../config.mjs";
10
10
  import { budgetOf, budgetVerdict } from "./budget.mjs";
11
- import { bumpCount, counterFileOf } from "./budget-counter.mjs";
11
+ import { bumpCount, counterFileOf, readState, stateFileOf, writeState } from "./budget-counter.mjs";
12
12
  import { checkoutRootOf } from "./checkout-root.mjs";
13
+ import { contextSettings, contextVerdict, estimateOf, handbackStamp } from "./context-signal.mjs";
14
+ import { agentTranscriptOf, contextOf, firstPromptOf, firstUsage, lastUsage } from "./transcript-usage.mjs";
15
+
16
+ const HANDBACK = "SubagentHandback";
13
17
 
14
18
  const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
15
19
 
@@ -20,9 +24,11 @@ export function decide(call, tmp = os.tmpdir()) {
20
24
  const root = checkoutRootOf(call.cwd ?? process.cwd());
21
25
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
22
26
 
27
+ let swarm;
23
28
  let budget;
24
29
  try {
25
- budget = budgetOf(load(root).swarm);
30
+ swarm = load(root).swarm;
31
+ budget = budgetOf(swarm);
26
32
  } catch (error) {
27
33
  // A config typo must not stop every agent; the agent sees the error and reports it.
28
34
  return context(`Tool-call budget is off: ${error.message}`);
@@ -34,7 +40,76 @@ export function decide(call, tmp = os.tmpdir()) {
34
40
  // A busy or read-only temp folder is the hook's own problem, never a reason to stop the agent.
35
41
  return null;
36
42
  }
37
- return budgetVerdict({ count, budget, call });
43
+ const verdict = budgetVerdict({ count, budget, call });
44
+ if (verdict?.hookSpecificOutput?.permissionDecision === "deny") return verdict;
45
+ return withSignal(verdict, contextSignal(call, { swarm, count, budget, tmp }), call);
46
+ }
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
+
54
+ /** What the context signal adds to this call: `{ note }`, `{ stamp }`, or null. It never throws. */
55
+ function contextSignal(call, { swarm, count, budget, tmp }) {
56
+ let settings;
57
+ try {
58
+ settings = contextSettings(swarm);
59
+ } catch (error) {
60
+ return count % contextDefaults.every === 0 ? { note: `Context signal is off: ${error.message}` } : null;
61
+ }
62
+ if (!settings) return null;
63
+ const handback = call.tool_name === HANDBACK;
64
+ if (!handback && count % settings.every !== 0) return null;
65
+ try {
66
+ const transcript = agentTranscriptOf(call);
67
+ const file = stateFileOf(call.session_id ?? "session", call.agent_id, tmp);
68
+ const state = readState(file);
69
+ if (!transcript) return handback || state.noTranscript ? null : noTranscriptNote(file, state);
70
+ const first = state.first > 0 ? state.first : contextOf(firstUsage(transcript));
71
+ if (!(first > 0)) return null;
72
+ const estimate = "estimate" in state ? state.estimate : estimateOf(firstPromptOf(transcript));
73
+ const latest = contextOf(lastUsage(transcript));
74
+ const next = { ...state, first, estimate };
75
+ let signal = null;
76
+ if (handback) {
77
+ const stamp = handbackStamp({ context: latest, first }, settings);
78
+ signal = stamp ? { stamp } : null;
79
+ } else {
80
+ const fired = state.fired ?? null;
81
+ const verdict = contextVerdict({ context: latest, first, count, budget, estimate, agentType: call.agent_type, fired }, settings);
82
+ if (verdict) {
83
+ next.fired = { level: verdict.level, at: count };
84
+ signal = { note: verdict.text };
85
+ }
86
+ }
87
+ if (state.first !== first || state.estimate !== estimate || next.fired !== state.fired) writeState(file, next);
88
+ return signal;
89
+ } catch {
90
+ // An unreadable transcript or a busy temp folder is the hook's own problem, never the agent's.
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /** The budget verdict with the signal added: the note joins its context, and a stamp rewrites the hand-back. */
96
+ function withSignal(verdict, signal, call) {
97
+ if (!signal) return verdict;
98
+ if (signal.stamp) {
99
+ const input = call.tool_input ?? {};
100
+ return {
101
+ hookSpecificOutput: {
102
+ hookEventName: "PreToolUse",
103
+ permissionDecision: "allow",
104
+ updatedInput: { ...input, message: `${String(input.message ?? "")}
105
+
106
+ ${signal.stamp}` },
107
+ },
108
+ };
109
+ }
110
+ const existing = verdict?.hookSpecificOutput?.additionalContext;
111
+ return context(existing ? `${existing}
112
+ ${signal.note}` : signal.note);
38
113
  }
39
114
 
40
115
  async function readStdin() {
@@ -88,3 +88,149 @@ test("the default budget reminds at its seventieth call", (t) => {
88
88
  const output = runGuard(ws, callOf(ws.linked, "agent-1"));
89
89
  assert.match(output.hookSpecificOutput.additionalContext, /call 70 of 100/);
90
90
  });
91
+
92
+ /** One subagent transcript in the layout Claude Code keeps, with one request per context size. @returns the main transcript path */
93
+ function transcripts(ws, agentId, contexts, prompt = "Read the brief.") {
94
+ const project = path.join(ws.tmp, "projects", "p");
95
+ const dir = path.join(project, "sess", "subagents");
96
+ mkdirSync(dir, { recursive: true });
97
+ const main = path.join(project, "sess.jsonl");
98
+ writeFileSync(main, "");
99
+ const lines = [
100
+ { type: "user", message: { role: "user", content: prompt } },
101
+ ...contexts.map((n, index) => ({
102
+ type: "assistant",
103
+ timestamp: new Date(index * 1000).toISOString(),
104
+ message: { id: `m${index}`, model: "claude-sonnet-5-5", role: "assistant", content: [], usage: { input_tokens: 2, cache_read_input_tokens: n - 2, cache_creation_input_tokens: 0 } },
105
+ })),
106
+ ];
107
+ writeFileSync(path.join(dir, `agent-${agentId}.jsonl`), `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`);
108
+ return main;
109
+ }
110
+
111
+ const signalCall = (ws, main, agentType = "architecture:sdd-implementer", tool_name = "Bash", tool_input = { command: "npm test" }) => ({
112
+ ...callOf(ws.linked, "a1", tool_name, tool_input),
113
+ agent_type: agentType,
114
+ transcript_path: main,
115
+ });
116
+ const noteOf = (output) => output?.hookSpecificOutput?.additionalContext ?? null;
117
+
118
+ test("a large implementer context gets the hand-off note once, and never a deny", (t) => {
119
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
120
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
121
+ const first = runGuard(ws, signalCall(ws, main));
122
+ assert.equal(first.hookSpecificOutput.permissionDecision, undefined);
123
+ assert.match(noteOf(first), /re-sends about 60K tokens, 6\.0x its first call \(10K\)/);
124
+ assert.match(noteOf(first), /`HANDOFF: <note path>`/);
125
+ assert.equal(runGuard(ws, signalCall(ws, main)), null, "the same level does not fire twice in a row");
126
+ });
127
+
128
+ test("a reviewer, or a prompt estimate with few calls left, gets only the keep-it-small note", (t) => {
129
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
130
+ const reviewer = runGuard(ws, signalCall(ws, transcripts(ws, "a1", [10_000, 60_000]), "architecture:sdd-reviewer"));
131
+ assert.match(noteOf(reviewer), /line range/);
132
+ assert.doesNotMatch(noteOf(reviewer), /HANDOFF/);
133
+ const ws2 = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
134
+ const estimated = runGuard(ws2, signalCall(ws2, transcripts(ws2, "a1", [10_000, 60_000], "Brief: b.md\nEstimate: 12")));
135
+ assert.doesNotMatch(noteOf(estimated), /HANDOFF/);
136
+ });
137
+
138
+ test("the check runs only every `every` calls", (t) => {
139
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 3 } });
140
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
141
+ assert.equal(runGuard(ws, signalCall(ws, main)), null);
142
+ assert.equal(runGuard(ws, signalCall(ws, main)), null);
143
+ assert.match(noteOf(runGuard(ws, signalCall(ws, main))) ?? "", /Context signal/);
144
+ });
145
+
146
+ test("a hand-back of a large agent gains a CONTEXT line through updatedInput", (t) => {
147
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 50 } });
148
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
149
+ const output = runGuard(ws, signalCall(ws, main, "architecture:sdd-reviewer", "SubagentHandback", { message: "VERDICT: APPROVED abc1234" }));
150
+ assert.equal(output.hookSpecificOutput.permissionDecision, "allow");
151
+ assert.match(output.hookSpecificOutput.updatedInput.message, /^VERDICT: APPROVED abc1234\n\nCONTEXT: this agent ended at about 60K tokens per call/);
152
+ });
153
+
154
+ test("a small hand-back and `context: false` change nothing", (t) => {
155
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
156
+ const small = transcripts(ws, "a1", [10_000, 12_000]);
157
+ assert.equal(runGuard(ws, signalCall(ws, small, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" })), null);
158
+ const off = workspace(t, { toolCallBudget: 100, context: false });
159
+ assert.equal(runGuard(off, signalCall(off, transcripts(off, "a1", [10_000, 60_000]))), null);
160
+ });
161
+
162
+ test("a wrong context key is reported as context at a check, and the budget still counts", (t) => {
163
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 0 } });
164
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
165
+ for (let index = 1; index < 5; index += 1) assert.equal(runGuard(ws, signalCall(ws, main)), null);
166
+ assert.match(noteOf(runGuard(ws, signalCall(ws, main))) ?? "", /Context signal is off: swarm\.context\.every/);
167
+ assert.equal(countOf(ws, "a1"), 5);
168
+ });
169
+
170
+ test("the budget reminder and the context note share one additionalContext", (t) => {
171
+ const ws = workspace(t, { toolCallBudget: 10, context: { every: 7 } });
172
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
173
+ let output = null;
174
+ for (let index = 0; index < 7; index += 1) output = runGuard(ws, signalCall(ws, main));
175
+ assert.match(noteOf(output), /Tool-call budget: this is call 7 of 10/);
176
+ assert.match(noteOf(output), /Context signal/);
177
+ });
178
+
179
+ test("a budget deny stays a deny, and a large context adds no note to it", (t) => {
180
+ const ws = workspace(t, { toolCallBudget: 3, context: { every: 3 } });
181
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
182
+ runGuard(ws, signalCall(ws, main));
183
+ runGuard(ws, signalCall(ws, main));
184
+ const denied = runGuard(ws, signalCall(ws, main));
185
+ assert.equal(denied.hookSpecificOutput.permissionDecision, "deny");
186
+ assert.match(denied.hookSpecificOutput.permissionDecisionReason, /call 3 of 3/);
187
+ assert.equal(noteOf(denied), null);
188
+ assert.doesNotMatch(JSON.stringify(denied), /Context signal/);
189
+ });
190
+
191
+ test("a hand-back stamp replaces the budget reminder on the same call, because the agent is ending", (t) => {
192
+ const ws = workspace(t, { toolCallBudget: 10, context: { every: 50 } });
193
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
194
+ for (let index = 1; index < 7; index += 1) assert.equal(runGuard(ws, signalCall(ws, main)), null);
195
+ const output = runGuard(ws, signalCall(ws, main, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" }));
196
+ assert.equal(countOf(ws, "a1"), 7, "call 7 of 10 is a reminder call");
197
+ assert.match(output.hookSpecificOutput.updatedInput.message, /CONTEXT: this agent ended/);
198
+ assert.equal(noteOf(output), null);
199
+ assert.doesNotMatch(JSON.stringify(output), /Tool-call budget/);
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
+ });
@@ -59,8 +59,9 @@ const deny = (count, budget) => ({
59
59
  `Tool-call budget spent: this is call ${count} of ${budget} (${KEY} in qc.config.json). ` +
60
60
  "Only the hand-off can run now. " +
61
61
  "1. Commit and push green work with git add, git commit and git push. " +
62
- "2. Write the hand-off note to a path under /handoffs/: what is done, what is left in order, and the exact next step. " +
63
- "3. Send the final report, and name the note. " +
62
+ "2. Write the hand-off note in a `handoffs/` folder beside the report file, outside every checkout: lines " +
63
+ "`Brief:`, `Worktree:`, `Branch:`, and `Head:`, and sections `## Done`, `## Left`, and `## Next step`. " +
64
+ "3. Send the final report with a line `HANDOFF: <note path>` in place of the GREEN line. " +
64
65
  "Read and read-only commands still run.",
65
66
  },
66
67
  });
@@ -0,0 +1,92 @@
1
+ // The branch that turns an agent's context size into a note: nothing, keep new output small, or hand off.
2
+ // It reads no file and never refuses a call; the budget guard gives it the numbers and prints the note.
3
+
4
+ import { contextDefaults, merge } from "../config.mjs";
5
+
6
+ const KEY = "swarm.context";
7
+ export const LEVELS = ["none", "summarize", "handoff"];
8
+ const ESTIMATE_LINE = /^[ \t]*(?:\*\*)?Estimate:(?:\*\*)?[ \t]*(\d+)/im;
9
+
10
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11
+ const wrong = (key, value, want) => new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
12
+
13
+ /** @returns the signal settings, or null when the repository turns it off; throws naming the key it got wrong. */
14
+ export function contextSettings(swarm = {}) {
15
+ const raw = swarm.context;
16
+ if (raw === false || raw === null) return null;
17
+ if (raw !== undefined && !isPlainObject(raw)) {
18
+ throw new Error(`${KEY} in qc.config.json must be an object or false, got ${JSON.stringify(raw)}`);
19
+ }
20
+ const settings = merge(contextDefaults, raw ?? {});
21
+ for (const key of ["every", "minCallsLeft", "repeatEvery"]) {
22
+ if (!Number.isInteger(settings[key]) || settings[key] < 1) throw wrong(key, settings[key], "a positive whole number");
23
+ }
24
+ if (typeof settings.summarizeRatio !== "number" || !(settings.summarizeRatio > 1)) {
25
+ throw wrong("summarizeRatio", settings.summarizeRatio, "a number above 1");
26
+ }
27
+ if (typeof settings.handoffRatio !== "number" || !(settings.handoffRatio > settings.summarizeRatio)) {
28
+ throw wrong("handoffRatio", settings.handoffRatio, "a number above summarizeRatio");
29
+ }
30
+ if (!Array.isArray(settings.handoffTypes) || !settings.handoffTypes.every((type) => typeof type === "string" && type !== "")) {
31
+ throw wrong("handoffTypes", settings.handoffTypes, "a list of agent types");
32
+ }
33
+ return settings;
34
+ }
35
+
36
+ /** The number on a prompt's `Estimate:` line, or null. */
37
+ export function estimateOf(prompt) {
38
+ const match = ESTIMATE_LINE.exec(String(prompt ?? ""));
39
+ return match ? Number(match[1]) : null;
40
+ }
41
+
42
+ /** The calls the task still needs: to the estimate while the count is under it, else to the budget. */
43
+ export function callsLeft({ count, budget, estimate = null }) {
44
+ const toBudget = Math.max(budget - count, 0);
45
+ return Number.isInteger(estimate) && estimate > count ? Math.min(estimate - count, toBudget) : toBudget;
46
+ }
47
+
48
+ function levelOf({ ratio, left, agentType }, settings) {
49
+ if (ratio >= settings.handoffRatio && left >= settings.minCallsLeft && settings.handoffTypes.includes(agentType)) return "handoff";
50
+ return ratio >= settings.summarizeRatio ? "summarize" : "none";
51
+ }
52
+
53
+ const thousands = (n) => `${Math.round(n / 1000)}K`;
54
+ const times = (ratio) => `${ratio.toFixed(1)}x`;
55
+
56
+ const summarizeText = ({ context, first, ratio }) =>
57
+ `Context signal: each call of this agent re-sends about ${thousands(context)} tokens, ${times(ratio)} its first call (${thousands(first)}). ` +
58
+ "New output adds to every later call: a line range costs less than a whole file, a summary of a long command output " +
59
+ "less than the output, and a file already in context needs no second read.";
60
+
61
+ const handoffText = ({ context, first, ratio, left }) =>
62
+ `Context signal: each call of this agent re-sends about ${thousands(context)} tokens, ${times(ratio)} its first call (${thousands(first)}), ` +
63
+ `with about ${left} calls of work left. A fresh agent starts near ${thousands(first)}, so the rest of the task costs less there. ` +
64
+ "The hand-off at the next green step: commit and push, write a note in a `handoffs/` folder beside the report file " +
65
+ "(lines `Brief:`, `Worktree:`, `Branch:`, and `Head:`; sections `## Done`, `## Left`, and `## Next step`), " +
66
+ "and send the report with a line `HANDOFF: <note path>`. The controller starts a fresh implementer from the note.";
67
+
68
+ /**
69
+ * The note for one check. `fired` is `{ level, at }` of the last note, or null.
70
+ * @returns `{ level, text }`, or null when there is nothing new to say
71
+ */
72
+ export function contextVerdict({ context, first, count, budget, estimate = null, agentType, fired = null }, settings) {
73
+ if (!(first > 0) || !(context > 0)) return null;
74
+ const ratio = context / first;
75
+ const left = callsLeft({ count, budget, estimate });
76
+ const level = levelOf({ ratio, left, agentType }, settings);
77
+ if (level === "none") return null;
78
+ const firedRank = fired ? Math.max(LEVELS.indexOf(fired.level), 0) : 0;
79
+ const repeat = level === "handoff" && fired?.level === "handoff" && count - fired.at >= settings.repeatEvery;
80
+ if (LEVELS.indexOf(level) <= firedRank && !repeat) return null;
81
+ const facts = { context, first, ratio, left };
82
+ return { level, text: level === "handoff" ? handoffText(facts) : summarizeText(facts) };
83
+ }
84
+
85
+ /** The line a hand-back gains when the agent ends large, so the controller can weigh a resume against a fresh agent. */
86
+ export function handbackStamp({ context, first }, settings) {
87
+ if (!(first > 0) || !(context > 0) || context / first < settings.summarizeRatio) return null;
88
+ return (
89
+ `CONTEXT: this agent ended at about ${thousands(context)} tokens per call, ${times(context / first)} its first call (${thousands(first)}). ` +
90
+ `A resume re-sends that on each call; a fresh agent of this type starts near ${thousands(first)}.`
91
+ );
92
+ }
@@ -0,0 +1,99 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { contextDefaults } from "../config.mjs";
4
+ import { LEVELS, callsLeft, contextSettings, contextVerdict, estimateOf, handbackStamp } from "./context-signal.mjs";
5
+
6
+ const settings = contextSettings();
7
+ const IMPL = "architecture:sdd-implementer";
8
+ const facts = (context, extra = {}) => ({ context, first: 40_000, count: 10, budget: 100, estimate: null, agentType: IMPL, fired: null, ...extra });
9
+
10
+ test("the signal is on with the defaults, and `false` turns it off", () => {
11
+ assert.deepEqual(contextSettings(), contextDefaults);
12
+ assert.deepEqual(contextSettings({ context: {} }), contextDefaults);
13
+ assert.equal(contextSettings({ context: false }), null);
14
+ assert.equal(contextSettings({ context: { every: 1 } }).every, 1);
15
+ assert.deepEqual(contextSettings({ context: { handoffTypes: ["x"] } }).handoffTypes, ["x"]);
16
+ });
17
+
18
+ test("a wrong key is a named config error", () => {
19
+ for (const context of [{ every: 0 }, { minCallsLeft: 1.5 }, { summarizeRatio: 1 }, { handoffRatio: 2 }, { handoffTypes: "x" }, "on"]) {
20
+ assert.throws(() => contextSettings({ context }), /swarm\.context/, JSON.stringify(context));
21
+ }
22
+ });
23
+
24
+ test("the calls left run to the prompt's estimate while the count is under it, else to the budget", () => {
25
+ assert.equal(callsLeft({ count: 10, budget: 100 }), 90);
26
+ assert.equal(callsLeft({ count: 10, budget: 100, estimate: 30 }), 20);
27
+ assert.equal(callsLeft({ count: 40, budget: 100, estimate: 30 }), 60);
28
+ assert.equal(callsLeft({ count: 120, budget: 100 }), 0);
29
+ });
30
+
31
+ test("an estimate line is read with or without bold", () => {
32
+ assert.equal(estimateOf("Brief: x\nEstimate: 25\n"), 25);
33
+ assert.equal(estimateOf("**Estimate:** 30 tool calls"), 30);
34
+ assert.equal(estimateOf("no line"), null);
35
+ assert.equal(estimateOf(null), null);
36
+ });
37
+
38
+ test("under summarizeRatio times the first call there is nothing to say", () => {
39
+ assert.equal(contextVerdict(facts(119_000), settings), null);
40
+ });
41
+
42
+ test("at summarizeRatio times the note says new output adds to every later call", () => {
43
+ const verdict = contextVerdict(facts(120_000), settings);
44
+ assert.equal(verdict.level, "summarize");
45
+ assert.match(verdict.text, /re-sends about 120K tokens, 3\.0x its first call \(40K\)/);
46
+ assert.match(verdict.text, /line range/);
47
+ assert.doesNotMatch(verdict.text, /HANDOFF/);
48
+ });
49
+
50
+ test("at handoffRatio times, with work left, a hand-off type gets the hand-off steps", () => {
51
+ const verdict = contextVerdict(facts(200_000), settings);
52
+ assert.equal(verdict.level, "handoff");
53
+ assert.match(verdict.text, /about 90 calls of work left/);
54
+ assert.match(verdict.text, /`HANDOFF: <note path>`/);
55
+ assert.match(verdict.text, /`handoffs\/`/);
56
+ });
57
+
58
+ test("too few calls left, or another type, keeps the note at summarize", () => {
59
+ assert.equal(contextVerdict(facts(200_000, { count: 90 }), settings).level, "summarize");
60
+ assert.equal(contextVerdict(facts(200_000, { estimate: 20 }), settings).level, "summarize");
61
+ assert.equal(contextVerdict(facts(200_000, { agentType: "architecture:sdd-reviewer" }), settings).level, "summarize");
62
+ });
63
+
64
+ test("each level fires once, and the hand-off repeats every repeatEvery calls", () => {
65
+ assert.equal(contextVerdict(facts(130_000, { fired: { level: "summarize", at: 5 } }), settings), null);
66
+ assert.equal(contextVerdict(facts(200_000, { fired: { level: "summarize", at: 5 } }), settings).level, "handoff");
67
+ assert.equal(contextVerdict(facts(200_000, { count: 20, fired: { level: "handoff", at: 10 } }), settings), null);
68
+ assert.equal(contextVerdict(facts(200_000, { count: 30, fired: { level: "handoff", at: 10 } }), settings).level, "handoff");
69
+ assert.equal(contextVerdict(facts(130_000, { count: 90, fired: { level: "handoff", at: 10 } }), settings), null);
70
+ assert.deepEqual(LEVELS, ["none", "summarize", "handoff"]);
71
+ });
72
+
73
+ test("a missing first or latest context says nothing", () => {
74
+ assert.equal(contextVerdict(facts(200_000, { first: 0 }), settings), null);
75
+ assert.equal(contextVerdict(facts(0), settings), null);
76
+ });
77
+
78
+ test("the hand-back stamp names the end context only at or over summarizeRatio", () => {
79
+ assert.equal(handbackStamp({ context: 100_000, first: 40_000 }, settings), null);
80
+ assert.match(handbackStamp({ context: 200_000, first: 40_000 }, settings), /^CONTEXT: this agent ended at about 200K tokens per call, 5\.0x its first call \(40K\)/);
81
+ assert.equal(handbackStamp({ context: 200_000, first: 0 }, settings), null);
82
+ });
83
+
84
+ test("an estimate far past the budget is capped at the budget", () => {
85
+ assert.equal(callsLeft({ count: 10, budget: 100, estimate: 500 }), 90);
86
+ });
87
+
88
+ test("exactly minCallsLeft calls left still hands off", () => {
89
+ assert.equal(contextVerdict(facts(200_000, { count: 85 }), settings).level, "handoff");
90
+ assert.equal(contextVerdict(facts(200_000, { count: 86 }), settings).level, "summarize");
91
+ });
92
+
93
+ test("the hand-back stamp fires at exactly summarizeRatio", () => {
94
+ assert.match(handbackStamp({ context: 120_000, first: 40_000 }, settings), /^CONTEXT: /);
95
+ });
96
+
97
+ test("a null context is the same as false", () => {
98
+ assert.equal(contextSettings({ context: null }), null);
99
+ });
@@ -5,7 +5,7 @@
5
5
  import { existsSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
- import { dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
8
+ import { dispatchNote, dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
9
9
  import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
10
10
  import { judgeTask, recordDispatch } from "./task-gate.mjs";
11
11
 
@@ -53,19 +53,23 @@ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
53
53
  // The task gate judges before the slot is claimed, so a refused task holds no slot.
54
54
  const task = judgeTask(call, tmp);
55
55
  if (task.refusal) return deny(task.refusal);
56
+ const note = dispatchNote(input, settings);
56
57
  const type = typeOf(input);
57
- if (!isImplementer(type, settings)) return noted(recordDispatch(task));
58
+ if (!isImplementer(type, settings)) return noted(recordDispatch(task), note);
58
59
  let holder;
59
60
  try {
60
61
  holder = claimSlot(dir, settings, now, idOf(call.tool_use_id));
61
62
  } catch {
62
63
  // A busy or read-only temp folder is the hook's own problem, never a reason to refuse a dispatch.
63
- return noted(recordDispatch(task));
64
+ return noted(recordDispatch(task), note);
64
65
  }
65
- return holder ? deny(slotRefusal({ type, ...holder })) : noted(recordDispatch(task));
66
+ return holder ? deny(slotRefusal({ type, ...holder })) : noted(recordDispatch(task), note);
66
67
  }
67
68
 
68
- const noted = (note) => (note ? context(note) : null);
69
+ const noted = (...notes) => {
70
+ const text = notes.filter(Boolean).join(" ");
71
+ return text ? context(text) : null;
72
+ };
69
73
 
70
74
  async function readStdin() {
71
75
  let data = "";
@@ -142,13 +142,12 @@ test("each allowed pair passes, including a full model id and a branch reviewer
142
142
  null,
143
143
  );
144
144
  decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
145
- assert.equal(
146
- decide(
147
- agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
148
- ws.tmp,
149
- ),
150
- null,
145
+ const pinned = decide(
146
+ agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
147
+ ws.tmp,
151
148
  );
149
+ assert.equal(pinned.hookSpecificOutput.permissionDecision, undefined);
150
+ assert.match(pinned.hookSpecificOutput.additionalContext, /share no prompt cache/);
152
151
  });
153
152
 
154
153
  test("a repository's models override replaces one type's families and leaves the rest at default", (t) => {
@@ -77,7 +77,9 @@ export function exploreSettings(swarm = {}) {
77
77
  if (typeof raw !== "object" || Array.isArray(raw)) {
78
78
  throw new Error(`${EXPLORE_KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
79
79
  }
80
- const { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt } = merge(exploreDefaults, raw);
80
+ const { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt, longOutput, excerptChars: set } = merge(exploreDefaults, raw);
81
+ // A repository that sets only maxOutputChars keeps its explore hooks: the excerpt default follows it.
82
+ const excerptChars = raw.excerptChars === undefined && Number.isInteger(maxOutputChars) ? Math.min(exploreDefaults.excerptChars, Math.floor(maxOutputChars / 2)) : set;
81
83
  if (!Array.isArray(tools) || !tools.every(isToolEntry)) {
82
84
  throw wrongExplore("tools", tools, 'a list of { "name", "use", "how" } strings');
83
85
  }
@@ -88,11 +90,14 @@ export function exploreSettings(swarm = {}) {
88
90
  ["maxReadLines", maxReadLines],
89
91
  ["maxGrepLines", maxGrepLines],
90
92
  ["maxOutputChars", maxOutputChars],
93
+ ["excerptChars", excerptChars],
91
94
  ]) {
92
95
  if (!Number.isInteger(value) || value < 1) throw wrongExplore(key, value, "a positive whole number");
93
96
  }
97
+ if (excerptChars >= maxOutputChars) throw wrongExplore("excerptChars", excerptChars, `smaller than maxOutputChars (${maxOutputChars})`);
94
98
  if (!isNameList(exempt)) throw wrongExplore("exempt", exempt, "a list of globs");
95
- return { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt };
99
+ if (longOutput !== "excerpt" && longOutput !== "hint") throw wrongExplore("longOutput", longOutput, '"excerpt" or "hint"');
100
+ return { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt, longOutput, excerptChars };
96
101
  }
97
102
 
98
103
  /** @returns the explore settings of the checkout that holds `cwd`, or null when it has no config or no section. */
@@ -160,6 +165,19 @@ export function dispatchRefusal(input, settings) {
160
165
  return null;
161
166
  }
162
167
 
168
+ /** A note for a dispatch that starts a second prompt cache for its type, or null. It never refuses. */
169
+ export function dispatchNote(input, settings) {
170
+ const type = typeOf(input);
171
+ const model = typeof input.model === "string" ? input.model.trim() : "";
172
+ if (model === "" || type === FORK || !settings.allowedTypes.includes(type)) return null;
173
+ if (MODEL_FAMILIES.includes(model.toLowerCase())) return null;
174
+ return (
175
+ `Dispatch note: ${type} sets its own model, and "${model}" is a full model id. Requests to different models share no prompt cache, ` +
176
+ `so this dispatch pays the type's shared first-call prefix again when the id differs from the definition's model. ` +
177
+ "A dispatch of this type with no `model` shares one cache with the others."
178
+ );
179
+ }
180
+
163
181
  /** The reason an implementer over the limit waits, with the two ways a slot frees. */
164
182
  export function slotRefusal({ type, claimedAt, expiresAt, slotFile, limit = 1, holders = [] }) {
165
183
  const frees = `If no implementer runs, because its dispatch was denied after this hook, delete ${slotFile}.`;