@aragon-agent/cli 0.6.62 → 0.6.64

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +143 -27
  3. package/dist/agent/controller.d.ts +66 -14
  4. package/dist/agent/controller.js +291 -81
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +62 -3
  7. package/dist/agent/team-notices.d.ts +57 -7
  8. package/dist/agent/team-notices.js +93 -10
  9. package/dist/app/App.js +199 -77
  10. package/dist/cli.js +4 -1
  11. package/dist/commands/builtins.js +2 -1
  12. package/dist/commands/catalog.js +1 -1
  13. package/dist/compaction/archive.d.ts +27 -1
  14. package/dist/compaction/archive.js +8 -0
  15. package/dist/compaction/budget.d.ts +73 -0
  16. package/dist/compaction/budget.js +89 -0
  17. package/dist/compaction/child.js +6 -1
  18. package/dist/compaction/command.js +147 -1
  19. package/dist/compaction/compactor.d.ts +132 -15
  20. package/dist/compaction/compactor.js +288 -95
  21. package/dist/compaction/context-command.js +21 -0
  22. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  23. package/dist/compaction/memory-agent-prompt.js +76 -0
  24. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  25. package/dist/compaction/memory-agent-tools.js +338 -0
  26. package/dist/compaction/memory-agent.d.ts +114 -0
  27. package/dist/compaction/memory-agent.js +220 -0
  28. package/dist/compaction/prune.d.ts +129 -0
  29. package/dist/compaction/prune.js +386 -0
  30. package/dist/compaction/retry-plan.d.ts +103 -0
  31. package/dist/compaction/retry-plan.js +136 -0
  32. package/dist/compaction/summarize-ladder.d.ts +149 -0
  33. package/dist/compaction/summarize-ladder.js +273 -0
  34. package/dist/compaction/wiring.d.ts +19 -0
  35. package/dist/compaction/wiring.js +65 -1
  36. package/dist/config/cli-commands.d.ts +2 -2
  37. package/dist/config/cli-commands.js +27 -0
  38. package/dist/config/env.d.ts +3 -1
  39. package/dist/config/env.js +44 -2
  40. package/dist/exec/events.d.ts +30 -0
  41. package/dist/exec/index.js +2 -0
  42. package/dist/exec/runner.js +16 -1
  43. package/dist/gene/commit-prepare.js +27 -1
  44. package/dist/gene/curator/curator.d.ts +15 -0
  45. package/dist/gene/curator/curator.js +26 -2
  46. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  47. package/dist/gene/curator/scripted-lane.js +101 -0
  48. package/dist/gene/curator/task-context.d.ts +21 -0
  49. package/dist/gene/curator/task-context.js +33 -0
  50. package/dist/gene/curator/task-runner.d.ts +10 -1
  51. package/dist/gene/curator/task-runner.js +39 -4
  52. package/dist/gene/curator/tool-support.js +11 -4
  53. package/dist/gene/curator/toolkit.d.ts +13 -0
  54. package/dist/gene/curator/toolkit.js +23 -1
  55. package/dist/gene/curator/tools-verify.js +2 -2
  56. package/dist/gene/curator/tools-write.js +6 -1
  57. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  58. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  59. package/dist/gene/curator/validate/knowledge.js +74 -11
  60. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  61. package/dist/gene/curator/validate/prompts.js +2 -2
  62. package/dist/gene/learn/draft-guard.d.ts +17 -0
  63. package/dist/gene/learn/draft-guard.js +113 -0
  64. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  65. package/dist/gene/learn/learn-prompt.js +27 -2
  66. package/dist/gene/learn/learner.js +20 -2
  67. package/dist/gene/queue.d.ts +16 -0
  68. package/dist/gene/queue.js +44 -1
  69. package/dist/governance/store/run-store.d.ts +20 -0
  70. package/dist/governance/store/run-store.js +54 -8
  71. package/dist/host/index.d.ts +1 -0
  72. package/dist/host/index.js +1 -0
  73. package/dist/host/interaction.d.ts +8 -17
  74. package/dist/host/interaction.js +50 -72
  75. package/dist/host/team-wake-driver.d.ts +90 -0
  76. package/dist/host/team-wake-driver.js +114 -0
  77. package/dist/logging/install.d.ts +59 -1
  78. package/dist/logging/install.js +15 -0
  79. package/dist/session/validate-session.js +11 -0
  80. package/dist/team/console-tools.d.ts +12 -0
  81. package/dist/team/console-tools.js +20 -3
  82. package/dist/team/console-view.js +11 -1
  83. package/dist/team/notices.d.ts +81 -4
  84. package/dist/team/notices.js +187 -22
  85. package/dist/team/prompt.js +1 -1
  86. package/dist/team/runtime.d.ts +67 -24
  87. package/dist/team/runtime.js +250 -31
  88. package/dist/team/stall-watch.d.ts +54 -0
  89. package/dist/team/stall-watch.js +119 -0
  90. package/dist/team/task-tool.js +2 -2
  91. package/dist/team/wake.d.ts +176 -0
  92. package/dist/team/wake.js +444 -0
  93. package/package.json +81 -81
