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
@@ -1,83 +1,158 @@
1
1
  /**
2
- * Whisper batcher for heartbeat ticks.
2
+ * Whisper batcher: the ONE place the shape of a heartbeat delivery is built.
3
3
  *
4
- * During a heartbeat tick, multiple cognitive modules may want to
5
- * whisper to the agent. If we just forward them through ctx.whisper,
6
- * the agent gets N separate messages -- which is both noisy and
7
- * expensive (each message becomes a turn boundary in the agent's
8
- * context).
4
+ * Two buffers feed it. The tick batcher collects module whispers and flushes
5
+ * them once per tick; the delayed buffer collects policy whispers and flushes
6
+ * them on the next before_agent_start. Both deliver the same shape: one
7
+ * clock line, one self-state line, numbered bodies. The shape has one
8
+ * owner here instead of a copy per flush site.
9
9
  *
10
- * The batcher intercepts the whisper call during the tick, buffers
11
- * messages grouped by priority, and flushes them as aggregated
12
- * messages per priority tier. High-priority messages flush first.
10
+ * Two rules make the delivered text trustworthy, and each is enforced by the
11
+ * way this module is written rather than by the emitter remembering it:
12
+ *
13
+ * 1. One snapshot per delivery. The clock comes from the seam, and a
14
+ * family that renders a measurement is re-rendered from the sample
15
+ * taken at delivery, so a label cannot outlive the number beside it.
16
+ * 2. Last arrival wins in a collapse. Keeping the first arrival per
17
+ * family is what printed the oldest label beside the newest numbers:
18
+ * the newest instruction is the only one whose advice can still apply.
13
19
  */
14
- import { formatLocalTime } from "../../../lib/utils/local-time.js";
20
+ import { formatLocalTime, nowOrOverride } from "../../../lib/utils/local-time.js";
15
21
  import { formatTokensK } from "../../../lib/detection/context-usage.js";
22
+ import { contextUsageTier, contextUsageTierMessage } from "../../../lib/detection/context-tiers.js";
16
23
  /** Render a token count compactly: 0 -> "0K", 1234 -> "1K", 237785 -> "238K". */
17
24
  function renderTokensK(tokens) {
18
25
  return formatTokensK(tokens);
19
26
  }
20
27
  /**
21
- * Self-state line (2 directive): every heartbeat
22
- * summary makes the agent self-aware of its own context health. ONE line,
23
- * <= 40 tokens, appended to every heartbeat summary:
28
+ * Self-state line: ONE line, appended to every heartbeat delivery.
29
+ *
30
+ * self-state: ctx 413K tok (41.3% measured)
24
31
  *
25
- * self-state: ctx 213K tok · cache 96% · dup 39 · tps-ema 87
32
+ * The count and the percent are one meter reading from one snapshot, and the
33
+ * provenance word is the meter's own (context-usage describeUsage), so the two
34
+ * cannot disagree and a reader can tell a large context from a badly counted
35
+ * one. A percent whose provenance is missing is not rendered at all: an
36
+ * unlabelled percentage is the class that cost a session its window.
26
37
  *
27
- * An unavailable metric renders "n/a" — never zero (a zero looks like a
28
- * healthy reading; "n/a" honestly says the telemetry is missing).
38
+ * Metrics this line no longer carries (cache-hit share, near-duplicate count,
39
+ * tok/s trend, hygiene acts) name no action at the moment they are read. They
40
+ * stay in the telemetry JSONL and in the tools an agent calls while
41
+ * diagnosing, where a reader has already decided to look. An unavailable
42
+ * metric renders "n/a", never zero: a zero looks like a healthy reading.
29
43
  */
