pi-braid 0.40.5 → 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 +89 -10
  13. package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
  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 +47 -10
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
  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 +1 -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 +196 -24
  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 +90 -20
  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
@@ -19,6 +19,7 @@ import { analyzeSession } from "../../analysis.js";
19
19
  import * as timerMod from "../../../../scheduling/timer/index.js";
20
20
  import { getState } from "../../../../enforcement/state.js";
21
21
  import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../../../lib/detection/context-thresholds.js";
22
+ import { turnBoundaryMayAbortRun, } from "../../../../../lib/events/turn-boundary.js";
22
23
  import { getCmState, isCompactionActive, log, recordNavigationAction } from "../shared.js";
23
24
  import { snapBoundaryOutsideToolBatch } from "../tool-batch-boundary.js";
24
25
  import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
@@ -258,6 +259,19 @@ export const DEGRADED_DEFERRAL_MS = 150;
258
259
  export function scheduleDegradedCompact(trigger) {
259
260
  setTimeout(trigger, DEGRADED_DEFERRAL_MS);
260
261
  }
262
+ /**
263
+ * Whether an arm may fire its own entry. Firing a compact aborts whatever run
264
+ * is live, so an arm that happens inside a turn boundary dispatch hands that
265
+ * boundary in and is judged by the same rule the TURN_END handler applies
266
+ * (the rule lives in lib/events/turn-boundary.ts; it owns the "no boundary
267
+ * known" case, which fires). Every other arm site runs inside a tool call,
268
+ * where there is no boundary to read and the prior contract stands: the arm
269
+ * drains unless a batch is still active (the arm's own call id keeps it
270
+ * parked, so it does not fire there).
271
+ */
272
+ function armMayDrainNow(boundary, ctx) {
273
+ return turnBoundaryMayAbortRun(boundary, () => captureUsage(ctx));
274
+ }
261
275
  /**
262
276
  * Arm a one-shot compaction at a safe boundary (next turn end or run settle).
263
277
  * Returns "pending-exists" when an LLM-class compaction is already armed: the
@@ -271,7 +285,7 @@ export function scheduleDegradedCompact(trigger) {
271
285
  */
272
286
  function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
273
287
  kind: "compact",
