pi-braid 0.40.3 → 0.40.6

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 (85) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +116 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +178 -17
  13. package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +74 -13
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-POLICY.md +8 -0
  49. package/docs/LOCAL_DEV.md +0 -1
  50. package/docs/ROADMAP.md +5 -5
  51. package/docs/SETUP.md +19 -18
  52. package/package.json +2 -1
  53. package/skills/herdr-topology/SKILL.md +6 -1
  54. package/skills/research/SKILL.md +32 -0
  55. package/skills/subagent-orchestration/SKILL.md +2 -2
  56. package/src/extensions/core/agent-environment/index.ts +4 -3
  57. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  58. package/src/extensions/core/prompt-builder/index.ts +12 -7
  59. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  60. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  61. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  62. package/src/extensions/core/skills-tool/auto-inject.ts +350 -27
  63. package/src/extensions/core/skills-tool/index.ts +217 -15
  64. package/src/extensions/core/skills-tool/reach.ts +256 -0
  65. package/src/extensions/core/skills-tool/skill-triggers.ts +130 -23
  66. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  67. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  68. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  69. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  70. package/src/extensions/enforcement/resume-state.ts +127 -0
  71. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  72. package/src/extensions/enforcement/whisper.ts +21 -1
  73. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  74. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  75. package/src/extensions/memory/AGENTS.md +25 -1
  76. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  77. package/src/lib/config/braid-paths.ts +20 -0
  78. package/src/lib/config/braid-settings.ts +46 -0
  79. package/src/lib/detection/context-tiers.ts +186 -13
  80. package/src/lib/events/AGENTS.md +1 -0
  81. package/src/lib/events/turn-boundary.ts +115 -0
  82. package/src/lib/orchestrator/workers.ts +33 -12
  83. package/src/lib/state/global-state.ts +1 -0
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/types/extension-context.d.ts +22 -79
@@ -84,6 +84,18 @@ interface BraidConfig {
84
84
  */
85
85
  closeGateWellFormedness?: string;
86
86
  };
87
+ /**
88
+ * Skills-layer config. `ranking` picks the tier policy of the `list_skills`
89
+ * relevance ranking: "auto" (default: the deterministic scorer answers, and
90
+ * the utility model is asked only when that answer is ambiguous), "keyword"
91
+ * (never call the model), "model" (always).
92
+ *
93
+ * Example: "braid": { "skills": { "ranking": "keyword" } }
94
+ */
95
+ skills?: {
96
+ /** "auto" | "keyword" | "model" — an unknown value falls back to "auto". */
97
+ ranking?: string;
98
+ };
87
99
  /**
88
100
  * Memory-layer config. Review-before-write quality gate on durable episode
89
101
  * writes: `writeGate` controls the per-site policies (repair/dedupe/reject)
@@ -556,6 +568,40 @@ export function getOwnerTimeZone(): string {
556
568
  return typeof tz === "string" && tz.trim() ? tz.trim() : DEFAULT_TIME_ZONE;
557
569
  }
558
570
 
571
+ // ── skills ranking (braid.skills.ranking) ──────────────────────────────────
572
+
573
+ /**
574
+ * Which tier may answer the `list_skills` relevance ranking.
575
+ *
576
+ * keyword — the deterministic scorer answers (the only implemented value;
577
+ * the default).
578
+ * auto — reserved: the policy wrote down for a model tier that would
579
+ * answer only on an ambiguous deterministic verdict. Measured and
580
+ * not kept, so it currently evaluates to the keyword path.
581
+ * model — reserved: the model answers whenever a task text exists. Same
582
+ * status as "auto".
583
+ */
584
+ export type SkillsRankingMode = "auto" | "keyword" | "model";
585
+
586
+ export const SKILLS_RANKING_DEFAULT: SkillsRankingMode = "keyword";
587
+
588
+ /**
589
+ * Resolve the ranking mode from a raw setting value. Unknown or malformed
590
+ * values fall back to the default rather than guessing: a typo must not turn a
591
+ * cheap catalog read into anything else. Pure.
592
+ */
593
+ export function resolveSkillsRankingMode(raw: unknown): SkillsRankingMode {
594
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
595
+ return value === "keyword" || value === "model" || value === "auto"
596
+ ? (value as SkillsRankingMode)
597
+ : SKILLS_RANKING_DEFAULT;
598
+ }
599
+
600
+ /** Read braid.skills.ranking from settings.json (default: "keyword"). */
601
+ export function getSkillsRankingMode(): SkillsRankingMode {
602
+ return resolveSkillsRankingMode(readSettings().braid?.skills?.ranking);
603
+ }
604
+
559
605
  // ── stale toolResult offload (braid.context.staleToolResultOffload) ────
