pi-braid 0.42.1 → 0.43.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  6. package/dist/extensions/core/polyfill/index.js +34 -131
  7. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  8. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  9. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  10. package/dist/extensions/enforcement/session-health.js +75 -5
  11. package/dist/extensions/enforcement/whisper.js +15 -1
  12. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  13. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  18. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  19. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  20. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  21. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  22. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  23. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  24. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  25. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  26. package/dist/extensions/self/watchdog/engine.js +25 -2
  27. package/dist/extensions/self/watchdog/index.js +14 -1
  28. package/dist/lib/ai/llm-call.js +23 -0
  29. package/dist/lib/ai/model-resolver.d.ts +11 -10
  30. package/dist/lib/ai/model-resolver.js +16 -19
  31. package/dist/lib/ai/presend-budget.d.ts +68 -0
  32. package/dist/lib/ai/presend-budget.js +83 -0
  33. package/dist/lib/config/braid-settings.d.ts +38 -0
  34. package/dist/lib/config/braid-settings.js +84 -0
  35. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  36. package/dist/lib/config/per-tool-settings.js +4 -4
  37. package/dist/lib/detection/context-tiers.d.ts +18 -5
  38. package/dist/lib/detection/context-tiers.js +51 -33
  39. package/dist/lib/detection/context-usage.d.ts +62 -1
  40. package/dist/lib/detection/context-usage.js +158 -1
  41. package/dist/lib/errors/llm-error.d.ts +14 -0
  42. package/dist/lib/errors/llm-error.js +44 -1
  43. package/dist/lib/state/global-state.d.ts +4 -8
  44. package/dist/lib/state/global-state.js +11 -28
  45. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  46. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  47. package/dist/lib/utils/wake-gate.d.ts +6 -0
  48. package/dist/lib/utils/wake-gate.js +52 -4
  49. package/docs/SETUP.md +7 -6
  50. package/package.json +8 -11
  51. package/src/extensions/core/polyfill/index.ts +29 -157
  52. package/src/extensions/enforcement/AGENTS.md +38 -1
  53. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  54. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  55. package/src/extensions/enforcement/session-health.ts +94 -5
  56. package/src/extensions/enforcement/whisper.ts +15 -1
  57. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  58. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  59. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  60. package/src/extensions/memory/AGENTS.md +37 -38
  61. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  62. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  63. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  64. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  65. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  66. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  67. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  68. package/src/extensions/self/watchdog/engine.ts +30 -2
  69. package/src/extensions/self/watchdog/index.ts +13 -1
  70. package/src/lib/ai/AGENTS.md +2 -0
  71. package/src/lib/ai/llm-call.ts +30 -0
  72. package/src/lib/ai/model-resolver.ts +16 -19
  73. package/src/lib/ai/presend-budget.ts +117 -0
  74. package/src/lib/config/braid-settings.ts +125 -0
  75. package/src/lib/config/per-tool-settings.ts +4 -4
  76. package/src/lib/detection/context-tiers.ts +52 -41
  77. package/src/lib/detection/context-usage.ts +211 -2
  78. package/src/lib/errors/llm-error.ts +55 -1
  79. package/src/lib/state/global-state.ts +11 -29
  80. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  81. package/src/lib/utils/wake-gate.ts +59 -4
@@ -54,6 +54,12 @@ import { createLogger } from "../core/logger.js";
54
54
  import { isRateLimitText } from "../errors/llm-error.js";
55
55
  import { isContextWindowErrorText } from "../errors/llm-error.js";
56
56
  import { sanitizeLlmErrorForLog, sanitizeLlmRequestText } from "./payload-hygiene.js";
