@aragon-agent/cli 0.6.61 → 0.6.63

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 (44) hide show
  1. package/README.md +99 -7
  2. package/dist/agent/headless.js +67 -6
  3. package/dist/agent/prompt-options.d.ts +7 -0
  4. package/dist/app/App.js +37 -5
  5. package/dist/commands/builtins.js +2 -1
  6. package/dist/commands/catalog.js +1 -1
  7. package/dist/compaction/archive.d.ts +27 -1
  8. package/dist/compaction/archive.js +8 -0
  9. package/dist/compaction/budget.d.ts +73 -0
  10. package/dist/compaction/budget.js +89 -0
  11. package/dist/compaction/child.js +6 -1
  12. package/dist/compaction/command.js +147 -1
  13. package/dist/compaction/compactor.d.ts +132 -15
  14. package/dist/compaction/compactor.js +288 -95
  15. package/dist/compaction/context-command.js +21 -0
  16. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  17. package/dist/compaction/memory-agent-prompt.js +76 -0
  18. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  19. package/dist/compaction/memory-agent-tools.js +338 -0
  20. package/dist/compaction/memory-agent.d.ts +114 -0
  21. package/dist/compaction/memory-agent.js +220 -0
  22. package/dist/compaction/prune.d.ts +129 -0
  23. package/dist/compaction/prune.js +386 -0
  24. package/dist/compaction/retry-plan.d.ts +103 -0
  25. package/dist/compaction/retry-plan.js +136 -0
  26. package/dist/compaction/summarize-ladder.d.ts +149 -0
  27. package/dist/compaction/summarize-ladder.js +273 -0
  28. package/dist/compaction/wiring.d.ts +19 -0
  29. package/dist/compaction/wiring.js +65 -1
  30. package/dist/config/cli-commands.d.ts +1 -1
  31. package/dist/config/cli-commands.js +16 -0
  32. package/dist/config/env.d.ts +3 -1
  33. package/dist/config/env.js +44 -2
  34. package/dist/exec/events.d.ts +30 -0
  35. package/dist/exec/runner.d.ts +9 -0
  36. package/dist/exec/runner.js +51 -2
  37. package/dist/host/controller-feed.d.ts +12 -3
  38. package/dist/host/controller-feed.js +1 -1
  39. package/dist/host/interaction.js +5 -2
  40. package/dist/logging/install.d.ts +38 -1
  41. package/dist/logging/install.js +12 -1
  42. package/dist/session/persist.js +21 -5
  43. package/dist/session/validate-session.js +18 -2
  44. package/package.json +3 -3
@@ -3,16 +3,16 @@ import { getLogger } from '../logging/logger.js';
3
3
  import { computeCost } from '@aragon-agent/tui/model/agent/usage';
4
4
  import { resolveFastTier } from '@aragon-agent/tui/model/fast/resolve';
5
5
  import { COMPACTION_LIMITS } from '@aragon-agent/tui/model/compaction/limits';
6
- import { buildDigest } from './digest.js';
7
- import { buildCompactedBlock, countProtectedPrefix } from './summary-prompt.js';
8
- import { accumulateUsage, describeTransportFailure, errorText, runSummarizeCall, buildSummarizeRequest, TRANSPORT_FAILURE_CODE, } from './summarize-call.js';
6
+ import { buildCompactedBlock, countProtectedPrefix, parseCompactedBlock, readGeneration } from './summary-prompt.js';
7
+ import { accumulateUsage, errorText, runSummarizeCall, TRANSPORT_FAILURE_CODE, } from './summarize-call.js';
9
8
  import { shouldCompactAt } from '@aragon-agent/tui/model/compaction/pressure';
10
9
  import { ContextMeter } from '@aragon-agent/tui/model/compaction/meter';
11
10
  import { CompactionOperation } from './operation.js';
12
11
  import { prepareMemoryInput } from './memory-input.js';
13
- import { mergeMemory, parseMemoryDelta } from './memory.js';
14
- import { validateMemoryDelta } from './memory-validation.js';
15
12
  import { renderMemoryMarkdown } from './memory-render.js';
13
+ import { citedMessageIds, planPrune } from './prune.js';
14
+ import { CompactionBudget } from './budget.js';
15
+ import { SummarizeLadder } from './summarize-ladder.js';
16
16
  import { compactionReasonCode, compactionReasonLine, } from '@aragon-agent/tui/model/compaction/reason-text';
17
17
  import { createCompactionIdentity, verifyCompactionIdentity, } from './memory-identity.js';