560
606
 
561
607
  /**
@@ -32,6 +32,7 @@ import {
32
32
  USAGE_WHISPER_WARNING,
33
33
  USAGE_WHISPER_CRITICAL,
34
34
  USAGE_COMPACT_MEDIUM,
35
+ USAGE_FIRED_RESET_BELOW,
35
36
  } from "./context-thresholds.js";
36
37
  import { tokenArms, formatTokensK } from "./context-usage.js";
37
38
  import { getResolvedContextWindow } from "../config/braid-settings.js";
@@ -135,26 +136,198 @@ export function contextUsageTokenMessage(
135
136
  );
136
137
  }
137
138
 
139
+ // ═══════════════════════════════════════════════════════════════════════════
140
+ // THE NUDGE LADDER (one scale, both units)
141
+ // ═══════════════════════════════════════════════════════════════════════════
142
+ // The cascade used to test one unit at a time: the token arms first, the
143
+ // percent tiers only when no token arm was reached. A token arm is a fraction
144
+ // of the same window the percent tiers measure, so 0.45W sits at 45% of EVERY
145
+ // window and the token line won from 45% upward. The advisory (50), warning
146
+ // (65), critical (75) and compact (80) tiers were therefore unreachable: an
147
+ // agent at 95% read the calm pipeline line an agent at 46% read, in the range
148
+ // where escalation is the whole point.
149
+ //
150
+ // So the arms are ONE ordered ladder, ordered by position on the axis both
151
+ // units measure — percent of the resolved window. The rung at the highest
152
+ // reached position wins and no rung can shadow a rung above it, whichever
153
+ // unit it is written in. Each rung keeps its own unit for the latch: the
154
+ // consumer re-arms on a fall back below the rung that fired, measured in that
155
+ // rung's unit (a percent bar in another unit re-arms a token arm immediately
156
+ // whenever the arm sits above the bar, which is the repeat loop itself).
157
+
158
+ export type ContextNudgeId =
159
+ | "tokens:soft"
160
+ | "tokens:warning"
161
+ | "percent:soft"
162
+ | "percent:advisory"
163
+ | "percent:warning"
164
+ | "percent:critical"
165
+ | "percent:compact";
166
+
167
+ export interface ContextNudgeRung {
168
+ /** Stable rung identity — what a latch records to suppress a repeat. */
169
+ id: ContextNudgeId;
170
+ /** Unit the rung is measured in, and the unit the latch re-arms in. */
171
+ unit: "tokens" | "percent";
172
+ /** The rung's threshold in `unit` (a resolved token count, or a percent). */
173
+ threshold: number;
174
+ /** The same threshold as a percent of the resolved window: ladder order. */
175
+ position: number;
176
+ }
177
+
178
+ export interface ContextNudge extends ContextNudgeRung {
179
+ message: string;
180
+ }
181
+
182
+ interface RungSpec extends ContextNudgeRung {
183
+ render: (usagePercent: number, usageTokens: number) => string;
184
+ }
185
+
138
186
  /**
139
- * Combined enforcement cascade: token tiers first (0.45W/0.18W — fire earlier
140
- * for large context windows), then the percent tiers (30/50/65/75/80).
141
- * Returns null when no tier is reached.
187
+ * The ladder for one window, weakest position first. Token rungs carry the
188
+ * absolute count in their copy (that is what they are for on a large window);
189
+ * percent rungs carry the percent.
142
190
  */
