pi-braid 0.42.1 → 0.43.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  6. package/dist/extensions/core/polyfill/index.js +34 -131
  7. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  8. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  9. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  10. package/dist/extensions/enforcement/session-health.js +75 -5
  11. package/dist/extensions/enforcement/whisper.js +15 -1
  12. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  13. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  18. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  19. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  20. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  21. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  22. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  23. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  24. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  25. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  26. package/dist/extensions/self/watchdog/engine.js +25 -2
  27. package/dist/extensions/self/watchdog/index.js +14 -1
  28. package/dist/lib/ai/llm-call.js +23 -0
  29. package/dist/lib/ai/model-resolver.d.ts +11 -10
  30. package/dist/lib/ai/model-resolver.js +16 -19
  31. package/dist/lib/ai/presend-budget.d.ts +68 -0
  32. package/dist/lib/ai/presend-budget.js +83 -0
  33. package/dist/lib/config/braid-settings.d.ts +38 -0
  34. package/dist/lib/config/braid-settings.js +84 -0
  35. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  36. package/dist/lib/config/per-tool-settings.js +4 -4
  37. package/dist/lib/detection/context-tiers.d.ts +18 -5
  38. package/dist/lib/detection/context-tiers.js +51 -33
  39. package/dist/lib/detection/context-usage.d.ts +62 -1
  40. package/dist/lib/detection/context-usage.js +158 -1
  41. package/dist/lib/errors/llm-error.d.ts +14 -0
  42. package/dist/lib/errors/llm-error.js +44 -1
  43. package/dist/lib/state/global-state.d.ts +4 -8
  44. package/dist/lib/state/global-state.js +11 -28
  45. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  46. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  47. package/dist/lib/utils/wake-gate.d.ts +6 -0
  48. package/dist/lib/utils/wake-gate.js +52 -4
  49. package/docs/SETUP.md +7 -6
  50. package/package.json +8 -11
  51. package/src/extensions/core/polyfill/index.ts +29 -157
  52. package/src/extensions/enforcement/AGENTS.md +38 -1
  53. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  54. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  55. package/src/extensions/enforcement/session-health.ts +94 -5
  56. package/src/extensions/enforcement/whisper.ts +15 -1
  57. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  58. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  59. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  60. package/src/extensions/memory/AGENTS.md +37 -38
  61. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  62. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  63. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  64. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  65. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  66. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  67. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  68. package/src/extensions/self/watchdog/engine.ts +30 -2
  69. package/src/extensions/self/watchdog/index.ts +13 -1
  70. package/src/lib/ai/AGENTS.md +2 -0
  71. package/src/lib/ai/llm-call.ts +30 -0
  72. package/src/lib/ai/model-resolver.ts +16 -19
  73. package/src/lib/ai/presend-budget.ts +117 -0
  74. package/src/lib/config/braid-settings.ts +125 -0
  75. package/src/lib/config/per-tool-settings.ts +4 -4
  76. package/src/lib/detection/context-tiers.ts +52 -41
  77. package/src/lib/detection/context-usage.ts +211 -2
  78. package/src/lib/errors/llm-error.ts +55 -1
  79. package/src/lib/state/global-state.ts +11 -29
  80. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  81. package/src/lib/utils/wake-gate.ts +59 -4
@@ -26,13 +26,9 @@ import { analyzeSession } from "../../analysis.js";
26
26
  import * as timerMod from "../../../../scheduling/timer/index.js";
27
27
  import { getState } from "../../../../enforcement/state.js";
28
28
  import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../../../lib/detection/context-thresholds.js";
29
- import {
30
- turnBoundaryMayAbortRun,
31
- type TurnBoundary,
32
- } from "../../../../../lib/events/turn-boundary.js";
33
29
  import { getCmState, isCompactionActive, log, recordNavigationAction } from "../shared.js";
34
30
  import { snapBoundaryOutsideToolBatch } from "../tool-batch-boundary.js";
35
- import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
31
+ import { formatTokensK, tokenArms } from "../../../../../lib/detection/context-usage.js";
36
32
  import { formatLocalTime } from "../../../../../lib/utils/local-time.js";