30
44
  export function buildSelfStateLine(sample) {
31
45
  const s = sample ?? {};
32
46
  const ctxTok = typeof s.contextTokens === "number" ? `${renderTokensK(s.contextTokens)} tok` : "n/a";
33
- const cache = typeof s.cacheHitShare === "number" ? `${Math.round(s.cacheHitShare)}%` : "n/a";
34
- const dup = typeof s.nearDupCount === "number" ? String(s.nearDupCount) : "n/a";
35
- const tps = typeof s.tpsEma === "number" ? `${Math.round(s.tpsEma)} tok/s` : "n/a";
36
- const acts = typeof s.hygieneActs === "number" ? String(s.hygieneActs) : null;
37
- const actPart = acts ? ` · acts ${acts}` : "";
38
- return `self-state: ctx ${ctxTok} · cache ${cache} · dup ${dup} · tps-ema ${tps}${actPart}`;
47
+ const percent = typeof s.contextPercent === "number" &&
48
+ typeof s.contextProvenance === "string" &&
49
+ s.contextProvenance.length > 0
50
+ ? ` (${s.contextPercent.toFixed(1)}% ${s.contextProvenance})`
51
+ : "";
52
+ return `self-state: ctx ${ctxTok}${percent}`;
39
53
  }
40
54
  /**
41
- * Flush batched whispers: group by priority tier, concatenate per tier,
42
- * and send as aggregated messages. This prevents N separate injected
43
- * messages per heartbeat tick when multiple modules activate.
44
- *
45
- * Fresh clock: every batched summary
46
- * (and its single-message form) prepends a `now:` line rendered by the
47
- * ONE local-time formatter (lib/utils/local-time.ts) so the agent never
48
- * reasons on a stale clock mid-session.
49
- *
50
- * Self-state (Refine-2): when `selfState` is provided (the caller
51
- * samples context tokens / cache-hit share / near-duplicates / tok/s trend
52
- * via lib/telemetry/context-heartbeat.ts getSelfStateSample), the summary
53
- * gains ONE self-state line right after the `now:` line — every heartbeat
54
- * summary makes the agent aware of its own context health. Absent sample =
55
- * no line (callers opt in).
55
+ * Render one batched delivery. The clock is read through the seam the envelope
56
+ * formatter uses, never from a fresh `Date` at flush time: a delivery that was
57
+ * delayed must not claim an instant it never observed.
58
+ */
59
+ export function renderHeartbeatDelivery(bodies, opts = {}) {
60
+ const nowLine = `now: ${formatLocalTime(opts.at ?? nowOrOverride(), true)}`;
61
+ const selfStateSuffix = opts.selfState ? `\n${opts.selfState}` : "";
62
+ const head = `${nowLine}${selfStateSuffix}`;
63
+ if (bodies.length === 1)
64
+ return `${head}\n${bodies[0]}`;
65
+ return `[Heartbeat Summary]\n${head}\n${bodies.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
66
+ }
67
+ /**
68
+ * Flush the tick buffer: group by priority tier, render one delivery per tier.
69
+ * Self-state (when a sample was taken) lands right after the clock line, so
70
+ * every heartbeat summary is also a self-state checkpoint.
56
71
  */
57
- export function flushWhisperBuffer(buffer, send, selfState) {
72
+ export function flushWhisperBuffer(buffer, send, selfState, at) {
58
73
  if (buffer.length === 0 || !send)
59
74
  return;
60
75
  const groups = new Map();
61
76
  for (const entry of buffer) {
62
- const p = entry.priority;
63
- if (!groups.has(p))
64
- groups.set(p, []);
65
- groups.get(p).push(entry.message);
77
+ const group = groups.get(entry.priority) ?? [];
78
+ group.push(entry.message);
79
+ groups.set(entry.priority, group);
66
80
  }
67
- // Flush one message per priority tier
68
81
  for (const [priority, messages] of groups) {
69
- const nowLine = `now: ${formatLocalTime(new Date(), true)}`;
70
- const selfStateSuffix = selfState ? `\n${selfState}` : "";
71
- if (messages.length === 1) {
72
- send(`${nowLine}${selfStateSuffix}\n${messages[0]}`, {
73
- category: "cognitive",
74
- priority: priority,
75
- });
76
- }
77
- else {
78
- const combined = `[Heartbeat Summary]\n${nowLine}${selfStateSuffix}\n${messages.map((m, i) => `${i + 1}. ${m}`).join("\n")}`;
79
- send(combined, { category: "cognitive", priority: priority });
80
- }
82
+ send(renderHeartbeatDelivery(messages, { selfState, at }), {
83
+ category: "cognitive",
84
+ priority,
85
+ });
86
+ }
87
+ }
88
+ /**
89
+ * Collapse key for the delayed buffer. A declared family is its own key (the
90
+ * emitter knows what it measured). The prose rules below cover emitters that
91
+ * still describe themselves by their first line: each one is a coupling, so a
92
+ * copy change there must come with a look at this list.
93
+ */
94
+ function dedupKey(entry) {
95
+ if (entry.family)
96
+ return `family:${entry.family}`;
97
+ const message = entry.message;
98
+ // Duplicate count messages: "39 near-duplicate messages..."
99
+ if (/^\d+ near-duplicate messages/.test(message))
100
+ return "duplicate-count";
101
+ // Context density messages
102
+ if (/^Low context density/.test(message))
103
+ return "density-low";
104
+ if (/^High density/.test(message))
105
+ return "density-high";
106
+ if (/^Context density still low/.test(message))
107
+ return "density-low-persistent";
108
+ // Proactive projection messages
109
+ if (/^\[proactive\]/.test(message))
110
+ return "proactive-projection";
111
+ // Degradation messages
112
+ if (/^Degradation detected/.test(message))
113
+ return "degradation";
114
+ // Fallback: use first 80 chars
115
+ return message.slice(0, 80);
116
+ }
117
+ /**
118
+ * The body to deliver for one entry.
119
+ *
120
+ * A declared family is re-rendered from the delivery sample, so the
121
+ * instruction and the number beside it describe one measurement. When the
122
+ * measured state no longer reaches the family's first arm, the entry is
123
+ * silence: advice about a condition that has passed is worse than none.
124
+ * With no measurement in hand the emitter's own wording stands: it carries no
125
+ * number, so it cannot contradict one.
126
+ */
127
+ function deliveryBody(entry, contextPercent) {
128
+ if (entry.family !== "context-tier")
129
+ return entry.message;
130
+ if (contextPercent === null)
131
+ return entry.message;
132
+ const tier = contextUsageTier(contextPercent);
133
+ return tier ? contextUsageTierMessage(tier.tier) : null;
134
+ }
135
+ /**
136
+ * Collapse the delayed buffer and render its deliveries: last arrival wins per
137
+ * key, then one delivery per priority tier.
138
+ */
139
+ export function renderDelayedDelivery(batch, opts = {}) {
140
+ const collapsed = new Map();
141
+ for (const entry of batch) {
142
+ // Last arrival wins: the newest instruction is the only one whose advice
143
+ // can still be right, and the keystroke of keying on the first arrival is
144
+ // what printed the oldest label beside the newest numbers.
145
+ collapsed.set(dedupKey(entry), entry);
146
+ }
147
+ const groups = new Map();
148
+ for (const entry of collapsed.values()) {
149
+ const body = deliveryBody(entry, opts.contextPercent ?? null);
150
+ if (body === null)
151
+ continue;
152
+ const group = groups.get(entry.priority) ?? [];
153
+ group.push(body);
154
+ groups.set(entry.priority, group);
81
155
  }
156
+ return [...groups.values()].map((bodies) => renderHeartbeatDelivery(bodies, opts));
82
157
  }
83
158
  //# sourceMappingURL=whisper-batcher.js.map
@@ -39,6 +39,7 @@ import errorCaptureFn from "./self/error-tracking/index.js";
39
39
  import watchdogFn from "./self/watchdog/index.js";
40
40
  import autoRecoveryFn from "./self/auto-recovery/index.js";
41
41
  import latentActivatorFn from "./self/latent-activator/index.js";
42
+ import pathMissFn from "./self/path-miss/index.js";
42
43
  // enforcement (turn pipeline: handlers, detection, substate)
43
44
  import enforcementFn from "./enforcement/index.js";
44
45
  // heartbeat (proactive background services: scheduler, analytics)
@@ -189,6 +190,11 @@ export const MANIFEST = [
189
190
  fn: latentActivatorFn,
190
191
  desc: "Latent behavior activator",
191
192
  },
193
+ {
194
+ id: "path-miss",
195
+ fn: pathMissFn,
196
+ desc: "Path-miss steer — name the listing that answers a missing path",
197
+ },
192
198
  // Watchdog (default-ON — liveness/stall state machine)
193
199
  // Default-ON per TG-HEARTBEAT-WATCHDOG-DESIGN.md ("default ON, NO new env
194
200
  // vars"); override via `broker.watchdog` in the one settings path that
@@ -15,7 +15,6 @@ import { StringEnum } from "@earendil-works/pi-ai";
15
15
  import { Type } from "typebox";
16
16
  import { createLogger } from "../../../lib/core/logger.js";
17
17
  import { applyWhisperEnvelope } from "../../../lib/utils/whisper-format.js";
18
- import { formatTokensK } from "../../../lib/detection/context-usage.js";
19
18
  import { existsSync, readFileSync } from "node:fs";
20
19
  import * as path from "node:path";
21
20
  import { braidDir, tagsSlugFromCwd } from "../../../lib/config/braid-paths.js";
@@ -128,13 +127,14 @@ function sendCompactNudge(pi, evaluated, usage, tokens) {
128
127
  // >= USAGE_TOKENS_ESCALATE (0.85W) escalated wording (archive-or-handoff)
129
128
  // >= HARD_BACKSTOP (0.90W) or usage >= 80 full pipeline message
130
129
  // else light tag/checkout message
131
- // Percent stays as the secondary trigger (sub-1M windows).
132
- const tokensK = formatTokensK(tokens);
130
+ // Percent stays as the secondary trigger (sub-1M windows). The text names
131
+ // the deadline and the action, never the number: the bars own the number,
132
+ // and a percentage copied into prose drifts from the meter.
133
133
  const pipelineMsg = tokens >= USAGE_TOKENS_ESCALATE()
134
- ? `Context at ${Math.round(usage)}% (~${tokensK} tokens). Escalated: archive the current phase with context_compress(action="archive"), or hand off to a fresh session (write a handoff note first).`
134
+ ? `Escalated: an armed compaction fires when the run settles. Archive the current phase with context_compress(action="archive"), or hand off to a fresh session (write a handoff note first).`
135
135
  : usage >= 80 || tokens >= HYGIENE_AUTO_COMPACT_HARD_BACKSTOP()
136
- ? `Context at ${Math.round(usage)}% (~${tokensK} tokens). Pipeline: context_navigate(action="tag") -> context_navigate(action="checkout") -> context_compress(action="archive") -> context_compress(action="slide").`
137
- : `Context at ${Math.round(usage)}% (~${tokensK} tokens). Tag with context_navigate(action="tag"), then context_navigate(action="checkout") to branch with a summary.`;
136
+ ? `An armed compaction fires when the run settles. Pipeline: context_navigate(action="tag") -> context_navigate(action="checkout") -> context_compress(action="archive") -> context_compress(action="slide").`
137
+ : `An armed compaction fires when the run settles. Tag with context_navigate(action="tag"), then context_navigate(action="checkout") to branch with a summary before the next task.`;
138
138
  sendTrackedMessage(pi, {
139
139
  customType: "context-lifecycle",
140
140
  content: [
@@ -145,7 +145,7 @@ function sendCompactNudge(pi, evaluated, usage, tokens) {
145
145
  ],
146
146
  display: true,
147
147
  details: { [BRAID_INJECTED]: true, [BRAID_SOURCE]: "context-lifecycle/compact-suggestion" },
148
- }, { delivery: "park", deliverAs: "steer" }, { type: "context", source: "context-lifecycle/compact-suggestion" });
148
+ }, { deliverAs: "nextTurn" }, { type: "context", source: "context-lifecycle/compact-suggestion" });
149
149
  log.info(`Suggested compact: ${evaluated.policy.name} (context ${Math.round(usage)}%, ` +
150
150
  `priority ${evaluated.policy.priority})`);
151
151
  }
@@ -225,7 +225,7 @@ function executeAction(evaluated, pi, ctx, usage, branchLength) {
225
225
  customType: "context-lifecycle",
226
226
  content: [{ type: "text", text: msg }],
227
227
  display: true,
228
- }, { delivery: "park", deliverAs: "steer" }, { type: "context", source: "context-lifecycle/nudge" });
228
+ }, { deliverAs: "nextTurn" }, { type: "context", source: "context-lifecycle/nudge" });
229
229
  }
230
230
  break;
231
231
  }
@@ -246,7 +246,8 @@ function hasConcreteCompressionSignal(evaluated) {
246
246
  /**
247
247
  * Proposals triggered by PERSISTENT conditions - usage %, token counts,
248
248
  * density - stay true across turns, so the policy re-fires every cooldown
249
- * with a fresh copy of the SAME advice ("Context at 55%. Consider archive").
249
+ * with a fresh copy of the SAME advice ("an armed compaction fires when the
250
+ * run settles").
250
251
  * This is the measured 33% exact-repeat class. Event-triggered proposals
251
252
  * (topic_shift, task_boundary, task_complexity, decision_density,
252
253
  * task_completion_candidate) fire on discrete moments and are NOT this class
@@ -486,7 +487,7 @@ async function queueProposal(evaluated, pi, ctx, branchLength) {
486
487
  customType: "context-lifecycle",
487
488
  content: [{ type: "text", text: msg }],
488
489
  display: true,
489
- }, { deliverAs: "steer", triggerTurn: true }, { type: "context", source: "context-lifecycle/phase-boundary-enforcement" });
490
+ }, { deliverAs: "nextTurn" }, { type: "context", source: "context-lifecycle/phase-boundary-enforcement" });
490
491
  // Track navigation whisper for escalation monitoring
491
492
  state(ctx).lastNavigationWhisperTurn = state(ctx).turnCount;
492
493
  }
@@ -19,6 +19,8 @@ export interface AuditResult {
19
19
  };
20
20
  /** How the usage number was produced (live working set vs fallback). */
21
21
  usageSource: string;
22
+ /** The short provenance word for the number: measured or estimated. */
23
+ usageSourceKind: "measured" | "estimated" | "unavailable";
22
24
  /** Whole-branch token sum - labeled "not sent" wherever displayed. */
23
25
  branchTokens: number;
24
26
  branchLength: number;
@@ -1,6 +1,6 @@
1
1
  import { getContextUsage } from "../../../lib/detection/context-tiers.js";
2
2
  import { formatTokensK } from "../../../lib/detection/context-usage.js";
3
- import { measureLiveUsage, tokenArms, resolveWindow, } from "../../../lib/detection/context-usage.js";
3
+ import { describeUsage, measureLiveUsage, tokenArms, resolveWindow, } from "../../../lib/detection/context-usage.js";
4
4
  import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../lib/detection/context-thresholds.js";
5
5
  import { isInternal } from "./handlers/shared.js";
6
6
  // isInternal comes from ./handlers/shared.js — the canonical list shared
@@ -38,6 +38,7 @@ export function analyzeSession(ctx) {
38
38
  const tree = sm.getTree();
39
39
  let usage = { percent: 0, tokens: 0, contextWindow: 0 };
40
40
  let usageSource = "unavailable";
41
+ let usageSourceKind = "unavailable";
41
42
  let branchTokens = 0;
42
43
  try {
43
44
  const live = measureLiveUsage(ctx);
@@ -47,7 +48,8 @@ export function analyzeSession(ctx) {
47
48
  tokens: live.tokens,
48
49
  contextWindow: live.contextWindow,
49
50
  };
50
- usageSource = `session tree (${live.windowSource} window)`;
51
+ usageSource = `session tree, ${live.windowSource} window, ${describeUsage(live)}`;
52
+ usageSourceKind = live.source;
51
53
  branchTokens = live.branchTokens;
52
54
  }
53
55
  else {
@@ -61,6 +63,7 @@ export function analyzeSession(ctx) {
61
63
  contextWindow: ctxUsage?.contextWindow ?? window.contextWindow,
62
64
  };
63
65
  usageSource = "ctx.getContextUsage fallback";
66
+ usageSourceKind = "estimated";
64
67
  branchTokens = usage.tokens;
65
68
  }
66
69
  }
@@ -233,6 +236,7 @@ export function analyzeSession(ctx) {
233
236
  return {
234
237
  usage,
235
238
  usageSource,
239
+ usageSourceKind,
236
240
  branchTokens,
237
241
  branchLength: branch.length,
238
242
  treeDepth: tree.length,
@@ -85,7 +85,7 @@ export async function handleOverflowFailure(pi, event, ctx, errorMessage) {
85
85
  try {
86
86
  const analysis = await analyzeSession(ctx);
87
87
  if (analysis.usage.percent >= 75) {
88
- log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (overflow)`);
88
+ log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (overflow)`);
89
89
  triggerEmergencyRotation(pi, ctx);
90
90
  return;
91
91
  }
@@ -150,7 +150,7 @@ export async function handleTransientError(pi, event, ctx, errorMessage) {
150
150
  try {
151
151
  const analysis = await analyzeSession(ctx);
152
152
  if (analysis.usage.percent >= 75) {
153
- log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (transient)`);
153
+ log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (transient)`);
154
154
  triggerEmergencyRotation(pi, ctx);
155
155
  return;
156
156
  }
@@ -252,7 +252,7 @@ export async function handleThresholdFailure(pi, event, ctx, errorMessage) {
252
252
  try {
253
253
  const analysis = await analyzeSession(ctx);
254
254
  if (analysis.usage.percent >= 75) {
255
- log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% - triggering emergency rotation (threshold)`);
255
+ log.warn(`[Critical] Context at ${analysis.usage.percent.toFixed(1)}% ${analysis.usageSourceKind} - triggering emergency rotation (threshold)`);
256
256
  triggerEmergencyRotation(pi, ctx);