274
- }) {
288
+ }, boundary) {
275
289
  const trigger = () => {
276
290
  try {
277
291
  // Signal to session_compact handler that this is agent-initiated
@@ -301,7 +315,14 @@ function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
301
315
  log.warn(`[context-compress] Pending queue overflow: dropped the newest armed ${dropped?.kind}` +
302
316
  ` (cap ${PENDING_COMPACT_QUEUE_MAX}); the first-armed entry still fires.`);
303
317
  }
304
- firePendingCompactionsIfSettled(ctx, st);
318
+ // Arming fires only where that is safe. Firing a compaction aborts whatever
319
+ // run is live, and an arm site is not in a position to tell: the tool path
320
+ // arms inside its own call (whose id parks the queue anyway), and the
321
+ // heartbeat's arm runs inside a turn_end dispatch, where whether the loop
322
+ // still has work to dispatch is a fact the event carries. That caller hands
323
+ // its boundary in; every other caller keeps the prior contract.
324
+ if (armMayDrainNow(boundary, ctx))
325
+ firePendingCompactionsIfSettled(ctx, st);
305
326
  return "queued";
306
327
  }
307
328
  catch {
@@ -326,7 +347,7 @@ function scheduleCompactionAtBatchSettle(pi, ctx, options, meta = {
326
347
  * trigger is queued for the next safe boundary. Returns null when the branch
327
348
  * is not longer than the keep window (nothing to slide).
328
349
  */
329
- function armSlideCompaction(pi, ctx, keepCount) {
350
+ function armSlideCompaction(pi, ctx, keepCount, boundary) {
330
351
  const sm = ctx.sessionManager;
331
352
  if (!sm || typeof sm.getBranch !== "function")
332
353
  return null;
@@ -374,7 +395,7 @@ function armSlideCompaction(pi, ctx, keepCount) {
374
395
  catch {
375
396
  // Non-fatal
376
397
  }
377
- scheduleCompactionAtBatchSettle(pi, ctx, { customInstructions: "SLIDE_MODE:true" }, { kind: "slide", cutEntryId });
398
+ scheduleCompactionAtBatchSettle(pi, ctx, { customInstructions: "SLIDE_MODE:true" }, { kind: "slide", cutEntryId }, boundary);
378
399
  return { cutEntryId, keptCount, droppedCount };
379
400
  }
380
401
  /**
@@ -401,9 +422,14 @@ function getAutoArmState(ctx) {
401
422
  * settle, never mid-run.
402
423
  *
403
424
  * Called from the heartbeat tick — the only cadence that runs while a session
404
- * works. Returns what happened and why, so the caller can log it.
425
+ * works, and the only arm site that runs inside a turn boundary dispatch. It
426
+ * hands that boundary in, so the arm is judged by the same rule the drain
427
+ * applies: a "toolUse" boundary below the 0.90W backstop leaves the entry
428
+ * queued for the next loop-done boundary instead of aborting the request the
429
+ * loop is about to dispatch. Returns what happened and why, so the caller can
430
+ * log it.
405
431
  */
406
- export function maybeArmAutoCompaction(pi, ctx) {
432
+ export function maybeArmAutoCompaction(pi, ctx, boundary) {
407
433
  const config = getAutoCompactConfig();
408
434
  if (!config.enabled)
409
435
  return { armed: false, reason: "disabled" };
@@ -426,7 +452,7 @@ export function maybeArmAutoCompaction(pi, ctx) {
426
452
  }
427
453
  const branchLength = ctx?.sessionManager?.getBranch?.().length ?? 0;
428
454
  const keep = resolveAutoSlideKeep(branchLength);
429
- const armed = armSlideCompaction(pi, ctx, keep);
455
+ const armed = armSlideCompaction(pi, ctx, keep, boundary);
430
456
  st.aboveCount = 0;
431
457
  if (!armed)
432
458
  return { armed: false, reason: "branch-too-short" };
@@ -488,10 +514,10 @@ export const contextCompressSchema = Type.Object({
488
514
  export function registerContextCompress(pi) {
489
515
  // Batch-settle scheduling: track the ACTIVE tool calls of every running
490
516
  // batch by call id and fire the deferred compaction only at a safe boundary
491
- // (turn_end or agent_settled). Never mid-batch (would drop a parallel
492
- // sibling's result) and never at tool_execution_end (the run is still live
493
- // there — an aborting compact would surface a spurious "This operation was
494
- // aborted" error and tear the finishing turn).
517
+ // (a loop-done turn_end or agent_settled). Never mid-batch (would drop a
518
+ // parallel sibling's result) and never at tool_execution_end (the run is
519
+ // still live there — an aborting compact would surface a spurious "This
520
+ // operation was aborted" error and tear the finishing turn).
495
521
  onEvent(pi, TOOL_EXECUTION_START, (event, ctx) => {
496
522
  try {
497
523
  const st = getBatchSettleState(ctx);
@@ -521,17 +547,22 @@ export function registerContextCompress(pi) {
521
547
  }
522
548
  });
523
549
  onEvent(pi, TURN_END, (event, ctx) => {
524
- // Between-turns boundary: the turn's assistant message and tool results
525
- // are already persisted when turn_end fires, so the abort inside
526
- // ctx.compact() cannot tear a live turn or drop a sibling result. The
527
- // persisted results carry the toolCallIds of the calls they answer, which
528
- // releases a call whose tool_execution_end never arrived; an active id
529
- // with NO result in this event is kept (it may still be executing, and a
530
- // count could not tell which sibling completed). A run kept alive by
550
+ // Turn boundary. The turn's assistant message and tool results are already
551
+ // persisted here, but that alone does not make the run safe to abort: a
552
+ // "toolUse" stop means the loop dispatches its next request the moment the
553
+ // handlers return, so the deferred ctx.compact() tears that request
554
+ // mid-stream and the compaction replaces the work it was about to do (the
555
+ // rule is lib/events/turn-boundary.ts, and its residual section lists the
556
+ // two cases a loop-done stop reason does not rule out). Only a loop-done
557
+ // boundary drains, except at the 0.90W hard backstop, which exists
558
+ // precisely to stop a runaway live loop before it overflows.
559
+ //
560
+ // The persisted results carry the toolCallIds of the calls they answer,
561
+ // which releases a call whose tool_execution_end never arrived; an active
562
+ // id with NO result in this event is kept (it may still be executing, and
563
+ // a count could not tell which sibling completed). A run kept alive by
531
564
  // continuous steers never reaches agent_settled — this boundary keeps an
532
- // armed compaction from stalling behind live work. A steer queued at this
533
- // moment survives: the loop appends it before the aborted response stream,
534
- // and its turn runs on the post-compaction resume. Ids are never blanket-
565
+ // armed compaction from stalling behind live work. Ids are never blanket-
535
566
  // reset here (only agent_settled owns that backstop, which is what keeps a
536
567
  // missed end event from parking the queue forever).
537
568
  try {
@@ -541,6 +572,8 @@ export function registerContextCompress(pi) {
541
572
  return;
542
573
  if (isCompactionActive(ctx))
543
574
  return;
575
+ if (!turnBoundaryMayAbortRun(event, () => captureUsage(ctx)))
576
+ return;
544
577
  firePendingCompactionsIfSettled(ctx, st);
545
578
  }
546
579
  catch {
@@ -55,6 +55,10 @@ export declare function checkpointDir(): string;
55
55
  export declare function errorDir(): string;
56
56
  /** Scratchpad root (one dir per project slug), resolved on every call. */
57
57
  export declare function scratchpadDir(): string;
58
+ /** Journal root (one dir per project slug), resolved on every call. Durable
59
+ * write state: the append-only record of what a seat decided, which a
60
+ * replacement seat reads before acting, so BRAID_HOME pinning must move it. */
61
+ export declare function journalDir(): string;
58
62
  /** Healthcheck scratch and report root, resolved on every call. Durable-write
59
63
  * state: the probes and the saved report must follow a pinned BRAID_HOME. */
60
64
  export declare function healthcheckDir(): string;
@@ -140,6 +144,16 @@ export declare const BRAID_CONFIG_FILE: string;
140
144
  * scratchpad/sessions convention), which matched nothing the writer ever
141
145
  * wrote and silently muted the `tags_prior` signal. */
142
146
  export declare function tagsSlugFromCwd(cwd?: string): string;
147
+ /**
148
+ * Append-only journal file for one project: `<journal root>/<slug>/journal.jsonl`.
149
+ *
150
+ * The slug is the scratchpad's `projectSlugFromCwd` form, passed in rather than
151
+ * re-derived here: the writer, the checker and the session-start pointer must
152
+ * name ONE file, and a second slug rule is how the tag file split into a writer
153
+ * and a reader that could never meet (see tagsSlugFromCwd). Resolved on every
154
+ * call, so a pinned BRAID_HOME writes and reads its own journal.
155
+ */
156
+ export declare function journalFilePath(projectSlug: string): string;
143
157
  /**
144
158
  * Get the lossless flush file path for one offloaded tool result.
145
159
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -107,6 +107,12 @@ export function errorDir() {
107
107
  export function scratchpadDir() {
108
108
  return path.join(braidDir(), "scratchpads");
109
109
  }
110
+ /** Journal root (one dir per project slug), resolved on every call. Durable
111
+ * write state: the append-only record of what a seat decided, which a
112
+ * replacement seat reads before acting, so BRAID_HOME pinning must move it. */
113
+ export function journalDir() {
114
+ return path.join(braidDir(), "journal");
115
+ }
110
116
  /** Healthcheck scratch and report root, resolved on every call. Durable-write
111
117
  * state: the probes and the saved report must follow a pinned BRAID_HOME. */
112
118
  export function healthcheckDir() {
@@ -257,6 +263,18 @@ export function tagsSlugFromCwd(cwd) {
257
263
  return "default";
258
264
  return cwd.split("/").filter(Boolean).join("-") || "default";
259
265
  }
266
+ /**
267
+ * Append-only journal file for one project: `<journal root>/<slug>/journal.jsonl`.
268
+ *
269
+ * The slug is the scratchpad's `projectSlugFromCwd` form, passed in rather than
270
+ * re-derived here: the writer, the checker and the session-start pointer must
271
+ * name ONE file, and a second slug rule is how the tag file split into a writer
272
+ * and a reader that could never meet (see tagsSlugFromCwd). Resolved on every
273
+ * call, so a pinned BRAID_HOME writes and reads its own journal.
274
+ */
275
+ export function journalFilePath(projectSlug) {
276
+ return path.join(journalDir(), projectSlug, "journal.jsonl");
277
+ }
260
278
  /**
261
279
  * Get the lossless flush file path for one offloaded tool result.
262
280
  * Layout: <offload dir>/<sessionId>/<toolName>-<toolCallId>.txt.
@@ -148,6 +148,27 @@ export declare function resolveMemoryWriteGateConfig(raw?: RawWriteGateBlock): M
148
148
  */
149
149
  export declare const DEFAULT_TIME_ZONE = "Europe/Moscow";
150
150
  export declare function getOwnerTimeZone(): string;
151
+ /**
152
+ * Which tier may answer the `list_skills` relevance ranking.
153
+ *
154
+ * keyword — the deterministic scorer answers (the only implemented value;
155
+ * the default).
156
+ * auto — reserved: the policy wrote down for a model tier that would
157
+ * answer only on an ambiguous deterministic verdict. Measured and
158
+ * not kept, so it currently evaluates to the keyword path.
159
+ * model — reserved: the model answers whenever a task text exists. Same
160
+ * status as "auto".
161
+ */
162
+ export type SkillsRankingMode = "auto" | "keyword" | "model";
163
+ export declare const SKILLS_RANKING_DEFAULT: SkillsRankingMode;
164
+ /**
165
+ * Resolve the ranking mode from a raw setting value. Unknown or malformed
166
+ * values fall back to the default rather than guessing: a typo must not turn a
167
+ * cheap catalog read into anything else. Pure.
168
+ */
169
+ export declare function resolveSkillsRankingMode(raw: unknown): SkillsRankingMode;
170
+ /** Read braid.skills.ranking from settings.json (default: "keyword"). */
171
+ export declare function getSkillsRankingMode(): SkillsRankingMode;
151
172
  /**
152
173
  * Sane defaults for the optional staleToolResultOffload params (defined next
153
174
  * to the schema per the design contract). Investigation suggests a size
@@ -197,6 +197,22 @@ export function getOwnerTimeZone() {
197
197
  const tz = settings.braid?.timezone;
198
198
  return typeof tz === "string" && tz.trim() ? tz.trim() : DEFAULT_TIME_ZONE;
199
199
  }
200
+ export const SKILLS_RANKING_DEFAULT = "keyword";
201
+ /**
202
+ * Resolve the ranking mode from a raw setting value. Unknown or malformed
203
+ * values fall back to the default rather than guessing: a typo must not turn a
204
+ * cheap catalog read into anything else. Pure.
205
+ */
206
+ export function resolveSkillsRankingMode(raw) {
207
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
208
+ return value === "keyword" || value === "model" || value === "auto"
209
+ ? value
210
+ : SKILLS_RANKING_DEFAULT;
211
+ }
212
+ /** Read braid.skills.ranking from settings.json (default: "keyword"). */
213
+ export function getSkillsRankingMode() {
214
+ return resolveSkillsRankingMode(readSettings().braid?.skills?.ranking);
215
+ }
200
216
  // ── stale toolResult offload (braid.context.staleToolResultOffload) ────
201
217
  /**
202
218
  * Sane defaults for the optional staleToolResultOffload params (defined next
@@ -53,10 +53,54 @@ export declare function contextUsageTierMessage(tier: ContextUsageTier, usagePer
53
53
  * fractions of the resolved window (0.45W warning, 0.18W soft).
54
54
  */
55
55
  export declare function contextUsageTokenMessage(level: "warning" | "soft", usagePercent: number, usageTokens: number): string;
56
+ export type ContextNudgeId = "tokens:soft" | "tokens:warning" | "percent:soft" | "percent:advisory" | "percent:warning" | "percent:critical" | "percent:compact";
57
+ export interface ContextNudgeRung {
58
+ /** Stable rung identity — what a latch records to suppress a repeat. */
59
+ id: ContextNudgeId;
60
+ /** Unit the rung is measured in, and the unit the latch re-arms in. */
61
+ unit: "tokens" | "percent";
62
+ /** The rung's threshold in `unit` (a resolved token count, or a percent). */
63
+ threshold: number;
64
+ /** The same threshold as a percent of the resolved window: ladder order. */
65
+ position: number;
66
+ }
67
+ export interface ContextNudge extends ContextNudgeRung {
68
+ message: string;
69
+ }
70
+ /**
71
+ * The strongest rung these numbers reach, or null below the first rung.
72
+ * Highest POSITION wins, not first match: that is what stops a token arm from
73
+ * shadowing a percent tier above it. Equal positions keep the earlier rung
74
+ * (the ladder is built weakest-first), and an equal position is not an
75
+ * escalation.
76
+ */
77
+ export declare function resolveContextNudge(usagePercent: number, usageTokens: number, window?: number | null): ContextNudge | null;
78
+ /**
79
+ * One rung by id, resolved against the window in hand: a window change
80
+ * re-derives the rung's bar instead of comparing a live count against a stale
81
+ * one. Unknown or absent ids yield null (a latch armed by something that is
82
+ * not a rung).
83
+ */
84
+ export declare function findContextNudgeRung(id: string | null | undefined, window?: number | null): ContextNudgeRung | null;
85
+ /**
86
+ * Has usage fallen back below the rung that armed the latch? The comparison is
87
+ * in the rung's own unit: a token rung clears on a token count below its arm,
88
+ * a percent rung on a percent below its threshold. With no recorded rung (the
89
+ * latch was armed by an act that then stood down) the percent reset bar
90
+ * applies, which is the pre-ladder behavior for that path.
91
+ */
92
+ export declare function contextNudgeFellBelow(id: string | null | undefined, usagePercent: number, usageTokens: number, window?: number | null): boolean;
93
+ /**
94
+ * Was this rung crossed from below since the previous sample? A nudge is an
95
+ * event: a session that lands above a rung and stays there must not read the
96
+ * same advice every turn, while a rung climbed past is new information. The
97
+ * previous sample is a token count, so a percent rung is tested against it
98
+ * re-expressed as a percent of the window in hand.
99
+ */
100
+ export declare function contextNudgeCrossed(rung: ContextNudgeRung, prevUsageTokens: number | undefined, window?: number | null): boolean;
56
101
  /**
57
- * Combined enforcement cascade: token tiers first (0.45W/0.18W — fire earlier
58
- * for large context windows), then the percent tiers (30/50/65/75/80).
59
- * Returns null when no tier is reached.
102
+ * Combined enforcement nudge: the strongest rung reached, its text, or null.
103
+ * Kept as a text accessor for callers that need nothing but the message.
60
104
  */
61
105
  export declare function contextUsageNudgeMessage(usagePercent: number, usageTokens: number, window?: number | null): string | null;
62
106
  /** The duck-typed usage shape current sites read. percent may be null (no data). */
@@ -25,7 +25,7 @@
25
25
  * here in a single copy too. Sites with different copy (heartbeat
26
26
  * policies) keep their own messages and only share the tier mapping.
27
27
  */
28
- import { USAGE_WHISPER_SOFT, USAGE_WHISPER_ADVISORY, USAGE_WHISPER_WARNING, USAGE_WHISPER_CRITICAL, USAGE_COMPACT_MEDIUM, } from "./context-thresholds.js";
28
+ import { USAGE_WHISPER_SOFT, USAGE_WHISPER_ADVISORY, USAGE_WHISPER_WARNING, USAGE_WHISPER_CRITICAL, USAGE_COMPACT_MEDIUM, USAGE_FIRED_RESET_BELOW, } from "./context-thresholds.js";
29
29
  import { tokenArms, formatTokensK } from "./context-usage.js";
30
30
  import { getResolvedContextWindow } from "../config/braid-settings.js";
31
31
  /**
@@ -91,22 +91,131 @@ export function contextUsageTokenMessage(level, usagePercent, usageTokens) {
91
91
  `Consider context_inspect(detail="prune") to see candidates, or tag position with context_navigate(action="tag").`);
92
92
  }
93
93
  /**
94
- * Combined enforcement cascade: token tiers first (0.45W/0.18W — fire earlier
95
- * for large context windows), then the percent tiers (30/50/65/75/80).
96
- * Returns null when no tier is reached.
94
+ * The ladder for one window, weakest position first. Token rungs carry the
95
+ * absolute count in their copy (that is what they are for on a large window);
96
+ * percent rungs carry the percent.
97
97
  */
98
- export function contextUsageNudgeMessage(usagePercent, usageTokens, window) {
98
+ function nudgeRungs(window) {
99
99
  const arms = tokenArms(window);
100
- if (usageTokens >= arms.warning) {
101
- return contextUsageTokenMessage("warning", usagePercent, usageTokens);
102
- }
103
- if (usageTokens >= arms.soft) {
104
- return contextUsageTokenMessage("soft", usagePercent, usageTokens);
100
+ const positionOf = (tokens) => (arms.W > 0 ? (tokens / arms.W) * 100 : 0);
101
+ const pct = (threshold) => ({ unit: "percent", threshold, position: threshold });
102
+ return [
103
+ {
104
+ id: "tokens:soft",
105
+ unit: "tokens",
106
+ threshold: arms.soft,
107
+ position: positionOf(arms.soft),
108
+ render: (p, t) => contextUsageTokenMessage("soft", p, t),
109
+ },
110
+ {
111
+ id: "percent:soft",
112
+ ...pct(USAGE_WHISPER_SOFT),
113
+ render: (p) => contextUsageTierMessage("soft", p),
114
+ },
115
+ {
116
+ id: "tokens:warning",
117
+ unit: "tokens",
118
+ threshold: arms.warning,
119
+ position: positionOf(arms.warning),
120
+ render: (p, t) => contextUsageTokenMessage("warning", p, t),
121
+ },
122
+ {
123
+ id: "percent:advisory",
124
+ ...pct(USAGE_WHISPER_ADVISORY),
125
+ render: (p) => contextUsageTierMessage("advisory", p),
126
+ },
127
+ {
128
+ id: "percent:warning",
129
+ ...pct(USAGE_WHISPER_WARNING),
130
+ render: (p) => contextUsageTierMessage("warning", p),
131
+ },
132
+ {
133
+ id: "percent:critical",
134
+ ...pct(USAGE_WHISPER_CRITICAL),
135
+ render: (p) => contextUsageTierMessage("critical", p),
136
+ },
137
+ {
138
+ id: "percent:compact",
139
+ ...pct(USAGE_COMPACT_MEDIUM),
140
+ render: (p) => contextUsageTierMessage("compact", p),
141
+ },
142
+ ];
143
+ }
144
+ /**
145
+ * The strongest rung these numbers reach, or null below the first rung.
146
+ * Highest POSITION wins, not first match: that is what stops a token arm from
147
+ * shadowing a percent tier above it. Equal positions keep the earlier rung
148
+ * (the ladder is built weakest-first), and an equal position is not an
149
+ * escalation.
150
+ */
151
+ export function resolveContextNudge(usagePercent, usageTokens, window) {
152
+ let best = null;
153
+ for (const rung of nudgeRungs(window)) {
154
+ const reached = rung.unit === "tokens" ? usageTokens >= rung.threshold : usagePercent >= rung.threshold;
155
+ if (reached && (best === null || rung.position > best.position))
156
+ best = rung;
105
157
  }
106
- const tier = contextUsageTier(usagePercent);
107
- if (!tier)
158
+ if (!best)
108
159
  return null;
109
- return contextUsageTierMessage(tier.tier, usagePercent);
160
+ return {
161
+ id: best.id,
162
+ unit: best.unit,
163
+ threshold: best.threshold,
164
+ position: best.position,
165
+ message: best.render(usagePercent, usageTokens),
166
+ };
167
+ }
168
+ /**
169
+ * One rung by id, resolved against the window in hand: a window change
170
+ * re-derives the rung's bar instead of comparing a live count against a stale
171
+ * one. Unknown or absent ids yield null (a latch armed by something that is
172
+ * not a rung).
173
+ */
174
+ export function findContextNudgeRung(id, window) {
175
+ if (!id)
176
+ return null;
177
+ for (const rung of nudgeRungs(window)) {
178
+ if (rung.id === id)
179
+ return { id: rung.id, unit: rung.unit, threshold: rung.threshold, position: rung.position };
180
+ }
181
+ return null;
182
+ }
183
+ /**
184
+ * Has usage fallen back below the rung that armed the latch? The comparison is
185
+ * in the rung's own unit: a token rung clears on a token count below its arm,
186
+ * a percent rung on a percent below its threshold. With no recorded rung (the
187
+ * latch was armed by an act that then stood down) the percent reset bar
188
+ * applies, which is the pre-ladder behavior for that path.
189
+ */
190
+ export function contextNudgeFellBelow(id, usagePercent, usageTokens, window) {
191
+ const rung = findContextNudgeRung(id, window);
192
+ if (!rung)
193
+ return usagePercent < USAGE_FIRED_RESET_BELOW;
194
+ return rung.unit === "tokens" ? usageTokens < rung.threshold : usagePercent < rung.threshold;
195
+ }
196
+ /**
197
+ * Was this rung crossed from below since the previous sample? A nudge is an
198
+ * event: a session that lands above a rung and stays there must not read the
199
+ * same advice every turn, while a rung climbed past is new information. The
200
+ * previous sample is a token count, so a percent rung is tested against it
201
+ * re-expressed as a percent of the window in hand.
202
+ */
203
+ export function contextNudgeCrossed(rung, prevUsageTokens, window) {
204
+ if (prevUsageTokens === undefined)
205
+ return true;
206
+ if (rung.unit === "tokens")
207
+ return prevUsageTokens < rung.threshold;
208
+ const { W } = tokenArms(window);
209
+ if (W <= 0)
210
+ return true;
211
+ return (prevUsageTokens / W) * 100 < rung.threshold;
212
+ }
213
+ /**
214
+ * Combined enforcement nudge: the strongest rung reached, its text, or null.
215
+ * Kept as a text accessor for callers that need nothing but the message.
216
+ */
217
+ export function contextUsageNudgeMessage(usagePercent, usageTokens, window) {
218
+ return resolveContextNudge(usagePercent, usageTokens, window)?.message ?? null;
110
219
  }
111
220
  /**
112
221
  * ONE duck-typed `getContextUsage()` extraction. Mirrors the fallbacks
@@ -0,0 +1,78 @@
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
+ import type { TurnEndEvent } from "@earendil-works/pi-coding-agent";
52
+ /**
53
+ * A boundary as this rule reads it: a real `turn_end` payload, or the partial
54
+ * projection a caller may hold. `undefined` means the caller has no boundary
55
+ * knowledge at all, which is a different statement from an empty boundary.
56
+ */
57
+ export type TurnBoundary = Partial<Pick<TurnEndEvent, "message">> | undefined;
58
+ /** The usage a backstop decision reads. */
59
+ export interface TurnBoundaryUsage {
60
+ /** Live tokens in the working set (compaction-aware). */
61
+ tokens: number;
62
+ /** The window the backstop fraction resolves against, when known. */
63
+ contextWindow?: number | null;
64
+ }
65
+ /**
66
+ * True when the boundary carries a stop reason that ends the turn's work.
67
+ * Fail-closed: a boundary with no readable reason, or one this rule does not
68
+ * recognize, is not loop-done.
69
+ */
70
+ export declare function turnBoundaryIsLoopDone(boundary: TurnBoundary): boolean;
71
+ /**
72
+ * Whether a deferred compaction may abort the run at this boundary.
73
+ *
74
+ * `readUsage` is called only when the boundary is not loop-done, so a
75
+ * loop-done boundary never pays for a usage measurement.
76
+ */
77
+ export declare function turnBoundaryMayAbortRun(boundary: TurnBoundary, readUsage?: () => TurnBoundaryUsage | null | undefined): boolean;
78
+ //# sourceMappingURL=turn-boundary.d.ts.map
@@ -0,0 +1,91 @@
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
+ import { tokenArms } from "../detection/context-usage.js";
52
+ import { getStopReason } from "../state/extension-state.js";
53
+ /**
54
+ * The stop reasons that end the turn's work, keyed by the union pi-ai
55
+ * declares. Typing the record as a total map over the reasons this rule does
56
+ * not park on makes a new provider stop reason a compile error here instead of
57
+ * a silent "park" or a silent "fire": someone has to classify it.
58
+ */
59
+ const LOOP_DONE_STOP_REASONS = {
60
+ stop: true,
61
+ length: true,
62
+ error: true,
63
+ aborted: true,
64
+ };
65
+ const LOOP_DONE = new Set(Object.keys(LOOP_DONE_STOP_REASONS));
66
+ /**
67
+ * True when the boundary carries a stop reason that ends the turn's work.
68
+ * Fail-closed: a boundary with no readable reason, or one this rule does not
69
+ * recognize, is not loop-done.
70
+ */
71
+ export function turnBoundaryIsLoopDone(boundary) {
72
+ const stopReason = getStopReason(boundary?.message);
73
+ return stopReason !== undefined && LOOP_DONE.has(stopReason);
74
+ }
75
+ /**
76
+ * Whether a deferred compaction may abort the run at this boundary.
77
+ *
78
+ * `readUsage` is called only when the boundary is not loop-done, so a
79
+ * loop-done boundary never pays for a usage measurement.
80
+ */
81
+ export function turnBoundaryMayAbortRun(boundary, readUsage) {
82
+ if (boundary === undefined)
83
+ return true;
84
+ if (turnBoundaryIsLoopDone(boundary))
85
+ return true;
86
+ const usage = readUsage?.();
87
+ if (!usage)
88
+ return false;
89
+ return usage.tokens >= tokenArms(usage.contextWindow).backstop;
90
+ }
91
+ //# sourceMappingURL=turn-boundary.js.map