pi-braid 0.42.0 → 0.43.0

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 (102) hide show
  1. package/CHANGELOG.md +1077 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
  6. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  7. package/dist/extensions/core/polyfill/index.js +34 -131
  8. package/dist/extensions/core/skills-tool/index.js +47 -26
  9. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  10. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  11. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  12. package/dist/extensions/enforcement/session-health.js +75 -5
  13. package/dist/extensions/enforcement/whisper.js +15 -1
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  18. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  19. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  20. package/dist/extensions/manifest.js +6 -0
  21. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  22. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  23. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  24. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  25. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  26. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  27. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  28. package/dist/extensions/self/path-miss/detect.d.ts +30 -0
  29. package/dist/extensions/self/path-miss/detect.js +67 -0
  30. package/dist/extensions/self/path-miss/index.d.ts +33 -0
  31. package/dist/extensions/self/path-miss/index.js +118 -0
  32. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  33. package/dist/extensions/self/watchdog/engine.js +25 -2
  34. package/dist/extensions/self/watchdog/index.js +14 -1
  35. package/dist/lib/ai/llm-call.js +23 -0
  36. package/dist/lib/ai/model-resolver.d.ts +11 -10
  37. package/dist/lib/ai/model-resolver.js +16 -19
  38. package/dist/lib/ai/presend-budget.d.ts +68 -0
  39. package/dist/lib/ai/presend-budget.js +83 -0
  40. package/dist/lib/config/braid-settings.d.ts +38 -0
  41. package/dist/lib/config/braid-settings.js +84 -0
  42. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  43. package/dist/lib/config/per-tool-settings.js +4 -4
  44. package/dist/lib/core/event-names.d.ts +1 -0
  45. package/dist/lib/core/event-names.js +1 -0
  46. package/dist/lib/detection/context-tiers.d.ts +18 -5
  47. package/dist/lib/detection/context-tiers.js +51 -33
  48. package/dist/lib/detection/context-usage.d.ts +62 -1
  49. package/dist/lib/detection/context-usage.js +158 -1
  50. package/dist/lib/errors/llm-error.d.ts +14 -0
  51. package/dist/lib/errors/llm-error.js +44 -1
  52. package/dist/lib/state/global-state.d.ts +4 -8
  53. package/dist/lib/state/global-state.js +11 -28
  54. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  55. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  56. package/dist/lib/utils/argument-report.d.ts +41 -0
  57. package/dist/lib/utils/argument-report.js +95 -0
  58. package/dist/lib/utils/wake-gate.d.ts +6 -0
  59. package/dist/lib/utils/wake-gate.js +52 -4
  60. package/docs/SETUP.md +7 -6
  61. package/package.json +11 -13
  62. package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
  63. package/src/extensions/core/polyfill/index.ts +29 -157
  64. package/src/extensions/core/skills-tool/index.ts +60 -37
  65. package/src/extensions/enforcement/AGENTS.md +38 -1
  66. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  67. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  68. package/src/extensions/enforcement/session-health.ts +94 -5
  69. package/src/extensions/enforcement/whisper.ts +15 -1
  70. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  71. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  72. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  73. package/src/extensions/manifest.ts +6 -0
  74. package/src/extensions/memory/AGENTS.md +37 -38
  75. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  76. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  77. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  78. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  79. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  80. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  81. package/src/extensions/self/AGENTS.md +2 -1
  82. package/src/extensions/self/path-miss/AGENTS.md +39 -0
  83. package/src/extensions/self/path-miss/detect.ts +78 -0
  84. package/src/extensions/self/path-miss/index.ts +135 -0
  85. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  86. package/src/extensions/self/watchdog/engine.ts +30 -2
  87. package/src/extensions/self/watchdog/index.ts +13 -1
  88. package/src/lib/ai/AGENTS.md +2 -0
  89. package/src/lib/ai/llm-call.ts +30 -0
  90. package/src/lib/ai/model-resolver.ts +16 -19
  91. package/src/lib/ai/presend-budget.ts +117 -0
  92. package/src/lib/config/braid-settings.ts +125 -0
  93. package/src/lib/config/per-tool-settings.ts +4 -4
  94. package/src/lib/core/event-names.ts +1 -0
  95. package/src/lib/detection/context-tiers.ts +52 -41
  96. package/src/lib/detection/context-usage.ts +211 -2
  97. package/src/lib/errors/llm-error.ts +55 -1
  98. package/src/lib/state/global-state.ts +11 -29
  99. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  100. package/src/lib/utils/AGENTS.md +1 -0
  101. package/src/lib/utils/argument-report.ts +105 -0
  102. 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
 
@@ -14,11 +14,12 @@ because they're specialized tools the user enables when they want them.
14
14
  | `watchdog/` | (TUI command) | Passive session monitor: uptime, idle time, message count. No LLM tool. |
15
15
  | `auto-recovery/` | (whisper-only) | On turn_start, checks for system degradation and suggests recovery. |
16
16
  | `latent-activator/` | `behavior` | Activates atomic behavior modes (planner, executor, reviewer, etc). |
17
+ | `path-miss/` | (whisper-only) | On a tool result that missed a path, names the listing that finds it. |
17
18
 
18
19
  ## Local Contracts
19
20
 
20
21
  - Most are **opt-in** (`disabledByDefault: true` in the manifest).
21
- - `auto-recovery` and `latent-activator` are always-on.
22
+ - `auto-recovery`, `latent-activator` and `path-miss` are always-on.
22
23
  - These extensions manipulate the agent's own state, not external state.
23
24
 
24
25
  ## Distinction from related categories
