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
@@ -8,12 +8,15 @@
8
8
  * scratchpad + write resume.json) to guarantee zero data loss.
9
9
  *
10
10
  * Safety gates, checked in order:
11
- * - Loop-done gate: the act never fires on a turn_end whose assistant
12
- * stopReason is "toolUse" -- the agent loop is live (the next model
13
- * call is pending) and ctx.compact() aborts it mid-run (manual
14
- * compaction never retries or continues the interrupted turn). The
15
- * only exception is the 0.90W backstop, which deliberately stops a
16
- * runaway loop before overflow.
11
+ * - Loop-done gate: the act aborts the run through ctx.compact(), so it only
12
+ * fires at a boundary the shared rule accepts
13
+ * (lib/events/turn-boundary.ts, the same rule the context_compress drain
14
+ * reads). That rule fires on a loop-done stop reason and parks on a live
15
+ * loop ("toolUse") or on a boundary it cannot read. The only exception is
16
+ * the 0.90W backstop, which deliberately stops a runaway loop before
17
+ * overflow. The rule's residual section names the cases a loop-done stop
18
+ * reason does not rule out: a tool call riding a non-"toolUse" stop
19
+ * reason, and a steer queued at any boundary.
17
20
  * - Mode awareness: the DETERMINISTIC slide path carries none of the
18
21
  * abort/corruption risk that justifies standing down, so it fires at
19
22
  * the act arm regardless of pi's compaction.enabled. Only the LLM
@@ -21,10 +24,11 @@
21
24
  * per act decision from the merged settings), native compaction owns
22
25
  * LLM compaction and the act stands down to nudge-only.
23
26
  *
