pi-braid 0.42.1 → 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 (81) hide show
  1. package/CHANGELOG.md +71 -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
@@ -40,7 +40,7 @@ import { pushRssSample, assessSustainedRssGrowth, RSS_RING_CAP } from "./rss-tel
40
40
  import { getRssBootTelemetry, setRssBootBaseline } from "../state/global-state.js";
41
41
  import { getExtensionState, hasExtensionState, safeSessionManagerTyped, } from "../state/extension-state.js";
42
42
  import { getContextUsage } from "../detection/context-tiers.js";
43
- import { measureLiveUsage } from "../detection/context-usage.js";
43
+ import { measureLiveUsage, describeUsage } from "../detection/context-usage.js";
44
44
  const log = createLogger("context-heartbeat");
45
45
  /** Sink directory (created on first append; see header note). */
46
46
  export function heartbeatTelemetryDir() {
@@ -389,20 +389,30 @@ export function collectAndEmitContextHeartbeat(ctx, opts = {}) {
389
389
  export function getSelfStateSample(ctx) {
390
390
  const sample = {
391
391
  contextTokens: null,
392
+ contextPercent: null,
393
+ contextProvenance: null,
392
394
  cacheHitShare: null,
393
395
  nearDupCount: null,
394
396
  tpsEma: null,
395
397
  hygieneActs: null,
396
398
  };
397
399
  try {
398
- // Context tokens: live read (compaction-aware session-tree measure),
399
- // not the last-tick snapshot — a summary rendered right after a slide
400
- // must not report the pre-slide size. Falls back to the duck-typed
401
- // accessor when the session tree is unavailable.
400
+ // Context size: live read (compaction-aware session-tree measure), not the
401
+ // last-tick snapshot - a summary rendered right after a slide must not
402
+ // report the pre-slide size.
403
+ //
404
+ // One instrument, and it is this one. Size, percent and provenance come
405
+ // from a single reading here; the provider accessor answers a different
406
+ // question over a different tree (session projection vs branch), and a
407
+ // delivery that prints both is two ages of one fact. When this meter has
408
+ // no reading, the line says n/a rather than borrowing a second opinion:
409
+ // the reader cannot act on a number whose instrument it cannot name.
402
410
  const live = measureLiveUsage(ctx);
403
- const usage = live ?? getContextUsage(ctx);
404
- if (usage && typeof usage.tokens === "number")
405
- sample.contextTokens = usage.tokens;
411
+ if (live) {
412
+ sample.contextTokens = live.tokens;
413
+ sample.contextPercent = live.percent;
414
+ sample.contextProvenance = describeUsage(live);
415
+ }
406
416
  }
407
417
  catch {
408
418
  /* keep null */
@@ -105,6 +105,12 @@
105
105
  */
106
106
  export declare function isAgentBusy(): boolean;
107
107
  export declare const RUN_REGION_MAX_MS = 120000;
108
+ /** Record that the last turn failed on request shape (a context-length refusal). */
109
+ export declare function noteRequestShapeFailure(detail: string): void;
110
+ /** The recorded request-shape failure, or null. */
111
+ export declare function requestShapeFailure(): string | null;
112
+ /** Clear the record (a request that fits went through, or a new session). */
113
+ export declare function clearRequestShapeFailure(): void;
108
114
  /** Whether a triggerTurn send should be gated (pre-flight tail in progress). */
109
115
  export declare function isRunRegionActive(): boolean;
110
116
  /** Test hook: reset module state between fixtures (also cancels the fail-safe). */
@@ -140,6 +140,26 @@ export const RUN_REGION_MAX_MS = 120_000;
140
140
  let _failSafeHandle = null;
141
141
  // Test hook: override the fail-safe bound (null restores the default).
142
142
  let _failSafeMsOverride = null;
143
+ /**
144
+ * Why the last turn could not be sent at all, when the reason is the SHAPE of
145
+ * the request rather than the state of the provider. A context-length refusal
146
+ * is permanent for a given context: every later turn carrying the same payload
147
+ * is refused the same way, so an ungated wake that starts one is not a retry,
148
+ * it is the same failure under a fresh request id.
149
+ */
150
+ let _requestShapeFailure = null;
151
+ /** Record that the last turn failed on request shape (a context-length refusal). */
152
+ export function noteRequestShapeFailure(detail) {
153
+ _requestShapeFailure = detail;
154
+ }
155
+ /** The recorded request-shape failure, or null. */
156
+ export function requestShapeFailure() {
157
+ return _requestShapeFailure;
158
+ }
159
+ /** Clear the record (a request that fits went through, or a new session). */
160
+ export function clearRequestShapeFailure() {
161
+ _requestShapeFailure = null;
162
+ }
143
163
  function failSafeMs() {
144
164
  return _failSafeMsOverride ?? RUN_REGION_MAX_MS;
145
165
  }
@@ -153,16 +173,42 @@ function clearFailSafe() {
153
173
  function armRunRegion() {
154
174
  _runRegionActive = true;
155
175
  clearFailSafe();
176
+ scheduleFailSafe();
177
+ // Do not keep the process alive for a stuck gate.
178
+ unrefFailSafe();
179
+ }
180
+ /** Let the process exit while a fail-safe window is pending. */
181
+ function unrefFailSafe() {
182
+ const handle = _failSafeHandle;
183
+ if (typeof handle?.unref === "function")
184
+ handle.unref();
185
+ }
186
+ /**
187
+ * One fail-safe window. Normally the gate opens here: a gate stuck closed by a
188
+ * pre-flight abort rewrites every wake into a queued steer that never starts a
189
+ * turn, which is its own failure.
190
+ *
191
+ * The exception is a recorded request-shape failure. There, opening the gate
192
+ * buys no safety - it starts the same doomed request again, and again. So the
193
+ * gate stays closed and the window re-arms: wakes keep arriving as steers into
194
+ * the session (the shape that reads them when a run does start) without
195
+ * starting one.
196
+ */
197
+ function scheduleFailSafe() {
156
198
  _failSafeHandle = setTimeout(() => {
157
199
  _failSafeHandle = null;
200
+ if (_requestShapeFailure) {
201
+ log.warn(`[wake-gate] fail-safe: keeping triggerTurn wakes gated - the last turn was refused on ` +
202
+ `request shape (context length), so the request it would start cannot succeed. ` +
203
+ `Remedy: compact the session. Detail: ${_requestShapeFailure}`);
204
+ scheduleFailSafe();
205
+ unrefFailSafe();
206
+ return;
207
+ }
158
208
  _runRegionActive = false;
159
209
  log.warn(`[wake-gate] fail-safe: run region auto-cleared after ${failSafeMs()}ms without a release event ` +
160
210
  `(pre-flight abort?) — triggerTurn wakes ungated again`);
161
211
  }, failSafeMs());
162
- // Do not keep the process alive for a stuck gate.
163
- if (typeof _failSafeHandle?.unref === "function") {
164
- _failSafeHandle.unref();
165
- }
166
212
  }
167
213
  /** Release the gate and cancel the fail-safe timer. */
168
214
  function releaseRunRegion() {
@@ -178,6 +224,7 @@ export function resetWakeGateForTests() {
178
224
  releaseRunRegion();
179
225
  _lastAgentCtx = null;
180
226
  _failSafeMsOverride = null;
227
+ _requestShapeFailure = null;
181
228
  }
182
229
  /** Test hook: shorten/extend the fail-safe bound (null restores the default). */
183
230
  export function _setWakeGateFailSafeMsForTests(ms) {
@@ -231,6 +278,7 @@ export function registerWakeGate(pi) {
231
278
  });
232
279
  pi.on(SESSION_SHUTDOWN, () => {
233
280
  releaseRunRegion();
281
+ _requestShapeFailure = null; // a new session starts without a shape verdict
234
282
  _lastAgentCtx = null; // no live session after shutdown: fail open until the next capture
235
283
  });
236
284
  }
package/docs/SETUP.md CHANGED
@@ -37,9 +37,9 @@ workspace manifest); if this table and `engines` ever disagree, trust
37
37
  from npm needs no checkout at all.
38
38
 
39
39
  **How the pi version resolves.** braid declares the `@earendil-works/pi-*`
40
- packages as peer dependencies with unconstrained (`*`) ranges. npm resolves
41
- peers at install time: against a compatible pi installation already in your
42
- tree when one exists, otherwise by auto-installing the current release. The
40
+ packages as peer dependencies in the `^1.2.0` range. npm resolves peers at
41
+ install time: against a compatible pi installation already in your tree when one
42
+ exists, otherwise by auto-installing a release that satisfies the range. The
43
43
  result is pinned in `package-lock.json`, so braid runs against whatever pi
44
44
  version your install resolved to rather than pinning its own;
45
45
  `npm ls @earendil-works/pi-coding-agent` shows what you got.
@@ -306,6 +306,7 @@ The user-global file always exists; the project one is optional and belongs to p
306
306
  | `braid.enforcement.nudgeConfigs.<type>` | object | built-in per-type defaults | Per-nudge-type overrides with leaf shape `braid.enforcement.nudgeConfigs.<type>.<key>`; accepted fields are `baseCooldownMs` (number), `escalateAfter` (number), and `deduplicate` (boolean). Types: `validation`, `recordFailure`, `malformed`, `memory`, `scratchpad`, `context`, `sessionSignals`. Invalid entries are logged and dropped. |
307
307
  | `braid.memory.writeGate` | object | gate ON, 20-min cooldown, `enforce` | Review-before-write gate on episode writes; `mode: "warn"` logs decisions and writes anyway; `sites` opts individual writers out. |
308
308
  | `braid.timers.maxWakeAttempts` | integer 1..10 | `3` | Redelivery cap for a failed timer wake before it is dropped with a visible notice. |
309
+ | `braid.session.routeBreaker` | object | ON, 3 failures, 1h floor | Route-failure latch: after `threshold` provider failures of any class except a context-window overflow or an abort since the session's last successful call, self-started turns park - timer wakes, watchdog escalations and explicitly-waking whispers are delivered non-waking, the content still reaches the session and the out-of-band line still fires. Released by a successful provider call, a clean wake turn, a route change, an owner recovery or a session start; while open it still releases one turn per `floorMs`. `enabled: false` makes it inert. |
309
310
  | `braid.timers.wakeAlert` | object | ON, `outcomeTimeouts: 2` | Dead-wake page: repeated outcome timeouts / exhausted redeliveries feed the watchdog's wake-delivery condition, which pages the owner out of band (telegram) once per episode plus one recovery line. `mode: "off"` disables the feed (delivery itself is unchanged); `outcomeTimeouts` is an integer 2..10 (1 would page on every normal long turn). |
310
311
  | `braid.context.contextLimitTokens` | positive number | provider context window | The window every surface computes with (usage math, density, fallbacks, pi-core threshold compaction and overflow detection, TUI footer). A CEILING: min(contextLimitTokens, true window) when known, else the cap; re-plumbed on session start and /reload and never widens a smaller true window. The provider catalog keeps the true size. |
311
312
  | `braid.context.toolResultSizeCap` | object | ON, 262144 chars | Capture-time cap: oversized tool results are flushed to disk and replaced by a stub. |
@@ -480,14 +481,14 @@ If the failure persists, open an issue with the full error from `npm run build`.
480
481
 
481
482
  ### TypeScript errors after upgrade
482
483
 
483
- braid declares `@earendil-works/pi-*` as peer dependencies with unconstrained
484
- (`*`) ranges, resolved at install time (see [Prerequisites](#prerequisites)).
484
+ braid declares `@earendil-works/pi-*` as peer dependencies in the `^1.2.0`
485
+ range, resolved at install time (see [Prerequisites](#prerequisites)).
485
486
  Make sure the pi packages are in this repo's dependency tree:
486
487
 
487
488
  ```bash
488
489
  ls node_modules/@earendil-works/ 2>/dev/null
489
490
  # If empty, the pi packages aren't in this repo's dependency tree.
490
- # Run `npm install` (npm auto-installs unconstrained peer dependencies),
491
+ # Run `npm install` (npm auto-installs peer dependencies inside the range),
491
492
  # or run pi from outside this repo.
492
493
  ```
493
494
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.42.1",
4
- "description": "Metacognitive extension suite for pi-coding-agent: enforcement, memory, reasoning, self-improvement, and structured cognitive signals.",
3
+ "version": "0.43.0",
4
+ "description": "Adds memory, plan tracking, and completion checks to the pi coding agent, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -89,16 +89,13 @@
89
89
  },
90
90
  "keywords": [
91
91
  "pi-package",
92
- "pi",
93
- "pi-extension",
94
92
  "pi-coding-agent",
95
- "llm-agent",
96
- "cognitive-systems",
97
- "enforcement",
98
- "planning",
99
- "metacognition",
100
- "self-improvement",
101
- "memory-management"
93
+ "pi-extension",
94
+ "coding-agent",
95
+ "agent-memory",
96
+ "context-management",
97
+ "subagents",
98
+ "skills"
102
99
  ],
103
100
  "author": "kifirkin",
104
101
  "license": "MIT",
@@ -3,10 +3,9 @@
3
3
  *
4
4
  * Three concerns:
5
5
  * 1. Model selection: /utility-model (the merged role) opens the
6
- * ModelSelectorComponent UI; /max-power-model is a deprecated alias of it
7
- * and /vision-model is a deprecated alias kept for one release. Model
8
- * resolution is handled by src/lib/ai/model-resolver.ts (used by
9
- * vision/metacognition tools directly).
6
+ * ModelSelectorComponent UI. Model resolution is handled by
7
+ * src/lib/ai/model-resolver.ts (used by vision/metacognition tools
8
+ * directly).
10
9
  * 2. Session manager patches: context_navigate and context_compress tools
11
10
  * need SessionManager methods in --no-session mode.
12
11
  * 3. Context window plumb: the session model reports braid's configured
@@ -31,11 +30,7 @@ import type {
31
30
  } from "@earendil-works/pi-coding-agent";
32
31
  import { ModelSelectorComponent, SettingsManager } from "@earendil-works/pi-coding-agent";
33
32
  import type { Model, Api } from "@earendil-works/pi-ai";
34
- import {
35
- resolveUtilityModel,
36
- resolveVisionModel,
37
- normaliseRoleSetting,
38
- } from "../../../lib/ai/model-resolver.js";
33
+ import { resolveUtilityModel, normaliseRoleSetting } from "../../../lib/ai/model-resolver.js";
39
34
  import {
40
35
  applyCompactionReserveTokens,
41
36
  applyConfiguredContextWindow,
@@ -52,10 +47,7 @@ const log = createLogger("polyfill");
52
47
  import {
53
48
  getCustomModelKey,
54
49
  getCustomModelKeys,
55
- consumeMaxPowerDeprecationNotice,
56
50
  UTILITY_MODEL_KEY,
57
- VISION_MODEL_KEY,
58
- MAX_POWER_MODEL_KEY,
59
51
  } from "../../../lib/state/global-state.js";
60
52
  import type { CustomModelKeyValue } from "../../../lib/state/global-state.js";
61
53
 
@@ -80,12 +72,6 @@ interface SessionManagerLike {
80
72
  getContextUsage?(): unknown;
81
73
  }
82
74
 
83
- // Type guard for checking if a model has image input capability
84
- function hasImageInput(model: { input?: unknown }): boolean {
85
- const input = model.input;
86
- return Array.isArray(input) && (input as unknown[]).includes("image");
87
- }
88
-
89
75
  /** Shared sessionManager reference - used by patchSessionManagerMethods */
90
76
  import { getExtensionState } from "../../../lib/state/extension-state.js";
91
77
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -153,26 +139,13 @@ async function setRoleSettingFromArgs(
153
139
  }
154
140
 
155
141
  /**
156
- * The /utility-model command body. The deprecated /max-power-model alias
157
- * drives the same function: the roles merged, so both commands write the one
158
- * canonical key and differ only in the deprecation notice.
142
+ * The /utility-model command body. The role it configures is also the one
143
+ * vision analysis falls back to, so there is no separate vision command.
159
144
  */
160
- async function runUtilityModelCommand(
161
- args: string,
162
- ctx: ExtensionCommandContext,
163
- viaDeprecatedAlias: boolean,
164
- ): Promise<void> {
165
- if (viaDeprecatedAlias) {
166
- ctx.ui.notify(
167
- "/max-power-model is deprecated: the max-power role merged into the utility role. " +
168
- "Use /utility-model; the alias is removed next release.",
169
- "warning",
170
- );
171
- }
172
-
145
+ async function runUtilityModelCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {
173
146
  if (!args || args.trim() === "") {
174
147
  if (ctx.hasUI) {
175
- await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", null, resolveUtilityModel);
148
+ await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", resolveUtilityModel);
176
149
  } else {
177
150
  const model = resolveUtilityModel(ctx);
178
151
  const patterns = configuredRolePatterns(UTILITY_MODEL_KEY);
@@ -215,9 +188,6 @@ function persistCustomKeys(): void {
215
188
  for (const [key, value] of map) {
216
189
  settings[key] = value;
217
190
  }
218
- // Any role write retires the legacy key in the same transaction: a
219
- // stale alias left on disk is resurrected by the next load.
220
- delete settings[MAX_POWER_MODEL_KEY];
221
191
  });
222
192
  } catch {
223
193
  // Non-fatal: settings won't persist but everything else still works
@@ -225,39 +195,16 @@ function persistCustomKeys(): void {
225
195
  }
226
196
 
227
197
  /**
228
- * Load custom keys from pi's settings.json into the in-memory map.
229
- * A role key carries either one pattern or an ordered list; both land in the
230
- * map in the list form the resolver walks. A value with no usable pattern is
198
+ * Load the utility role from pi's settings.json into the in-memory map.
199
+ * The key carries either one pattern or an ordered list; both land in the map
200
+ * in the list form the resolver walks. A value with no usable pattern is
231
201
  * treated as unset rather than stored as something that resolves to nothing.
232
202
  */
233
203
  function loadCustomKeysFromDisk(): void {
234
204
  try {
235
205
  const settings = readSettingsFile();
236
- const map = getCustomModelKeys();
237
- for (const key of [VISION_MODEL_KEY, UTILITY_MODEL_KEY]) {
238
- const value = toRoleSettingValue(normaliseRoleSetting(settings[key]));
239
- if (value !== undefined) map.set(key, value);
240
- }
241
-
242
- // Deprecated alias: a legacy maxPowerModel value loads under the canonical
243
- // key when that key carries no usable value on disk (canonical wins when
244
- // both are present). The legacy key is never stored under its own name;
245
- // one process-global notice tells the user to move the value before the
246
- // alias is removed.
247
- const canonical = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
248
- if (canonical === undefined) {
249
- const legacy = toRoleSettingValue(normaliseRoleSetting(settings[MAX_POWER_MODEL_KEY]));
250
- if (legacy !== undefined) {
251
- map.set(UTILITY_MODEL_KEY, legacy);
252
- if (consumeMaxPowerDeprecationNotice()) {
253
- log.warn(
254
- `${MAX_POWER_MODEL_KEY} is deprecated and now loads as ${UTILITY_MODEL_KEY}. ` +
255
- `Move the value to ${UTILITY_MODEL_KEY} (for example /utility-model <pattern>); ` +
256
- "the legacy key is removed next release.",
257
- );
258
- }
259
- }
260
- }
206
+ const value = toRoleSettingValue(normaliseRoleSetting(settings[UTILITY_MODEL_KEY]));
207
+ if (value !== undefined) getCustomModelKeys().set(UTILITY_MODEL_KEY, value);
261
208
  } catch {
262
209
  // Non-fatal: no prior settings or parse error
263
210
  }
@@ -347,59 +294,7 @@ export default function polyfillExtension(pi: ExtensionAPI) {
347
294
  "No args = show current setting. Smaller/faster models preferred. " +
348
295
  "Examples: /utility-model provider/model-id, /utility-model a/b,c/d, " +
349
296
  "/utility-model clear",
350
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, false),
351
- });
352
-
353
- pi.registerCommand("vision-model", {
354
- description:
355
- "Set or show the vision model. Accepts one model or an ordered list " +
356
- "(comma-separated); every entry must accept image input. " +
357
- "No args opens the (vision-filtered) selector UI. " +
358
- "Examples: /vision-model provider/model-id, /vision-model a/b,c/d, /vision-model clear",
359
- handler: async (args, ctx) => {
360
- ctx.ui.notify(
361
- "/vision-model is deprecated: image analysis falls back to the utility list's first " +
362
- "image-capable model. The setting keeps priority this release; the command is removed next release.",
363
- "warning",
364
- );
365
- if (!args || args.trim() === "") {
366
- if (ctx.hasUI) {
367
- const visionFilter = (m: Model<Api>) => hasImageInput(m as { input?: unknown });
368
- await openModelSelectorUI(ctx, VISION_MODEL_KEY, "Vision", visionFilter);
369
- } else {
370
- const model = resolveVisionModel(ctx);
371
- const patterns = configuredRolePatterns(VISION_MODEL_KEY);
372
- ctx.ui.notify(
373
- patterns.length === 0
374
- ? `Vision model: ${model?.id ?? "none"} (auto-detected)`
375
- : `Vision model${patterns.length > 1 ? "s" : ""}: ${patterns.join(" -> ")}` +
376
- ` (using: ${model?.id ?? "none"})`,
377
- "info",
378
- );
379
- }
380
- return;
381
- }
382
-
383
- const text = args.trim();
384
- if (text === "clear" || text === "reset") {
385
- await clearModelSetting(VISION_MODEL_KEY);
386
- ctx.ui.notify("Vision model cleared (will auto-detect)", "info");
387
- return;
388
- }
389
-
390
- await setRoleSettingFromArgs(ctx, VISION_MODEL_KEY, "Vision", "", text);
391
- },
392
- });
393
-
394
- // Max-power model command (deprecated alias)
395
- pi.registerCommand("max-power-model", {
396
- description:
397
- "Deprecated alias of /utility-model: the max-power role merged into the " +
398
- "utility role. Set/show/clear operate on the canonical utility setting; " +
399
- "the alias is removed next release. " +
400
- "Examples: /max-power-model provider/model-id, /max-power-model a/b,c/d, " +
401
- "/max-power-model clear",
402
- handler: (args, ctx) => runUtilityModelCommand(args, ctx, true),
297
+ handler: (args, ctx) => runUtilityModelCommand(args, ctx),
403
298
  });
404
299
  }
405
300
 
@@ -416,11 +311,9 @@ async function clearModelSetting(key: string): Promise<void> {
416
311
  getCustomModelKeys().delete(key);
417
312
  // persistCustomKeys writes only the keys still in the map, so deleting from
418
313
  // the map alone left the old value in settings.json and the next session
419
- // resurrected it. "Clear" has to clear the stored setting as well, and a
420
- // clear is a role write: it retires the deprecated legacy key too.
314
+ // resurrected it. "Clear" has to clear the stored setting as well.
421
315
  updateSettings((settings) => {
422
316
  delete settings[key];
423
- delete settings[MAX_POWER_MODEL_KEY];
424
317
  });
425
318
  }
426
319
 
@@ -454,8 +347,7 @@ async function openModelSelectorUI(
454
347
  ctx: ExtensionCommandContext,
455
348
  settingKey: string,
456
349
  roleLabel: string,
457
- scopeFilter: ((m: Model<Api>) => boolean) | null,
458
- resolveFn: (ctx: ExtensionContext) => Model<Api> | undefined = resolveVisionModel,
350
+ resolveFn: (ctx: ExtensionContext) => Model<Api> | undefined,
459
351
  ): Promise<void> {
460
352
  const modelRegistry = ctx.modelRegistry;
461
353
 
@@ -478,28 +370,17 @@ async function openModelSelectorUI(
478
370
  const prefProvider = currentRoleModel?.provider ?? mainModel?.provider;
479
371
 
480
372
  const allModels = modelRegistry.getAvailable();
481
- let scopedModels: { model: Model<Api>; thinkingLevel?: string }[];
482
-
483
- if (scopeFilter) {
484
- const filtered = allModels.filter(scopeFilter);
485
- filtered.sort((a, b) => {
486
- if (currentRoleModel && a.id === currentRoleModel.id) return -1;
487
- if (currentRoleModel && b.id === currentRoleModel.id) return 1;
488
- if (prefProvider && a.provider === prefProvider) return -1;
489
- if (prefProvider && b.provider === prefProvider) return 1;
490
- return a.id.localeCompare(b.id);
491
- });
492
- scopedModels = filtered.map((m) => ({ model: m }));
493
- } else {
494
- allModels.sort((a, b) => {
495
- if (currentRoleModel && a.id === currentRoleModel.id) return -1;
496
- if (currentRoleModel && b.id === currentRoleModel.id) return 1;
497
- if (prefProvider && a.provider === prefProvider) return -1;
498
- if (prefProvider && b.provider === prefProvider) return 1;
499
- return a.id.localeCompare(b.id);
500
- });
501
- scopedModels = allModels.map((m) => ({ model: m }));
502
- }
373
+
374
+ allModels.sort((a, b) => {
375
+ if (currentRoleModel && a.id === currentRoleModel.id) return -1;
376
+ if (currentRoleModel && b.id === currentRoleModel.id) return 1;
377
+ if (prefProvider && a.provider === prefProvider) return -1;
378
+ if (prefProvider && b.provider === prefProvider) return 1;
379
+ return a.id.localeCompare(b.id);
380
+ });
381
+ const scopedModels: { model: Model<Api>; thinkingLevel?: string }[] = allModels.map((m) => ({
382
+ model: m,
383
+ }));
503
384
 
504
385
  // Capture selected model from the dialog
505
386
  let selectedModel: Model<Api> | undefined;
@@ -507,15 +388,6 @@ async function openModelSelectorUI(
507
388
  await ctx.ui.custom(async (tui, _theme, _keybindings, done) => {
508
389
  const onSelect = async (model: Model<Api>) => {
509
390
  selectedModel = model;
510
-
511
- // Warn if a non-vision model was picked for the vision role
512
- if (scopeFilter && !hasImageInput(model as { input?: unknown })) {
513
- ctx.ui.notify(
514
- `[warn] ${model.id} does not support image input. Vision analysis may fail.`,
515
- "warning",
516
- );
517
- }
518
-
519
391
  done(model);
520
392
  };
521
393
  const onCancel = () => done(undefined as unknown);
@@ -561,8 +433,8 @@ async function openModelSelectorUI(
561
433
  if (!selectedModel) return;
562
434
 
563
435
  // Store the role-specific key only. Do NOT call pi.setModel() - that would change
564
- // the default model, which is NOT what we want for utility/vision role selection.
565
- // model-resolver.ts reads these custom keys and uses them directly.
436
+ // the default model, which is NOT what we want for utility role selection.
437
+ // model-resolver.ts reads this custom key and uses it directly.
566
438
  const pattern = `${selectedModel.provider}/${selectedModel.id}`;
567
439
  await setModelSetting(settingKey, pattern);
568
440
 
@@ -52,7 +52,7 @@ allow sub-state modules to be tested in isolation.
52
52
 
53
53
  - **Wake (`triggerTurn: true`)**: enforcement-critical, turn-outcome,
54
54
  reasoning, metacognition, auto-recovery, analytics-degrade,
55
- threshold-exhausted, emergency-rotation, navigation-checkout, context-80%+,
55
+ threshold-exhausted, emergency-rotation, navigation-checkout,
56
56
  three-memory-reliability, compaction-retry errors.
57
57
  - **No wake**: everything else. The delivery class decides how the message
58
58
  reaches the run (see the delivery contract in `lib/utils/injection-tracker.ts`):
@@ -66,8 +66,45 @@ allow sub-state modules to be tested in isolation.
66
66
  API-error guidance. Memory/hint/SOP channels park - they provide context
67
67
  for the agent's natural flow.
68
68
 
69
+ The context line from `register-turn-end-hygiene.ts` is `deliverAs:
70
+ "nextTurn"`: it is queued for the next user prompt, never steered into the
71
+ run it describes. A steer at a turn boundary is what kept a
72
+ compaction-armed loop alive, and the line names the deadline (an armed
73
+ compaction fires when the run settles) rather than restating a percentage.
74
+
69
75
  See individual handler files in `handlers/` for the per-source policy.
70
76
 
77
+ ### Route-failure latch (wake demotion)
78
+
79
+ `session-health.ts` owns a second latch on the same turn-start question. A run
80
+ that ends on a provider error (`agent_end` with an assistant `stopReason:
81
+ "error"`) feeds `recordRouteFailure(ctx, category)` with the category its raw
82
+ error text classifies to; every category counts except `context_window` and
83
+ `abort`, which are not evidence about the route. The counter is read only by
84
+ `isRouteLatchOpen(ctx)` and `isTurnStartBlocked(ctx)`, so the three seams that
85
+ self-start a turn cannot disagree:
86
+
87
+ - the timer wake path already asks `isTurnStartBlocked` once per fire and
88
+ demotes through `deliverDemotedFire` (no scheduling change);
89
+ - watchdog escalations ask it once per bark and deliver `quietWhisper` while
90
+ the tg line still fires;
91
+ - an explicitly-waking whisper (`triggerTurn: true`) in `whisper.ts` is
92
+ demoted to the ordinary non-waking steer.
93
+
94
+ The last two ask the route-only half, `isRouteLatchOpen`, deliberately: neither
95
+ seam ever consulted the terminal breaker, and the off switch has to make this
96
+ change inert rather than partially active.
97
+
98
+ Release signals: any successful provider call (`recordLlmSuccess`), a clean
99
+ wake turn, a route change (`model_select`), an owner recovery
100
+ (`setSessionHealthMode "healthy"`) and a session start. While the latch stays
101
+ open the predicate still releases one self-started turn per
102
+ `braid.session.routeBreaker.floorMs` and restamps the clock, so a parked
103
+ session neither starves nor loops. `braid.session.routeBreaker.enabled =
104
+ false` makes every part of this inert. Fixtures:
105
+ `test/runtime/lib/test-route-latch.mjs` (the six design fixtures and the
106
+ off-switch control family).
107
+
71
108
  ## Over-correction gate setting
72
109
 
73
110
  | Setting | Default | Effect | Read cadence |
@@ -13,6 +13,8 @@ import { getState } from "../state.js";
13
13
  import { classify } from "../../../lib/ai/text-classifier.js";
14
14
  import { CRITICS } from "../../../lib/ai/critic-registry.js";
15
15
  import { errorTypeFallback } from "../../../lib/ai/critic-fallbacks.js";
16
+ import { classifyLlmError } from "../../../lib/errors/llm-error.js";
17
+ import { recordRouteFailure } from "../session-health.js";
16
18
 
17
19
  export function registerAgentEndApiErrorHandler(pi: ExtensionAPI): void {
18
20
  pi.on(AGENT_END, async (event: any, ctx: ExtensionContext) => {
@@ -32,6 +34,17 @@ export function registerAgentEndApiErrorHandler(pi: ExtensionAPI): void {
32
34
 
33
35
  getState(ctx).validationFailures++;
34
36
 
37
+ // Count the failure for the route-failure latch BEFORE the nudge cooldown
38
+ // below: the cooldown throttles the message, not the observation. A run
39
+ // that ends on a provider error is the only evidence the latch has, and
40
+ // the auxiliary calls classifyRetryError makes are excluded from it by
41
+ // design (they are what releases the latch, never what feeds it).
42
+ try {
43
+ recordRouteFailure(ctx, classifyLlmError(finalError).category);
44
+ } catch {
45
+ // A broken counter must never suppress the nudge.
46
+ }
47
+
35
48
  const now = Date.now();
36
49
  if (now - getState(ctx).lastNudgeTime < getState(ctx).nudgeCooldownMs) return;
37
50
  getState(ctx).lastNudgeTime = now;
@@ -63,6 +63,7 @@ import {
63
63
  contextNudgeCrossed,
64
64
  } from "../../../lib/detection/context-tiers.js";
65
65
  import {
66
+ describeUsage,
66
67
  measureLiveUsage,
67
68
  tokenArms,
68
69
  formatTokensK,
@@ -205,12 +206,14 @@ async function checkContextUsage(
205
206
  let usagePercent = 0;
206
207
  let usageTokens = 0;
207
208
  let usageWindow: number | undefined;
209
+ let usageProvenance: string | undefined;
208
210
  try {
209
211
  const live = measureLiveUsage(ctx);
210
212
  if (live) {
211
213
  usagePercent = live.percent;
212
214
  usageTokens = live.tokens;
213
215
  usageWindow = live.contextWindow;
216
+ usageProvenance = describeUsage(live);
214
217
  }
215
218
  } catch {
216
219
  /* live measurement unavailable - the skip below records it */
@@ -336,7 +339,7 @@ async function checkContextUsage(
336
339
  // token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
337
340
  // 80%. The strongest rung reached wins, so no token arm can shadow a
338
341
  // percent tier above it (see lib/detection/context-tiers.ts).
339
- const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
342
+ const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow, usageProvenance);
340
343
  if (nudge) {
341
344
  const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
342
345
  if (state.contextNudgeSent) {
@@ -355,7 +358,10 @@ async function checkContextUsage(
355
358
  }
356
359
  state.contextNudgeSent = true;
357
360
  state.contextNudgeRung = nudge.id;
358
- sendEnforcementWhisper(pi, ctx, nudge.message);
361
+ // Queued for the next user prompt, never steered into the run: the line is
362
+ // advice about a run that may still dispatch, and a steer at this boundary
363
+ // is exactly the delivery that kept a compaction-armed loop alive.
364
+ sendEnforcementWhisper(pi, ctx, nudge.message, false, { deliverAs: "nextTurn" });
359
365
  }
360
366
  }
361
367