@@ -0,0 +1,39 @@
1
+ <!-- status: current -->
2
+
3
+ # src/extensions/self/path-miss/ - Path-Miss Steer
4
+
5
+ When a tool result reports a missing path, one whisper says which move would
6
+ have found it. The failure is the moment the cheaper instrument is obvious;
7
+ without it the agent guesses again.
8
+
9
+ ## Files
10
+
11
+ | File | Purpose |
12
+ | ----------- | ---------------------------------------------------------------------------------------------------- |
13
+ | `index.ts` | The emitter: subscribes to tool results, holds the budget, sends through `sendTrackedMessage`. |
14
+ | `detect.ts` | Recognises a missing-path failure and names the path. Pure: no state, no delivery, no extension API. |
15
+
16
+ ## Local Contracts
17
+
18
+ - **One line per turn, at most one line per path per session.** The turn flag
19
+ is reset by the `input` handler (the same boundary the whisper family uses);
20
+ the per-path set is keyed on the session id and bounded.
21
+ - **No new event registration.** The emitter rides pi's existing `tool_result`
22
+ event, the only seat that carries both the failure text and the call's own
23
+ arguments - the call's `path` is stronger evidence than a parse of the
24
+ message.
25
+ - **Delivered as a live steer** (`delivery: "live"`), so it reaches a running
26
+ loop and never wakes one by itself.
27
+ - **A suppressed send does not spend the path's budget.** If the whisper funnel
28
+ drops the line, the path stays steerable.
29
+ - **Only a missing path is a path miss.** `EACCES`, an unreadable file and a
30
+ failed assertion each call for a different next move.
31
+ - Tool coverage: `read`, `edit`, `write`, `bash`. A failure from any other tool
32
+ is not classified, whatever its text says.
33
+
34
+ ## Related modules
35
+
36
+ - `lib/utils/injection-tracker.ts` - `sendTrackedMessage`, the delivery trunk
37
+ (envelope, flood cap, delivery class).
38
+ - `extensions/self/auto-recovery/` and `extensions/self/watchdog/` - the
39
+ neighbouring whisper emitters.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Recognition of a missing-path tool failure, and the path it names.
3
+ *
4
+ * The shapes below are the ones the tools actually emit on this platform,
5
+ * measured rather than invented:
6
+ *
7
+ * read ENOENT: no such file or directory, access '/x/y.ts'
8
+ * edit Could not edit file: /x/y.ts. Error code: ENOENT.
9
+ * bash ls: /x/y: No such file or directory
10
+ * bash /bin/bash: line 0: cd: /x/y: No such file or directory
11
+ *
12
+ * Two of those carry a usable path in the call and the rest only in the text,
13
+ * so the call wins when it has one: a path the model asked for is the path the
14
+ * whisper should name, even when the tool's own wording echoes it loosely.
15
+ *
16
+ * Only a missing path is a path miss. A permission error, an unreadable file
17
+ * or a failed assertion is a different failure with a different next move, and
18
+ * steering toward `ls` there would cost a call without teaching anything.
19
+ */
20
+
21
+ /** Tools whose failure can mean "the path was a guess". */
22
+ const PATH_BEARING_TOOLS = new Set(["read", "edit", "write", "bash"]);
23
+
24
+ /** The two spellings of "this path is not there" the tools emit. */
25
+ const MISSING_PATH = /ENOENT|no such file or directory/i;
26
+
27
+ /** A path quoted by a Node error: `ENOENT: ..., access '/x/y'`. */
28
+ const QUOTED_AFTER_SYSCALL =
29
+ /\b(?:access|open|stat|lstat|scandir|opendir|unlink|readlink)\s+'([^']+)'/;
30
+
31
+ /** A shell builtin naming the directory it could not enter. */
32
+ const BASH_CD_TARGET = /(?:^|[:\s])cd:\s+(.+?):\s*no such file/i;
33
+
34
+ /** A program naming the operand it could not find: `ls: /x/y: No such file`. */
35
+ const PROGRAM_OPERAND = /([^\s:]+):\s*no such file or directory/i;
36
+
37
+ /** A bare errno (`ENOENT`), not a path. */
38
+ const ERRNO_ONLY = /^[A-Z][A-Z0-9_]*$/;
39
+
40
+ export interface PathMiss {
41
+ /** The tool whose call missed. */
42
+ tool: string;
43
+ /** The path that was not there, as the tool or the call reported it. */
44
+ path: string;
45
+ }
46
+
47
+ /** The path the call itself asked for, when the tool takes one. */
48
+ function pathFromCall(input: unknown): string | undefined {
49
+ if (!input || typeof input !== "object") return undefined;
50
+ const path = (input as { path?: unknown }).path;
51
+ return typeof path === "string" && path.length > 0 ? path : undefined;
52
+ }
53
+
54
+ /** The path an error message names, when the call did not carry one. */
55
+ function pathFromText(text: string): string | undefined {
56
+ const candidates = [
57
+ QUOTED_AFTER_SYSCALL.exec(text)?.[1],
58
+ BASH_CD_TARGET.exec(text)?.[1],
59
+ PROGRAM_OPERAND.exec(text)?.[1],
60
+ ];
61
+ for (const candidate of candidates) {
62
+ const path = candidate?.trim();
63
+ if (!path || ERRNO_ONLY.test(path)) continue;
64
+ return path;
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ /**
70
+ * The path a failed call missed, or null when this result is not a path miss.
71
+ */
72
+ export function detectPathMiss(toolName: string, input: unknown, text: string): PathMiss | null {
73
+ if (!PATH_BEARING_TOOLS.has(toolName)) return null;
74
+ if (!text || !MISSING_PATH.test(text)) return null;
75
+ const path = pathFromCall(input) ?? pathFromText(text);
76
+ if (!path) return null;
77
+ return { tool: toolName, path };
78
+ }