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,6 +26,7 @@
26
26
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
27
27
  import { getExtensionState } from "../../lib/state/extension-state.js";
28
28
  import type { ClassifiedLlmError, LlmErrorCategory } from "../../lib/errors/llm-error.js";
29
+ import { getRouteBreakerConfig } from "../../lib/config/braid-settings.js";
29
30
 
30
31
  export type SessionHealthMode =
31
32
  | "healthy"
@@ -68,6 +69,26 @@ export interface SessionHealthState {
68
69
  * the current episode. Diagnostic; cleared together with the counter.
69
70
  */
70
71
  breakerOpenedAt?: number;
72
+ /**
73
+ * Provider failures of any class except context_window/abort since the last
74
+ * successful LLM call. The route-failure latch reads this; only an explicit
75
+ * reset (clean turn, provider success, route change, owner recovery,
76
+ * session start) lowers it.
77
+ */
78
+ routeErrorsSinceHealthyTurn: number;
79
+ /**
80
+ * ms timestamp of the first time routeErrorsSinceHealthyTurn reached the
81
+ * configured threshold in the current episode. One half of the floor's
82
+ * clock; undefined while the latch has never opened.
83
+ */
84
+ routeLatchOpenedAt?: number;
85
+ /**
86
+ * ms timestamp of the last turn the floor released while the latch stayed
87
+ * open. The other half of the floor's clock: the predicate allows exactly
88
+ * one self-started turn per `floorMs`, then this stamp closes the gate for
89
+ * the next window.
90
+ */
91
+ routeLatchLastReleaseAt?: number;
71
92
  }
72
93
 