24
- * ctx.compact() calls this._disconnectFromAgent() + this.abort() in pi-core
25
- * (agent-session.js:1245). To keep the handler's synchronous part off the
26
- * abort path, the compact call is deferred via setTimeout(0). Resume after
27
- * the compaction is register-session-compact's decision, not ours.
27
+ * ctx.compact() aborts the current agent operation first and never retries or
28
+ * continues the interrupted turn (pi-core's agent-session compact()). To keep
29
+ * the handler's synchronous part off the abort path, the compact call is
30
+ * deferred via setTimeout(0). Resume after the compaction is
31
+ * register-session-compact's decision, not ours.
28
32
  *
29
33
  * Discoverability (scratchpad/memory/episodes surfacing) fires from
30
34
  * SESSION_START (register-session-start-discoverability.ts), before the
@@ -33,25 +37,31 @@
33
37
 
34
38
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
35
39
  import { SettingsManager, getAgentDir } from "@earendil-works/pi-coding-agent";
36
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
40
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
37
41
  import * as path from "node:path";
38
42
  import { execSync } from "node:child_process";
39
43
  import { createLogger } from "../../../lib/core/logger.js";
40
44
  import { registerTurnEndHandler } from "../../../lib/events/turn-end-coordinator.js";
45
+ import { turnBoundaryMayAbortRun } from "../../../lib/events/turn-boundary.js";
41
46
  import { sendEnforcementWhisper } from "../whisper.js";
42
47
  import { getState } from "../state.js";
43
48
  import { fileMutationQueue } from "../../../lib/utils/file-mutation-queue.js";
44
- import { braidDir, scratchpadDir } from "../../../lib/config/braid-paths.js";
49
+ import { braidDir } from "../../../lib/config/braid-paths.js";
45
50
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
46
51
  import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
52
+ import { readResumeScratchpadState } from "../resume-state.js";
47
53
  import { isCompactionActive, getCmState } from "../../memory/context-manager/handlers/shared.js";
48
54
  import { snapBoundaryOutsideToolBatch } from "../../memory/context-manager/handlers/tool-batch-boundary.js";
49
55
  import {
50
56
  USAGE_COMPACT_AGGRESSIVE,
51
- USAGE_FIRED_RESET_BELOW,
52
57
  HYGIENE_AUTO_COMPACT_MIN_TURNS,
53
58
  } from "../../../lib/detection/context-thresholds.js";
54
- import { contextUsageNudgeMessage } from "../../../lib/detection/context-tiers.js";
59
+ import {
60
+ resolveContextNudge,
61
+ findContextNudgeRung,
62
+ contextNudgeFellBelow,
63
+ contextNudgeCrossed,
64
+ } from "../../../lib/detection/context-tiers.js";
55
65
  import {
56
66
  measureLiveUsage,
57
67
  tokenArms,
@@ -70,13 +80,16 @@ const log = createLogger("enforcement:turn-end-hygiene");
70
80
 
71
81
  // Pre-save safety: flush scratchpad + write resume.json
72
82
 
73
- function saveStateBeforeCompact(cwd: string, ctx: ExtensionContext): void {
83
+ async function saveStateBeforeCompact(cwd: string, ctx: ExtensionContext): Promise<void> {
74
84
  try {
75
85
  // 1. Flush file mutation queue + scratchpad debounced queue
76
86
  // Pre-compaction flush is best-effort: a failed flush loses only the
77
- // newest queued writes; blocking compaction would lose far more.
87
+ // newest queued writes; blocking compaction would lose far more. The
88
+ // scratchpad flush is awaited because the resume read below reads the
89
+ // checkpoint log that flush appends to - unawaited, the pre-save could
90
+ // record the previous turn's pad, or none at all.
78
91
  fileMutationQueue.flushAll().catch(() => {});
79
- flushPendingScratchpadWrites().catch(() => {});
92
+ await flushPendingScratchpadWrites().catch(() => {});
80
93
  } catch {
81
94
  // flush APIs themselves failed — compaction must still proceed
82
95
  }
@@ -89,31 +102,15 @@ function saveStateBeforeCompact(cwd: string, ctx: ExtensionContext): void {
89
102
  // No reader consumes either key; the fields both writers carry are the
90
103
  // ones the reader reads back.
91
104
  const slug = projectSlugFromCwd(cwd);
92
- let goal: string | null = null;
93
- let openPlans: Array<{ id: string; text: string }> = [];
94
- let recentDecisions: Array<{ id: string; text: string }> = [];
95
- // Prior state is a READ: the scratchpad root is resolved on every call, so
96
- // a pinned run reads the tree the scratchpad writer wrote to, and a
97
- // segment rename in the accessor moves this reader with the writer. A
98
- // refused root (no absolute braid home) or a corrupt section degrades to
99
- // no prior-state section instead of failing the resume write below.
100
- try {
101
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
102
- if (existsSync(scratchpadFile)) {
103
- const content = readFileSync(scratchpadFile, "utf-8");
104
- const parsed = JSON.parse(content);
105
- goal = parsed.goal ?? null;
106
- openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
107
- .filter((p: any) => !p.done)
108
- .slice(0, 10)
109
- .map((p: any) => ({ id: p.id ?? "", text: p.text ?? "" }));
110
- recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
111
- .slice(-5)
112
- .map((d: any) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
113
- }
114
- } catch (err) {
115
- log.debug(`scratchpad prior-state read failed: ${err}`);
116
- }
105
+ // Prior state is a READ through the scratchpad store's own loader (the
106
+ // checkpoint log, not a hand-built path), so a schema or storage change
107
+ // in the store moves this reader with it. A refused root (no absolute
108
+ // braid home) or a corrupt section degrades to an empty prior-state
109
+ // section instead of failing the resume write below.
110
+ const resumeState = await readResumeScratchpadState(slug);
111
+ const goal = resumeState.goal;
112
+ const openPlans = resumeState.openPlans;
113
+ const recentDecisions = resumeState.recentDecisions;
117
114
 
118
115
  let uncommittedFiles: string[] = [];
119
116
  try {
@@ -188,7 +185,11 @@ function compactionEnabledPerCheck(ctx: ExtensionContext): boolean {
188
185
  }
189
186
  }
190
187
 
191
- function checkContextUsage(pi: ExtensionAPI, ctx: ExtensionContext, event: any): void {
188
+ async function checkContextUsage(
189
+ pi: ExtensionAPI,
190
+ ctx: ExtensionContext,
191
+ event: any,
192
+ ): Promise<void> {
192
193
  const state = getState(ctx);
193
194
  if (!state?.enforcementActive) return;
194
195
 
@@ -221,16 +222,22 @@ function checkContextUsage(pi: ExtensionAPI, ctx: ExtensionContext, event: any):
221
222
  recordHygieneSkip(state);
222
223
  return;
223
224
  }
224
- // The previous usable turn's live sample (the soft tier's crossing
225
- // witness), captured before this turn's sample replaces it.
225
+ // The previous usable turn's live sample (the crossing witness), captured
226
+ // before this turn's sample replaces it.
226
227
  const prevLiveTokens = state.liveUsageSamples[state.liveUsageSamples.length - 1];
227
228
  recordLiveUsageSample(state, usageTokens);
228
229
 
229
- // Re-arm the shared context-nudge latch when usage has dropped (e.g.,
230
- // after compaction). The bar is the named policy value, not a literal.
231
- // It governs the higher tiers only; the soft tier re-arms on its own arm
232
- // crossing, gated at the cascade below.
233
- if (state.contextNudgeSent && usagePercent < USAGE_FIRED_RESET_BELOW) {
230
+ // Re-arm the shared context-nudge latch in the unit that armed it: a token
231
+ // rung clears on a fall back below that token arm, a percent rung below its
232
+ // own percent. A bar in the other unit clears a token arm on the very next
233
+ // turn whenever the arm sits above the bar (0.45W is 45% of every window,
234
+ // below the 50% bar), which is the repeat loop this latch exists to stop.
235
+ // The rung id stays recorded: it is the floor a weaker rung must cross to be
236
+ // news rather than a descent.
237
+ if (
238
+ state.contextNudgeSent &&
239
+ contextNudgeFellBelow(state.contextNudgeRung, usagePercent, usageTokens, usageWindow)
240
+ ) {
234
241
  state.contextNudgeSent = false;
235
242
  }
236
243
 
@@ -255,14 +262,18 @@ function checkContextUsage(pi: ExtensionAPI, ctx: ExtensionContext, event: any):
255
262
  recordHygieneSkip(state);
256
263
  return;
257
264
  }
258
- // Loop-done gate: "toolUse" means the agent loop is live -- the next
259
- // model call is queued inside the running agent operation, and
260
- // ctx.compact() aborts it (manual compaction never retries or continues
261
- // the interrupted turn). Act only on a loop-done stop; the 0.90W
262
- // backstop below still acts mid-loop to stop a runaway loop before
263
- // overflow (its purpose).
264
- const loopDone = (event as any)?.message?.stopReason !== "toolUse";
265
- if (!loopDone && !atHardBackstop) {
265
+ // Loop-done gate: the act runs ctx.compact(), which aborts the running
266
+ // agent operation (manual compaction never retries or continues the
267
+ // interrupted turn), so the boundary decides it. One rule, shared with the
268
+ // context_compress drain: a loop-done stop fires, a live loop parks, an
269
+ // unreadable boundary parks, and the 0.90W backstop below still acts
270
+ // mid-loop to stop a runaway loop before overflow (its purpose).
271
+ if (
272
+ !turnBoundaryMayAbortRun(event, () => ({
273
+ tokens: usageTokens,
274
+ contextWindow: usageWindow,
275
+ }))
276
+ ) {
266
277
  recordHygieneSkip(state);
267
278
  return;
268
279
  }
@@ -287,9 +298,15 @@ function checkContextUsage(pi: ExtensionAPI, ctx: ExtensionContext, event: any):
287
298
  ? "token"
288
299
  : "percent";
289
300
  state.contextNudgeSent = true;
301
+ // The act is not a nudge rung: leave no rung recorded, so the nudge
302
+ // block stays suppressed behind the act (and the percent reset bar
303
+ // governs this latch) exactly as before.
304
+ state.contextNudgeRung = null;
290
305
 
291
- // Pre-save safety net before compaction
292
- saveStateBeforeCompact((ctx as { cwd?: string }).cwd ?? "", ctx);
306
+ // Pre-save safety net before compaction. Awaited: the act arms right
307
+ // after, and the write must land before the compaction it protects
308
+ // against. ctx.compact itself is deferred to a macrotask below.
309
+ await saveStateBeforeCompact((ctx as { cwd?: string }).cwd ?? "", ctx);
293
310
 
294
311
  const kind = armHygieneAct(ctx, trigger, plan);
295
312
  if (!kind) {
@@ -314,28 +331,31 @@ function checkContextUsage(pi: ExtensionAPI, ctx: ExtensionContext, event: any):
314
331
  }
315
332
  }
316
333
 
317
- if (state.contextNudgeSent) return;
318
-
319
- // Progressive nudge: token tiers first, then percent tiers. Cascade shared
320
- // from lib/detection/context-tiers.ts (contextUsageNudgeMessage):
321
- // token arms 0.45W/0.18W fire earlier for large windows, then percent tiers
322
- // soft (30%) -> advisory (50%) -> warning (65%) -> critical (75%) ->
323
- // compact (80%).
324
- const nudgeMessage = contextUsageNudgeMessage(usagePercent, usageTokens, usageWindow);
325
- if (nudgeMessage) {
326
- // Soft-tier crossing gate: the cascade's sub-warning level is the soft
327
- // token text (the percent tiers are shadowed by the token arms, which
328
- // fire first). It fires on the turn its arm is crossed from below, not
329
- // on every turn inside the band. The shared latch above re-arms below
330
- // USAGE_FIRED_RESET_BELOW, a bar above the soft arm, so without this
331
- // gate the same whisper re-injected every turn from the soft arm up to
332
- // the reset bar. The higher tiers keep the shared latch untouched.
333
- if (usageTokens < arms.warning) {
334
- const crossedSoftArm = prevLiveTokens === undefined || prevLiveTokens < arms.soft;
335
- if (!crossedSoftArm) return;
334
+ // Progressive nudge: ONE ladder over both units, ordered by position
335
+ // (percent of the resolved window) — token soft 0.18W, percent soft 30%,
336
+ // token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
337
+ // 80%. The strongest rung reached wins, so no token arm can shadow a
338
+ // percent tier above it (see lib/detection/context-tiers.ts).
339
+ const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
340
+ if (nudge) {
341
+ const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
342
+ if (state.contextNudgeSent) {
343
+ // The latch holds the rung that fired; a strictly stronger rung is new
344
+ // information and may pass it. Without this the ladder went quiet from
345
+ // the first rung upward and an agent at 95% read the 45% line.
346
+ if (!lastFired || nudge.position <= lastFired.position) return;
347
+ } else if (
348
+ lastFired &&
349
+ nudge.position < lastFired.position &&
350
+ !contextNudgeCrossed(nudge, prevLiveTokens, usageWindow)
351
+ ) {
352
+ // A weaker rung that usage merely settled at (a descent, not a
353
+ // crossing) is not news; a rung climbed back past is.
354
+ return;
336
355
  }
337
356
  state.contextNudgeSent = true;
338
- sendEnforcementWhisper(pi, ctx, nudgeMessage);
357
+ state.contextNudgeRung = nudge.id;
358
+ sendEnforcementWhisper(pi, ctx, nudge.message);
339
359
  }
340
360
  }
341
361
 
@@ -440,7 +460,7 @@ function armHygieneAct(
440
460
  export function registerTurnEndHygiene(pi: ExtensionAPI): void {
441
461
  registerTurnEndHandler("turn-end-hygiene", 5, async (event, ctx) => {
442
462
  try {
443
- checkContextUsage(pi, ctx, event);
463
+ await checkContextUsage(pi, ctx, event);
444
464
  } catch (err) {
445
465
  log.error("turn-end-hygiene error:", err);
446
466
  }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Resume handoff state - the scratchpad program a fresh seat needs after a
3
+ * mastership transfer.
4
+ *
5
+ * The resume file (`<braidDir>/sessions/<slug>/resume.json`) is written by
6
+ * two handlers (the turn-end pre-save, the session shutdown writer) and read
7
+ * by a third (session-start discoverability). All three need the same
8
+ * projection of the scratchpad, so it lives here once.
9
+ *
10
+ * The scratchpad is an append-only checkpoint log (`events.jsonl`, last line
11
+ * wins), not a single JSON snapshot, so this reads through the store's own
12
+ * loader - `loadScratchpadFromDisk` - instead of re-deriving a path and a
13
+ * parse. The loader also runs the store's migrations, which is why a legacy
14
+ * `latest.json` still yields state here.
15
+ *
16
+ * The field names come from `TaskScratchpad`: `plan`, `decisions`,
17
+ * `key_learnings`. Reading `plans`/`learnings` off the persisted state
18
+ * silently yields nothing.
19
+ */
20
+
21
+ import { createLogger } from "../../lib/core/logger.js";
22
+ import { loadScratchpadFromDisk } from "../memory/scratchpad/persistence.js";
23
+ import type { TaskScratchpad } from "../memory/scratchpad/types.js";
24
+
25
+ const log = createLogger("enforcement:resume-state");
26
+
27
+ /**
28
+ * How many entries of each list the resume file carries. Sized for a
29
+ * transfer, not an audit: the first open plan steps are the program a
30
+ * successor continues (later steps are usually its to rewrite), and five
31
+ * decisions/learnings cover the recent working assumptions. The uncapped
32
+ * counts travel alongside so a reader can report "20 open, 10 shown".
33
+ */
34
+ export const RESUME_OPEN_PLAN_LIMIT = 10;
35
+ export const RESUME_RECENT_DECISION_LIMIT = 5;
36
+ export const RESUME_RECENT_LEARNING_LIMIT = 5;
37
+
38
+ /** A plan step is live once it has been started (see `add_plan`/`mark_done`). */
39
+ export type ResumePlanStatus = "in_progress" | "pending";
40
+
41
+ export interface ResumePlanItem {
42
+ id: string;
43
+ text: string;
44
+ status: ResumePlanStatus;
45
+ }
46
+
47
+ export interface ResumeDecisionItem {
48
+ id: string;
49
+ text: string;
50
+ reason?: string;
51
+ }
52
+
53
+ export interface ResumeLearningItem {
54
+ category: string;
55
+ content: string;
56
+ }
57
+
58
+ export interface ResumeScratchpadState {
59
+ goal: string | null;
60
+ /** First RESUME_OPEN_PLAN_LIMIT unfinished steps, in plan order. */
61
+ openPlans: ResumePlanItem[];
62
+ /** Unfinished steps overall, before the display cap. */
63
+ openPlanCount: number;
64
+ recentDecisions: ResumeDecisionItem[];
65
+ recentLearnings: ResumeLearningItem[];
66
+ }
67
+
68
+ /** The projection of "no scratchpad": every section empty, never undefined. */
69
+ export function emptyResumeScratchpadState(): ResumeScratchpadState {
70
+ return {
71
+ goal: null,
72
+ openPlans: [],
73
+ openPlanCount: 0,
74
+ recentDecisions: [],
75
+ recentLearnings: [],
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Project a loaded scratchpad onto the resume fields. Pure: the input pad is
81
+ * never mutated.
82
+ *
83
+ * Plan completion lives in `doneTurn` (mark_done stamps the turn and leaves
84
+ * the step in `plan`), so "open" is `doneTurn === 0` - the step is still in
85
+ * the plan, unfinished. A started-but-unfinished step is the live one.
86
+ */
87
+ export function projectResumeScratchpad(pad: TaskScratchpad | null): ResumeScratchpadState {
88
+ if (!pad) return emptyResumeScratchpadState();
89
+
90
+ const openSteps = pad.plan.filter((step) => !step.doneTurn);
91
+ return {
92
+ goal: pad.goal && pad.goal.length > 0 ? pad.goal : null,
93
+ openPlans: openSteps.slice(0, RESUME_OPEN_PLAN_LIMIT).map((step) => ({
94
+ id: step.id,
95
+ text: step.text,
96
+ status: step.startTurn > 0 ? "in_progress" : "pending",
97
+ })),
98
+ openPlanCount: openSteps.length,
99
+ recentDecisions: pad.decisions.slice(-RESUME_RECENT_DECISION_LIMIT).map((decision) => ({
100
+ id: decision.id,
101
+ text: decision.text,
102
+ ...(decision.reason ? { reason: decision.reason } : {}),
103
+ })),
104
+ recentLearnings: pad.key_learnings
105
+ .slice(-RESUME_RECENT_LEARNING_LIMIT)
106
+ .map((learning) => ({ category: learning.category, content: learning.content })),
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Read this project's scratchpad and project it onto the resume fields.
112
+ *
113
+ * Degrades to the empty projection on any read failure: a resume file with no
114
+ * prior-state section is worth less than a program, but far more than a
115
+ * handler that threw during shutdown or before a compaction. The refusal is
116
+ * logged at debug - the empty projection is the visible outcome.
117
+ */
118
+ export async function readResumeScratchpadState(
119
+ projectSlug: string,
120
+ ): Promise<ResumeScratchpadState> {
121
+ try {
122
+ return projectResumeScratchpad(await loadScratchpadFromDisk(projectSlug));
123
+ } catch (err) {
124
+ log.debug(`scratchpad read for resume failed: ${err}`);
125
+ return emptyResumeScratchpadState();
126
+ }
127
+ }
@@ -67,6 +67,15 @@ export function resetScratchpadState(s: ScratchpadState): void {
67
67
 
68
68
  export interface ContextHygieneState {
69
69
  contextNudgeSent: boolean;
70
+ /**
71
+ * The nudge-ladder rung that armed `contextNudgeSent` (its id), or null when
72
+ * the latch was armed by something that is not a rung (the hygiene act) or
73
+ * by nothing yet. The latch re-arms in this rung's unit, and the rung is the
74
+ * floor a weaker rung has to cross to be news rather than a descent. Survives
75
+ * the re-arm; cleared when a compaction or a context tool makes a fresh
76
+ * start.
77
+ */
78
+ contextNudgeRung: string | null;
70
79
  lastContextCheckTurn: number;
71
80
  lastCompactionTurn: number;
72
81
  overflowRecently: number;
@@ -110,6 +119,7 @@ export interface ContextHygieneState {
110
119
  export function createContextHygieneState(): ContextHygieneState {
111
120
  return {
112
121
  contextNudgeSent: false,
122
+ contextNudgeRung: null,
113
123
  lastContextCheckTurn: 0,
114
124
  lastCompactionTurn: 0,
115
125
  overflowRecently: 0,
@@ -126,6 +136,7 @@ export function createContextHygieneState(): ContextHygieneState {
126
136
 
127
137
  export function resetContextHygieneState(s: ContextHygieneState): void {
128
138
  s.contextNudgeSent = false;
139
+ s.contextNudgeRung = null;
129
140
  s.lastContextCheckTurn = 0;
130
141
  s.lastCompactionTurn = 0;
131
142
  s.overflowRecently = 0;
@@ -174,18 +185,21 @@ export function recordLiveUsageSample(s: ContextHygieneState, tokens: number): v
174
185
  /** Mark context nudge as sent (system sends nudge to agent). */
175
186
  export function markNudgeSent(s: ContextHygieneState, turn: number): void {
176
187
  s.contextNudgeSent = true;
188
+ s.contextNudgeRung = null;
177
189
  s.lastContextCheckTurn = turn;
178
190
  }
179
191
 
180
192
  /** Reset context nudge (e.g., after compaction freed space). */
181
193
  export function resetNudge(s: ContextHygieneState): void {
182
194
  s.contextNudgeSent = false;
195
+ s.contextNudgeRung = null;
183
196
  }
184
197
 
185
198
  /** Record that a context management tool was used. */
186
199
  export function recordContextTool(s: ContextHygieneState, turn: number): void {
187
200
  s.lastContextCheckTurn = turn;
188
201
  s.contextNudgeSent = false;
202
+ s.contextNudgeRung = null;
189
203
  }
190
204
 
191
205
  /** Record that compaction happened. Also resets scratchpad nudge timer. */
@@ -196,6 +210,9 @@ export function recordCompaction(
196
210
  s.lastCompactionTurn = turn;
197
211
  s.lastContextCheckTurn = turn;
198
212
  s.contextNudgeSent = false;
213
+ // A compaction is a fresh start: usage dropped by construction, so the rung
214
+ // that armed the old latch says nothing about where the next nudge belongs.
215
+ s.contextNudgeRung = null;
199
216
  s.overflowRecently = turn;
200
217
  if (typeof s.lastScratchpadNudgeTurn === "number") {
201
218
  s.lastScratchpadNudgeTurn = turn;
@@ -44,6 +44,17 @@ const log = createLogger("enforcement");
44
44
  * options.deliverAs - Delivery mode. Defaults to `"steer"` for a
45
45
  * non-waking whisper; left undefined when triggerTurn:true so
46
46
  * pi-core's wake branch is not shadowed by the nextTurn queue.
47
+ * options.bypassFloodCap - Skip the per-turn/per-source whisper flood cap
48
+ * in the funnel (see `sendTrackedMessage`'s JSDoc). Opt-in
49
+ * per call site, default false, and reserved for a wake
50
+ * whose loss is a correctness bug rather than a lost nudge:
51
+ * the post-compaction resume, which is the only thing that
52
+ * hands the aborted loop back. Every enforcement whisper
53
+ * shares the `enforcement/whisper` bucket, so three ordinary
54
+ * advisories in one turn are enough to spend it - a blanket
55
+ * exemption for `triggerTurn` would instead turn every
56
+ * waking caller into a flood risk, which is why the cap is
57
+ * bypassed here per call rather than in the funnel.
47
58
  *
48
59
  * Nudges are suppressed when braid.suppressNudges=true in settings.json.
49
60
  */
@@ -52,7 +63,12 @@ export function sendEnforcementWhisper(
52
63
  ctx: ExtensionContext,
53
64
  message: string,
54
65
  critical: boolean = false,
55
- options?: { triggerTurn?: boolean; deliverAs?: "steer" | "nextTurn"; delivery?: "live" | "park" },
66
+ options?: {
67
+ triggerTurn?: boolean;
68
+ deliverAs?: "steer" | "nextTurn";
69
+ delivery?: "live" | "park";
70
+ bypassFloodCap?: boolean;
71
+ },
56
72
  ): void {
57
73
  // Cognitive nudge suppression - separate from confirm dialogs
58
74
  if (areCognitiveNudgesDisabled()) {
@@ -116,5 +132,9 @@ export function sendEnforcementWhisper(
116
132
  },
117
133
  { deliverAs, triggerTurn, delivery },
118
134
  { type: "enforcement", source: "enforcement/whisper" },
135
+ // Forwarded per call, never defaulted on: the funnel's flood cap stays
136
+ // the gate for every enforcement whisper that does not ask for the
137
+ // exemption explicitly.
138
+ { bypassFloodCap: options?.bypassFloodCap === true },
119
139
  );
120
140
  }
@@ -115,12 +115,18 @@ function newestUserText(ctx: ExtensionContext): string {
115
115
  import type { CognitiveModule, ModuleContext, PolicyEngine } from "./types.js";
116
116
  import { DEFAULT_CONFIG, getState, getMemoryState } from "./state.js";
117
117
  import { updateMetaLearning, getAdaptiveInterval } from "./meta-learning.js";
118
- import { createDefaultPolicies, VERIFICATION_TOOLS, WEB_TOOLS, CODE_TOOLS } from "./policies.js";
118
+ import {
119
+ createDefaultPolicies,
120
+ isVerificationToolCall,
121
+ WEB_TOOLS,
122
+ CODE_TOOLS,
123
+ } from "./policies.js";
119
124
  import {
120
125
  formatPendingCompactionsLine,
121
126
  maybeArmAutoCompaction,
122
127
  } from "../../memory/context-manager/handlers/tools/context-compress.js";
123
128
  import { pushBounded } from "../../../lib/utils/bounded.js";
129
+ import type { TurnBoundary } from "../../../lib/events/turn-boundary.js";
124
130
  import { RSS_RING_CAP } from "../../../lib/telemetry/rss-telemetry.js";
125
131
  import { recallerModule } from "./modules/recaller.js";
126
132
  import { reflectionConsolidatorModule } from "./modules/reflection-consolidator.js";
@@ -317,6 +323,7 @@ function tick(
317
323
  state: import("./types.js").HeartbeatState,
318
324
  config: import("./types.js").HeartbeatConfig,
319
325
  ctx: ExtensionContext,
326
+ turnEvent?: TurnBoundary,
320
327
  ): void {
321
328
  state.stats.totalTicks++;
322
329
 
@@ -407,7 +414,7 @@ function tick(
407
414
  log.warn(`[heartbeat] pending-compaction advisory failed: ${err}`);
408
415
  }
409
416
  try {
410
- maybeArmAutoCompaction(pi, ctx);
417
+ maybeArmAutoCompaction(pi, ctx, turnEvent);
411
418
  } catch (err) {
412
419
  log.warn(`[heartbeat] context auto-arm check failed: ${err}`);
413
420
  }
@@ -622,7 +629,7 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
622
629
 
623
630
  // Event: turn_end
624
631
 
625
- pi.on(TURN_END, async (_event: any, ctx: ExtensionContext) => {
632
+ pi.on(TURN_END, async (event: any, ctx: ExtensionContext) => {
626
633
  const state = getState(ctx);
627
634
  if (!state.enabled || !config.enabled) return;
628
635
 
@@ -637,7 +644,12 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
637
644
  const interval = getAdaptiveInterval(state);
638
645
  if (state.turnCount % interval !== 0) return;
639
646
 
640
- tick(pi, state, config, ctx);
647
+ // The boundary travels with the tick: the usage-driven auto-arm arms inside
648
+ // this dispatch, and a drain there can only be judged from the event that
649
+ // named the boundary. Dropping this argument is invisible to every other
650
+ // fixture, so one drives the real handler end to end:
651
+ // test/runtime/heartbeat/test-turn-boundary-arm-wiring.mjs.
652
+ tick(pi, state, config, ctx, event);
641
653
  });
642
654
 
643
655
  // Event: before_agent_start - flush delayed whispers
@@ -685,7 +697,10 @@ export default function heartbeatExtension(pi: ExtensionAPI) {
685
697
  const toolName = event?.toolName as string;
686
698
  if (!toolName) return;
687
699
 
688
- if (VERIFICATION_TOOLS.has(toolName)) {
700
+ // Verification activity is a name set plus bash by its command shape:
701
+ // a search or diff run through bash is the same activity the hint is
702
+ // about, and counting every bash call (edits, builds) would silence it.
703
+ if (isVerificationToolCall(toolName, event?.input)) {
689
704
  state.metaLearning.toolTracking.verificationCount++;
690
705
  state.metaLearning.toolTracking.lastVerificationTurn = state.policyTurnCount;
691
706
  }