57
+ import {
58
+ calibrateEstimate,
59
+ estimatePayloadTokens,
60
+ resolveWindow,
61
+ } from "../detection/context-usage.js";
62
+ import { guardAgainstDoomedSend } from "./presend-budget.js";
57
63
  import {
58
64
  getContextEmergencyOffloadRunner,
59
65
  getExtensionCtxProvider,
@@ -421,6 +427,30 @@ export async function callLlm(
421
427
  messages: [{ role: "user", content: userSafe.text, timestamp: Date.now() }],
422
428
  };
423
429
 
430
+ // ── pre-send budget ──
431
+ // A request over the window cannot succeed, and a provider 400 is a late,
432
+ // expensive way to learn it. Measure the payload the provider would receive
433
+ // (system + messages, calibrated against this session's own measured ratio),
434
+ // add the output budget, and compare against the resolved window - a
435
+ // configured cap binding below the model's window counts, because the
436
+ // provider will refuse what the cap already refused.
437
+ const resolvedWindow = resolveWindow((model as { contextWindow?: number }).contextWindow);
438
+ const budget = await guardAgainstDoomedSend({
439
+ measure: () =>
440
+ calibrateEstimate(
441
+ estimatePayloadTokens({ systemPrompt: context.systemPrompt, messages: context.messages }),
442
+ ).tokens,
443
+ outputTokens: maxTokens,
444
+ contextWindow: resolvedWindow.contextWindow,
445
+ // The only compaction available to an auxiliary call is the published
446
+ // offload: it shrinks the session's largest toolResults, which is where an
447
+ // oversized prompt came from. One attempt; nothing freed means still over.
448
+ compact: async () => (await runEmergencyOffloadForCall()) > 0,
449
+ onRefusal: (line) => log.error(line),
450
+ subject: "LLM call",
451
+ });
452
+ if (!budget.allowed) return { error: budget.line };
453
+
424
454
  // ── per-model concurrency limiter: acquire ONCE at function entry, release in finally ──
425
455
  // (One slot per callLlm invocation, not per retry - otherwise retries could
426
456
  // pile up beyond MAX_CONCURRENT_PER_MODEL.)
@@ -1,14 +1,14 @@
1
1
  /**
2
2
  * Model resolution helpers for pi-braid extensions.
3
3
  *
4
- * Resolves the merged auxiliary role (utilityModel) and the deprecated vision
5
- * alias: a setting may hold one model pattern or an ordered list, and the
4
+ * Resolves the merged auxiliary role (utilityModel) and the model a vision call
5
+ * needs: a setting may hold one model pattern or an ordered list, and the
6
6
  * resolver walks the list with the provider layer deciding per entry.
7
7
  */
8
8
 
9
9
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import type { Model, Api } from "@earendil-works/pi-ai";
11
- import { getCustomModelKey, UTILITY_MODEL_KEY, VISION_MODEL_KEY } from "../state/global-state.js";
11
+ import { getCustomModelKey, UTILITY_MODEL_KEY } from "../state/global-state.js";
12
12
  import { callLlm, isModelRouteUsable } from "./llm-call.js";
13
13
  import type { LlmCallOptions } from "./llm-call.js";
14
14
 
@@ -95,30 +95,27 @@ export function resolveUtilityModels(ctx: ExtensionContext): Model<Api>[] {
95
95
  }
96
96
 
97
97
  /**
98
- * Get the best vision model.
98
+ * The model a vision call should use.
99
+ *
99
100
  * Priority:
100
- * 1. Custom visionModel setting (deprecated alias, honored this release);
101
- * when it is an ordered list, the first entry that accepts image input
102
- * and whose route the provider layer reports usable
103
- * 2. Current model if vision-capable
104
- * 3. The merged role's first image-capable entry whose route the provider
105
- * layer reports usable (same ordered-list semantics as any role)
106
- * 4. First available vision model
101
+ * 1. The current model when it accepts images: the image stays in the call
102
+ * that already carries the prompt and the conversation
103
+ * 2. The merged role's first image-capable entry whose route the provider
104
+ * layer reports usable (the same ordered-list semantics as any role)
105
+ * 3. The first available model that accepts images
106
+ *
107
+ * A text-only entry is never selected for an image call.
107
108
  */
108
109
  export function resolveVisionModel(ctx: ExtensionContext): Model<Api> | undefined {
109
- // 1. Deprecated role key; still priority 1 for one release
110
- const custom = resolveRoleModel(ctx, VISION_MODEL_KEY, true);
111
- if (custom) return custom;
112
-
113
- // 2. Current model if vision-capable
110
+ // 1. Current model if vision-capable
114
111
  if (ctx.model?.input?.includes("image")) return ctx.model;
115
112
 
116
- // 3. The merged role supplies an image-capable entry, so the vision pin is
117
- // redundant after this release except as a determinism override.
113
+ // 2. The merged role supplies an image-capable entry; a text-only entry in
114
+ // the list is skipped rather than sent an image.
118
115
  const role = resolveRoleModel(ctx, UTILITY_MODEL_KEY, true);
119
116
  if (role) return role;
120
117
 
121
- // 4. First available vision model
118
+ // 3. First available vision model
122
119
  const available = ctx.modelRegistry.getAvailable();
123
120
  return available.find((m) => m?.input?.includes("image"));
124
121
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Pre-send budget: compare the request about to be sent against the model's
3
+ * resolved window, and refuse instead of letting the provider refuse.
4
+ *
5
+ * Why here: this is a request-layer decision. It needs three things at once -
6
+ * the outgoing payload, the requested output budget, and the resolved window -
7
+ * and only the layer that BUILDS the request has all three. A consumer that
8
+ * reads a percentage sees a number someone else measured; it cannot see what
9
+ * the provider is about to be handed.
10
+ *
11
+ * Why a guard and not a warning: a request over the window cannot succeed, so
12
+ * sending it buys nothing and costs a full round trip, a retry, and a session
13
+ * that looks wedged to whoever is watching. The remedy that actually frees
14
+ * space is compaction, and the caller owns it - so the guard runs it once and
15
+ * re-measures, and only then decides.
16
+ */
17
+
18
+ import { formatTokensK } from "../detection/context-usage.js";
19
+
20
+ export interface SendBudgetInput {
21
+ /** Calibrated tokens of the payload as it stands now. */
22
+ payloadTokens: number;
23
+ /** The output budget the request asks for; it is spent from the same window. */
24
+ outputTokens: number;
25
+ /** Resolved window (a configured cap may already bind below the model's). */
26
+ contextWindow: number;
27
+ }
28
+
29
+ export interface SendBudgetVerdict {
30
+ fits: boolean;
31
+ /** payloadTokens + outputTokens. */
32
+ projectedTokens: number;
33
+ contextWindow: number;
34
+ /** Tokens past the window; 0 when the request fits. */
35
+ overBy: number;
36
+ }
37
+
38
+ export function checkSendBudget(input: SendBudgetInput): SendBudgetVerdict {
39
+ const projectedTokens = input.payloadTokens + Math.max(0, input.outputTokens);
40
+ const contextWindow = input.contextWindow;
41
+ const overBy = contextWindow > 0 ? Math.max(0, projectedTokens - contextWindow) : 0;
42
+ return {
43
+ fits: contextWindow > 0 && overBy === 0,
44
+ projectedTokens,
45
+ contextWindow,
46
+ overBy,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The one line a refusal is allowed to say. It carries the three numbers a
52
+ * reader needs to act (payload, output budget, window) and names the remedy,
53
+ * because "context overflow" alone leaves nothing to do.
54
+ */
55
+ export function formatSendBudgetRefusal(verdict: SendBudgetVerdict, subject = "request"): string {
56
+ const window =
57
+ verdict.contextWindow > 0 ? formatTokensK(verdict.contextWindow) : "unknown window";
58
+ return (
59
+ `Context budget refused: ${subject} needs ${formatTokensK(verdict.projectedTokens)} ` +
60
+ `(payload + output budget) against a ${window} window, over by ${formatTokensK(verdict.overBy)}. ` +
61
+ `Nothing was sent. Compact first (\`context_compress action="archive"\`), or lower the output ` +
62
+ `budget, then retry.`
63
+ );
64
+ }
65
+
66
+ export type GuardedSend =
67
+ | { allowed: true; verdict: SendBudgetVerdict; compacted: boolean }
68
+ | { allowed: false; verdict: SendBudgetVerdict; line: string; compacted: boolean };
69
+
70
+ /**
71
+ * Decide whether the send may proceed: measure, compare, and when the request
72
+ * cannot fit, run the caller's compaction ONCE and measure again.
73
+ *
74
+ * `compact` returns true only when it actually freed context. A compaction
75
+ * that frees nothing must not re-open the door - the second measurement is the
76
+ * one that decides, and it is taken after the compaction, not assumed from it.
77
+ * `measure` is called fresh each time for the same reason: the payload after a
78
+ * compaction is a different payload.
79
+ */
80
+ export async function guardAgainstDoomedSend(params: {
81
+ measure: () => number;
82
+ outputTokens: number;
83
+ contextWindow: number;
84
+ compact?: () => Promise<boolean> | boolean;
85
+ onRefusal?: (line: string, verdict: SendBudgetVerdict) => void;
86
+ subject?: string;
87
+ }): Promise<GuardedSend> {
88
+ const window = params.contextWindow;
89
+ let verdict = checkSendBudget({
90
+ payloadTokens: params.measure(),
91
+ outputTokens: params.outputTokens,
92
+ contextWindow: window,
93
+ });
94
+ if (verdict.fits) return { allowed: true, verdict, compacted: false };
95
+
96
+ let compacted = false;
97
+ if (params.compact) {
98
+ try {
99
+ compacted = (await params.compact()) === true;
100
+ } catch {
101
+ // A failed compaction leaves the request where it was: still over.
102
+ compacted = false;
103
+ }
104
+ }
105
+ if (compacted) {
106
+ verdict = checkSendBudget({
107
+ payloadTokens: params.measure(),
108
+ outputTokens: params.outputTokens,
109
+ contextWindow: window,
110
+ });
111
+ if (verdict.fits) return { allowed: true, verdict, compacted: true };
112
+ }
113
+
114
+ const line = formatSendBudgetRefusal(verdict, params.subject);
115
+ params.onRefusal?.(line, verdict);
116
+ return { allowed: false, verdict, line, compacted };
117
+ }
@@ -159,6 +159,27 @@ interface BraidConfig {
159
159
  /** Terminal errors before the gate closes. Default 3. */
160
160
  threshold?: number;
161
161
  };
162
+ /**
163
+ * Route-failure wake breaker: while a session has accumulated
164
+ * `threshold` provider failures of any class except a context-window
165
+ * overflow or an abort since its last successful call, timer wakes,
166
+ * watchdog escalations and explicitly-waking whispers are delivered
167
+ * without starting a turn. `floorMs` is the one self-started turn the
168
+ * latch releases after that long with no successful release signal, so a
169
+ * parked session is never permanently starved of turns. Default
170
+ * { enabled: true, threshold: 3, floorMs: 3600000 }.
171
+ *
172
+ * Example:
173
+ * "braid": { "session": { "routeBreaker": { "enabled": false } } }
174
+ */
175
+ routeBreaker?: {
176
+ /** false makes the whole breaker inert (byte-identical to pre-breaker behavior). */
177
+ enabled?: boolean;
178
+ /** Provider failures since the last successful call before wakes park. Default 3. */
179
+ threshold?: number;
180
+ /** The one released turn's cadence while the latch stays open. Default 3600000 (1h). */
181
+ floorMs?: number;
182
+ };
162
183
  };
163
184
  timers?: {
164
185
  /**
@@ -1117,6 +1138,110 @@ export function getTerminalBreakerConfig(): TerminalBreakerConfig {
1117
1138
  return resolveTerminalBreaker(readSettings().braid?.session?.terminalBreaker);
1118
1139
  }
1119
1140
 
1141
+ // ── route-failure wake breaker (braid.session.routeBreaker) ────────────
1142
+
1143
+ /** Default provider-failure count before self-started turns park. */
1144
+ export const ROUTE_BREAKER_DEFAULT_THRESHOLD = 3;
1145
+ /** Upper bound for a configured threshold (guards a typo'd huge value). */
1146
+ export const ROUTE_BREAKER_THRESHOLD_MAX = 20;
1147
+ /**
1148
+ * Default cadence of the single released turn while the latch stays open.
1149
+ * One hour: long enough that a parked session does not spend a call per
1150
+ * retry against a route that is failing every time, short enough that an
1151
+ * owner who never touches the session still gets an automatic attempt.
1152
+ */
1153
+ export const ROUTE_BREAKER_DEFAULT_FLOOR_MS = 3_600_000;
1154
+ /** Bounds on a configured floor: below the slowest retry cadence it would
1155
+ * release a turn per retry; above a day it stops being a floor at all. */
1156
+ export const ROUTE_BREAKER_FLOOR_MIN_MS = 60_000;
1157
+ export const ROUTE_BREAKER_FLOOR_MAX_MS = 86_400_000;
1158
+
1159
+ export interface RouteBreakerConfig {
1160
+ /** Master gate. Default true. */
1161
+ enabled: boolean;
1162
+ /** Provider failures since the last successful call before wakes park. */
1163
+ threshold: number;
1164
+ /** The one released turn's cadence while the latch stays open. */
1165
+ floorMs: number;
1166
+ }
1167
+
1168
+ /** Warned once per process about an invalid routeBreaker field. */
1169
+ let _warnedInvalidRouteBreaker = false;
1170
+
1171
+ /** Once-per-process warning for an ignored routeBreaker value. */
1172
+ function _warnInvalidRouteBreaker(field: "threshold" | "floorMs", value: unknown): void {
1173
+ if (_warnedInvalidRouteBreaker) return;
1174
+ _warnedInvalidRouteBreaker = true;
1175
+ const expected =
1176
+ field === "threshold"
1177
+ ? `an integer 1..${ROUTE_BREAKER_THRESHOLD_MAX}`
1178
+ : `an integer ${ROUTE_BREAKER_FLOOR_MIN_MS}..${ROUTE_BREAKER_FLOOR_MAX_MS} (ms)`;
1179
+ const fallback =
1180
+ field === "threshold" ? ROUTE_BREAKER_DEFAULT_THRESHOLD : ROUTE_BREAKER_DEFAULT_FLOOR_MS;
1181
+ _log.warn(
1182
+ `Invalid braid.session.routeBreaker in settings.json - ignoring ${field} and ` +
1183
+ `using the default (${fallback}). Expected ${expected}.`,
1184
+ { field, value },
1185
+ );
1186
+ }
1187
+
1188
+ /**
1189
+ * Pure resolver for braid.session.routeBreaker. Absent block ⇒ default-on with
1190
+ * threshold 3 and a 1h floor. `enabled: false` ⇒ the breaker is inert. A
1191
+ * threshold or floor that is not a valid integer in range warns once and
1192
+ * falls back to its default; a non-object block counts as absent. Kept pure
1193
+ * so the validation is unit-testable without touching live settings.json.
1194
+ */
1195
+ export function resolveRouteBreaker(raw: unknown): RouteBreakerConfig {
1196
+ const defaults: RouteBreakerConfig = {
1197
+ enabled: true,
1198
+ threshold: ROUTE_BREAKER_DEFAULT_THRESHOLD,
1199
+ floorMs: ROUTE_BREAKER_DEFAULT_FLOOR_MS,
1200
+ };
1201
+ if (raw === undefined || raw === null || typeof raw !== "object") return defaults;
1202
+ const block = raw as { enabled?: unknown; threshold?: unknown; floorMs?: unknown };
1203
+ const enabled = block.enabled !== false;
1204
+ let threshold = defaults.threshold;
1205
+ if (block.threshold !== undefined) {
1206
+ const v = block.threshold;
1207
+ if (
1208
+ typeof v === "number" &&
1209
+ Number.isInteger(v) &&
1210
+ v >= 1 &&
1211
+ v <= ROUTE_BREAKER_THRESHOLD_MAX
1212
+ ) {
1213
+ threshold = v;
1214
+ } else {
1215
+ _warnInvalidRouteBreaker("threshold", v);
1216
+ }
1217
+ }
1218
+ let floorMs = defaults.floorMs;
1219
+ if (block.floorMs !== undefined) {
1220
+ const v = block.floorMs;
1221
+ if (
1222
+ typeof v === "number" &&
1223
+ Number.isInteger(v) &&
1224
+ v >= ROUTE_BREAKER_FLOOR_MIN_MS &&
1225
+ v <= ROUTE_BREAKER_FLOOR_MAX_MS
1226
+ ) {
1227
+ floorMs = v;
1228
+ } else {
1229
+ _warnInvalidRouteBreaker("floorMs", v);
1230
+ }
1231
+ }
1232
+ return { enabled, threshold, floorMs };
1233
+ }
1234
+
1235
+ /**
1236
+ * Read the effective route-failure wake-breaker config from settings.json,
1237
+ * fresh on every call (no caching), like the other readers. The predicate and
1238
+ * the feed read this once per call; the floor's clock leans on it, so a
1239
+ * runtime change takes effect on the next turn-start question.
1240
+ */
1241
+ export function getRouteBreakerConfig(): RouteBreakerConfig {
1242
+ return resolveRouteBreaker(readSettings().braid?.session?.routeBreaker);
1243
+ }
1244
+
1120
1245
  // ── wake-delivery stall alert (braid.timers.wakeAlert) ───────────────
1121
1246
 
1122
1247
  /** Default wake-delivery alerting: on, page after 2 outcome timeouts. */
@@ -10,10 +10,10 @@
10
10
  *
11
11
  * This module is the one writer for settings.json. Every write goes through
12
12
  * `updateSettings`, which keeps read-modify-write in a single synchronous
13
- * transaction and installs the result with temp-file-plus-rename. The model
14
- * Two writers rewriting the whole file from their own async read-modify-write
15
- * can interleave: the later write replaces the file with its own read snapshot
16
- * and drops the other's key (a `/vision-model` key lost to a concurrent
13
+ * transaction and installs the result with temp-file-plus-rename. Two writers
14
+ * rewriting the whole file from their own async read-modify-write can
15
+ * interleave: the later write replaces the file with its own read snapshot
16
+ * and drops the other's key (a `/utility-model` key lost to a concurrent
17
17
  * toggle).
18
18
  *
19
19
  * A refused write is reported as a return value, not a thrown exception. The
@@ -34,7 +34,7 @@ import {
34
34
  USAGE_COMPACT_MEDIUM,
35
35
  USAGE_FIRED_RESET_BELOW,
36
36
  } from "./context-thresholds.js";
37
- import { tokenArms, formatTokensK } from "./context-usage.js";
37
+ import { tokenArms } from "./context-usage.js";
38
38
  import { getResolvedContextWindow } from "../config/braid-settings.js";
39
39
 
40
40
  // ═══════════════════════════════════════════════════════════════════════════
@@ -80,34 +80,52 @@ export function contextUsageTier(usagePercent: number): ContextUsageTierInfo | n
80
80
  // ENFORCEMENT NUDGE MESSAGES (byte-identical across all enforcement sites)
81
81
  // ═══════════════════════════════════════════════════════════════════════════
82
82
 
83
- /** Percent-tier nudge message text (identical at every enforcement site). */
84
- export function contextUsageTierMessage(tier: ContextUsageTier, usagePercent: number): string {
85
- const pct = Math.round(usagePercent);
83
+ /**
84
+ * The deadline every whisper states instead of restating its number. The bars
85
+ * live in context-thresholds.ts and the meter in context-usage.ts; a
86
+ * percentage copied into prose is a second copy that drifts from the one
87
+ * owner. What the reader cannot derive from the bar is WHEN the cost lands:
88
+ * the compaction the advice leads to is armed, not immediate.
89
+ */
90
+ const SETTLE_DEADLINE = "an armed compaction fires when the run settles";
91
+
92
+ /**
93
+ * Percent-tier nudge message text (identical at every enforcement site).
94
+ * One sentence names the state and the deadline, then the action. No number
95
+ * is restated: the rung's bar selected this message, and the meter rendered
96
+ * the count where a count belongs (context_inspect, the tool result).
97
+ */
98
+ export function contextUsageTierMessage(tier: ContextUsageTier): string {
86
99
  switch (tier) {
87
100
  case "compact":
88
101
  return (
89
- `Context at ${pct}%. Pipeline: context_navigate(action="tag") -> ` +
90
- `context_compress(action="archive") -> context_compress(action="slide"). Tag your position first.`
102
+ `Context is at the compaction arm; ${SETTLE_DEADLINE}. ` +
103
+ `Tag with context_navigate(action="tag") and archive with ` +
104
+ `context_compress(action="archive") before starting the next task.`
91
105
  );
92
106
  case "critical":
93
107
  return (
94
- `Context at ${pct}%. Tag with context_navigate(action="tag"), then ` +
95
- `context_compress(action="archive") to branch with a summary.`
108
+ `Context is above the critical arm; ${SETTLE_DEADLINE}. ` +
109
+ `Tag with context_navigate(action="tag") and archive with ` +
110
+ `context_compress(action="archive") before starting the next task.`
96
111
  );
97
112
  case "warning":
98
113
  return (
99
- `Context at ${pct}%. Warning — tag with context_navigate(action="tag"), then ` +
100
- `context_compress(action="archive") to branch with a summary.`
114
+ `Context is above the warning arm; ${SETTLE_DEADLINE}. ` +
115
+ `Tag with context_navigate(action="tag") and archive with ` +
116
+ `context_compress(action="archive") before starting the next task.`
101
117
  );
102
118
  case "advisory":
103
119
  return (
104
- `Context at ${pct}%. Advisory — consider context_compress(action="archive") for completed tasks. ` +
105
- `context_navigate(action="tag") to mark your position first.`
120
+ `Context is above the advisory arm; ${SETTLE_DEADLINE}. ` +
121
+ `Archive completed work with context_compress(action="archive") and tag with ` +
122
+ `context_navigate(action="tag") before starting the next task.`
106
123
  );
107
124
  case "soft":
108
125
  return (
109
- `Context at ${pct}%. Soft whisper — consider context_inspect(detail="prune") ` +
110
- `to see candidates for archival.`
126
+ `Context is above the soft arm; ${SETTLE_DEADLINE}. ` +
127
+ `Inspect with context_inspect(detail="prune") for candidates, then tag with ` +
128
+ `context_navigate(action="tag") before starting the next task.`
111
129
  );
112
130
  }
113
131
  }
@@ -115,25 +133,12 @@ export function contextUsageTierMessage(tier: ContextUsageTier, usagePercent: nu
115
133
  /**
116
134
  * Token-tier nudge message text (identical at every enforcement site).
117
135
  * `level` mirrors the tier reached by the token-count check; arms are
118
- * fractions of the resolved window (0.45W warning, 0.18W soft).
136
+ * fractions of the resolved window (0.45W warning, 0.18W soft). The text is
137
+ * the tier's: a rung is a threshold, not a label, and the whisper no longer
138
+ * renders the count that selected it.
119
139
  */
120
- export function contextUsageTokenMessage(
121
- level: "warning" | "soft",
122
- usagePercent: number,
123
- usageTokens: number,
124
- ): string {
125
- const tokensK = formatTokensK(usageTokens);
126
- const pct = Math.round(usagePercent);
127
- if (level === "warning") {
128
- return (
129
- `Context at ${tokensK} tokens (${pct}%). ` +
130
- `Pipeline: context_navigate(action="tag") -> context_compress(action="archive") -> context_compress(action="slide").`
131
- );
132
- }
133
- return (
134
- `Context at ${tokensK} tokens. ` +
135
- `Consider context_inspect(detail="prune") to see candidates, or tag position with context_navigate(action="tag").`
136
- );
140
+ export function contextUsageTokenMessage(level: "warning" | "soft"): string {
141
+ return contextUsageTierMessage(level === "warning" ? "warning" : "soft");
137
142
  }
138
143
 
139
144
  // ═══════════════════════════════════════════════════════════════════════════
@@ -180,7 +185,7 @@ export interface ContextNudge extends ContextNudgeRung {
180
185
  }
181
186
 
182
187
  interface RungSpec extends ContextNudgeRung {
183
- render: (usagePercent: number, usageTokens: number) => string;
188
+ render: () => string;
184
189
  }
185
190
 
186
191
  /**
@@ -198,39 +203,39 @@ function nudgeRungs(window?: number | null): RungSpec[] {
198
203
  unit: "tokens",
199
204
  threshold: arms.soft,
200
205
  position: positionOf(arms.soft),
201
- render: (p, t) => contextUsageTokenMessage("soft", p, t),
206
+ render: () => contextUsageTokenMessage("soft"),
202
207
  },
203
208
  {
204
209
  id: "percent:soft",
205
210
  ...pct(USAGE_WHISPER_SOFT),
206
- render: (p) => contextUsageTierMessage("soft", p),
211
+ render: () => contextUsageTierMessage("soft"),
207
212
  },
208
213
  {
209
214
  id: "tokens:warning",
210
215
  unit: "tokens",
211
216
  threshold: arms.warning,
212
217
  position: positionOf(arms.warning),
213
- render: (p, t) => contextUsageTokenMessage("warning", p, t),
218
+ render: () => contextUsageTokenMessage("warning"),
214
219
  },
215
220
  {
216
221
  id: "percent:advisory",
217
222
  ...pct(USAGE_WHISPER_ADVISORY),
218
- render: (p) => contextUsageTierMessage("advisory", p),
223
+ render: () => contextUsageTierMessage("advisory"),
219
224
  },
220
225
  {
221
226
  id: "percent:warning",
222
227
  ...pct(USAGE_WHISPER_WARNING),
223
- render: (p) => contextUsageTierMessage("warning", p),
228
+ render: () => contextUsageTierMessage("warning"),
224
229
  },
225
230
  {
226
231
  id: "percent:critical",
227
232
  ...pct(USAGE_WHISPER_CRITICAL),
228
- render: (p) => contextUsageTierMessage("critical", p),
233
+ render: () => contextUsageTierMessage("critical"),
229
234
  },
230
235
  {
231
236
  id: "percent:compact",
232
237
  ...pct(USAGE_COMPACT_MEDIUM),
233
- render: (p) => contextUsageTierMessage("compact", p),
238
+ render: () => contextUsageTierMessage("compact"),
234
239
  },
235
240
  ];
236
241
  }
@@ -246,6 +251,12 @@ export function resolveContextNudge(
246
251
  usagePercent: number,
247
252
  usageTokens: number,
248
253
  window?: number | null,
254
+ /**
255
+ * How the number was produced (measured / estimated). Rendered with the
256
+ * message so a reader can tell a large context from a badly counted one;
257
+ * the ladder itself is unchanged, since a rung is a bar, not a label.
258
+ */
259
+ provenance?: string,
249
260
  ): ContextNudge | null {
250
261
  let best: RungSpec | null = null;
251
262
  for (const rung of nudgeRungs(window)) {
@@ -259,7 +270,7 @@ export function resolveContextNudge(
259
270
  unit: best.unit,
260
271
  threshold: best.threshold,
261
272
  position: best.position,
262
- message: best.render(usagePercent, usageTokens),
273
+ message: provenance ? `${best.render()} (${provenance})` : best.render(),
263
274
  };
264
275
  }
265
276