257
257
  return;
258
258
  }
@@ -15,6 +15,8 @@ import { determineCompressionLevel } from "../../../../lib/detection/compression
15
15
  import { semanticCompress } from "../semantic-compress.js";
16
16
  import { updateContextDensity } from "../../../heartbeat/analytics/index.js";
17
17
  import { AGENT_END } from "../../../../lib/core/event-names.js";
18
+ import { clearRequestShapeFailure, noteRequestShapeFailure, } from "../../../../lib/utils/wake-gate.js";
19
+ import { isContextLengthRequestShape } from "../../../../lib/errors/llm-error.js";
18
20
  import { log, getCmState, compactionRetryState, overflowRetryState, COMPACTION_RETRY_MAX_ATTEMPTS, OVERFLOW_RETRY_MAX_ATTEMPTS, COMPACTION_RETRY_CUSTOM_TYPE, resetCompactionRetry, resetOverflowRetry, getCompactionRetryDelay, getOverflowRetryDelay, } from "./shared.js";
19
21
  export function registerAgentEndRetryHandler(pi) {
20
22
  pi.on(AGENT_END, async (event, ctx) => {
@@ -112,9 +114,19 @@ export function registerAgentEndApiErrorHandler(pi) {
112
114
  break;
113
115
  }
114
116
  }
115
- if (!lastAssistant || lastAssistant.stopReason !== "error")
117
+ if (!lastAssistant || lastAssistant.stopReason !== "error") {
118
+ // A turn that ended without an error means a request fit and came back:
119
+ // the shape verdict from an earlier refusal no longer applies.
120
+ clearRequestShapeFailure();
116
121
  return;
122
+ }
117
123
  const finalError = lastAssistant.errorMessage ?? "Unknown error";
124
+ // A context-length refusal is the request's shape, not the provider's
125
+ // mood. Record it here so the wake gate can keep failed-open wakes from
126
+ // re-firing a request that cannot succeed.
127
+ if (isContextLengthRequestShape(finalError)) {
128
+ noteRequestShapeFailure(finalError.slice(0, 200));
129
+ }
118
130
  sendTrackedMessage(pi, {
119
131
  customType: "context",
120
132
  content: [
@@ -13,7 +13,6 @@
13
13
  */
14
14
  import { Type } from "typebox";
15
15
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
- import { type TurnBoundary } from "../../../../../lib/events/turn-boundary.js";
17
16
  /**
18
17
  * Read the pending queue without creating state (inspect surfaces it).
19
18
  * Exported so context_inspect and the heartbeat advisory can report
@@ -32,8 +31,8 @@ export declare function readPendingCompactions(ctx: any): Array<{
32
31
  export declare function hasPendingLlmCompaction(ctx: any): boolean;
33
32
  /**
34
33
  * One pending-state line for the armed-but-unfired compaction queue
35
- * ("slide armed 17:28 — fires at the next turn boundary; live usage drops
36
- * when it lands"). Null when nothing is pending: no surface may fabricate an
34
+ * ("slide armed 17:28 — fires when the run settles; live usage drops when it
35
+ * lands"). Null when nothing is pending: no surface may fabricate an
37
36
  * expectation of a drop that is not armed. Shared by context_inspect and the
38
37
  * heartbeat advisory so both state the same fact the same way.
39
38
  */
@@ -61,20 +60,17 @@ export declare function resolveAutoSlideKeep(branchLength: number): number;
61
60
  * Usage-driven auto-arm: when live usage sits above the configured threshold
62
61
  * for `confirmTicks` consecutive observations, arm ONE deterministic slide so
63
62
  * a session that never gets a manual cleanup still gets relief. Reuses the
64
- * accounting context_inspect computes (analyzeSession), the same pending
65
- * queue the tool arms drain through, and the same boundary discipline: arming
66
- * only queues; the compaction itself still fires at the next turn boundary or
67
- * settle, never mid-run.
63
+ * accounting context_inspect computes (analyzeSession) and the same pending
64
+ * queue the tool arms drain through: arming only queues; the compaction itself
65
+ * fires when the run settles (or at the 0.90W backstop), never mid-run.
68
66
  *
69
67
  * Called from the heartbeat tick — the only cadence that runs while a session
70
- * works, and the only arm site that runs inside a turn boundary dispatch. It
71
- * hands that boundary in, so the arm is judged by the same rule the drain
72
- * applies: a "toolUse" boundary below the 0.90W backstop leaves the entry
73
- * queued for the next loop-done boundary instead of aborting the request the
74
- * loop is about to dispatch. Returns what happened and why, so the caller can
75
- * log it.
68
+ * works. Arming only queues: the entry waits for `agent_settled`, because the
69
+ * tick runs while the run is live and nothing at that point can prove the loop
70
+ * has no request left to dispatch. Returns what happened and why, so the
71
+ * caller can log it.
76
72
  */
77
- export declare function maybeArmAutoCompaction(pi: ExtensionAPI, ctx: any, boundary?: TurnBoundary): {
73
+ export declare function maybeArmAutoCompaction(pi: ExtensionAPI, ctx: any): {
78
74
  armed: boolean;
79
75
  reason: string;
80
76
  };