73
94
  function emptyCategoryCounts(): Record<LlmErrorCategory, number> {
@@ -90,6 +111,7 @@ const DEFAULT_STATE: SessionHealthState = {
90
111
  providerSuccessCount: 0,
91
112
  consolidationSkipsByMode: {},
92
113
  terminalErrorsSinceHealthyTurn: 0,
114
+ routeErrorsSinceHealthyTurn: 0,
93
115
  };
94
116
 
95
117
  /**
@@ -119,6 +141,9 @@ export function getSessionHealth(ctx: ExtensionContext): SessionHealthState {
119
141
  if (typeof s.terminalErrorsSinceHealthyTurn !== "number") {
120
142
  s.terminalErrorsSinceHealthyTurn = 0;
121
143
  }
144
+ if (typeof s.routeErrorsSinceHealthyTurn !== "number") {
145
+ s.routeErrorsSinceHealthyTurn = 0;
146
+ }
122
147
  return s;
123
148
  }
124
149
 
@@ -127,17 +152,71 @@ export function getSessionHealth(ctx: ExtensionContext): SessionHealthState {
127
152
  * terminally? Latch state only — no provider/model/error names, so callers in
128
153
  * generic layers (the timer wake path) cannot learn a domain fact from it.
129
154
  *
130
- * `threshold` lets a caller pass the configured bound; the default keeps the
131
- * built-in N. Open-ness is derived from the monotonic counter, which only the
132
- * explicit reset signals (session_start, owner recovery, route change) and a
133
- * clean wake turn lower — hence "latch".
155
+ * `threshold` lets a caller pass the configured bound for the terminal
156
+ * counter; the default keeps the built-in N. Open-ness is derived from the
157
+ * monotonic counter, which only the explicit reset signals (session_start,
158
+ * owner recovery, route change) and a clean wake turn lower — hence "latch".
159
+ *
160
+ * The route disjunct is the second latch on the same question: a route that
161
+ * fails every self-started turn parks them too, on its own configured
162
+ * threshold and floor. It is asked here, once, so the three seams that
163
+ * self-start turns cannot each keep their own answer.
134
164
  */
135
165
  export function isTurnStartBlocked(
136
166
  ctx: ExtensionContext,
137
167
  threshold: number = TERMINAL_BREAKER_N,
138
168
  ): boolean {
139
169
  const s = getSessionHealth(ctx);
140
- return s.terminalErrorsSinceHealthyTurn >= threshold;
170
+ return s.terminalErrorsSinceHealthyTurn >= threshold || isRouteLatchOpen(ctx);
171
+ }
172
+
173
+ /**
174
+ * Is the route-failure latch open right now? The route-only half of
175
+ * `isTurnStartBlocked`, for the two seams that must not inherit the terminal
176
+ * wake policy: a watchdog escalation and an explicitly-waking whisper never
177
+ * consulted the terminal breaker, so their demotion has to key on the route
178
+ * fact alone. `braid.session.routeBreaker.enabled = false` answers false
179
+ * unconditionally, which is what makes the off switch inert rather than
180
+ * partial.
181
+ *
182
+ * The floor is a release, not a bypass: while the latch stays open the
183
+ * predicate lets exactly one self-started turn through per `floorMs` and
184
+ * stamps the release, so a parked session cannot starve and cannot loop.
185
+ */
186
+ export function isRouteLatchOpen(ctx: ExtensionContext): boolean {
187
+ const cfg = getRouteBreakerConfig();
188
+ if (!cfg.enabled) return false;
189
+ const s = getSessionHealth(ctx);
190
+ if (s.routeErrorsSinceHealthyTurn < cfg.threshold) return false;
191
+ const anchor = Math.max(s.routeLatchOpenedAt ?? 0, s.routeLatchLastReleaseAt ?? 0);
192
+ if (Date.now() - anchor < cfg.floorMs) return true;
193
+ s.routeLatchLastReleaseAt = Date.now();
194
+ return false;
195
+ }
196
+
197
+ /**
198
+ * Count one provider failure for the route latch. The category decides
199
+ * whether it counts: a context-window overflow and an operator abort are not
200
+ * evidence about the route, and counting them would park the very wakes a
201
+ * recovery needs. Read by `isRouteLatchOpen` only — deliberately not folded
202
+ * into `recordLlmError`, whose consumers (mode, terminal counter, degraded
203
+ * rows) must keep their own semantics.
204
+ */
205
+ export function recordRouteFailure(ctx: ExtensionContext, category: LlmErrorCategory): void {
206
+ if (category === "context_window" || category === "abort") return;
207
+ const s = getSessionHealth(ctx);
208
+ s.routeErrorsSinceHealthyTurn++;
209
+ if (s.routeLatchOpenedAt === undefined) {
210
+ const cfg = getRouteBreakerConfig();
211
+ if (s.routeErrorsSinceHealthyTurn >= cfg.threshold) s.routeLatchOpenedAt = Date.now();
212
+ }
213
+ }
214
+
215
+ /** Drop the route latch and every stamp the floor reads. */
216
+ function clearRouteLatch(s: SessionHealthState): void {
217
+ s.routeErrorsSinceHealthyTurn = 0;
218
+ s.routeLatchOpenedAt = undefined;
219
+ s.routeLatchLastReleaseAt = undefined;
141
220
  }
142
221
 
143
222
  /** Clear the latch and its counter (the reset signals share this). */
@@ -145,6 +224,10 @@ export function clearTerminalBreaker(ctx: ExtensionContext): void {
145
224
  const s = getSessionHealth(ctx);
146
225
  s.terminalErrorsSinceHealthyTurn = 0;
147
226
  s.breakerOpenedAt = undefined;
227
+ // A clean turn, a route change, an owner recovery and a session start all
228
+ // mean the route is being retried from a fresh premise: the route latch
229
+ // releases on the same signals.
230
+ clearRouteLatch(s);
148
231
  }
149
232
 
150
233
  export function recordLlmError(ctx: ExtensionContext, err: ClassifiedLlmError): void {
@@ -203,6 +286,12 @@ export function recordLlmSuccess(ctx: ExtensionContext): void {
203
286
  s.consecutiveErrors = 0;
204
287
  s.consecutiveHealthyTurns++;
205
288
 
289
+ // Any successful provider call is a release signal for the route latch: the
290
+ // route just answered, so the premise the latch parks on ("every attempt on
291
+ // this route fails") is false. Deliberately not gated on a run outcome — a
292
+ // parked session makes no self-started call, so this is how it re-opens.
293
+ clearRouteLatch(s);
294
+
206
295
  // Recover from degraded/aborted after enough healthy turns.
207
296
  if (s.mode === "degraded" || s.mode === "aborted" || s.mode === "context_overflow") {
208
297
  if (s.consecutiveHealthyTurns >= HEALTHY_CLEAR_TURNS) {
@@ -9,6 +9,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
9
  import { sendTrackedMessage } from "../../lib/utils/injection-tracker.js";
10
10
  import { recordNudgeSent } from "../../lib/reasoning/nudge-analytics.js";
11
11
  import { areCognitiveNudgesDisabled } from "../../lib/config/braid-settings.js";
12
+ import { isRouteLatchOpen } from "./session-health.js";
12
13
 
13
14
  const log = createLogger("enforcement");
14
15
 
@@ -116,7 +117,20 @@ export function sendEnforcementWhisper(
116
117
  // mid-turn compaction (context_compress tool). Undefined `deliverAs` falls
117
118
  // through to the triggerTurn branch and calls agent.prompt(), the same wake
118
119
  // path the timer extension uses.
119
- const triggerTurn = options?.triggerTurn ?? false;
120
+ const requestedTriggerTurn = options?.triggerTurn ?? false;
121
+ // Route-failure latch: a whisper that asked to wake the agent must not
122
+ // start a turn into a route that has failed every attempt since the last
123
+ // successful call. The advisory is not withdrawn — the same text still
124
+ // reaches the session as the ordinary non-waking steer; only the wake is
125
+ // withheld, so the next self-started call is not a doomed one. Only the
126
+ // route half of the turn-start question applies here: an explicitly-waking
127
+ // whisper never consulted the terminal breaker, and making it do so now
128
+ // would park the post-compaction resume on a signal it never used to read.
129
+ const demoted = requestedTriggerTurn && isRouteLatchOpen(ctx);
130
+ if (demoted) {
131
+ log.info("[whisper] waking whisper demoted to non-waking (route latch open)");
132
+ }
133
+ const triggerTurn = requestedTriggerTurn && !demoted;
120
134
  const deliverAs = options?.deliverAs ?? (triggerTurn ? undefined : "steer");
121
135
  // Default class for a non-waking enforcement whisper: live. An enforcement
122
136
  // advisory's value is read during the run it fires in (see the delivery
@@ -62,7 +62,7 @@ import { getSessionIdSafe } from "../../../lib/state/extension-state.js";
62
62
  import { deriveProjectIdFromCwd } from "../../../lib/memory/past-insights.js";
63
63
  import { shouldWriteOutcomeEpisode } from "../../../lib/memory/write-quality.js";
64
64
  import { getMemoryWriteGateConfig } from "../../../lib/config/braid-settings.js";
65
- import { formatLocalTime } from "../../../lib/utils/local-time.js";
65
+ import { nowOrOverride } from "../../../lib/utils/local-time.js";
66
66
 
67
67
  /** Derive a short project id from the current working directory. */
68
68
  function deriveProject(ctx: ExtensionContext): string {
@@ -126,7 +126,6 @@ import {
126
126
  maybeArmAutoCompaction,
127
127
  } from "../../memory/context-manager/handlers/tools/context-compress.js";
128
128
  import { pushBounded } from "../../../lib/utils/bounded.js";
129
- import type { TurnBoundary } from "../../../lib/events/turn-boundary.js";
130
129
  import { RSS_RING_CAP } from "../../../lib/telemetry/rss-telemetry.js";
131
130
  import { recallerModule } from "./modules/recaller.js";
132
131
  import { reflectionConsolidatorModule } from "./modules/reflection-consolidator.js";
@@ -155,12 +154,10 @@ const log = createLogger("heartbeat");
155
154
  // standalone messages that could be confused with user input.
156
155
  //
157
156
  // Keyed by sessionId (from getSessionIdSafe). Cleaned up on session_shutdown.
158
- interface WhisperBufferEntry {
159
- message: string;
160
- priority: string;
157
+ interface DelayedWhisperEntry extends WhisperBufferEntry {
161
158
  source: string;
162
159
  }
163
- const _heartbeatWhisperBuffer = new Map<string, WhisperBufferEntry[]>();
160
+ const _heartbeatWhisperBuffer = new Map<string, DelayedWhisperEntry[]>();
164
161
 
165
162
  // Outcome-episode write gate.
166
163
  // Review-before-write quality gate on the session_outcome sender. The hasSignal
@@ -169,11 +166,17 @@ const _heartbeatWhisperBuffer = new Map<string, WhisperBufferEntry[]>();
169
166
  // process) so the cooldown actually throttles back-to-back session ends.
170
167
  let _lastOutcomeWriteAt = 0;
171
168
 
172
- function bufferHeartbeatWhisper(
169
+ /**
170
+ * Buffer one whisper for the next delivery. Exported because it and
171
+ * flushDelayedWhispers are the delivery boundary a fixture must drive to
172
+ * assert on the text that ships (the same pair before_agent_start calls).
173
+ */
174
+ export function bufferHeartbeatWhisper(
173
175
  sessionId: string,
174
176
  message: string,
175
177
  priority: string,
176
178
  source: string,
179
+ family?: WhisperFamily,
177
180
  ): void {
178
181
  let buffer = _heartbeatWhisperBuffer.get(sessionId);
179
182
  if (!buffer) {
@@ -184,69 +187,33 @@ function bufferHeartbeatWhisper(
184
187
  // ticks can pile up while the session is idle (no before_agent_start to
185
188
  // flush). Cap at 100 entries per session, drop-oldest — stale heartbeat
186
189
  // messages past 100 are noise by definition.
187
- pushBounded(buffer, { message, priority, source }, 100);
190
+ pushBounded(buffer, { message, priority, source, family }, 100);
188
191
  }
189
192
 
190
- function flushDelayedWhispers(sessionId: string, pi: ExtensionAPI, selfState?: string): void {
193
+ /**
194
+ * Drain the delayed buffer as one delivery per priority tier.
195
+ *
196
+ * The sample is taken here, at delivery, and is the only source of the
197
+ * numbers and of the tier the context family is re-labelled with: a family
198
+ * rendered from an older reading is what printed a label beside numbers it
199
+ * never measured.
200
+ */
201
+ export function flushDelayedWhispers(
202
+ sessionId: string,
203
+ pi: ExtensionAPI,
204
+ sample?: SelfStateSample,
205
+ ): void {
191
206
  const buffer = _heartbeatWhisperBuffer.get(sessionId);
192
207
  if (!buffer || buffer.length === 0) return;
193
208
  const batch = buffer.splice(0);
194
209
 
195
- // Deduplicate near-duplicate messages: extract a semantic type key from
196
- // each message. Messages of the same type (e.g., "Context at 40%..." and
197
- // "Context at 50%...") collapse to one, so the Heartbeat Summary never
198
- // lists 9 near-identical context-percentage messages with slightly
199
- // different token counts.
200
- function dedupKey(message: string): string {
201
- // Context percentage messages: "Context at 40%. context_tag..."
202
- if (/^Context at \d+%/.test(message)) return "context-percentage";
203
- // Duplicate count messages: "39 near-duplicate messages..."
204
- if (/^\d+ near-duplicate messages/.test(message)) return "duplicate-count";
205
- // Context density messages
206
- if (/^Low context density/.test(message)) return "density-low";
207
- if (/^High density/.test(message)) return "density-high";
208
- if (/^Context density still low/.test(message)) return "density-low-persistent";
209
- // Proactive projection messages
210
- if (/^\[proactive\]/.test(message)) return "proactive-projection";
211
- // Degradation messages
212
- if (/^Degradation detected/.test(message)) return "degradation";
213
- // Fallback: use first 80 chars
214
- return message.slice(0, 80);
215
- }
216
- interface DedupEntry {
217
- message: string;
218
- priority: string;
219
- }
220
- const deduped: DedupEntry[] = [];
221
- const seen = new Set<string>();
222
- for (const entry of batch) {
223
- const key = dedupKey(entry.message);
224
- if (seen.has(key)) continue;
225
- seen.add(key);
226
- deduped.push({ message: entry.message, priority: entry.priority });
227
- }
228
-
229
- // Aggregate by priority tier
230
- const groups = new Map<string, string[]>();
231
- for (const entry of deduped) {
232
- const p = entry.priority;
233
- if (!groups.has(p)) groups.set(p, []);
234
- groups.get(p)!.push(entry.message);
235
- }
210
+ const deliveries = renderDelayedDelivery(batch, {
211
+ at: nowOrOverride(),
212
+ contextPercent: sample?.contextPercent ?? null,
213
+ selfState: buildSelfStateLine(sample),
214
+ });
236
215
 
237
- for (const [, messages] of groups) {
238
- // Fresh clock: every Heartbeat Summary carries a `now:` line (date +
239
- // owner-TZ time via the ONE formatter) so a long session never reasons on
240
- // a stale clock — the heartbeat is the only mid-session channel guaranteed
241
- // to re-fire. One context-health line follows the clock (tokens /
242
- // cache-hit / near-dups / tok-s trend), so every heartbeat delivery is
243
- // also a self-state checkpoint.
244
- const nowLine = `now: ${formatLocalTime(new Date(), true)}`;
245
- const selfStateSuffix = selfState ? `\n${selfState}` : "";
246
- const text =
247
- messages.length === 1
248
- ? `${nowLine}${selfStateSuffix}\n${messages[0]}`
249
- : `[Heartbeat Summary]\n${nowLine}${selfStateSuffix}\n${messages.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
216
+ for (const text of deliveries) {
250
217
  try {
251
218
  sendTrackedMessage(
252
219
  pi,
@@ -310,11 +277,19 @@ export function sendSopCoachWhisper(pi: ExtensionAPI, message: string): void {
310
277
  }
311
278
 
312
279
  // Whisper Batching
313
- // flushWhisperBuffer lives in ./whisper-batcher.ts. The tick function
314
- // imports it to flush module whispers as aggregated messages.
315
- import { flushWhisperBuffer } from "./whisper-batcher.js";
316
- import { buildSelfStateLine } from "./whisper-batcher.js";
280
+ // flushWhisperBuffer and the delayed-delivery renderer live in
281
+ // ./whisper-batcher.ts. This file owns the buffer and the send channel; the
282
+ // batcher owns the text, so the shipped delivery and the tested delivery are
283
+ // the same function.
284
+ import {
285
+ flushWhisperBuffer,
286
+ buildSelfStateLine,
287
+ renderDelayedDelivery,
288
+ type WhisperBufferEntry,
289
+ type WhisperFamily,
290
+ } from "./whisper-batcher.js";
317
291
  import { getSelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
292
+ import type { SelfStateSample } from "../../../lib/telemetry/context-heartbeat.js";
318
293
 
319
294
  // Tick Engine
320
295
 
@@ -323,7 +298,6 @@ function tick(
323
298
  state: import("./types.js").HeartbeatState,
324
299
  config: import("./types.js").HeartbeatConfig,
325
300
  ctx: ExtensionContext,
326
- turnEvent?: TurnBoundary,
327
301
  ): void {
328
302
  state.stats.totalTicks++;
329
303
 
@@ -414,7 +388,7 @@ function tick(
414
388
  log.warn(`[heartbeat] pending-compaction advisory failed: ${err}`);
415
389
  }
416
390
  try {
417
- maybeArmAutoCompaction(pi, ctx, turnEvent);
391
+ maybeArmAutoCompaction(pi, ctx);
418
392
  } catch (err) {
419
393
  log.warn(`[heartbeat] context auto-arm check failed: ${err}`);
420
394
  }
@@ -644,12 +618,9 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
644
618
  const interval = getAdaptiveInterval(state);
645
619
  if (state.turnCount % interval !== 0) return;
646
620
 
647
- // The boundary travels with the tick: the usage-driven auto-arm arms inside
648
- // this dispatch, and a drain there can only be judged from the event that
649
- // named the boundary. Dropping this argument is invisible to every other
650
- // fixture, so one drives the real handler end to end:
651
- // test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs.
652
- tick(pi, state, config, ctx, event);
621
+ // The tick arms the usage-driven auto compaction on its own cadence. The
622
+ // arm only queues; the queue drains at settle (or the 0.90W backstop).
623
+ tick(pi, state, config, ctx);
653
624
  });
654
625
 
655
626
  // Event: before_agent_start - flush delayed whispers
@@ -668,9 +639,11 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
668
639
  if (typeof prompt === "string" && prompt.length > 0) {
669
640
  getTurnStartPrompt(ctx).prompt = prompt;
670
641
  }
671
- // Self-state (Refine-2): every heartbeat-family delivery carries the
672
- // self-state line. Sampling never throws; missing telemetry -> "n/a".
673
- flushDelayedWhispers(sid, pi, buildSelfStateLine(getSelfStateSample(ctx)));
642
+ // The sample is taken here, at delivery: the self-state line and the
643
+ // context family's arm are both rendered from it, so one delivery never
644
+ // prints two ages of one fact. Sampling never throws; missing telemetry
645
+ // renders "n/a".
646
+ flushDelayedWhispers(sid, pi, getSelfStateSample(ctx));
674
647
  });
675
648
 
676
649
  // Event: tool_call
@@ -810,9 +783,9 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
810
783
  // (below) still delivers immediately because it uses
811
784
  // deliverAs:"steer" and is time-critical (at ≥90% context the
812
785
  // whisper may never get a next turn — steer it into the current run).
813
- (msg: string) => {
786
+ (msg: string, family?: WhisperFamily) => {
814
787
  const sid = getSessionIdSafe(ctx) ?? "anonymous";
815
- bufferHeartbeatWhisper(sid, msg, "medium", "heartbeat/policy");
788
+ bufferHeartbeatWhisper(sid, msg, "medium", "heartbeat/policy", family);
816
789
  },
817
790
  (msg: string) => {
818
791
  sendTrackedMessage(
@@ -10,17 +10,17 @@ import type { Policy, PolicyContext, BeliefStore } from "../../../lib/store/beli
10
10
  import type { ToolTracking } from "./types.js";
11
11
  import { createLogger } from "../../../lib/core/logger.js";
12
12
  import {
13
- USAGE_WHISPER_SOFT,
14
- USAGE_WHISPER_ADVISORY,
15
- USAGE_WHISPER_WARNING,
16
13
  USAGE_WHISPER_CRITICAL,
17
14
  USAGE_FIRED_RESET_BELOW,
18
15
  } from "../../../lib/detection/context-thresholds.js";
19
16
  import {
20
17
  CONTEXT_USAGE_TIERS,
18
+ contextUsageTierMessage,
21
19
  getContextUsage,
20
+ type ContextUsageTier,
22
21
  type ContextUsageTierInfo,
23
22
  } from "../../../lib/detection/context-tiers.js";
23
+ import type { WhisperFamily } from "./whisper-batcher.js";
24
24
 
25
25
  const log = createLogger("heartbeat:policies");
26
26
 
@@ -417,7 +417,7 @@ export function isVerificationToolCall(toolName: string, input: unknown): boolea
417
417
  export function createDefaultPolicies(
418
418
  getToolTracking: () => ToolTracking,
419
419
  onSignal: (type: string, data: Record<string, unknown>) => void,
420
- sendWhisper: (msg: string) => void,
420
+ sendWhisper: (msg: string, family?: WhisperFamily) => void,
421
421
  sendSteerMessage: (msg: string) => void,
422
422
  ): Policy[] {
423
423
  return [
@@ -435,10 +435,11 @@ export function createDefaultPolicies(
435
435
  return turnsSince >= 10 && t.totalToolsUsed > 3;
436
436
  },
437
437
  action: async (ctx: PolicyContext) => {
438
+ // One instruction, not a menu. The agent does not need to be asked
439
+ // whether it is sure; it needs the step that would settle it.
438
440
  sendWhisper(
439
441
  "No verification (grep/read/search) in 10+ turns. " +
440
- "Consider: Are you sure the implementation is correct? " +
441
- "Verify with grep or read to confirm.",
442
+ "Verify with grep or read before continuing.",
442
443
  );
443
444
  onSignal("verification_reminder", {
444
445
  turn: ctx.turnNumber,
@@ -510,48 +511,38 @@ export function createDefaultPolicies(
510
511
  // subset). Values are always present per the wiring (heartbeat-scheduler
511
512
  // index.ts), so these defaults never fire — preserved from the original
512
513
  // required-typed destructure.
513
- const { percent = 0, tokens = 0, contextWindow = 0 } = usage;
514
+ const { percent = 0 } = usage;
514
515
 
515
516
  if (percent < USAGE_FIRED_RESET_BELOW && _firedThresholds.size > 0) {
516
517
  _firedThresholds.clear();
517
518
  }
518
519
 
519
- // Threshold ladder: soft -> advisory -> warning -> critical
520
- // Each threshold fires ONCE until usage resets below USAGE_FIRED_RESET_BELOW.
521
- // Pipeline taught fully at critical level; lighter hints below that.
522
- // Tier→(threshold, priority) mapping shared from
523
- // lib/detection/context-tiers.ts (CONTEXT_USAGE_TIERS); this policy
524
- // keeps its own per-tier message copy (different copy from the
525
- // enforcement nudge text).
526
- const TIER_MESSAGES: Record<"soft" | "advisory" | "warning" | "critical", string> = {
527
- soft: `Context at ${USAGE_WHISPER_SOFT}%. Inspect and track: context_inspect(detail="quick"). Tag with context_navigate(action="tag") to mark progress.`,
528
- advisory: `Context at ${USAGE_WHISPER_ADVISORY}%. Light pruning: context_inspect(detail="prune") then context_compress(action="archive") or context_navigate(action="tag") + context_compress(action="archive").`,
529
- warning: `Context at ${USAGE_WHISPER_WARNING}%. Deep compaction: tag + archive now. Pipeline: context_navigate(action="tag") -> context_compress(action="archive") -> compact if needed.`,
530
- critical: `CRITICAL: Context at ${USAGE_WHISPER_CRITICAL}%. FORCE IMMEDIATE HYGIENE. Pipeline: context_navigate(action="tag") -> context_compress(action="archive") -> context_compress(action="slide"). Do not continue work until done.`,
531
- };
532
-
533
- const thresholds: Array<{ pct: number; priority: "low" | "medium" | "high"; msg: string }> =
534
- CONTEXT_USAGE_TIERS.filter(
535
- (
536
- t,
537
- ): t is ContextUsageTierInfo & { tier: "soft" | "advisory" | "warning" | "critical" } =>
538
- t.tier !== "compact",
539
- )
540
- .slice()
541
- .reverse()
542
- .map((t) => ({ pct: t.threshold, priority: t.priority, msg: TIER_MESSAGES[t.tier] }));
543
-
544
- for (const { pct, msg } of thresholds) {
545
- if (percent >= pct && !_firedThresholds.has(pct)) {
546
- _firedThresholds.add(pct);
547
- sendWhisper(
548
- `${msg} (${tokens?.toLocaleString()} / ${contextWindow?.toLocaleString()} tokens, ${percent?.toFixed(1)}%)`,
549
- );
550
- if (pct === USAGE_WHISPER_CRITICAL) {
551
- const finalizationMessage =
552
- `[heartbeat] Context critical at ${percent?.toFixed(1)}%. ` +
553
- `Tag your position with context_navigate(action="tag") now and archive with context_compress(action="archive").`;
554
- sendSteerMessage(finalizationMessage);
520
+ // Threshold ladder: soft -> advisory -> warning -> critical, each
521
+ // firing ONCE until usage resets below USAGE_FIRED_RESET_BELOW.
522
+ //
523
+ // A rung decides WHETHER a whisper fires; it is never what the
524
+ // whisper prints. A threshold is a configuration value, and a delivery
525
+ // that prints it puts a number where a reader expects a reading. The
526
+ // wording lives with the meter in lib/detection/context-tiers.ts (one
527
+ // owner for both the enforcement ladder and this one), and the number
528
+ // the reader acts on is the measurement sampled at delivery, carrying
529
+ // its own provenance word.
530
+ const thresholds = CONTEXT_USAGE_TIERS.filter(
531
+ (t): t is ContextUsageTierInfo & { tier: Exclude<ContextUsageTier, "compact"> } =>
532
+ t.tier !== "compact",
533
+ )
534
+ .slice()
535
+ .reverse();
536
+
537
+ for (const { tier, threshold } of thresholds) {
538
+ if (percent >= threshold && !_firedThresholds.has(threshold)) {
539
+ _firedThresholds.add(threshold);
540
+ // The family marker lets the batcher re-render this instruction
541
+ // from the measurement taken at delivery, so the arm named here and
542
+ // the percent printed beside it are one snapshot.
543
+ sendWhisper(contextUsageTierMessage(tier), "context-tier");
544
+ if (threshold === USAGE_WHISPER_CRITICAL) {
545
+ sendSteerMessage(contextUsageTierMessage("critical"));
555
546
  log.warn(`Auto-finalize triggered at ${USAGE_WHISPER_CRITICAL}%`);
556
547
  }
557
548
  break;