@@ -0,0 +1,386 @@
1
+ /**
2
+ * The redundancy pass - stage 0 of a compaction (context-compaction-v3 W1).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHAT THIS IS FOR. A long autonomous run is mostly REPEATED tool output: the
7
+ * same `bash` command re-run three times, one file read five times, an `npm
8
+ * test` log that appears twice. None of that needs a model to identify, and all
9
+ * of it is what pushes a digest past the summarizer's window - the most common
10
+ * reason a compaction declines. Rewriting those bodies costs no tokens of its
11
+ * own and can make the summary unnecessary altogether.
12
+ *
13
+ * PURE AND TOTAL. No I/O, no clock, no configuration read: every input arrives
14
+ * in `PruneInput`, so the pass is testable against a real session fixture and
15
+ * its output is byte-stable for byte-stable input.
16
+ *
17
+ * IT NEVER DELETES A MESSAGE (D-2). `planPrune` returns a same-length copy in
18
+ * which some BODIES are replaced by a fixed ASCII placeholder; `role`,
19
+ * `toolCallId` and `isError` are untouched, so `validateHistory`'s
20
+ * `tool_call` <-> `tool_result` pairing still holds.
21
+ *
22
+ * THE FIRST AND THE LAST COPY OF ANY REPEATED BODY ALWAYS SURVIVE. That is the
23
+ * rule that makes a stub honest: the earliest copy shows what the run actually
24
+ * produced, the latest shows what is still true, and only the copies in between
25
+ * - which say the same thing again - are replaced.
26
+ */
27
+ import { estimatePromptTokens } from '@aragon-agent/core';
28
+ import { COMPACTION_LIMITS as LIMITS } from '@aragon-agent/tui/model/compaction/limits';
29
+ /**
30
+ * The fixed noise regexes (D-13: six, hard-coded, never configured).
31
+ *
32
+ * THEY DESCRIBE SHAPE, NOT CONTENT: a timing suffix, a trailing percentage, a
33
+ * rule of separator characters, a lone ANSI escape, a lone progress word, and a
34
+ * blank line. A body made ONLY of these says nothing - which is a claim this
35
+ * list can make and a user-extensible list could not, because "your regex ate
36
+ * the error message" would then be a supported outcome.
37
+ */
38
+ const NOISE_PATTERNS = [
39
+ /\bcompleted in \d+(\.\d+)?\s?m?s\b/i,
40
+ /^\s*\d{1,3}%\s*\|?\s*$/,
41
+ /^\s*[|/\\+=_-]{1,4}\s*$/,
42
+ // eslint-disable-next-line no-control-regex
43
+ /^\s*\u001b\[[0-9;]*[A-Za-z]\s*$/,
44
+ /^\s*(?:\.{2,}|ok|done)\s*$/i,
45
+ /^\s*$/,
46
+ ];
47
+ /** The prefix every placeholder starts with; `isPruned` and idempotence rest on it. */
48
+ const STUB_HEAD = '[pruned ';
49
+ /** The placeholder for a replaced body. ASCII only, one line, fixed field order. */
50
+ export function pruneStub(kind, originalChars, keptId) {
51
+ const kept = keptId === undefined ? '' : ` duplicate-of=${keptId}`;
52
+ return `${STUB_HEAD}${kind}${kept} originalChars=${originalChars}]`;
53
+ }
54
+ /** Whether a body was already rewritten by an earlier pass (hard rule 9). */
55
+ function isPruned(text) {
56
+ return text.trimStart().startsWith(STUB_HEAD);
57
+ }
58
+ /** A message's body as plain text; images and non-text parts contribute nothing. */
59
+ function bodyText(message) {
60
+ if (message.role === 'assistant') {
61
+ return message.content
62
+ .filter((block) => block.type === 'text')
63
+ .map((block) => block.text)
64
+ .join('\n');
65
+ }
66
+ const { content } = message;
67
+ if (typeof content === 'string')
68
+ return content;
69
+ return content.flatMap((part) => part.type === 'text' ? [part.text] : []).join('\n');
70
+ }
71
+ /** Replace one message's body, keeping every structural field exactly as it was. */
72
+ function withBody(message, text) {
73
+ if (message.role !== 'assistant')
74
+ return { ...message, content: text };
75
+ let replaced = false;
76
+ const content = message.content.map((block) => {
77
+ if (block.type !== 'text')
78
+ return block;
79
+ const next = replaced ? '' : text;
80
+ replaced = true;
81
+ return { type: 'text', text: next };
82
+ });
83
+ return replaced ? { ...message, content } : message;
84
+ }
85
+ /**
86
+ * Normalise before comparing (hard rules 7 and 8).
87
+ *
88
+ * CRLF is folded, trailing whitespace is dropped per line, noise lines are
89
+ * removed, and the result is capped at `pruneBodyChars` so the pass stays
90
+ * linear in the input size no matter how large one body is.
91
+ */
92
+ function normalize(text) {
93
+ const capped = text.length > LIMITS.pruneBodyChars ? text.slice(0, LIMITS.pruneBodyChars) : text;
94
+ const lines = capped.replace(/\r\n/g, '\n').split('\n').map((line) => line.trimEnd());
95
+ const kept = lines.filter((line) => !NOISE_PATTERNS.some((pattern) => pattern.test(line)));
96
+ // EVERY LINE WAS NOISE: one marker, so two such bodies compare equal without
97
+ // looking like the empty-body rule.
98
+ return kept.length === 0 ? '[noise]' : kept.join('\n');
99
+ }
100
+ /** A stable, dependency-free digest of a normalised body. */
101
+ function hash(text) {
102
+ let value = 0x811c9dc5;
103
+ for (let index = 0; index < text.length; index += 1) {
104
+ value ^= text.charCodeAt(index);
105
+ value = Math.imul(value, 0x01000193) >>> 0;
106
+ }
107
+ return `${text.length.toString(36)}:${value.toString(36)}`;
108
+ }
109
+ /** `toolCallId` -> the tool and its arguments, so a re-run can be recognised. */
110
+ function callIndex(messages) {
111
+ const calls = new Map();
112
+ for (const message of messages) {
113
+ if (message.role !== 'assistant')
114
+ continue;
115
+ for (const block of message.content) {
116
+ if (block.type !== 'tool_call')
117
+ continue;
118
+ calls.set(block.toolCallId, {
119
+ toolName: block.toolName, args: JSON.stringify(block.args ?? {}),
120
+ });
121
+ }
122
+ }
123
+ return calls;
124
+ }
125
+ /** The path a `read_file` call targeted, or `null` for anything else. */
126
+ function readPath(call) {
127
+ if (call?.toolName !== 'read_file')
128
+ return null;
129
+ try {
130
+ const args = JSON.parse(call.args);
131
+ return typeof args.path === 'string' ? args.path : null;
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ }
137
+ function sourceId(generation, index) {
138
+ return `g${generation}:m${index}`;
139
+ }
140
+ /**
141
+ * Which messages the pass may touch: the head band, never a user message, never
142
+ * a body the existing memory quotes, never one an earlier pass already rewrote.
143
+ */
144
+ function eligibility(work) {
145
+ const { input } = work;
146
+ return input.messages.map((message, index) => {
147
+ if (index < input.protectedPrefix || index >= input.tailStart)
148
+ return false;
149
+ work.scanned += 1;
150
+ if (message.role === 'user')
151
+ return false;
152
+ if (input.citedIds.has(sourceId(input.generation, index))) {
153
+ work.skippedCited += 1;
154
+ return false;
155
+ }
156
+ return !isPruned(work.bodies[index]);
157
+ });
158
+ }
159
+ /** Record one rewrite, and skip it when it would not actually shorten the body. */
160
+ function rewrite(work, index, kind, body, kept) {
161
+ const before = work.bodies[index].length;
162
+ const replaced = withBody(work.input.messages[index], body);
163
+ const after = bodyText(replaced).length;
164
+ // A REWRITE MUST SHORTEN THE BODY. A stub is ~70 characters; rewriting a
165
+ // two-line duplicate with a longer placeholder would make the digest BIGGER,
166
+ // and there is no third option here - prune never drops a message (D-2), so a
167
+ // body that cannot be made shorter is one this pass leaves alone. Real
168
+ // redundancy in the field is long (a test log, a 4 000-line build), which is
169
+ // the case this rule is sized for.
170
+ if (after >= before)
171
+ return;
172
+ work.view[index] = replaced;
173
+ work.pruned.add(index);
174
+ work.removedChars += Math.max(0, before - after);
175
+ work.actions.push({
176
+ kind,
177
+ messageIndex: index,
178
+ sourceId: sourceId(work.input.generation, index),
179
+ ...(kept === undefined ? {} : { keptIndex: kept }),
180
+ removedChars: Math.max(0, before - after),
181
+ clipped: kind === 'oversized-body',
182
+ });
183
+ }
184
+ /** Replace a body by its placeholder, naming the copy that was kept. */
185
+ function stubFor(work, index, kind, kept) {
186
+ const original = work.bodies[index];
187
+ const keptId = kept === undefined ? undefined : sourceId(work.input.generation, kept);
188
+ rewrite(work, index, kind, pruneStub(kind, original.length, keptId), kept);
189
+ }
190
+ /** Rule 1: whitespace-only and noise-only tool results. */
191
+ function pruneEmptyAndNoise(work) {
192
+ work.input.messages.forEach((message, index) => {
193
+ if (message.role !== 'tool_result' || !work.eligible[index])
194
+ return;
195
+ const text = work.bodies[index];
196
+ if (text.trim().length === 0) {
197
+ // Zero-length removal is still a body change, so `rewrite` is skipped and
198
+ // the stub is written directly: the point is that the model stops reading
199
+ // a blank line as evidence.
200
+ work.view[index] = withBody(message, pruneStub('empty-tool-result', 0));
201
+ work.pruned.add(index);
202
+ work.actions.push({
203
+ kind: 'empty-tool-result', messageIndex: index,
204
+ sourceId: sourceId(work.input.generation, index), removedChars: 0, clipped: false,
205
+ });
206
+ return;
207
+ }
208
+ const onlyNoise = normalize(text) === '[noise]';
209
+ if (onlyNoise)
210
+ stubFor(work, index, 'noise-only-body');
211
+ });
212
+ }
213
+ /** Rule 2: an earlier read of a path that a later read supersedes. */
214
+ function pruneSupersededReads(work) {
215
+ const lastRead = new Map();
216
+ work.input.messages.forEach((message, index) => {
217
+ if (message.role !== 'tool_result')
218
+ return;
219
+ const path = readPath(work.calls.get(message.toolCallId));
220
+ if (path !== null)
221
+ lastRead.set(path, index);
222
+ });
223
+ work.input.messages.forEach((message, index) => {
224
+ if (message.role !== 'tool_result' || !work.eligible[index])
225
+ return;
226
+ const path = readPath(work.calls.get(message.toolCallId));
227
+ const kept = path === null ? undefined : lastRead.get(path);
228
+ if (kept === undefined || kept <= index)
229
+ return;
230
+ stubFor(work, index, 'superseded-file-read', kept);
231
+ });
232
+ }
233
+ /** The signature a re-run must repeat: same tool, same arguments, same body. */
234
+ function dedupeKey(work, index) {
235
+ const message = work.input.messages[index];
236
+ const body = work.normalized[index];
237
+ if (message.role !== 'tool_result' || body.length === 0)
238
+ return '';
239
+ const call = work.calls.get(message.toolCallId);
240
+ return call === undefined
241
+ ? `dup\u0000${hash(body)}`
242
+ : `rerun\u0000${call.toolName}\u0000${call.args}\u0000${hash(body)}`;
243
+ }
244
+ /**
245
+ * Rule 3: identical bodies, first and last kept.
246
+ *
247
+ * AN ERROR BODY IS NOT SPECIAL-CASED HERE, and that is the point: the shape that
248
+ * protects a failed test log (D-3) is the shape that handles every other repeat
249
+ * - the first and the last copy survive, so the failure is still readable and
250
+ * still adjacent to the fix, while the retries in between stop costing context.
251
+ */
252
+ function pruneDuplicates(work) {
253
+ const groups = new Map();
254
+ for (let index = 0; index < work.input.messages.length; index += 1) {
255
+ const key = dedupeKey(work, index);
256
+ if (!key)
257
+ continue;
258
+ const group = groups.get(key);
259
+ if (group)
260
+ group.push(index);
261
+ else
262
+ groups.set(key, [index]);
263
+ }
264
+ for (const [key, indexes] of groups) {
265
+ if (indexes.length < 3)
266
+ continue;
267
+ const kind = key.startsWith('rerun\u0000')
268
+ ? 'repeat-command-output' : 'duplicate-tool-result';
269
+ const kept = indexes[indexes.length - 1];
270
+ for (const index of indexes.slice(1, -1)) {
271
+ if (work.eligible[index] && !work.pruned.has(index))
272
+ stubFor(work, index, kind, kept);
273
+ }
274
+ }
275
+ }
276
+ /** Rule 6: a body over `pruneBodyChars` keeps its head and its tail. */
277
+ function pruneOversized(work) {
278
+ work.input.messages.forEach((message, index) => {
279
+ if (message.role !== 'tool_result' || !work.eligible[index])
280
+ return;
281
+ const text = work.bodies[index];
282
+ if (text.length <= LIMITS.pruneBodyChars)
283
+ return;
284
+ // THE MARKER ITSELF IS THE IDEMPOTENCE TEST. The clipped body is never
285
+ // shorter than `pruneBodyChars` (head + marker + tail), so a length test
286
+ // alone would clip it again on the next pass.
287
+ if (text.includes('\n[pruned oversized '))
288
+ return;
289
+ const half = Math.floor(LIMITS.pruneBodyChars / 2);
290
+ const head = text.slice(0, half);
291
+ const tail = text.slice(-half);
292
+ const marker = `[pruned oversized originalChars=${text.length}`
293
+ + ` kept=${head.length + tail.length}]`;
294
+ rewrite(work, index, 'oversized-body', `${head}\n${marker}\n${tail}`);
295
+ });
296
+ }
297
+ /** Rule 4: two consecutive assistant bodies that are the same streaming residue. */
298
+ function pruneAssistantResidue(work) {
299
+ const { messages } = work.input;
300
+ for (let index = 1; index < messages.length; index += 1) {
301
+ const current = messages[index];
302
+ const previous = messages[index - 1];
303
+ if (current.role !== 'assistant' || previous.role !== 'assistant')
304
+ continue;
305
+ if (!work.eligible[index] || !work.eligible[index - 1])
306
+ continue;
307
+ if (hasToolCall(current) || hasToolCall(previous))
308
+ continue;
309
+ const text = work.bodies[index];
310
+ if (text.trim().length === 0)
311
+ continue;
312
+ if (normalize(text) !== normalize(work.bodies[index - 1]))
313
+ continue;
314
+ stubFor(work, index, 'duplicate-assistant-text', index - 1);
315
+ }
316
+ }
317
+ /** Whether an assistant message carries a tool call (never rewritten, rule 4). */
318
+ function hasToolCall(message) {
319
+ return message.role === 'assistant'
320
+ && message.content.some((block) => block.type === 'tool_call');
321
+ }
322
+ /**
323
+ * Plan the redundancy pass for one compaction band.
324
+ *
325
+ * ORDER IS THE SEMANTICS. Empty and noise-only bodies go first (their identity is
326
+ * free), then superseded file reads, then repeats, then oversized clipping -
327
+ * because clipping changes the text two bodies are compared by.
328
+ */
329
+ export function planPrune(input) {
330
+ const bodies = input.messages.map(bodyText);
331
+ const work = {
332
+ input,
333
+ bodies,
334
+ normalized: bodies.map((text) => text.length === 0 ? '' : normalize(text)),
335
+ view: [...input.messages],
336
+ actions: [],
337
+ eligible: [],
338
+ pruned: new Set(),
339
+ removedChars: 0,
340
+ scanned: 0,
341
+ skippedCited: 0,
342
+ calls: callIndex(input.messages),
343
+ };
344
+ work.eligible = eligibility(work);
345
+ pruneEmptyAndNoise(work);
346
+ pruneSupersededReads(work);
347
+ pruneDuplicates(work);
348
+ pruneOversized(work);
349
+ pruneAssistantResidue(work);
350
+ const before = estimatePromptTokens([...input.messages]);
351
+ const after = estimatePromptTokens(work.view);
352
+ return {
353
+ messages: work.view,
354
+ actions: work.actions,
355
+ removedChars: work.removedChars,
356
+ removedTokens: Math.max(0, before - after),
357
+ scanned: work.scanned,
358
+ skippedCited: work.skippedCited,
359
+ };
360
+ }
361
+ /** The character count of one message body, for callers that report a ratio. */
362
+ export function messageBodyChars(message) {
363
+ return bodyText(message).length;
364
+ }
365
+ /**
366
+ * The ids the EXISTING memory quotes, for `PruneInput.citedIds` (P1-3).
367
+ *
368
+ * READ FROM THE PRIOR MEMORY ITSELF rather than from the digest it will become,
369
+ * because the prune has to happen BEFORE the digest exists. Every reference the
370
+ * validator can check is included: the anchor, the protected user messages, each
371
+ * item's sources, and each clipped tool result's message id.
372
+ */
373
+ export function citedMessageIds(prior) {
374
+ const ids = new Set();
375
+ if (!prior)
376
+ return ids;
377
+ ids.add(prior.originalTask.sourceId);
378
+ for (const entry of prior.userMessages)
379
+ ids.add(entry.id);
380
+ for (const item of prior.items)
381
+ for (const source of item.sources)
382
+ ids.add(source.messageId);
383
+ for (const clip of prior.coverage.clippedToolResults)
384
+ ids.add(clip.messageId);
385
+ return ids;
386
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The failure-to-action table (context-compaction-v3 W2).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY A TABLE AND NOT A RETRY COUNT. The old ladder re-asked the same question
7
+ * twice and gave up: two attempts, the second with "Previous delta rejected",
8
+ * and a whole compaction spent on a model that had no way to see what it got
9
+ * wrong. A failure here is one of five different facts - the model answered
10
+ * unusably, the request did not fit, the request never arrived, the budget ran
11
+ * out, or nothing about retrying can help - and each deserves a DIFFERENT action.
12
+ * Encoding that as data (`classifyFailure` / `planRetry`) is what makes the
13
+ * whole matrix assertable in one place, and what stops "retry" from quietly
14
+ * becoming the answer to a structural refusal.
15
+ *
16
+ * PURE, NO CLOCK, NO I/O. Two functions over strings and numbers.
17
+ */
18
+ /** What kind of failure one reason code names. */
19
+ export type FailureKind =
20
+ /** The model answered and we could not use the answer. */
21
+ 'semantic'
22
+ /** The request does not fit the summarizer's window. */
23
+ | 'window'
24
+ /** The request never got an answer (network, or our own call timeout). */
25
+ | 'transport'
26
+ /** The per-operation spend ceiling was reached. */
27
+ | 'budget'
28
+ /** Nothing about re-asking can help (no key, no model, no safe cut). */
29
+ | 'structural'
30
+ /** The user or the engine stopped this operation. */
31
+ | 'cancel'
32
+ /** The agent loop used its own wall-clock budget (P0-2). */
33
+ | 'timeout'
34
+ /**
35
+ * A failure with no recognisable code - an adapter throw, an unexpected error.
36
+ *
37
+ * IT IS NOT 'structural'. Structural means "nothing about re-asking can help" and
38
+ * names reasons we understand (`no_api_key`, `nothing_to_drop`); an unrecognised
39
+ * failure is exactly the case where a DIFFERENT endpoint may still work, which is
40
+ * why it is routed like a transport failure rather than stopped outright.
41
+ */
42
+ | 'unknown';
43
+ export interface RetryState {
44
+ /** 1-based: how many real calls this operation has already made. */
45
+ attempt: number;
46
+ /** Whether the current summarizer reaches the same endpoint as the main model. */
47
+ sameEndpoint: boolean;
48
+ /** Semantic repairs already spent (defaults to `attempt - 1`). */
49
+ repairs?: number;
50
+ /** Digest shrinks already spent. */
51
+ shrinks?: number;
52
+ /** Turns the agent loop has left; `0` means no new turn may start. */
53
+ turnsLeft: number;
54
+ /** Token budget left; `0` = unlimited, a NEGATIVE value = exhausted (D-8). */
55
+ budgetLeft: number;
56
+ }
57
+ export type RetryAction =
58
+ /** Re-ask the same model, carrying the validator's receipt. */
59
+ {
60
+ kind: 'retry-repair';
61
+ hint: string;
62
+ }
63
+ /** Shrink the digest by `factor` and ask again. */
64
+ | {
65
+ kind: 'retry-shrink';
66
+ factor: number;
67
+ }
68
+ /** Switch to the main model (only meaningful on a different endpoint). */
69
+ | {
70
+ kind: 'escalate-main';
71
+ }
72
+ /** Re-send unchanged (same endpoint, nothing new to say). */
73
+ | {
74
+ kind: 'retry-plain';
75
+ } | {
76
+ kind: 'stop';
77
+ code: string;
78
+ };
79
+ /** The semantic repairs one operation may spend before changing model. */
80
+ export declare const MAX_REPAIRS = 3;
81
+ /** The digest shrinks one operation may spend before changing model. */
82
+ export declare const MAX_SHRINKS = 2;
83
+ /** The agent loop's second chance after it stopped without submitting. */
84
+ export declare const MAX_AGENT_RESTARTS = 1;
85
+ /**
86
+ * Classify one reason string.
87
+ *
88
+ * THE CODE IS READ THE WAY `compactionReasonCode` READS IT (everything before
89
+ * the first colon), because every caller already produces `<code>: <detail>`.
90
+ * `timeout` is `transport` and `agent_timeout` is `timeout` on purpose: the
91
+ * first is our call ceiling on a request that never answered, the second is the
92
+ * loop's own wall clock, and only the second means "do not start another turn".
93
+ */
94
+ export declare function classifyFailure(reason: string): FailureKind;
95
+ /**
96
+ * What to do after one failure.
97
+ *
98
+ * EVERY BRANCH IS BOUNDED, and every bound is a constant above: a table with no
99
+ * ceilings is an infinite loop with better spelling. `turnsLeft` and
100
+ * `budgetLeft` are checked FIRST, because neither a repair nor an escalation is
101
+ * worth planning when there is no turn or no money left to carry it out.
102
+ */
103
+ export declare function planRetry(reason: string, state: RetryState): RetryAction;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The failure-to-action table (context-compaction-v3 W2).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY A TABLE AND NOT A RETRY COUNT. The old ladder re-asked the same question
7
+ * twice and gave up: two attempts, the second with "Previous delta rejected",
8
+ * and a whole compaction spent on a model that had no way to see what it got
9
+ * wrong. A failure here is one of five different facts - the model answered
10
+ * unusably, the request did not fit, the request never arrived, the budget ran
11
+ * out, or nothing about retrying can help - and each deserves a DIFFERENT action.
12
+ * Encoding that as data (`classifyFailure` / `planRetry`) is what makes the
13
+ * whole matrix assertable in one place, and what stops "retry" from quietly
14
+ * becoming the answer to a structural refusal.
15
+ *
16
+ * PURE, NO CLOCK, NO I/O. Two functions over strings and numbers.
17
+ */
18
+ const SEMANTIC = new Set(['invalid_memory_delta', 'empty_memory_delta']);
19
+ const AGENT_SEMANTIC = new Set(['agent_incomplete', 'turn_limit']);
20
+ const WINDOW = new Set(['summarizer_window_exceeded', 'digest_budget_exceeded']);
21
+ const TRANSPORT = new Set(['summarizer_unreachable', 'timeout']);
22
+ const BUDGET = new Set(['budget_exhausted', 'budget_tokens', 'budget_usd']);
23
+ const CANCEL = new Set(['aborted', 'cancelled', 'stale_history']);
24
+ const TIMEOUT = new Set(['agent_timeout', 'manager_timeout']);
25
+ /**
26
+ * The codes that really are terminal.
27
+ *
28
+ * THE LIST IS EXPLICIT AND SHORT ON PURPOSE. Everything else - including text this
29
+ * table has never seen - is `unknown`, which is routed like a transport failure:
30
+ * try the main model if it lives on another endpoint, otherwise stop. Reading an
31
+ * unrecognised error as "nothing can help" would give up on the one class of
32
+ * failure where a different endpoint most plausibly does.
33
+ */
34
+ const KNOWN_STRUCTURAL = new Set([
35
+ 'no_api_key', 'no_summarizer_model', 'nothing_to_drop', 'no_token_reclaim',
36
+ 'protected_memory_too_large', 'protected_multimodal_tail', 'invalid_prior_memory',
37
+ 'invalid_history', 'insufficient_reclaim', 'disabled', 'already_running',
38
+ 'adoption_failed', 'pruned_no_gain',
39
+ ]);
40
+ /** The semantic repairs one operation may spend before changing model. */
41
+ export const MAX_REPAIRS = 3;
42
+ /** The digest shrinks one operation may spend before changing model. */
43
+ export const MAX_SHRINKS = 2;
44
+ /** The agent loop's second chance after it stopped without submitting. */
45
+ export const MAX_AGENT_RESTARTS = 1;
46
+ /**
47
+ * Classify one reason string.
48
+ *
49
+ * THE CODE IS READ THE WAY `compactionReasonCode` READS IT (everything before
50
+ * the first colon), because every caller already produces `<code>: <detail>`.
51
+ * `timeout` is `transport` and `agent_timeout` is `timeout` on purpose: the
52
+ * first is our call ceiling on a request that never answered, the second is the
53
+ * loop's own wall clock, and only the second means "do not start another turn".
54
+ */
55
+ export function classifyFailure(reason) {
56
+ const code = reason.split(':', 1)[0].trim();
57
+ if (TIMEOUT.has(code))
58
+ return 'timeout';
59
+ if (BUDGET.has(code))
60
+ return 'budget';
61
+ if (CANCEL.has(code))
62
+ return 'cancel';
63
+ if (WINDOW.has(code))
64
+ return 'window';
65
+ if (TRANSPORT.has(code))
66
+ return 'transport';
67
+ if (SEMANTIC.has(code) || AGENT_SEMANTIC.has(code))
68
+ return 'semantic';
69
+ return KNOWN_STRUCTURAL.has(code) ? 'structural' : 'unknown';
70
+ }
71
+ /**
72
+ * What to do after one failure.
73
+ *
74
+ * EVERY BRANCH IS BOUNDED, and every bound is a constant above: a table with no
75
+ * ceilings is an infinite loop with better spelling. `turnsLeft` and
76
+ * `budgetLeft` are checked FIRST, because neither a repair nor an escalation is
77
+ * worth planning when there is no turn or no money left to carry it out.
78
+ */
79
+ export function planRetry(reason, state) {
80
+ const code = reason.split(':', 1)[0].trim();
81
+ const repairs = state.repairs ?? Math.max(0, state.attempt - 1);
82
+ const shrinks = state.shrinks ?? 0;
83
+ if (state.turnsLeft <= 0)
84
+ return { kind: 'stop', code: code || 'turn_limit' };
85
+ if (state.budgetLeft < 0)
86
+ return { kind: 'stop', code: 'budget_exhausted' };
87
+ switch (classifyFailure(reason)) {
88
+ case 'cancel':
89
+ return { kind: 'stop', code: code || 'cancelled' };
90
+ case 'budget':
91
+ return { kind: 'stop', code: 'budget_exhausted' };
92
+ case 'timeout':
93
+ // THE CODE IS CARRIED, NOT REPLACED: `manager_timeout` and `agent_timeout`
94
+ // are different facts - the engine cut us, or we cut ourselves - and each
95
+ // has its own wording, so reporting one as the other would send a reader
96
+ // to the wrong ceiling.
97
+ return { kind: 'stop', code: code || 'agent_timeout' };
98
+ case 'structural':
99
+ return { kind: 'stop', code: code || 'structural' };
100
+ case 'transport':
101
+ case 'unknown':
102
+ // D-6: core's `withRetry` already owns backoff on this endpoint. Asking
103
+ // again here would multiply the quota a rate-limited provider sees, so
104
+ // only a DIFFERENT endpoint is worth another request - and that is also
105
+ // the only honest answer to a failure we cannot name.
106
+ return state.sameEndpoint ? { kind: 'stop', code } : { kind: 'escalate-main' };
107
+ case 'window':
108
+ if (shrinks < MAX_SHRINKS)
109
+ return { kind: 'retry-shrink', factor: 0.5 };
110
+ return state.sameEndpoint ? { kind: 'stop', code } : { kind: 'escalate-main' };
111
+ case 'semantic':
112
+ default:
113
+ return planSemantic(code, { ...state, repairs }, reason);
114
+ }
115
+ }
116
+ /** The semantic branch: repair in place, then change model, then stop. */
117
+ function planSemantic(code, state, reason) {
118
+ if (AGENT_SEMANTIC.has(code)) {
119
+ // ONE RESTART ONLY. The second run carries "the previous run never
120
+ // submitted", which is information the first run did not have; a third run
121
+ // would repeat the second verbatim.
122
+ return state.repairs < MAX_AGENT_RESTARTS
123
+ ? { kind: 'retry-repair', hint: 'The previous run ended without compaction_submit.' }
124
+ : { kind: 'stop', code };
125
+ }
126
+ if (state.repairs < MAX_REPAIRS) {
127
+ // THE HINT IS THE RECEIPT (200 characters is the system-prompt budget the
128
+ // single-shot path already used), not a paraphrase of it: a model that is told
129
+ // WHICH field failed fixes that field, and one that is told "validation failed"
130
+ // guesses.
131
+ return { kind: 'retry-repair', hint: `Fix this and resubmit: ${reason.slice(0, 200)}` };
132
+ }
133
+ // NOTHING LEFT TO REPAIR WITH THIS MODEL. Escalating to the endpoint we are
134
+ // already on is a no-op dressed as a retry, so it stops instead.
135
+ return state.sameEndpoint ? { kind: 'stop', code } : { kind: 'escalate-main' };
136
+ }