18
18
  export class Compactor {
@@ -29,6 +29,11 @@ export class Compactor {
29
29
  costUsd = 0;
30
30
  consecutiveNoProgress = 0;
31
31
  consecutiveTransportFailures = 0;
32
+ consecutiveSemanticFailures = 0;
33
+ prunedActions = 0;
34
+ prunedChars = 0;
35
+ /** The operation the engine has most recently settled, for `/compact status`. */
36
+ settled = null;
32
37
  selfDisabled = false;
33
38
  selfDisabledReason;
34
39
  pendingManual = null;
@@ -41,9 +46,14 @@ export class Compactor {
41
46
  identity;
42
47
  legacyFailureNotified = false;
43
48
  maxPerRun;
49
+ /** `undefined` = follow the config; `false` = this instance never runs the agent. */
50
+ agenticOverride;
51
+ /** The retry ladder, built on first use (see `get ladder`). */
52
+ ladderCache = null;
44
53
  constructor(deps, opts) {
45
54
  this.deps = deps;
46
55
  this.maxPerRun = opts?.maxPerRun ?? COMPACTION_LIMITS.maxPerRun;
56
+ this.agenticOverride = opts?.agentic;
47
57
  }
48
58
  onRunStart() {
49
59
  this.compactionsThisRun = 0;
@@ -113,7 +123,8 @@ export class Compactor {
113
123
  return { action: 'keep', reason: 'already_running' };
114
124
  const manual = this.pendingManual;
115
125
  this.pendingManual = null;
116
- const keepRecentTurns = this.deps.getConfig().compaction.keepRecentTurns;
126
+ const config = this.deps.getConfig().compaction;
127
+ const keepRecentTurns = config.keepRecentTurns;
117
128
  const state = {
118
129
  operation: new CompactionOperation(++this.serial, ctx.signal, COMPACTION_LIMITS.operationTimeoutMs),
119
130
  epoch: this.historyEpoch, settings: this.settingsKey(),
@@ -121,6 +132,10 @@ export class Compactor {
121
132
  threshold: this.deps.getConfig().compaction.threshold,
122
133
  started: Date.now(), messages: [...ctx.messages], model: '',
123
134
  keepRelaxed: false, keepRecentTurns,
135
+ // THE CEILING IS PER OPERATION, AND IT IS BUILT HERE (W3 / D-8): one
136
+ // object per `compact()` call is what makes "this compaction may spend at
137
+ // most N" true, and what keeps `wouldExceed` reading a live ledger.
138
+ budget: new CompactionBudget({ tokens: config.budgetTokens, usd: config.budgetUsd }),
124
139
  };
125
140
  this.active = state;
126
141
  this.compactionsThisRun += 1;
@@ -151,9 +166,10 @@ export class Compactor {
151
166
  // legal cut at all, because every candidate leaves fewer than
152
167
  // `keepRecentTurns` USER messages behind it. 107 of 119 long sessions on the
153
168
  // reporting machine were in exactly that state.
169
+ const protectedPrefix = countProtectedPrefix(state.messages, this.identity);
154
170
  const plan = planCompaction(state.messages, {
155
171
  keepRecentTurns: config.keepRecentTurns,
156
- protectedPrefix: countProtectedPrefix(state.messages, this.identity),
172
+ protectedPrefix,
157
173
  retainMessages: COMPACTION_LIMITS.minRetainedMessages,
158
174
  });
159
175
  if (!plan)
@@ -161,8 +177,18 @@ export class Compactor {
161
177
  state.keepRelaxed = plan.keepRelaxed === true;
162
178
  state.retainedTurns = plan.retainedTurns;
163
179
  state.retainedMessages = state.messages.length - plan.cutIndex;
180
+ // P0-1: THE CUT IS COMPUTED FIRST, AND THE REDUNDANCY PASS RUNS ON IT.
181
+ // `plan.cutIndex` is the one number that says which messages are about to
182
+ // leave the history, so pruning before the planner is not implementable -
183
+ // and pruning after it is also more truthful: only the band being replaced is
184
+ // ever rewritten.
185
+ const pruned = this.pruneStage(state, plan.cutIndex, protectedPrefix);
186
+ const band = pruned?.messages ?? state.messages;
187
+ const relief = this.pruneOnlyCandidate(state, pruned, plan.cutIndex, ctx);
188
+ if (relief)
189
+ return relief;
164
190
  this.phase(state, 'digesting');
165
- const input = prepareMemoryInput({ messages: state.messages, cutIndex: plan.cutIndex,
191
+ const input = prepareMemoryInput({ messages: band, cutIndex: plan.cutIndex,
166
192
  ...(this.identity ? { identity: this.identity } : {}) });
167
193
  if (input.imagesDemoted > 0) {
168
194
  this.log.info('images_demoted', { count: input.imagesDemoted });
@@ -191,6 +217,88 @@ export class Compactor {
191
217
  this.finishRecord(state, { action: 'replace', mode: 'summarized', messages: candidate }, summary);
192
218
  return { action: 'replace', mode: 'summarized', messages: candidate, summary };
193
219
  }
220
+ /**
221
+ * Stage 0: rewrite redundant bodies in the band about to be replaced (W1).
222
+ *
223
+ * ZERO MODEL COST, AND ZERO EVENTS WHEN IT FINDS NOTHING: the phase is emitted
224
+ * only when at least one body actually changed, so a session with
225
+ * `compaction.prune` off - or one with nothing redundant - produces the same
226
+ * stream it produced before this feature existed.
227
+ */
228
+ pruneStage(state, cutIndex, protectedPrefix) {
229
+ if (!this.deps.getConfig().compaction.prune)
230
+ return null;
231
+ const prior = this.priorMemory(state.messages);
232
+ const plan = planPrune({
233
+ messages: state.messages,
234
+ protectedPrefix,
235
+ tailStart: cutIndex,
236
+ generation: readGeneration(state.messages, this.identity),
237
+ citedIds: citedMessageIds(prior),
238
+ });
239
+ if (plan.actions.length === 0)
240
+ return null;
241
+ state.prune = plan;
242
+ this.phase(state, 'pruning');
243
+ this.log.info('compaction_prune', {
244
+ actions: plan.actions.length, bodies: plan.scanned, removedChars: plan.removedChars,
245
+ removedTokens: plan.removedTokens, skippedCited: plan.skippedCited,
246
+ });
247
+ return plan;
248
+ }
249
+ /** The prior memory this history carries, when its identity still verifies. */
250
+ priorMemory(messages) {
251
+ if (!this.identity || !verifyCompactionIdentity(messages, this.identity))
252
+ return undefined;
253
+ try {
254
+ return parseCompactedBlock(messages[1])?.memory;
255
+ }
256
+ catch {
257
+ return undefined;
258
+ }
259
+ }
260
+ /**
261
+ * The free win: when pruning alone already clears the threshold, do not
262
+ * summarize at all.
263
+ *
264
+ * IT MUST STILL SATISFY `checkCandidate`, which is why the candidate goes
265
+ * through the same gate the summarized one does - a prune-only splice that
266
+ * reclaims nothing (`no_token_reclaim`) or that leaves the history above the
267
+ * window (`protected_memory_too_large`) is not a win, and falling through to
268
+ * the summary is the honest answer.
269
+ */
270
+ pruneOnlyCandidate(state, pruned, cutIndex, ctx) {
271
+ if (!pruned || pruned.removedTokens < COMPACTION_LIMITS.pruneMinTokens)
272
+ return null;
273
+ const candidate = pruned.messages;
274
+ try {
275
+ this.checkCandidate(candidate, state, ctx.systemPrompt);
276
+ }
277
+ catch {
278
+ // Not a win on its own; the summary continues with the pruned band.
279
+ this.log.info('compaction_prune_only_rejected', { cutIndex, reason: 'candidate' });
280
+ return null;
281
+ }
282
+ const after = estimatePromptTokens(candidate, ctx.systemPrompt)
283
+ + Math.max(0, state.pressure.estimateOffset ?? 0);
284
+ if (after >= state.threshold * state.pressure.contextWindow)
285
+ return null;
286
+ this.phase(state, 'applying');
287
+ state.candidate = candidate;
288
+ // THE PORT STILL SEES `truncated` (DH-5): the engine's question is narrower
289
+ // than the card's - "was this history reduced without a summary" - and the
290
+ // answer is yes. The card gets `relieved`, which is the truth about WHAT was
291
+ // reduced (bodies, not messages).
292
+ const outcome = {
293
+ action: 'replace', mode: 'truncated', messages: candidate,
294
+ };
295
+ this.finishRecord(state, outcome, undefined, 'relieved');
296
+ this.log.info('compaction_prune_only', {
297
+ actions: pruned.actions.length, removedChars: pruned.removedChars,
298
+ removedTokens: pruned.removedTokens,
299
+ });
300
+ return outcome;
301
+ }
194
302
  selectInput(input, instructions) {
195
303
  const choice = this.resolveSummarizer();
196
304
  if (!choice)
@@ -231,92 +339,51 @@ export class Compactor {
231
339
  anchor: input.anchorShape, generation: input.generation });
232
340
  this.checkCandidate([input.anchor, block, ...input.tail], state, systemPrompt);
233
341
  }
234
- digestFor(input, choice, instructions) {
235
- const window = this.deps.getModelInfoFor(choice.ref).contextWindow;
236
- const digest = buildDigest({ head: input.head, anchor: input.anchor, generation: input.generation,
237
- startIndex: input.headStartIndex, summarizerWindow: window,
238
- ...(input.prior ? { priorMemory: input.prior } : {}),
239
- ...(input.legacySummary ? { legacySummary: input.legacySummary } : {}) });
240
- const request = buildSummarizeRequest({ ref: choice.ref, apiKey: '', digest: digest.text,
241
- hasPriorSummary: !!input.prior, signal: new AbortController().signal, now: 0,
242
- ...(instructions ? { instructions } : {}) });
243
- if (estimatePromptTokens(request.messages, request.systemPrompt) +
244
- COMPACTION_LIMITS.summaryOutputTokens + CONTEXT_SAFETY_MARGIN_TOKENS >= window) {
245
- // A DIFFERENT GATE FROM THE DIGEST'S LENGTH BUDGET, and it keeps a different
246
- // reason code on purpose (A1). This one is the REAL ceiling - the actual
247
- // request does not fit the summarizer's window - so it must still refuse.
248
- // Giving it the length budget's name would send `selectInput`'s retry ladder
249
- // and every log reader after the wrong cause.
250
- throw new Error('summarizer_window_exceeded');
251
- }
252
- return digest;
342
+ /**
343
+ * The digest for whichever path will send it, delegated to the ladder.
344
+ *
345
+ * the code that picks the path: `summarize-ladder.ts` owns the ask, the classify
346
+ * and the ask-again loop, and this file keeps the ORDER of the stages. Two
347
+ * ceilings act on that loop (the attempt count and the operation ledger) and
348
+ * both are checked there, before a request is sent.
349
+ */
350
+ digestFor(input, choice, instructions, shrink = 1) {
351
+ return this.ladder.digestFor(input, choice, instructions, shrink);
253
352
  }
254
- async summarize(state, input, selected, instructions) {
255
- let choice = selected.choice;
256
- let digest = selected.digest;
257
- // WHAT THE NEXT ATTEMPT IS TOLD WENT WRONG: only a rejection of the model's own
258
- // output. A request that never got an answer (`transportFailure`) is a different
259
- // fact and is tracked apart - framing it as "Previous delta rejected" told a model
260
- // that had never seen the earlier request to correct an error it did not make
261
- // (compaction-network-error-fetch-failed RC-4).
262
- let previousError;
263
- let transportFailure = null;
264
- for (let attempt = 0; attempt < 2; attempt += 1) {
265
- if (state.operation.signal.aborted)
266
- throw new Error('aborted');
267
- if (attempt > 0 && this.shouldEscalate(choice, transportFailure)) {
268
- choice = this.mainChoice();
269
- digest = this.digestFor(input, choice, instructions);
270
- }
271
- const answer = await this.callOnce(state, choice, {
272
- digest: digest.text, hasPriorSummary: !!input.prior,
273
- ...(instructions ? { instructions } : {}),
274
- ...(previousError ? { validationError: previousError } : {}),
275
- }).then((reply) => ({ text: reply, transport: null }), (error) => {
276
- const transport = describeTransportFailure(error, state.operation.signal);
277
- if (transport === null)
278
- previousError = errorText(error);
279
- return { text: null, transport };
280
- });
281
- transportFailure = answer.transport;
282
- if (state.operation.signal.aborted)
283
- throw new Error(previousError ?? 'aborted');
284
- const text = answer.text;
285
- if (text === null)
286
- continue;
287
- try {
288
- const delta = parseMemoryDelta(text);
289
- validateMemoryDelta(delta, { sourceMap: digest.sourceMap, prior: input.prior,
290
- hasSummarizableMessages: digest.coverage.summarizedMessages > 0 });
291
- return mergeMemory({ input, delta, sourceMap: digest.sourceMap, coverage: digest.coverage });
292
- }
293
- catch (error) {
294
- previousError = errorText(error);
295
- if (!/invalid_memory_delta|empty_memory_delta/.test(previousError))
296
- throw error;
297
- }
298
- }
299
- // THE LAST ATTEMPT'S KIND DECIDES THE REASON: a failure to reach the summarizer must
300
- // settle as `summarizer_unreachable` even when an earlier attempt got an unusable
301
- // answer, otherwise it would be counted as "no progress" and push toward a pause.
302
- if (transportFailure !== null)
303
- throw new Error(transportFailure);
304
- throw new Error(previousError ?? 'invalid_memory_delta');
353
+ /** Whether the multi-turn path is both configured and wired. */
354
+ agentic() {
355
+ const enabled = this.agenticOverride ?? this.deps.getConfig().compaction.agentic;
356
+ return enabled && this.deps.runAgentTurn !== undefined;
305
357
  }
306
358
  /**
307
- * Whether the second attempt moves to the main model.
359
+ * The retry ladder, built on first use out of this compactor's own primitives.
308
360
  *
309
- * After an unusable answer it always does (a stronger model may do better). After a
310
- * transport failure it only does when the main model is reached through a DIFFERENT
311
- * endpoint: against the same one the switch is a no-op that also rebuilds the digest,
312
- * and the retry should simply be the same request again.
361
+ * and a class field initializer runs before the constructor's parameter
362
+ * session where `compaction.enabled` is false, which never needs it.
313
363
  */
314
- shouldEscalate(current, transportFailure) {
315
- if (transportFailure === null)
316
- return true;
317
- const main = this.mainChoice();
318
- return current.ref.providerId !== main.ref.providerId ||
319
- (current.ref.baseUrl ?? '') !== (main.ref.baseUrl ?? '');
364
+ get ladder() {
365
+ this.ladderCache ??= new SummarizeLadder({
366
+ isAgentic: () => this.agentic(),
367
+ runAgentTurn: (request) => this.runAgentTurn(request),
368
+ getModelInfoFor: (ref) => this.deps.getModelInfoFor(ref),
369
+ emit: (event) => this.deps.emit(event),
370
+ noteUsage: (ref, usage) => this.noteUsage(ref, usage),
371
+ log: this.log,
372
+ callOnce: (state, choice, request) => this.callOnce(state, choice, request),
373
+ mainChoice: () => this.mainChoice(),
374
+ });
375
+ return this.ladderCache;
376
+ }
377
+ /** The one agent-turn port, refused rather than asserted when it is absent. */
378
+ async runAgentTurn(request) {
379
+ const runTurn = this.deps.runAgentTurn;
380
+ if (!runTurn)
381
+ throw new Error('agent_unavailable');
382
+ return runTurn(request);
383
+ }
384
+ /** The retry ladder (W2): its table, its attempts and its ceilings are the ladder's. */
385
+ async summarize(state, input, selected, instructions) {
386
+ return this.ladder.summarize(state, input, selected, instructions);
320
387
  }
321
388
  async callOnce(state, choice, input) {
322
389
  const apiKey = this.deps.getApiKey(choice.ref.providerId, choice.role);
@@ -423,7 +490,7 @@ export class Compactor {
423
490
  : { retainedMessages: state.retainedMessages }),
424
491
  };
425
492
  }
426
- finishRecord(state, outcome, summary) {
493
+ finishRecord(state, outcome, summary, modeOverride) {
427
494
  if (this.active !== state)
428
495
  return;
429
496
  // A DECLINE IS COUNTED EVEN WHEN IT HAS A CARD, so `/compact status` and the
@@ -435,7 +502,8 @@ export class Compactor {
435
502
  const p = state.pressure;
436
503
  const record = {
437
504
  index: state.index, trigger: state.trigger,
438
- mode: outcome.action === 'replace' ? 'summarized' : 'none', applied: false,
505
+ mode: modeOverride ?? (outcome.action === 'replace' ? 'summarized' : 'none'),
506
+ applied: false,
439
507
  ...(outcome.action === 'keep' ? { reason: outcome.reason } : {}),
440
508
  messagesBefore: state.messages.length,
441
509
  messagesAfter: outcome.action === 'replace' ? outcome.messages.length : state.messages.length,
@@ -444,25 +512,58 @@ export class Compactor {
444
512
  memoryVersion: 2,
445
513
  ...this.relaxedFields(state),
446
514
  ...(state.elided ? { elidedMessages: state.elided } : {}),
515
+ ...(state.prune && state.prune.actions.length > 0 ? { prune: this.pruneRecord(state.prune) } : {}),
516
+ ...(state.agent ? { agent: state.agent } : {}),
517
+ ...(state.stoppedBy ? { stoppedBy: state.stoppedBy } : {}),
518
+ // THE BUDGET IS DISCLOSED ON EVERY ATTEMPT THAT SPENT ANYTHING, including
519
+ // one that failed - the money is gone either way, and "what did this cost"
520
+ // must be answerable from the card that cost it.
521
+ ...(state.budget.snapshot().spentTokens > 0 ? { budget: state.budget.snapshot() } : {}),
447
522
  decision: { occupied: p.occupied, contextWindow: p.contextWindow,
448
523
  threshold: state.threshold,
449
524
  source: p.source, deltaTokens: p.deltaTokens },
450
525
  };
451
526
  this.deps.emit({ type: 'compaction_end', record });
452
527
  }
528
+ /** The prune tally in record shape, with the per-kind counters the card shows. */
529
+ pruneRecord(plan) {
530
+ const kinds = {};
531
+ for (const action of plan.actions) {
532
+ kinds[action.kind] = (kinds[action.kind] ?? 0) + 1;
533
+ }
534
+ return {
535
+ actions: plan.actions.length,
536
+ removedChars: plan.removedChars,
537
+ removedTokens: plan.removedTokens,
538
+ kinds,
539
+ inspected: plan.scanned,
540
+ };
541
+ }
453
542
  /** Commit only the engine/host verdict; candidates have no authority before this point. */
454
543
  settleOperation(verdict) {
455
544
  const state = this.active;
456
545
  if (!state || !state.operation.settle())
457
546
  return false;
458
547
  this.active = null;
548
+ this.settled = state;
459
549
  if (verdict.applied && state.candidate) {
460
- this.identity = createCompactionIdentity(state.candidate);
461
- this.generation = state.generation ?? this.generation;
550
+ // IDENTITY ONLY WHEN A SUMMARY WAS APPLIED. A prune-only splice keeps the
551
+ // history's own prefix, so the adopted identity is the one already held -
552
+ // and there may be none at all, because most histories that get pruned have
553
+ // never been compacted before (`createCompactionIdentity` throws on a
554
+ // candidate whose second message is not a compacted block). `state.generation`
555
+ // is set exactly on the summarize path, which makes it the discriminator
556
+ // rather than a guess about the candidate's shape.
557
+ if (state.generation !== undefined) {
558
+ this.identity = createCompactionIdentity(state.candidate);
559
+ this.generation = state.generation;
560
+ }
462
561
  this.appliedCompactions += 1;
463
562
  this.recordApplied(verdict.tokensBefore ?? state.pressure.occupied, verdict.tokensAfter);
464
563
  // A summary came back, so the path to the summarizer works.
465
564
  this.consecutiveTransportFailures = 0;
565
+ this.consecutiveSemanticFailures = 0;
566
+ this.applyPruneTotals(state);
466
567
  this.meter().onHistorySpliced();
467
568
  const projected = (verdict.tokensAfter + (state.pressure.estimateOffset ?? 0)) /
468
569
  state.pressure.contextWindow;
@@ -498,7 +599,8 @@ export class Compactor {
498
599
  * summarizer, which proves the path works, so the transport streak ends.
499
600
  */
500
601
  noteFailure(trigger, reason) {
501
- if (compactionReasonCode(reason) === TRANSPORT_FAILURE_CODE) {
602
+ const code = compactionReasonCode(reason);
603
+ if (code === TRANSPORT_FAILURE_CODE) {
502
604
  this.noteTransportFailure(trigger, reason);
503
605
  return;
504
606
  }
@@ -506,8 +608,40 @@ export class Compactor {
506
608
  return;
507
609
  if (trigger !== 'manual')
508
610
  this.consecutiveTransportFailures = 0;
611
+ // `manager_timeout` IS A CEILING, NOT A FAILURE (P0-2 / R-2). The engine cut
612
+ // the operation because the whole compaction ran past 120 s; counting that as
613
+ // "no progress" would pause auto-compaction after two slow histories, which is
614
+ // exactly the outcome `agentDeadlineMs` exists to prevent.
615
+ if (code === 'manager_timeout') {
616
+ this.log.warn('compaction_manager_timeout', { trigger, reason });
617
+ return;
618
+ }
619
+ // A SEMANTIC failure means the path to the model WORKS (it answered), so it
620
+ // gets its own, larger counter instead of the 2-strike structural one.
621
+ if (code === 'invalid_memory_delta' || code === 'empty_memory_delta'
622
+ || code === 'agent_incomplete' || code === 'turn_limit') {
623
+ this.noteSemanticFailure(trigger, reason);
624
+ return;
625
+ }
509
626
  this.noteNoProgress(trigger, reason);
510
627
  }
628
+ /**
629
+ * The third counter (W2): "the model answered, and we could not use the answer".
630
+ *
631
+ * SEPARATE FROM `stuckLimit` ON PURPOSE. Sharing one counter meant two unusable
632
+ * deltas - the common shape of a bad summarizer on a long band - paused
633
+ * auto-compaction for the rest of the run, even though every one of those
634
+ * attempts proved the transport, the key and the model all worked.
635
+ */
636
+ noteSemanticFailure(trigger, reason) {
637
+ if (trigger === 'manual')
638
+ return;
639
+ this.consecutiveSemanticFailures += 1;
640
+ if (this.consecutiveSemanticFailures < COMPACTION_LIMITS.semanticStuckLimit ||
641
+ this.selfDisabled)
642
+ return;
643
+ this.selfDisable(trigger, reason);
644
+ }
511
645
  noteTransportFailure(trigger, reason) {
512
646
  if (trigger === 'manual')
513
647
  return;
@@ -539,23 +673,66 @@ export class Compactor {
539
673
  this.deps.notify('warn', `Auto-compaction paused: ${compactionReasonLine(reason)}. History preserved. Use /compact.`);
540
674
  }
541
675
  measure(_probe) { return this.meter().current(); }
676
+ /**
677
+ * Fold one applied operation's pruning into the session totals (W1).
678
+ *
679
+ * COUNTED ONLY WHEN THE SPLICE LANDED, for the same reason `tokensReclaimed`
680
+ * is: a candidate the engine refused reclaimed nothing, so reporting its saving
681
+ * would be a number the history never benefited from.
682
+ */
683
+ applyPruneTotals(state) {
684
+ if (!state.prune)
685
+ return;
686
+ this.prunedActions += state.prune.actions.length;
687
+ this.prunedChars += state.prune.removedChars;
688
+ }
689
+ /** The last operation's budget snapshot and agent effort, for `/compact status`. */
690
+ lastSettled() {
691
+ return this.settled;
692
+ }
693
+ /**
694
+ * The settled operation's prune detail, for the archive (W1).
695
+ *
696
+ * THE RECORD CARRIES COUNTS ONLY, because it is dispatched into the reducer and
697
+ * retained in view state; the per-action detail (`messageIndex`, `sourceId`,
698
+ * `removedChars`) is what makes an audit of a pruned body possible and belongs
699
+ * on disk, not in React state (RV-3's rule for the dropped history).
700
+ */
701
+ lastPruneActions() {
702
+ const plan = this.settled?.prune;
703
+ if (!plan)
704
+ return [];
705
+ return plan.actions.map((action) => ({
706
+ kind: action.kind,
707
+ messageIndex: action.messageIndex,
708
+ sourceId: action.sourceId,
709
+ ...(action.keptIndex === undefined ? {} : { keptIndex: action.keptIndex }),
710
+ removedChars: action.removedChars,
711
+ clipped: action.clipped,
712
+ }));
713
+ }
542
714
  lastMeasured() { return this.meter().lastPublished(); }
543
715
  recordApplied(tokensBefore, tokensAfter) {
544
716
  this.tokensReclaimed += Math.max(0, tokensBefore - tokensAfter);
545
717
  }
546
718
  sessionTotals() {
719
+ const last = this.lastSettled();
547
720
  return { compactions: this.compactions, applied: this.appliedCompactions,
548
721
  declined: this.declined,
549
722
  tokensReclaimed: this.tokensReclaimed, usage: this.sessionUsage, costUsd: this.costUsd,
550
723
  pricingUnknown: this.pricingUnknown, inFlight: this.active !== null,
551
724
  selfDisabled: this.selfDisabled, generation: this.generation,
552
- ...(this.selfDisabledReason ? { selfDisabledReason: this.selfDisabledReason } : {}) };
725
+ ...(this.selfDisabledReason ? { selfDisabledReason: this.selfDisabledReason } : {}),
726
+ prune: { actions: this.prunedActions, chars: this.prunedChars },
727
+ ...(last ? { budget: last.budget.snapshot() } : {}),
728
+ ...(last?.agent ? { agent: last.agent } : {}) };
553
729
  }
554
730
  clearSelfDisable() {
555
731
  this.selfDisabled = false;
556
732
  this.selfDisabledReason = undefined;
557
733
  this.consecutiveNoProgress = 0;
558
734
  this.consecutiveTransportFailures = 0;
735
+ this.consecutiveSemanticFailures = 0;
559
736
  }
560
737
  isSelfDisabled() { return this.selfDisabled; }
561
738
  resolveSummarizer() {
@@ -596,6 +773,16 @@ export class Compactor {
596
773
  return JSON.stringify([config.provider, config.model, config.baseUrl, config.compaction,
597
774
  this.deps.getSystemPrompt()]);
598
775
  }
776
+ /**
777
+ * The ONE accounting entry for spend (P1-5).
778
+ *
779
+ * `onUsage` is the only callback every real call funnels through - the agent's
780
+ * turns, the single-shot fallback and core's own `withRetry` attempts - so the
781
+ * BUDGET IS CHARGED HERE and nowhere else. Putting the charge inside
782
+ * `runMemoryAgent` instead would have left the D-14 fallback un-metered, which
783
+ * would have made "default unlimited, adjustable" a promise that only held for
784
+ * models that support tools.
785
+ */
599
786
  noteUsage(ref, usage) {
600
787
  this.sessionUsage = accumulateUsage(this.sessionUsage, usage);
601
788
  const pricingUnknown = !this.deps.isPricedModel(ref);
@@ -603,6 +790,12 @@ export class Compactor {
603
790
  if (pricingUnknown)
604
791
  this.pricingUnknown = true;
605
792
  this.costUsd += costUsd;
793
+ this.active?.budget.charge({ usage, costUsd, pricingUnknown });
794
+ if (pricingUnknown && this.deps.getConfig().compaction.budgetUsd > 0) {
795
+ // D-9: THE DOLLAR GATE IS EXPLICITLY OFF, and silence here would present a
796
+ // ceiling that is not being enforced as if it were.
797
+ this.log.info('compaction_budget_price_unknown', { model: ref.modelId });
798
+ }
606
799
  this.deps.emit({ type: 'usage', usage, modelRef: ref, costUsd, pricingUnknown });
607
800
  }
608
801
  }
@@ -36,6 +36,7 @@ export function formatContextReport(ctx) {
36
36
  lines.push(` Window ${windowLine(usage)}`);
37
37
  lines.push(` Since measured ${freshnessLine(usage)}`);
38
38
  lines.push(` Compaction ${compactionLine(ctx)}`);
39
+ lines.push(` Compact budget ${budgetLine(ctx)}`);
39
40
  lines.push(` Session spend ${spendLine(ctx)}`);
40
41
  // THE SENTENCE THAT MAKES THE LINE ABOVE HONEST (D-7 / N-3). The session
41
42
  // total folds in subagents, the fast tier and compaction's own summarization
@@ -168,6 +169,26 @@ function compactionLine(ctx) {
168
169
  return (`on - ${thresholds}, ${count} this session, ` +
169
170
  `${formatTokens(snapshot.tokensReclaimed)} reclaimed`);
170
171
  }
172
+ /**
173
+ * `none (unlimited)` / `42.3k / 200k tokens, $0.11 / $0.50` (W3).
174
+ *
175
+ * ONE LINE, AND IT ANSWERS BOTH HALVES: what the ceiling is and what the last
176
+ * operation spent against it. A session that has not compacted yet still shows
177
+ * the ceiling, because "may this spend anything" is answerable before it does.
178
+ */
179
+ function budgetLine(ctx) {
180
+ const config = ctx.controller.getCompactionConfig();
181
+ const budget = ctx.controller.getCompactionSnapshot().budget;
182
+ const tokens = config.budgetTokens > 0
183
+ ? `${formatTokens(config.budgetTokens)} tokens/operation` : 'tokens unlimited';
184
+ const usd = config.budgetUsd > 0
185
+ ? `${formatCost(config.budgetUsd)}/operation` : 'USD unlimited';
186
+ if (!budget)
187
+ return `${tokens}, ${usd} (nothing spent yet)`;
188
+ const spent = `${formatTokens(budget.spentTokens)} tokens` +
189
+ (budget.priceUnknown ? ', USD n/a' : `, ${formatCost(budget.spentUsd)}`) + ' last operation';
190
+ return `${spent} - ${tokens}, ${usd}`;
191
+ }
171
192
  /**
172
193
  * `1.24M in (incl. 940k cache read, 12k cache write) / 48.2k out, $3.21`
173
194
  *
@@ -0,0 +1,32 @@
1
+ import type { PreparedMemoryInput } from './memory-input.js';
2
+ import type { DigestResult } from './digest.js';
3
+ /** Bumped when the wording changes, never when the tool schemas change. */
4
+ export declare const MEMORY_AGENT_BLOCK_VERSION = "v3-2026-11";
5
+ export interface MemoryAgentPromptInput {
6
+ /** Character ceiling of the answer this agent is asked to produce. */
7
+ maxChars: number;
8
+ /** The user's `/compact <instructions>` focus, when they typed one. */
9
+ instructions?: string;
10
+ /** Whether a prior memory block exists (changes only one sentence). */
11
+ hasPrior: boolean;
12
+ /** The receipt from the previous failed turn, when this is a repair. */
13
+ repairHint?: string;
14
+ }
15
+ /**
16
+ * The system prompt: the flow, the two hard boundaries a model can predict, and
17
+ * nothing else. Target is 700 characters; it is assembled from parts so the
18
+ * optional ones cost nothing when absent.
19
+ */
20
+ export declare function buildMemoryAgentSystemPrompt(input: MemoryAgentPromptInput): string;
21
+ /**
22
+ * The first user message: a MAP OF THE BAND, never the digest body (P1-4).
23
+ *
24
+ * THE WHOLE POINT OF THE AGENT IS THAT THE FIRST REQUEST IS SMALL. Sending the
25
+ * digest here would put back every token the multi-turn design saves - and the
26
+ * window projection in `digestFor` would still have to fit it, which is the gate
27
+ * this path exists to escape. So the opening names the range, the counts and the
28
+ * prior memory's size, then points at `compaction_outline`.
29
+ */
30
+ export declare function buildMemoryAgentOpening(input: PreparedMemoryInput, digest: DigestResult): string;
31
+ /** The ceiling the delta text is measured against; one place, so tests pin it. */
32
+ export declare function memoryAgentMaxChars(): number;