37
33
  import {
38
34
  getAutoCompactConfig,
@@ -95,30 +91,29 @@ function optionalNumber(v: unknown): number | undefined {
95
91
  // Batch-settle compaction scheduler.
96
92
  // Contract: the tool returns its result FIRST (execute() resolves before a
97
93
  // compaction is armed), but ctx.compact() — which aborts the turn — fires only
98
- // at a boundary where the abort cannot tear live work: agent_settled (the run
99
- // fully settled, abort a clean no-op), or a turn_end that reads as loop-done.
100
- // The rule that decides the second case lives in one place
101
- // (lib/events/turn-boundary.ts) and is shared with the hygiene act, because a
102
- // copy of it drifts silently. Read the residual there too: a loop-done stop
103
- // reason is necessary, not sufficient. The loop still dispatches when a tool
104
- // call rides a non-"toolUse" stop reason, and when a steer is queued at any
105
- // boundary (pi polls steering after the turn_end emit), so a boundary this
106
- // rule accepts can still reach the abort it exists to avoid. The 0.90W hard
107
- // backstop is the one deliberate mid-loop cut, kept for a loop whose usage must
108
- // not be allowed to overflow. A boundary with a tool call still active is
109
- // unsafe for a further reason: a parallel sibling's result has not been
110
- // delivered, so the abort drops it while the agent is still streaming its
111
- // response to the context_compress result, surfacing a spurious "This operation
112
- // was aborted" error in the TUI and tearing the finishing turn. agent_settled
113
- // alone never drains a run kept alive by continuous steers, so the armed
114
- // compaction stalls behind live work while usage keeps climbing, hence the
115
- // turn_end boundary. The arm side asks the same question, from the one arm site
116
- // that can see a boundary: the heartbeat's usage-driven auto-arm runs inside a
117
- // turn_end dispatch and hands that event in, so a live-loop boundary below the
118
- // 0.90W backstop leaves its entry queued for the next loop-done boundary (pinned
119
- // end to end by test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs).
120
- // Arming inside a tool call has no boundary to read, and its own call id parks
121
- // the queue there anyway.
94
+ // where no request can be in flight. `agent_settled` is that place: pi-core
95
+ // emits it after the run-active flag is cleared, so the abort is a clean no-op
96
+ // and the post-compaction resume wake lands on an idle session.
97
+ //
98
+ // `turn_end` is not that place. Its handlers return before the loop polls its
99
+ // STEERING QUEUE, and a non-empty poll dispatches another request in the same
100
+ // tick; a queued steer is enough. The loop's dispatch decision lives in that
101
+ // queue, not in the assistant message's stop reason, so no reading of the
102
+ // boundary can prove the run has nothing left to do. A drain here fires
103
+ // `ctx.compact()` into the request the steer created, and `AgentSession.compact()`
104
+ // aborts it first: the run ends with "This operation was aborted", not with
105
+ // the answer the steer asked for.
106
+ //
107
+ // The one deliberate exception is the 0.90W hard backstop. A run that never
108
+ // settles (continuous steers, a long tool loop) would otherwise reach overflow
109
+ // with the queue still armed, and an overflow costs more than the turn this
110
+ // abort can lose. Above that arm the queue drains at a turn boundary.
111
+ //
112
+ // A batch with a tool call still active is unsafe for a further reason: a
113
+ // parallel sibling's result has not been delivered, so the abort drops it
114
+ // while the agent is still streaming its response to the context_compress
115
+ // result. The backstop refuses to fire while the active set is non-empty;
116
+ // `agent_settled` clears whatever is left and then drains.
122
117
  //
123
118
  // Active work is tracked by TOOL CALL ID, never by a count: tool_execution_start
124
119
  // registers an id, tool_execution_end deletes its own, and a turn boundary
@@ -184,8 +179,8 @@ function getBatchSettleState(ctx: any): BatchSettleState {
184
179
  /**
185
180
  * Release the call ids a turn's persisted tool results account for. A result
186
181
  * with no usable id is ignored: an unmatched active id stays protective, so a
187
- * malformed event can only delay a drain to a later boundary or the settle
188
- * backstop, never release a sibling that is still executing.
182
+ * malformed event can only delay a drain to the settle backstop, never
183
+ * release a sibling that is still executing.
189
184
  */
190
185
  function releaseSettledToolCallIds(st: BatchSettleState, toolResults: unknown): void {
191
186
  if (!Array.isArray(toolResults)) return;
@@ -226,8 +221,8 @@ export function hasPendingLlmCompaction(ctx: any): boolean {
226
221
 
227
222
  /**
228
223
  * One pending-state line for the armed-but-unfired compaction queue
229
- * ("slide armed 17:28 — fires at the next turn boundary; live usage drops
230
- * when it lands"). Null when nothing is pending: no surface may fabricate an
224
+ * ("slide armed 17:28 — fires when the run settles; live usage drops when it
225
+ * lands"). Null when nothing is pending: no surface may fabricate an
231
226
  * expectation of a drop that is not armed. Shared by context_inspect and the
232
227
  * heartbeat advisory so both state the same fact the same way.
233
228
  */
@@ -238,7 +233,7 @@ export function formatPendingCompactionsLine(ctx: any): string | null {
238
233
  const kinds = [...new Set(pending.map((p) => p.kind))].join("+");
239
234
  const armedClock = formatLocalTime(new Date(newest.armedAt));
240
235
  return (
241
- `${kinds} armed ${armedClock} — fires at the next turn boundary (turn end or run settle); ` +
236
+ `${kinds} armed ${armedClock} — fires when the run settles (or at the 0.90W backstop); ` +
242
237
  `until then live usage reads pre-compaction state`
243
238
  );
244
239
  }
@@ -336,21 +331,7 @@ export function scheduleDegradedCompact(trigger: () => void): void {
336
331
  }
337
332
 
338
333
  /**
339
- * Whether an arm may fire its own entry. Firing a compact aborts whatever run
340
- * is live, so an arm that happens inside a turn boundary dispatch hands that
341
- * boundary in and is judged by the same rule the TURN_END handler applies
342
- * (the rule lives in lib/events/turn-boundary.ts; it owns the "no boundary
343
- * known" case, which fires). Every other arm site runs inside a tool call,
344
- * where there is no boundary to read and the prior contract stands: the arm
345
- * drains unless a batch is still active (the arm's own call id keeps it
346
- * parked, so it does not fire there).
347
- */
348
- function armMayDrainNow(boundary: TurnBoundary | undefined, ctx: any): boolean {
349
- return turnBoundaryMayAbortRun(boundary, () => captureUsage(ctx));
350
- }
351
-
352
- /**
353
- * Arm a one-shot compaction at a safe boundary (next turn end or run settle).
334
+ * Arm a one-shot compaction for the settle drain (or the 0.90W backstop).
354
335
  * Returns "pending-exists" when an LLM-class compaction is already armed: the
355
336
  * caller must NOT have written its own range/anchor state in that case (the
356
337
  * drain fires the first-armed trigger with the FIRST declaration's state).
@@ -367,7 +348,6 @@ function scheduleCompactionAtBatchSettle(
367
348
  meta: { kind: PendingCompaction["kind"]; cutEntryId?: string; firstKeptEntryId?: string } = {
368
349
  kind: "compact",
369
350
  },
370
- boundary?: TurnBoundary,
371
351
  ): "queued" | "pending-exists" {
372
352
  const trigger = () => {
373
353
  try {
@@ -389,7 +369,7 @@ function scheduleCompactionAtBatchSettle(
389
369
  if (isLlmClass(meta.kind) && st.pending.some((p) => isLlmClass(p.kind))) {
390
370
  log.info(
391
371
  `[context-compress] ${meta.kind} arm refused: an LLM-class compaction is ` +
392
- `already armed and will fire at the next boundary.`,
372
+ `already armed and will fire when the run settles.`,
393
373
  );
394
374
  return "pending-exists";
395
375
  }
@@ -401,13 +381,11 @@ function scheduleCompactionAtBatchSettle(
401
381
  ` (cap ${PENDING_COMPACT_QUEUE_MAX}); the first-armed entry still fires.`,
402
382
  );
403
383
  }
404
- // Arming fires only where that is safe. Firing a compaction aborts whatever
405
- // run is live, and an arm site is not in a position to tell: the tool path
406
- // arms inside its own call (whose id parks the queue anyway), and the
407
- // heartbeat's arm runs inside a turn_end dispatch, where whether the loop
408
- // still has work to dispatch is a fact the event carries. That caller hands
409
- // its boundary in; every other caller keeps the prior contract.
410
- if (armMayDrainNow(boundary, ctx)) firePendingCompactionsIfSettled(ctx, st);
384
+ // Arming never fires. Every arm site runs while the run is live - inside
385
+ // the tool call that asked for it, or inside the heartbeat's turn_end
386
+ // dispatch - and no arm site can see the steering queue that decides
387
+ // whether another request follows. The entry waits for the settle drain or
388
+ // the 0.90W backstop.
411
389
  return "queued";
412
390
  } catch {
413
391
  // Degraded path: batch-settle bookkeeping is unavailable (extension state
@@ -429,14 +407,13 @@ function scheduleCompactionAtBatchSettle(
429
407
  * and the usage-driven auto-arm, so both produce the same cut shape: the
430
408
  * boundary is snapped out of any tool batch, the slide state is persisted for
431
409
  * the SLIDE_MODE compaction branch, an audit entry is appended, and the
432
- * trigger is queued for the next safe boundary. Returns null when the branch
433
- * is not longer than the keep window (nothing to slide).
410
+ * trigger is queued for the settle drain. Returns null when the branch is not
411
+ * longer than the keep window (nothing to slide).
434
412
  */
435
413
  function armSlideCompaction(
436
414
  pi: ExtensionAPI,
437
415
  ctx: any,
438
416
  keepCount: number,
439
- boundary?: TurnBoundary,
440
417
  ): { cutEntryId: string; keptCount: number; droppedCount: number } | null {
441
418
  const sm = ctx.sessionManager;
442
419
  if (!sm || typeof sm.getBranch !== "function") return null;
@@ -493,7 +470,6 @@ function armSlideCompaction(
493
470
  ctx,
494
471
  { customInstructions: "SLIDE_MODE:true" },
495
472
  { kind: "slide", cutEntryId },
496
- boundary,
497
473
  );
498
474
  return { cutEntryId, keptCount, droppedCount };
499
475
  }
@@ -523,23 +499,19 @@ function getAutoArmState(ctx: any): AutoArmState {
523
499
  * Usage-driven auto-arm: when live usage sits above the configured threshold
524
500
  * for `confirmTicks` consecutive observations, arm ONE deterministic slide so
525
501
  * a session that never gets a manual cleanup still gets relief. Reuses the
526
- * accounting context_inspect computes (analyzeSession), the same pending
527
- * queue the tool arms drain through, and the same boundary discipline: arming
528
- * only queues; the compaction itself still fires at the next turn boundary or
529
- * settle, never mid-run.
502
+ * accounting context_inspect computes (analyzeSession) and the same pending
503
+ * queue the tool arms drain through: arming only queues; the compaction itself
504
+ * fires when the run settles (or at the 0.90W backstop), never mid-run.
530
505
  *
531
506
  * Called from the heartbeat tick — the only cadence that runs while a session
532
- * works, and the only arm site that runs inside a turn boundary dispatch. It
533
- * hands that boundary in, so the arm is judged by the same rule the drain
534
- * applies: a "toolUse" boundary below the 0.90W backstop leaves the entry
535
- * queued for the next loop-done boundary instead of aborting the request the
536
- * loop is about to dispatch. Returns what happened and why, so the caller can
537
- * log it.
507
+ * works. Arming only queues: the entry waits for `agent_settled`, because the
508
+ * tick runs while the run is live and nothing at that point can prove the loop
509
+ * has no request left to dispatch. Returns what happened and why, so the
510
+ * caller can log it.
538
511
  */
539
512
  export function maybeArmAutoCompaction(
540
513
  pi: ExtensionAPI,
541
514
  ctx: any,
542
- boundary?: TurnBoundary,
543
515
  ): { armed: boolean; reason: string } {
544
516
  const config: ResolvedAutoCompactConfig = getAutoCompactConfig();
545
517
  if (!config.enabled) return { armed: false, reason: "disabled" };
@@ -560,13 +532,13 @@ export function maybeArmAutoCompaction(
560
532
  }
561
533
  const branchLength = ctx?.sessionManager?.getBranch?.().length ?? 0;
562
534
  const keep = resolveAutoSlideKeep(branchLength);
563
- const armed = armSlideCompaction(pi, ctx, keep, boundary);
535
+ const armed = armSlideCompaction(pi, ctx, keep);
564
536
  st.aboveCount = 0;
565
537
  if (!armed) return { armed: false, reason: "branch-too-short" };
566
538
  log.info(
567
539
  `[context-compress] Auto-arm: usage sustained at ${usage.percent.toFixed(1)}% ` +
568
540
  `(>= ${config.armPercent}% for ${config.confirmTicks} observations) — slide armed ` +
569
- `(${armed.droppedCount} entries before the cut), fires at the next boundary.`,
541
+ `(${armed.droppedCount} entries before the cut), fires when the run settles.`,
570
542
  );
571
543
  return { armed: true, reason: `usage ${usage.percent.toFixed(1)}% sustained` };
572
544
  }
@@ -653,9 +625,9 @@ export const contextCompressSchema = Type.Object({
653
625
 
654
626
  export function registerContextCompress(pi: ExtensionAPI): void {
655
627
  // Batch-settle scheduling: track the ACTIVE tool calls of every running
656
- // batch by call id and fire the deferred compaction only at a safe boundary
657
- // (a loop-done turn_end or agent_settled). Never mid-batch (would drop a
658
- // parallel sibling's result) and never at tool_execution_end (the run is
628
+ // batch by call id and fire the deferred compaction when the run settles
629
+ // (plus the 0.90W backstop at a turn boundary). Never mid-batch (would drop
630
+ // a parallel sibling's result) and never at tool_execution_end (the run is
659
631
  // still live there — an aborting compact would surface a spurious "This
660
632
  // operation was aborted" error and tear the finishing turn).
661
633
  onEvent(pi, TOOL_EXECUTION_START, (event: any, ctx: any) => {
@@ -663,7 +635,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
663
635
  const st = getBatchSettleState(ctx);
664
636
  st.activeToolCallIds.add(toolCallIdOf(event) ?? UNIDENTIFIED_TOOL_CALL);
665
637
  } catch {
666
- // Settle tracking is unavailable — the pending compact then only fires
638
+ // Settle tracking is unavailable — the pending compact then fires only
667
639
  // via AGENT_SETTLED below, which is the conservative path.
668
640
  }
669
641
  });
@@ -676,53 +648,47 @@ export function registerContextCompress(pi: ExtensionAPI): void {
676
648
  // NOTE: do NOT fire here. The run is still active (the agent is
677
649
  // processing this tool's result and streaming its next response); an
678
650
  // aborting compact now would surface a spurious "This operation was
679
- // aborted" error and tear the finishing turn. Safe boundaries are
680
- // turn_end (below) and agent_settled.
651
+ // aborted" error and tear the finishing turn. The settle drain owns the
652
+ // fire.
681
653
  } catch {
682
654
  // Settle tracking unavailable — see TOOL_EXECUTION_START above; the
683
655
  // AGENT_SETTLED handler remains the conservative trigger.
684
656
  }
685
657
  });
686
658
  onEvent(pi, TURN_END, (event: any, ctx: any) => {
687
- // Turn boundary. The turn's assistant message and tool results are already
688
- // persisted here, but that alone does not make the run safe to abort: a
689
- // "toolUse" stop means the loop dispatches its next request the moment the
690
- // handlers return, so the deferred ctx.compact() tears that request
691
- // mid-stream and the compaction replaces the work it was about to do (the
692
- // rule is lib/events/turn-boundary.ts, and its residual section lists the
693
- // two cases a loop-done stop reason does not rule out). Only a loop-done
694
- // boundary drains, except at the 0.90W hard backstop, which exists
695
- // precisely to stop a runaway live loop before it overflows.
659
+ // The 0.90W hard backstop, the ONLY drain that fires while the run may
660
+ // still dispatch. Below it the queue waits for `agent_settled`: the loop
661
+ // polls its steering queue after this dispatch and a single queued steer
662
+ // starts another request, which the deferred ctx.compact() would abort.
663
+ // Above it the overflow is the worse failure: a run kept alive by
664
+ // continuous steers never settles, and without this cut the queue stays
665
+ // armed until the context is gone.
696
666
  //
697
667
  // The persisted results carry the toolCallIds of the calls they answer,
698
668
  // which releases a call whose tool_execution_end never arrived; an active
699
669
  // id with NO result in this event is kept (it may still be executing, and
700
- // a count could not tell which sibling completed). A run kept alive by
701
- // continuous steers never reaches agent_settled — this boundary keeps an
702
- // armed compaction from stalling behind live work. Ids are never blanket-
703
- // reset here (only agent_settled owns that backstop, which is what keeps a
704
- // missed end event from parking the queue forever).
670
+ // a count could not tell which sibling completed). The active set is never
671
+ // blanket-reset here; agent_settled owns that release.
705
672
  try {
706
673
  const st = getBatchSettleState(ctx);
707
674
  releaseSettledToolCallIds(st, event?.toolResults);
708
675
  if (st.pending.length === 0 || st.activeToolCallIds.size > 0) return;
709
676
  if (isCompactionActive(ctx)) return;
710
- if (!turnBoundaryMayAbortRun(event, () => captureUsage(ctx))) return;
677
+ const usage = captureUsage(ctx);
678
+ if (!usage || usage.tokens < tokenArms(usage.contextWindow).backstop) return;
711
679
  firePendingCompactionsIfSettled(ctx, st);
712
680
  } catch {
713
- // A failed boundary drain must not tear the turn_end event pipeline;
714
- // the pending compactions retry on the next boundary.
681
+ // A failed backstop check must not tear the turn_end event pipeline;
682
+ // the queue stays armed for the settle drain.
715
683
  }
716
684
  });
717
685
  onEvent(pi, AGENT_SETTLED, (_event: any, ctx: any) => {
718
- // Backstop boundary: the run has fully settled, so ctx.compact()'s
719
- // abort() is a clean no-op — no spurious abort error, no torn turn, and
720
- // the post-compaction resume wake lands when the session is
721
- // idle/promptable. The whole pending queue drains here (coalesced); the
722
- // active set is cleared so parked compactions always fire even when a
723
- // start never saw its end and no turn boundary ever accounted for it.
724
- // Turn boundaries drain first when a run stays alive; this handler catches
725
- // everything they cannot reach.
686
+ // The one unconditional drain: `agent_settled` is emitted after the run
687
+ // is no longer active, so ctx.compact()'s abort() is a clean no-op — no
688
+ // torn request, and the post-compaction resume wake lands when the
689
+ // session is idle/promptable. The whole pending queue drains here
690
+ // (coalesced), and the active set is cleared first so a parked compaction
691
+ // always fires even when a start never saw its end.
726
692
  try {
727
693
  const st = getBatchSettleState(ctx);
728
694
  st.activeToolCallIds.clear();
@@ -804,7 +770,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
804
770
  ` Before: ${usageLine2}`,
805
771
  ` Keep recent: ${params?.keep ?? "auto"}`,
806
772
  ``,
807
- `Compaction armed; it fires at the next turn boundary (turn end or run settle) — live usage will NOT drop until it lands.`,
773
+ `Compaction armed; it fires when the run settles — live usage will NOT drop until it lands.`,
808
774
  `Agent will resume automatically after compaction completes.`,
809
775
  `Run context_inspect(detail='quick') after resume to verify.`,
810
776
  ].join("\n"),
@@ -886,7 +852,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
886
852
  }
887
853
 
888
854
  // LLM-class dedup: refuse BEFORE any state write. An already-armed
889
- // compaction fires at the next boundary with the FIRST declaration's
855
+ // compaction fires when the run settles with the FIRST declaration's
890
856
  // range; a second arm here would overwrite rangeMode (clobber-class
891
857
  // loss) and queue an entry that can never fire.
892
858
  if (hasPendingLlmCompaction(ctx)) {
@@ -895,7 +861,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
895
861
  {
896
862
  type: "text" as const,
897
863
  text: [
898
- `**Archive skipped — a compaction is already armed and will fire at the next turn boundary.**`,
864
+ `**Archive skipped — a compaction is already armed and will fire when the run settles.**`,
899
865
  `Nothing was recorded for "${topic}"; the pending compaction covers the cleanup.`,
900
866
  `After it lands, re-run this archive if the range still needs a record.`,
901
867
  ].join("\n"),
@@ -1193,8 +1159,8 @@ export function registerContextCompress(pi: ExtensionAPI): void {
1193
1159
  }
1194
1160
  feedbackLines.push(
1195
1161
  "",
1196
- "Compaction is armed and fires at the next turn boundary (turn end or run settle) — it may " +
1197
- "land while the run stays alive; live usage will NOT drop until it fires.",
1162
+ "Compaction is armed and fires when the run settles — live usage " +
1163
+ "will NOT drop until it fires.",
1198
1164
  "Verify after it lands: context_inspect(detail='quick') shows the drop and any still-pending arm.",
1199
1165
  );
1200
1166
 
@@ -1283,7 +1249,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
1283
1249
  }
1284
1250
 
1285
1251
  // LLM-class dedup (same contract as archive): an armed compaction
1286
- // fires at the next boundary; refuse before writing the tag or the
1252
+ // fires when the run settles; refuse before writing the tag or the
1287
1253
  // archive anchor so the first declaration stands unmodified.
1288
1254
  if (hasPendingLlmCompaction(ctx)) {
1289
1255
  return {
@@ -1291,7 +1257,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
1291
1257
  {
1292
1258
  type: "text" as const,
1293
1259
  text: [
1294
- `**Deep clean skipped — a compaction is already armed and will fire at the next turn boundary.**`,
1260
+ `**Deep clean skipped — a compaction is already armed and will fire when the run settles.**`,
1295
1261
  `Nothing was tagged for "${topic}"; the pending compaction covers the cleanup.`,
1296
1262
  ].join("\n"),
1297
1263
  },
@@ -1349,7 +1315,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
1349
1315
  ` 2. ~${count} entries before the tag point, estimated`,
1350
1316
  ` 3. Compaction scheduled${usageLine}`,
1351
1317
  "",
1352
- `Compaction armed; it fires at the next turn boundary (turn end or run settle) — live usage will NOT drop until it lands.`,
1318
+ `Compaction armed; it fires when the run settles — live usage will NOT drop until it lands.`,
1353
1319
  `Agent will resume automatically after compaction completes.`,
1354
1320
  `Run context_inspect(detail='quick') after resume to verify.`,
1355
1321
  "",
@@ -1482,7 +1448,7 @@ export function registerContextCompress(pi: ExtensionAPI): void {
1482
1448
  ` ~${droppedCount} entries before the slide point, estimated`,
1483
1449
  ` Before: ${usageLine}`,
1484
1450
  ``,
1485
- `Compaction armed; it fires at the next turn boundary (turn end or run settle) — live usage will NOT drop until it lands.`,
1451
+ `Compaction armed; it fires when the run settles — live usage will NOT drop until it lands.`,
1486
1452
  `Agent will resume automatically after compaction completes.`,
1487
1453
  `Run context_inspect(detail='quick') after resume to verify.`,
1488
1454
  ].join("\n"),
@@ -202,10 +202,20 @@ retry arming or outcome resolution. Fixture:
202
202
 
203
203
  ### Wake guard settings
204
204
 
205
- | Setting | Default | Effect | Read cadence |
206
- | ----------------------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
207
- | `braid.session.terminalBreaker.threshold` | `3` (enabled by default) | After this many terminal-class LLM errors, a timer wake is delivered as a non-waking steer until a clean turn resets the gate. Set `enabled: false` to disable the breaker. | Re-read at use time, once per fire checked by the breaker. |
208
- | `braid.timers.wakeAlert.mode` | `"on"` | Enables the watchdog wake-delivery alert feed. `"off"` disables alerting only; timer delivery and retries continue unchanged. | Re-read at use time for each alert check. |
205
+ | Setting | Default | Effect | Read cadence |
206
+ | ----------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- |
207
+ | `braid.session.terminalBreaker.threshold` | `3` (enabled by default) | After this many terminal-class LLM errors, a timer wake is delivered as a non-waking steer until a clean turn resets the gate. Set `enabled: false` to disable the breaker. | Re-read at use time, once per fire checked by the breaker. |
208
+ | `braid.session.routeBreaker.enabled` | `true` | Route-failure latch. After `threshold` provider failures of any class except a context-window overflow or an abort since the session's last successful call, a timer wake, a watchdog escalation and an explicitly-waking whisper are delivered non-waking (the text still reaches the session) until a release signal. `false` makes the latch inert. | Re-read at use time, once per fire checked by the breaker. |
209
+ | `braid.session.routeBreaker.threshold` | `3` | Provider failures since the last successful call before the latch opens. Integer 1..20; an invalid value warns once and falls back. | Re-read at use time, once per fire checked by the breaker. |
210
+ | `braid.session.routeBreaker.floorMs` | `3600000` (1h) | While the latch stays open the gate releases exactly one self-started turn per floor and restarts the clock, so a parked session never starves and never loops. Integer 60000..86400000 ms; invalid warns once and falls back. | Re-read at use time, once per fire checked by the breaker. |
211
+ | `braid.timers.wakeAlert.mode` | `"on"` | Enables the watchdog wake-delivery alert feed. `"off"` disables alerting only; timer delivery and retries continue unchanged. | Re-read at use time for each alert check. |
212
+
213
+ `terminalBreakerBlocksWake` opens with `braid.session.terminalBreaker.enabled`, so
214
+ `enabled: false` there restores the pre-gate fire path in full: the fire path then
215
+ asks no turn-start question at all and the route latch has no effect on timer
216
+ wakes either. That precedence is deliberate - the terminal block's documented
217
+ promise is byte-identical pre-gate behaviour - and it is the one interaction
218
+ between the two blocks.
209
219
 
210
220
  The post-compaction stack overflow was caused by `triggerTurn: true` firing **mid-tool-execution**. The fix is the **busy guard** (below). The compaction-resume timer was removed in 2026-07-11 because pi-core's agent loop automatically continues after **auto**-compaction (`_runAutoCompaction()` continues on `willRetry`/overflow or queued messages); the 3-minute fallback timer was firing as spurious noise on that path. That does NOT cover the manual `ctx.compact()` path (agent-initiated `context_compress` tool): manual compaction aborts the loop and never resumes it - the resume there is the enforcement `session_compact` re-orientation whisper with `triggerTurn: true` (see `enforcement/handlers/register-session-compact.ts`), which was verified and fixed 2026-08-02.
211
221
 
@@ -1,28 +1,46 @@
1
1
  <!-- status: current -->
2
2
 
3
- # src/extensions/watchdog/ - Session Health Monitor
3
+ # src/extensions/watchdog/ - Session Health Monitor and Escalation Engine
4
4
 
5
- A **background monitor** that tracks session metrics (uptime, idle time, message
6
- count) and surfaces them via a TUI command. No LLM-callable tools.
7
-
8
- ## Disambiguation: this is NOT the only "watchdog" in the codebase
9
-
10
- This is the only thing called "watchdog" now. Previously there was an
11
- `auto-singleton/` watchdog (an agent-callable inactivity timer), but that
12
- was removed in the 2026-06 tool-inventory audit. The `timer` tool covers the
13
- use case it addressed.
14
-
15
- The Session watchdog is purely a **passive observer** (it doesn't act).
5
+ A **background monitor** with two layers: a passive per-session observer
6
+ (uptime, idle time, message count, surfaced via the `watchdog-status` TUI
7
+ command) and an active engine that detects stall/quota/tunnel/dead-wake
8
+ conditions with no model call and escalates them.
16
9
 
17
10
  ## Files
18
11
 
19
- | File | Purpose |
20
- | ---------- | --------------------------------------------------------------------------------------------------------------------------- |
21
- | `index.ts` | The only file. ~102L. Tracks per-session state in a Map keyed by session file path. Subscribes to `analytics_alert` events. |
12
+ | File | Purpose |
13
+ | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
14
+ | `index.ts` | Extension surface: per-session state, whisper/tg delivery, engine wiring, turn-progress feeds, session shutdown. |
15
+ | `engine.ts` | The state machine: condition latches, milestone ladders, escalation budget, stall classification, wake-delivery feed. |
16
+ | `config.ts` | `broker.watchdog` reader (mode, cadences, thresholds). Defaults live in `engine.ts`; invalid fields fall back to them. |
22
17
 
23
18
  ## Local Contracts
24
19
 
25
- - Module is opt-in (`disabledByDefault: true`).
26
- - Module id: `watchdog` (kebab-case).
27
- - Not LLM-callable. The agent cannot trigger it - only the user can, via the `watchdog-status` command.
20
+ - Default-ON (`manifest.ts` declares no `disabledByDefault`), module id `watchdog`, dependency `agent-environment`.
21
+ - Not LLM-callable: the agent cannot trigger it.
28
22
  - `broker.watchdog` is read when the extension factory loads. Restart the agent after changing it.
23
+
24
+ ## Escalation delivery
25
+
26
+ `fireEscalation` is the one escalation action: a whisper plus an optional
27
+ one-line tg signal. The whisper's delivery class follows the session's
28
+ route-failure latch (`isRouteLatchOpen` from the enforcement health module,
29
+ read once per bark, fail-open):
30
+
31
+ - latch closed: `wakeWhisper` (`triggerTurn: true`) - the bark wakes the agent;
32
+ - latch open: `quietWhisper` - the same text reaches the session on the next
33
+ turn, and the tg line still fires, because the page costs no provider call
34
+ and the turn the bark would have started is the call the latch exists to
35
+ save.
36
+
37
+ The route-failure latch and its settings are documented in
38
+ `extensions/enforcement/AGENTS.md`; fixture:
39
+ `test/runtime/lib/test-route-latch.mjs`.
40
+
41
+ ## Fixtures
42
+
43
+ - `test/runtime/self/test-watchdog-engine.mjs` - condition latches, ladders, budget.
44
+ - `test/runtime/self/test-watchdog-stall-ladder.mjs` - stall classification and remediation.
45
+ - `test/runtime/self/test-watchdog-wake-delivery.mjs` - the timer-to-watchdog dead-wake feed.
46
+ - `test/runtime/self/test-watchdog-unknown-failure-ring.mjs` - unclassified-failure retention.
@@ -20,7 +20,8 @@
20
20
  * 3. tunnel-down: ≥ tunnelFailures consecutive getUpdates failures
21
21
  * (telegram emits the transition; this engine hosts the
22
22
  * confirmation gate + escalation).
23
- * - ESCALATE: waking whisper (wakeWhisper) + optional 1-line tg signal
23
+ * - ESCALATE: waking whisper (wakeWhisper) + optional 1-line tg signal,
24
+ * or the quiet whisper when the session's route latch is open
24
25
  * (tgSignal). The FIRST escalation of an open condition always fires
25
26
  * (threshold crossing). Repeats while the condition stays continuously
26
27
  * open are milestone-throttled so one long outage cannot flood the owner
@@ -228,6 +229,12 @@ export interface WatchdogEngineDeps {
228
229
  /** True when a timer/wake is due for this session: a due wake legitimately
229
230
  * keeps a quiet session quiet, so the turn is not classified dead. */
230
231
  isWakeDue?: (key: string) => boolean;
232
+ /** True when a self-started turn would park right now (the session's route
233
+ * has failed every attempt since its last successful call). An escalation
234
+ * is then delivered through `quietWhisper` while the out-of-band signal
235
+ * still fires — the content is not withdrawn, only the turn it would
236
+ * start. Absent or throwing ⇒ never parked (fail-open). */
237
+ isTurnStartBlocked?: () => boolean;
231
238
  log?: (level: "debug" | "info" | "warn" | "error", message: string, ...rest: unknown[]) => void;
232
239
  }
233
240
 
@@ -484,8 +491,29 @@ export function createWatchdogEngine(
484
491
  return openConditions().length > 0;
485
492
  }
486
493
 
494
+ /**
495
+ * Fail-open read of the turn-start latch. A broken reader costs the gate,
496
+ * never the escalation: the bark still fires, it just wakes.
497
+ */
498
+ function turnStartBlocked(): boolean {
499
+ try {
500
+ return deps.isTurnStartBlocked?.() === true;
501
+ } catch {
502
+ return false;
503
+ }
504
+ }
505
+
487
506
  function fireEscalation(text: string, tg: string): void {
488
- wakeWhisper(text);
507
+ // While the route latch is open a waking bark would spend the very call
508
+ // the gate exists to save. The escalation is not dropped: the same text
509
+ // rides the quiet channel into the session, and the tg line — which costs
510
+ // no provider call — still fires, so the owner keeps the out-of-band
511
+ // signal.
512
+ if (turnStartBlocked()) {
513
+ quietWhisper(text);
514
+ } else {
515
+ wakeWhisper(text);
516
+ }
489
517
  try {
490
518
  tgSignal?.(tg);
491
519
  } catch {
@@ -56,7 +56,7 @@ import {
56
56
  import { loadWatchdogConfig } from "./config.js";
57
57
  import { createWatchdogEngine, type WatchdogEngine } from "./engine.js";
58
58
  import { appendContextHeartbeatLine } from "../../../lib/telemetry/context-heartbeat.js";
59
- import { getSessionHealth } from "../../enforcement/session-health.js";
59
+ import { getSessionHealth, isRouteLatchOpen } from "../../enforcement/session-health.js";
60
60
 
61
61
  const log = createLogger("watchdog");
62
62
 
@@ -310,6 +310,18 @@ export default function (pi: ExtensionAPI) {
310
310
  return false;
311
311
  }
312
312
  },
313
+ // Route-failure latch: the engine asks the health layer, once per
314
+ // escalation, whether a self-started turn would park. While it is
315
+ // open the bark rides the quiet channel and the tg line below still
316
+ // fires (see fireEscalation). Read-only, fail-open: a broken reader
317
+ // must never silence an escalation.
318
+ isTurnStartBlocked: () => {
319
+ try {
320
+ return isRouteLatchOpen(ctx);
321
+ } catch {
322
+ return false;
323
+ }
324
+ },
313
325
  log: (level, message, ...rest) => {
314
326
  switch (level) {
315
327
  case "debug":
@@ -20,11 +20,13 @@ and result parsing.
20
20
  | `llm-call.ts` | Auxiliary LLM calls: dispatched through the session's `ctx.modelRegistry.streamSimple` (pi-core resolves credential, headers, transport), with two-tier retry, backoff, rate-limit circuit breaker, and abort handling. |
21
21
  | `judge-budget.ts` | The consolidated judges' output-budget contract in one place: one judge completion across the model tiers (session → utility) with no `maxTokens` on the first attempt (callLlm sizes it from the prompt), plus exactly one retry at `min(8192, model.maxTokens)` when a completion ends at its own output ceiling without a verdict. Also owns the shared outcome vocabulary (`budget-exhausted` / `unparseable` / `invalid-fields` / `call-error`). Each judge supplies its own reader for the response. |
22
22
  | `payload-hygiene.ts` | Raw-payload hygiene at the LLM-call boundary: error text collapses to one line for logs/returns (status + excerpt + type + size, base64 redacted); request-body hygiene for edge/WAF page dumps plus in-place neutralization of the edge filter's request trigger (a space inserted, text kept). |
23
+ | `presend-budget.ts` | Pre-send budget: the calibrated payload estimate plus the requested output budget against the resolved window, the single actionable refusal line, and the guard that measures, compacts once, re-measures and only then allows the send. Lives here because only the layer that builds a request has all three numbers. |
23
24
  | `model-resolver.ts` | Resolves the merged role (utilityModel) and the deprecated vision alias to catalog models; each accepts a scalar or an ordered list. |
24
25
 
25
26
  ## Local Contracts
26
27
 
27
28
  - All LLM calls should go through `llm-call.ts` for consistent abort/retry behavior.
29
+ - **A request is compared against the window before it is sent.** `presend-budget.ts` owns that comparison (calibrated payload + output budget vs the resolved window); a send path that skips it hands the provider a request that cannot fit and pays a round trip to learn so.
28
30
  - **A consolidated judge (one prompt asking for a JSON verdict) goes through `judge-budget.ts`** - never a hand-rolled `callLlm` with a small explicit `maxTokens`. Thinking tokens count against `max_tokens` on reasoning models and the channel cannot always be switched off, so a small ceiling starves the answer; `judge-budget.ts` owns the budget, the bounded retry, and the tier walk.
29
31
  - All classifications should go through `text-classifier.ts` - it handles the utility-model-first gate via `critic-gate.ts`.
30
32
  - **All post-loop LLM calls (agent_end, post-turn analysis, reflection, etc.) should go through `post-loop-classify.ts`** - it bundles the 4 post-loop guarantees (signal thread, abort demotion, 8s default timeout, onFailure fallback) that hand-rolled callers have repeatedly gotten wrong. See `src/extensions/heartbeat/AGENTS.md` for the abort-handling contract.