143
- export function contextUsageNudgeMessage(
191
+ function nudgeRungs(window?: number | null): RungSpec[] {
192
+ const arms = tokenArms(window);
193
+ const positionOf = (tokens: number): number => (arms.W > 0 ? (tokens / arms.W) * 100 : 0);
194
+ const pct = (threshold: number) => ({ unit: "percent" as const, threshold, position: threshold });
195
+ return [
196
+ {
197
+ id: "tokens:soft",
198
+ unit: "tokens",
199
+ threshold: arms.soft,
200
+ position: positionOf(arms.soft),
201
+ render: (p, t) => contextUsageTokenMessage("soft", p, t),
202
+ },
203
+ {
204
+ id: "percent:soft",
205
+ ...pct(USAGE_WHISPER_SOFT),
206
+ render: (p) => contextUsageTierMessage("soft", p),
207
+ },
208
+ {
209
+ id: "tokens:warning",
210
+ unit: "tokens",
211
+ threshold: arms.warning,
212
+ position: positionOf(arms.warning),
213
+ render: (p, t) => contextUsageTokenMessage("warning", p, t),
214
+ },
215
+ {
216
+ id: "percent:advisory",
217
+ ...pct(USAGE_WHISPER_ADVISORY),
218
+ render: (p) => contextUsageTierMessage("advisory", p),
219
+ },
220
+ {
221
+ id: "percent:warning",
222
+ ...pct(USAGE_WHISPER_WARNING),
223
+ render: (p) => contextUsageTierMessage("warning", p),
224
+ },
225
+ {
226
+ id: "percent:critical",
227
+ ...pct(USAGE_WHISPER_CRITICAL),
228
+ render: (p) => contextUsageTierMessage("critical", p),
229
+ },
230
+ {
231
+ id: "percent:compact",
232
+ ...pct(USAGE_COMPACT_MEDIUM),
233
+ render: (p) => contextUsageTierMessage("compact", p),
234
+ },
235
+ ];
236
+ }
237
+
238
+ /**
239
+ * The strongest rung these numbers reach, or null below the first rung.
240
+ * Highest POSITION wins, not first match: that is what stops a token arm from
241
+ * shadowing a percent tier above it. Equal positions keep the earlier rung
242
+ * (the ladder is built weakest-first), and an equal position is not an
243
+ * escalation.
244
+ */
245
+ export function resolveContextNudge(
144
246
  usagePercent: number,
145
247
  usageTokens: number,
146
248
  window?: number | null,
147
- ): string | null {
148
- const arms = tokenArms(window);
149
- if (usageTokens >= arms.warning) {
150
- return contextUsageTokenMessage("warning", usagePercent, usageTokens);
249
+ ): ContextNudge | null {
250
+ let best: RungSpec | null = null;
251
+ for (const rung of nudgeRungs(window)) {
252
+ const reached =
253
+ rung.unit === "tokens" ? usageTokens >= rung.threshold : usagePercent >= rung.threshold;
254
+ if (reached && (best === null || rung.position > best.position)) best = rung;
151
255
  }
152
- if (usageTokens >= arms.soft) {
153
- return contextUsageTokenMessage("soft", usagePercent, usageTokens);
256
+ if (!best) return null;
257
+ return {
258
+ id: best.id,
259
+ unit: best.unit,
260
+ threshold: best.threshold,
261
+ position: best.position,
262
+ message: best.render(usagePercent, usageTokens),
263
+ };
264
+ }
265
+
266
+ /**
267
+ * One rung by id, resolved against the window in hand: a window change
268
+ * re-derives the rung's bar instead of comparing a live count against a stale
269
+ * one. Unknown or absent ids yield null (a latch armed by something that is
270
+ * not a rung).
271
+ */
272
+ export function findContextNudgeRung(
273
+ id: string | null | undefined,
274
+ window?: number | null,
275
+ ): ContextNudgeRung | null {
276
+ if (!id) return null;
277
+ for (const rung of nudgeRungs(window)) {
278
+ if (rung.id === id)
279
+ return { id: rung.id, unit: rung.unit, threshold: rung.threshold, position: rung.position };
154
280
  }
155
- const tier = contextUsageTier(usagePercent);
156
- if (!tier) return null;
157
- return contextUsageTierMessage(tier.tier, usagePercent);
281
+ return null;
282
+ }
283
+
284
+ /**
285
+ * Has usage fallen back below the rung that armed the latch? The comparison is
286
+ * in the rung's own unit: a token rung clears on a token count below its arm,
287
+ * a percent rung on a percent below its threshold. With no recorded rung (the
288
+ * latch was armed by an act that then stood down) the percent reset bar
289
+ * applies, which is the pre-ladder behavior for that path.
290
+ */
291
+ export function contextNudgeFellBelow(
292
+ id: string | null | undefined,
293
+ usagePercent: number,
294
+ usageTokens: number,
295
+ window?: number | null,
296
+ ): boolean {
297
+ const rung = findContextNudgeRung(id, window);
298
+ if (!rung) return usagePercent < USAGE_FIRED_RESET_BELOW;
299
+ return rung.unit === "tokens" ? usageTokens < rung.threshold : usagePercent < rung.threshold;
300
+ }
301
+
302
+ /**
303
+ * Was this rung crossed from below since the previous sample? A nudge is an
304
+ * event: a session that lands above a rung and stays there must not read the
305
+ * same advice every turn, while a rung climbed past is new information. The
306
+ * previous sample is a token count, so a percent rung is tested against it
307
+ * re-expressed as a percent of the window in hand.
308
+ */
309
+ export function contextNudgeCrossed(
310
+ rung: ContextNudgeRung,
311
+ prevUsageTokens: number | undefined,
312
+ window?: number | null,
313
+ ): boolean {
314
+ if (prevUsageTokens === undefined) return true;
315
+ if (rung.unit === "tokens") return prevUsageTokens < rung.threshold;
316
+ const { W } = tokenArms(window);
317
+ if (W <= 0) return true;
318
+ return (prevUsageTokens / W) * 100 < rung.threshold;
319
+ }
320
+
321
+ /**
322
+ * Combined enforcement nudge: the strongest rung reached, its text, or null.
323
+ * Kept as a text accessor for callers that need nothing but the message.
324
+ */
325
+ export function contextUsageNudgeMessage(
326
+ usagePercent: number,
327
+ usageTokens: number,
328
+ window?: number | null,
329
+ ): string | null {
330
+ return resolveContextNudge(usagePercent, usageTokens, window)?.message ?? null;
158
331
  }
159
332
 
160
333
  // ═══════════════════════════════════════════════════════════════════════════
@@ -15,6 +15,7 @@ communication that doesn't fit pi core's event model.
15
15
  | `timer-bus.ts` | Channel for timer-related cross-extension communication. |
16
16
  | `timer-types.ts` | Type definitions for timer events. |
17
17
  | `turn-end-coordinator.ts` | Coordinates handlers that need to run at turn end (post-message-end). Provides ordering and dedup. |
18
+ | `turn-boundary.ts` | The one rule for which `turn_end` boundaries a deferred compaction may abort a run at (allow-list over `message.stopReason`, fail-closed on unreadable boundaries). Shared by the context_compress drain and the enforcement hygiene act. |
18
19
 
19
20
  ## Local Contracts
20
21
 
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The turn-boundary rule: whether a deferred compaction may fire at a given
3
+ * `turn_end`.
4
+ *
5
+ * A deferred `ctx.compact()` aborts the active agent operation, and pi's
6
+ * manual compaction never retries or continues the interrupted turn. So the
7
+ * abort has to land where nothing is in flight, which makes the boundary a
8
+ * question about the run, not about the compaction: is the loop still
9
+ * dispatching?
10
+ *
11
+ * One home for that question. Two sites read it today (the drain in the
12
+ * context_compress batch scheduler and the hygiene act in enforcement), and a
13
+ * copy drifts silently: a wrong answer shows up as a torn turn under load,
14
+ * never as a failing check.
15
+ *
16
+ * The rule is an ALLOW-LIST over `message.stopReason`, not a deny-list, so an
17
+ * unreadable or unrecognized boundary parks instead of firing:
18
+ *
19
+ * "stop" the model finished its response. fire
20
+ * "length" the response hit its output ceiling. fire
21
+ * "error" the turn ended in an error. fire
22
+ * "aborted" the run was aborted. fire
23
+ * "toolUse" the loop dispatches its next request as park
24
+ * soon as the turn_end handlers return.
25
+ * "pending" the response is not final yet. park
26
+ * "deferred" the provider deferred the response. park
27
+ * absent, or the boundary says nothing usable. An park
28
+ * any other unreadable boundary is not evidence that the
29
+ * value loop is done.
30
+ *
31
+ * RESIDUAL, and the reason this rule is narrower than the safety property it
32
+ * stands for: a loop-done stop reason is necessary, not sufficient. The loop
33
+ * dispatches anyway in two measured cases, a tool call carrying a non-"toolUse"
34
+ * stop reason ("length" with tool calls, for instance) and a steer queued at
35
+ * any boundary (pi polls steering after the turn_end emit). A boundary the rule
36
+ * reads as loop-done while either holds still reaches the abort it exists to
37
+ * avoid. Reading "is anything left to dispatch" from the loop itself would
38
+ * close that gap; this rule does not, and it is the whole of what the drain
39
+ * and the act share.
40
+ *
41
+ * Two deliberate exceptions:
42
+ * - The 0.90W hard backstop cuts a live loop anyway. Above 0.90W of the
43
+ * window the loop is the runaway this exists to stop, so the abort it
44
+ * risks is cheaper than the overflow it prevents. Usage arrives from the
45
+ * caller because each site measures it from its own source.
46
+ * - No boundary at all (`undefined`) fires, keeping the pre-existing
47
+ * contract for callers that arm without boundary knowledge. The tool path
48
+ * is parked there by its own tool call identity instead (an arm inside a
49
+ * live batch still holds an active call id).
50
+ */
51
+
52
+ import type { StopReason } from "@earendil-works/pi-ai";
53
+ import type { TurnEndEvent } from "@earendil-works/pi-coding-agent";
54
+ import { tokenArms } from "../detection/context-usage.js";
55
+ import { getStopReason } from "../state/extension-state.js";
56
+
57
+ /**
58
+ * A boundary as this rule reads it: a real `turn_end` payload, or the partial
59
+ * projection a caller may hold. `undefined` means the caller has no boundary
60
+ * knowledge at all, which is a different statement from an empty boundary.
61
+ */
62
+ export type TurnBoundary = Partial<Pick<TurnEndEvent, "message">> | undefined;
63
+
64
+ /** The usage a backstop decision reads. */
65
+ export interface TurnBoundaryUsage {
66
+ /** Live tokens in the working set (compaction-aware). */
67
+ tokens: number;
68
+ /** The window the backstop fraction resolves against, when known. */
69
+ contextWindow?: number | null;
70
+ }
71
+
72
+ /**
73
+ * The stop reasons that end the turn's work, keyed by the union pi-ai
74
+ * declares. Typing the record as a total map over the reasons this rule does
75
+ * not park on makes a new provider stop reason a compile error here instead of
76
+ * a silent "park" or a silent "fire": someone has to classify it.
77
+ */
78
+ const LOOP_DONE_STOP_REASONS: Record<
79
+ Exclude<StopReason, "toolUse" | "pending" | "deferred">,
80
+ true
81
+ > = {
82
+ stop: true,
83
+ length: true,
84
+ error: true,
85
+ aborted: true,
86
+ };
87
+
88
+ const LOOP_DONE = new Set<string>(Object.keys(LOOP_DONE_STOP_REASONS));
89
+
90
+ /**
91
+ * True when the boundary carries a stop reason that ends the turn's work.
92
+ * Fail-closed: a boundary with no readable reason, or one this rule does not
93
+ * recognize, is not loop-done.
94
+ */
95
+ export function turnBoundaryIsLoopDone(boundary: TurnBoundary): boolean {
96
+ const stopReason = getStopReason(boundary?.message);
97
+ return stopReason !== undefined && LOOP_DONE.has(stopReason);
98
+ }
99
+
100
+ /**
101
+ * Whether a deferred compaction may abort the run at this boundary.
102
+ *
103
+ * `readUsage` is called only when the boundary is not loop-done, so a
104
+ * loop-done boundary never pays for a usage measurement.
105
+ */
106
+ export function turnBoundaryMayAbortRun(
107
+ boundary: TurnBoundary,
108
+ readUsage?: () => TurnBoundaryUsage | null | undefined,
109
+ ): boolean {
110
+ if (boundary === undefined) return true;
111
+ if (turnBoundaryIsLoopDone(boundary)) return true;
112
+ const usage = readUsage?.();
113
+ if (!usage) return false;
114
+ return usage.tokens >= tokenArms(usage.contextWindow).backstop;
115
+ }
@@ -1234,14 +1234,15 @@ export function productionWriteRefusalDetail(read: ProductionWriteRead): string
1234
1234
  // scanned <n> <unit> at <revision>
1235
1235
  //
1236
1236
  // `n` is a non-negative integer, `unit` one lowercase word (`files`, `rows`,
1237
- // ...), and `revision` a 7-to-40-char hex sha or a ref name. The stamp is the
1238
- // reporter's own claim, so it is worth exactly what one comparison against git
1239
- // makes it worth: the merge path resolves the named revision, counts the
1240
- // entries that revision's tree holds, and refuses the merge when the recorded
1241
- // number sits below that census (a scan that ran before staging, certifying
1242
- // fewer tracked entries than the commit carries). The parse and the comparison
1243
- // are pure, with the count supplied by the caller; nothing here reads what the
1244
- // scanned files mean.
1237
+ // `test-files` — lowercase letters and digits, hyphen/underscore-joined), and
1238
+ // `revision` a 7-to-40-char hex sha or a ref name. The stamp is the reporter's
1239
+ // own claim, so it is worth exactly what one comparison against git makes it
1240
+ // worth: the merge path resolves the named revision, counts the entries that
1241
+ // revision's tree holds, and refuses the merge when the recorded number sits
1242
+ // below that census (a scan that ran before staging, certifying fewer tracked
1243
+ // entries than the commit carries). The parse and the comparison are pure,
1244
+ // with the count supplied by the caller; nothing here reads what the scanned
1245
+ // files mean.
1245
1246
 
1246
1247
  export interface PopulationStamp {
1247
1248
  /** Population size the gate recorded. */
@@ -1256,9 +1257,16 @@ export interface PopulationStamp {
1256
1257
  * Bare-token revision rules: an all-hex token is a sha only at 7-40 chars, so
1257
1258
  * a six-char prefix does not slip through the ref-name alternative as a
1258
1259
  * revision git can never resolve.
1260
+ *
1261
+ * The unit is one token of lowercase letters and digits, joined by single
1262
+ * hyphens or underscores and starting with a letter: a reporter writes
1263
+ * `test-files` as readily as `files`, and the earlier letters-only rule threw
1264
+ * that evidence away as unreadable. A unit is never a phrase — `scanned 5 test
1265
+ * files at main` stays refused, because a two-word unit cannot be told from a
1266
+ * malformed stamp.
1259
1267
  */
1260
1268
  const POPULATION_STAMP_RE =
1261
- /^scanned (\d+) ([a-z]+) at ([0-9a-fA-F]{7,40}|[A-Za-z0-9][A-Za-z0-9._/-]*)$/;
1269
+ /^scanned (\d+) ([a-z][a-z0-9]*(?:[_-][a-z0-9]+)*) at ([0-9a-fA-F]{7,40}|[A-Za-z0-9][A-Za-z0-9._/-]*)$/;
1262
1270
  const ALL_HEX_RE = /^[0-9a-fA-F]+$/;
1263
1271
 
1264
1272
  /** Parse the stamp shape above; null when the value is not that shape. */
@@ -1321,7 +1329,19 @@ function populationLines(rows: PopulationRowRead[]): string[] {
1321
1329
  lines.push(`population stamp unreadable: row ${row.row} ${JSON.stringify(row.raw)}`);
1322
1330
  continue;
1323
1331
  }
1324
- if (row.stamp === null || row.stamp.unit !== "files") continue;
1332
+ if (row.stamp === null) continue;
1333
+ if (row.stamp.unit !== "files") {
1334
+ // A stamp names the population it scanned. Only `files` is a census
1335
+ // subject here (the tracked-entry count at the revision), so another
1336
+ // unit is read and named but never compared — and never dropped as if it
1337
+ // had been unreadable, which is what the old unit pattern did to
1338
+ // `test-files`.
1339
+ lines.push(
1340
+ `population recorded: ${row.stamp.n} ${row.stamp.unit} at ${row.stamp.revision} ` +
1341
+ `(row ${row.row}; unit is not the tracked-entry census, not compared)`,
1342
+ );
1343
+ continue;
1344
+ }
1325
1345
  if (row.verdict === "unresolved") {
1326
1346
  lines.push(
1327
1347
  `population delta: recorded ${row.stamp.n} at ${row.stamp.revision} ` +
@@ -1344,8 +1364,9 @@ function populationLines(rows: PopulationRowRead[]): string[] {
1344
1364
  * Read every gate row for a population stamp and compare the `files` ones
1345
1365
  * against the census the caller supplies for their named revision. Pure: the
1346
1366
  * count is a lookup parameter, so the parse and the comparison are testable
1347
- * without a repository. Rows of another unit are not census subjects and are
1348
- * left uncompared; an unreadable stamp is named, never silently dropped.
1367
+ * without a repository. Rows of another unit are not census subjects: they are
1368
+ * read, named in the lines, and left uncompared; an unreadable stamp is named,
1369
+ * never silently dropped.
1349
1370
  */
1350
1371
  export function readPopulationStamps(gates: unknown, censusAt: PopulationCensus): PopulationRead {
1351
1372
  const rows: PopulationRowRead[] = [];
@@ -794,6 +794,7 @@ export type DiscoverySignalType =
794
794
  | "sessions_prior"
795
795
  | "resume"
796
796
  | "tags_prior"
797
+ | "journal_prior"
797
798
  | "context_hygiene_tip";
798
799
 
799
800
  /** Get the shared shown-signal-types set (process-global, survives /reload). */
@@ -10,7 +10,7 @@ Misc utilities that don't fit a more specific subdir.
10
10
  | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
11
  | `injection-tracker.ts` | Tracks all messages injected into the agent's context. Provides the chokepoint `sendTrackedMessage` for whisper cap and metadata. |
12
12
  | `memory-fence.ts` | Memory-context fence (`<memory-context>` + one system note) for recalled-memory injections. `sanitizeMemoryContext` strips fence-escape tags from stored memory text; `fenceMemoryContext` wraps payloads at the send sites (whisper-recall, cross-recall, recaller, SOP coach, SOP suggestions, past insights, hints, session-recall). Render-only: never persisted, never applied to tool results. |
13
- | `whisper-format.ts` | Universal whisper envelope (`[braid-whisper - <subsystem>]`). Applied at the trunk by `sendTrackedMessage` so every system-injected message is clearly distinguished from human user input. See `../pi-braid-evaluation/docs-archive/ENFORCEMENT-WHISPER-CONTENT-AUDIT.md` §7.16. |
13
+ | `whisper-format.ts` | Universal whisper envelope (`[braid-whisper - <subsystem>]`). Applied at the trunk by `sendTrackedMessage` so every system-injected message is clearly distinguished from human user input.. |
14
14
  | `extension-utils.ts` | Helpers for working with the ExtensionContext. |
15
15
  | `file-mutation-queue.ts` | Serializes file mutations to prevent races. |
16
16
  | `filter-safe-to-remove.ts` | Determines which messages can be safely removed from context (compaction). |
@@ -1,85 +1,28 @@
1
1
  /**
2
- * @fileoverview Extension context type augmentations for pi-braid.
2
+ * @fileoverview Extension context type seat for pi-braid.
3
3
  *
4
- * Centralizes knowledge of @earendil-works/pi-coding-agent's ExtensionContext
5
- * structure - what is directly accessible vs. what must be obtained via ctx.
6
- */
7
-
8
- import type { ExtensionContext as BaseExtensionContext } from "@earendil-works/pi-coding-agent";
9
-
10
- // Extended with pi-braid's own session state helpers
11
- declare module "@earendil-works/pi-coding-agent" {
12
- interface ExtensionContext {
13
- /** Whisper a low-priority hint without blocking execution */
14
- whisper?(message: string, opts?: WhisperOptions): void;
15
- /** Send enforcement signal for compliance verification */
16
- enforcer?: {
17
- sendEnforcementWhisper?(message: string): void;
18
- verifyCompliance?(response: string): Promise<EnforcementSignal[]>;
19
- };
20
- /** Analytics for tracking metrics, tool calls, session data */
21
- analytics?: {
22
- recordToolCall?(
23
- toolName: string,
24
- timestamp: number,
25
- metadata?: Record<string, unknown>,
26
- ): void;
27
- recordSignal?(signal: EnforcementSignal): void;
28
- recordDegradation?(event: DegradationEvent): void;
29
- };
30
- }
31
- }
32
-
33
- /**
34
- * The agent's ExtensionContext object exposes these fields:
4
+ * Braid uses pi-core's own `ExtensionContext` and does not augment it. A local
5
+ * augmentation would let braid compile against members no runtime provides; the
6
+ * one that lived here declared `ctx.whisper`, `ctx.enforcer` and
7
+ * `ctx.analytics`, none of which pi ever sets, and no code called them.
35
8
  *
36
- * - model: the currently active Model<Api>
37
- * - modelRegistry: provider registry (find(provider, modelId), getAvailable(), getAll())
38
- * - settingsManager: user settings (getDefaultProvider(), getDefaultModel(), etc.)
39
- * - toolRegistry: registered tools
9
+ * What the context actually carries (pi-core 1.2.0 and 1.4.0 declare the same
10
+ * member set, member for member):
40
11
  *
41
- * Tool execute functions DO NOT receive ctx directly - they only get:
42
- * (toolCallId, params, signal, onUpdate, _ctx)
43
- * where _ctx is undefined for extension tools (only builtin tools get it).
12
+ * - `ui`, `mode`, `hasUI`, `cwd`
13
+ * - `sessionManager`, `modelRegistry`, `model`, `scopedModels`, `thinkingLevel`
14
+ * - `isIdle()`, `isProjectTrusted()`, `signal`, `abort()`, `hasPendingMessages()`
15
+ * - `shutdown()`, `getContextUsage()`, `compact()`, `getSystemPrompt()`
44
16
  *
45
- * So extension tools should NOT rely on _ctx for model resolution.
46
- * Instead:
47
- * - Listen to "model_select" events and cache the model
48
- * - Or use pi.model if the ExtensionApi exposes it
49
- */
50
- export type { BaseExtensionContext as ExtensionContext };
51
-
52
- /**
53
- * Type for the `pi` object (ExtensionApi) used in extensions.
54
- * Note: this is NOT the same as ExtensionContext.
17
+ * Tool `execute` receives this context as its fifth argument, typed
18
+ * `ExtensionToolContext`: the same members plus `tools` and `executeTool()`.
19
+ * Command handlers receive `ExtensionCommandContext`, which adds session
20
+ * control (`getSystemPromptOptions`, `waitForIdle`, `newSession`, `fork`,
21
+ * `navigateTree`, `switchSession`, `reload`) that is only safe in
22
+ * user-initiated commands.
23
+ *
24
+ * The `pi` object (`ExtensionAPI`) has no `model` member, and no
25
+ * `modelRegistry` member: a tool that needs the active model reads it from the
26
+ * `ctx` argument.
55
27
  */
56
- export interface ExtensionApi {
57
- registerTool(name: string, definition: unknown): void;
58
- on(event: string, handler: (...args: unknown[]) => void): void;
59
- model?: unknown;
60
- modelRegistry?: unknown;
61
- }
62
-
63
- // ── Supporting types ────────────────────────────────────────────────────────
64
-
65
- interface WhisperOptions {
66
- category?: "enforcement" | "quality" | "safety" | "cognitive";
67
- priority?: "low" | "medium" | "high";
68
- }
69
-
70
- interface EnforcementSignal {
71
- type: "compliance" | "deception" | "incomplete" | "hallucination" | "scope_violation";
72
- severity: number;
73
- confidence: number;
74
- evidence: string;
75
- remediation: string;
76
- nudgeType: "whisper" | "warn" | "block";
77
- category: "enforcement" | "quality" | "safety";
78
- }
79
-
80
- interface DegradationEvent {
81
- timestamp: number;
82
- reason: string;
83
- severity: number;
84
- action?: string;
85
- }
28
+ export type { ExtensionContext } from "@earendil-works/pi-coding-agent";