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,7 +8,8 @@
8
8
  *
9
9
  * This handler runs in SessionPhase.Background (fire-and-forget, non-blocking)
10
10
  * so it doesn't delay agent startup. It checks for:
11
- * 1. Scratchpad latest.json for this project
11
+ * 1. Scratchpad checkpoint log for this project (`events.jsonl`, last
12
+ * checkpoint)
12
13
  * 2. Episodes file with content
13
14
  * 3. Semantic memory file with content
14
15
  * 4. Prior session .jsonl files (session-recall)
@@ -32,8 +33,9 @@ import { sendEnforcementWhisper } from "../whisper.js";
32
33
  import { getState } from "../state.js";
33
34
  import { enforcementSignals } from "../signals.js";
34
35
  import { isProjectSignalShown, markProjectSignalShown, reconstructShownSignalsFromBranch, } from "../../../lib/state/global-state.js";
35
- import { scratchpadDir, episodesFilePath, semanticMemoryFilePath, AGENT, braidDir, tagsSlugFromCwd, } from "../../../lib/config/braid-paths.js";
36
+ import { episodesFilePath, semanticMemoryFilePath, AGENT, braidDir, journalFilePath, tagsSlugFromCwd, } from "../../../lib/config/braid-paths.js";
36
37
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
38
+ import { readResumeScratchpadState } from "../resume-state.js";
37
39
  const log = createLogger("enforcement:session-start-discoverability");
38
40
  /**
39
41
  * Register the SESSION_START discoverability handler.
@@ -67,29 +69,22 @@ export function registerSessionStartDiscoverability(pi) {
67
69
  for (const key of Object.keys(enforcementSignals)) {
68
70
  delete enforcementSignals[key];
69
71
  }
70
- // 1. Scratchpad. The store root is resolved on every call, never a
71
- // module-load constant: a pinned run must read the tree the writers
72
- // wrote to, and a refused root (no absolute braid home) degrades.
72
+ // 1. Scratchpad. Read through the store's own loader (the checkpoint
73
+ // log), never a hand-built snapshot path: the snapshot file this
74
+ // branch used to open has not been written for years, so the signal
75
+ // was armed against a file that never existed. The store root is
76
+ // resolved on every call, never a module-load constant, so a pinned
77
+ // run reads the tree the writers wrote to.
73
78
  try {
74
79
  const slug = projectSlugFromCwd(cwd);
75
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
76
- if (existsSync(scratchpadFile)) {
77
- const stat = statSync(scratchpadFile);
78
- if (stat.size > 10) {
79
- const content = readFileSync(scratchpadFile, "utf-8");
80
- const parsed = JSON.parse(content);
81
- const hasGoal = parsed.goal && parsed.goal.length > 0;
82
- const openPlans = Array.isArray(parsed.plans)
83
- ? parsed.plans.filter((p) => !p.done).length
84
- : 0;
85
- if (hasGoal || openPlans > 0) {
86
- signals.push({
87
- type: "scratchpad_prior",
88
- text: `Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
89
- `Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
90
- });
91
- }
92
- }
80
+ const prior = await readResumeScratchpadState(slug);
81
+ const openPlans = prior.openPlanCount;
82
+ if (prior.goal || openPlans > 0) {
83
+ signals.push({
84
+ type: "scratchpad_prior",
85
+ text: `Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
86
+ `Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
87
+ });
93
88
  }
94
89
  }
95
90
  catch (err) {
@@ -203,7 +198,32 @@ export function registerSessionStartDiscoverability(pi) {
203
198
  catch {
204
199
  // ignore
205
200
  }
206
- // 7. Context hygiene & state preservation tip: forward-looking
201
+ // 7. The owner-input journal. The path comes from the constant the
202
+ // writer appends through, never a hand-built shape: two spellings for
203
+ // one file is how the scratchpad pointer armed itself against a file
204
+ // nothing writes (see step 1).
205
+ try {
206
+ const slug = projectSlugFromCwd(cwd);
207
+ const journalFile = journalFilePath(slug);
208
+ if (existsSync(journalFile)) {
209
+ const count = readFileSync(journalFile, "utf-8")
210
+ .split("\n")
211
+ .filter((line) => line.trim()).length;
212
+ if (count > 0) {
213
+ signals.push({
214
+ type: "journal_prior",
215
+ text: `The project journal holds ${count} entr${count === 1 ? "y" : "ies"} at ${journalFile} -- ` +
216
+ `what earlier seats decided and why, readable without their sessions. ` +
217
+ `Read the open program before acting (digest printer: packages/core/scripts/check-journal.mjs --digest), ` +
218
+ `so a decision gets superseded, not rediscovered.`,
219
+ });
220
+ }
221
+ }
222
+ }
223
+ catch {
224
+ // ignore
225
+ }
226
+ // 8. Context hygiene & state preservation tip: forward-looking
207
227
  // guidance — when prior state exists, remind the agent how to manage
208
228
  // context and preserve state against crashes.
209
229
  // Shown only when there's prior state to manage (other signals exist).
@@ -220,14 +240,21 @@ export function registerSessionStartDiscoverability(pi) {
220
240
  // persistence (via `projectSlugFromCwd`) lets `pi --session <id>` (a new
221
241
  // process) read previously shown signals from disk and skip them, so the
222
242
  // discoverability bundle doesn't re-fire on session resume.
243
+ // Signal types that must reach every seat, not only the first. The
244
+ // dedupe below -- and the branch entries it writes -- exists so a
245
+ // resumed session is not told what it already saw. A journal pointer is
246
+ // aimed at a seat that has never seen this project, so a mark left by an
247
+ // earlier seat is exactly the one-shot failure it exists to repair.
248
+ const alwaysShown = new Set(["journal_prior"]);
223
249
  const slug = signals.length > 0 && (cwd ? projectSlugFromCwd(cwd) : "");
224
- const unseenSignals = slug
225
- ? signals.filter((s) => !isProjectSignalShown(slug, s.type))
226
- : signals.filter((s) => !isProjectSignalShown("default", s.type));
250
+ const projectKey = slug || "default";
251
+ const unseenSignals = signals.filter((s) => alwaysShown.has(s.type) || !isProjectSignalShown(projectKey, s.type));
227
252
  if (unseenSignals.length > 0) {
228
253
  const bundled = unseenSignals.map((s) => s.text).join("\n");
229
254
  for (const s of unseenSignals) {
230
- markProjectSignalShown(slug || "default", s.type, pi);
255
+ if (alwaysShown.has(s.type))
256
+ continue;
257
+ markProjectSignalShown(projectKey, s.type, pi);
231
258
  }
232
259
  // Informational pointers to prior state: park (no forced turn).
233
260
  sendEnforcementWhisper(pi, ctx, bundled, false, { delivery: "park" });
@@ -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
@@ -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,42 +24,48 @@
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
31
35
  * first turn.
32
36
  */
33
37
  import { SettingsManager, getAgentDir } from "@earendil-works/pi-coding-agent";
34
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
38
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
35
39
  import * as path from "node:path";
36
40
  import { execSync } from "node:child_process";
37
41
  import { createLogger } from "../../../lib/core/logger.js";
38
42
  import { registerTurnEndHandler } from "../../../lib/events/turn-end-coordinator.js";
43
+ import { turnBoundaryMayAbortRun } from "../../../lib/events/turn-boundary.js";
39
44
  import { sendEnforcementWhisper } from "../whisper.js";
40
45
  import { getState } from "../state.js";
41
46
  import { fileMutationQueue } from "../../../lib/utils/file-mutation-queue.js";
42
- import { braidDir, scratchpadDir } from "../../../lib/config/braid-paths.js";
47
+ import { braidDir } from "../../../lib/config/braid-paths.js";
43
48
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
44
49
  import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
50
+ import { readResumeScratchpadState } from "../resume-state.js";
45
51
  import { isCompactionActive, getCmState } from "../../memory/context-manager/handlers/shared.js";
46
52
  import { snapBoundaryOutsideToolBatch } from "../../memory/context-manager/handlers/tool-batch-boundary.js";
47
- import { USAGE_COMPACT_AGGRESSIVE, USAGE_FIRED_RESET_BELOW, HYGIENE_AUTO_COMPACT_MIN_TURNS, } from "../../../lib/detection/context-thresholds.js";
48
- import { contextUsageNudgeMessage } from "../../../lib/detection/context-tiers.js";
53
+ import { USAGE_COMPACT_AGGRESSIVE, HYGIENE_AUTO_COMPACT_MIN_TURNS, } from "../../../lib/detection/context-thresholds.js";
54
+ import { resolveContextNudge, findContextNudgeRung, contextNudgeFellBelow, contextNudgeCrossed, } from "../../../lib/detection/context-tiers.js";
49
55
  import { measureLiveUsage, tokenArms, formatTokensK, } from "../../../lib/detection/context-usage.js";
50
56
  import { recordCompaction, recordHygieneAct, recordHygieneSkip, recordLiveUsageSample, } from "../substate/context-hygiene-state.js";
51
57
  const log = createLogger("enforcement:turn-end-hygiene");
52
58
  // Pre-save safety: flush scratchpad + write resume.json
53
- function saveStateBeforeCompact(cwd, ctx) {
59
+ async function saveStateBeforeCompact(cwd, ctx) {
54
60
  try {
55
61
  // 1. Flush file mutation queue + scratchpad debounced queue
56
62
  // Pre-compaction flush is best-effort: a failed flush loses only the
57
- // newest queued writes; blocking compaction would lose far more.
63
+ // newest queued writes; blocking compaction would lose far more. The
64
+ // scratchpad flush is awaited because the resume read below reads the
65
+ // checkpoint log that flush appends to - unawaited, the pre-save could
66
+ // record the previous turn's pad, or none at all.
58
67
  fileMutationQueue.flushAll().catch(() => { });
59
- flushPendingScratchpadWrites().catch(() => { });
68
+ await flushPendingScratchpadWrites().catch(() => { });
60
69
  }
61
70
  catch {
62
71
  // flush APIs themselves failed — compaction must still proceed
@@ -69,32 +78,15 @@ function saveStateBeforeCompact(cwd, ctx) {
69
78
  // No reader consumes either key; the fields both writers carry are the
70
79
  // ones the reader reads back.
71
80
  const slug = projectSlugFromCwd(cwd);
72
- let goal = null;
73
- let openPlans = [];
74
- let recentDecisions = [];
75
- // Prior state is a READ: the scratchpad root is resolved on every call, so
76
- // a pinned run reads the tree the scratchpad writer wrote to, and a
77
- // segment rename in the accessor moves this reader with the writer. A
78
- // refused root (no absolute braid home) or a corrupt section degrades to
79
- // no prior-state section instead of failing the resume write below.
80
- try {
81
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
82
- if (existsSync(scratchpadFile)) {
83
- const content = readFileSync(scratchpadFile, "utf-8");
84
- const parsed = JSON.parse(content);
85
- goal = parsed.goal ?? null;
86
- openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
87
- .filter((p) => !p.done)
88
- .slice(0, 10)
89
- .map((p) => ({ id: p.id ?? "", text: p.text ?? "" }));
90
- recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
91
- .slice(-5)
92
- .map((d) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
93
- }
94
- }
95
- catch (err) {
96
- log.debug(`scratchpad prior-state read failed: ${err}`);
97
- }
81
+ // Prior state is a READ through the scratchpad store's own loader (the
82
+ // checkpoint log, not a hand-built path), so a schema or storage change
83
+ // in the store moves this reader with it. A refused root (no absolute
84
+ // braid home) or a corrupt section degrades to an empty prior-state
85
+ // section instead of failing the resume write below.
86
+ const resumeState = await readResumeScratchpadState(slug);
87
+ const goal = resumeState.goal;
88
+ const openPlans = resumeState.openPlans;
89
+ const recentDecisions = resumeState.recentDecisions;
98
90
  let uncommittedFiles = [];
99
91
  try {
100
92
  // Scope to the project dir only. When ctx.cwd is missing, `cwd` is "" and
@@ -165,7 +157,7 @@ function compactionEnabledPerCheck(ctx) {
165
157
  return true;
166
158
  }
167
159
  }
168
- function checkContextUsage(pi, ctx, event) {
160
+ async function checkContextUsage(pi, ctx, event) {
169
161
  const state = getState(ctx);
170
162
  if (!state?.enforcementActive)
171
163
  return;
@@ -196,15 +188,19 @@ function checkContextUsage(pi, ctx, event) {
196
188
  recordHygieneSkip(state);
197
189
  return;
198
190
  }
199
- // The previous usable turn's live sample (the soft tier's crossing
200
- // witness), captured before this turn's sample replaces it.
191
+ // The previous usable turn's live sample (the crossing witness), captured
192
+ // before this turn's sample replaces it.
201
193
  const prevLiveTokens = state.liveUsageSamples[state.liveUsageSamples.length - 1];
202
194
  recordLiveUsageSample(state, usageTokens);
203
- // Re-arm the shared context-nudge latch when usage has dropped (e.g.,
204
- // after compaction). The bar is the named policy value, not a literal.
205
- // It governs the higher tiers only; the soft tier re-arms on its own arm
206
- // crossing, gated at the cascade below.
207
- if (state.contextNudgeSent && usagePercent < USAGE_FIRED_RESET_BELOW) {
195
+ // Re-arm the shared context-nudge latch in the unit that armed it: a token
196
+ // rung clears on a fall back below that token arm, a percent rung below its
197
+ // own percent. A bar in the other unit clears a token arm on the very next
198
+ // turn whenever the arm sits above the bar (0.45W is 45% of every window,
199
+ // below the 50% bar), which is the repeat loop this latch exists to stop.
200
+ // The rung id stays recorded: it is the floor a weaker rung must cross to be
201
+ // news rather than a descent.
202
+ if (state.contextNudgeSent &&
203
+ contextNudgeFellBelow(state.contextNudgeRung, usagePercent, usageTokens, usageWindow)) {
208
204
  state.contextNudgeSent = false;
209
205
  }
210
206
  // Auto-compact arms (fractions of the resolved window W)
@@ -225,14 +221,16 @@ function checkContextUsage(pi, ctx, event) {
225
221
  recordHygieneSkip(state);
226
222
  return;
227
223
  }
228
- // Loop-done gate: "toolUse" means the agent loop is live -- the next
229
- // model call is queued inside the running agent operation, and
230
- // ctx.compact() aborts it (manual compaction never retries or continues
231
- // the interrupted turn). Act only on a loop-done stop; the 0.90W
232
- // backstop below still acts mid-loop to stop a runaway loop before
233
- // overflow (its purpose).
234
- const loopDone = event?.message?.stopReason !== "toolUse";
235
- if (!loopDone && !atHardBackstop) {
224
+ // Loop-done gate: the act runs ctx.compact(), which aborts the running
225
+ // agent operation (manual compaction never retries or continues the
226
+ // interrupted turn), so the boundary decides it. One rule, shared with the
227
+ // context_compress drain: a loop-done stop fires, a live loop parks, an
228
+ // unreadable boundary parks, and the 0.90W backstop below still acts
229
+ // mid-loop to stop a runaway loop before overflow (its purpose).
230
+ if (!turnBoundaryMayAbortRun(event, () => ({
231
+ tokens: usageTokens,
232
+ contextWindow: usageWindow,
233
+ }))) {
236
234
  recordHygieneSkip(state);
237
235
  return;
238
236
  }
@@ -256,8 +254,14 @@ function checkContextUsage(pi, ctx, event) {
256
254
  ? "token"
257
255
  : "percent";
258
256
  state.contextNudgeSent = true;
259
- // Pre-save safety net before compaction
260
- saveStateBeforeCompact(ctx.cwd ?? "", ctx);
257
+ // The act is not a nudge rung: leave no rung recorded, so the nudge
258
+ // block stays suppressed behind the act (and the percent reset bar
259
+ // governs this latch) exactly as before.
260
+ state.contextNudgeRung = null;
261
+ // Pre-save safety net before compaction. Awaited: the act arms right
262
+ // after, and the write must land before the compaction it protects
263
+ // against. ctx.compact itself is deferred to a macrotask below.
264
+ await saveStateBeforeCompact(ctx.cwd ?? "", ctx);
261
265
  const kind = armHygieneAct(ctx, trigger, plan);
262
266
  if (!kind) {
263
267
  // The deterministic state could not be armed: stand down instead of
@@ -273,29 +277,31 @@ function checkContextUsage(pi, ctx, event) {
273
277
  return;
274
278
  }
275
279
  }
276
- if (state.contextNudgeSent)
277
- return;
278
- // Progressive nudge: token tiers first, then percent tiers. Cascade shared
279
- // from lib/detection/context-tiers.ts (contextUsageNudgeMessage):
280
- // token arms 0.45W/0.18W fire earlier for large windows, then percent tiers
281
- // soft (30%) -> advisory (50%) -> warning (65%) -> critical (75%) ->
282
- // compact (80%).
283
- const nudgeMessage = contextUsageNudgeMessage(usagePercent, usageTokens, usageWindow);
284
- if (nudgeMessage) {
285
- // Soft-tier crossing gate: the cascade's sub-warning level is the soft
286
- // token text (the percent tiers are shadowed by the token arms, which
287
- // fire first). It fires on the turn its arm is crossed from below, not
288
- // on every turn inside the band. The shared latch above re-arms below
289
- // USAGE_FIRED_RESET_BELOW, a bar above the soft arm, so without this
290
- // gate the same whisper re-injected every turn from the soft arm up to
291
- // the reset bar. The higher tiers keep the shared latch untouched.
292
- if (usageTokens < arms.warning) {
293
- const crossedSoftArm = prevLiveTokens === undefined || prevLiveTokens < arms.soft;
294
- if (!crossedSoftArm)
280
+ // Progressive nudge: ONE ladder over both units, ordered by position
281
+ // (percent of the resolved window) — token soft 0.18W, percent soft 30%,
282
+ // token warning 0.45W, advisory 50%, warning 65%, critical 75%, compact
283
+ // 80%. The strongest rung reached wins, so no token arm can shadow a
284
+ // percent tier above it (see lib/detection/context-tiers.ts).
285
+ const nudge = resolveContextNudge(usagePercent, usageTokens, usageWindow);
286
+ if (nudge) {
287
+ const lastFired = findContextNudgeRung(state.contextNudgeRung, usageWindow);
288
+ if (state.contextNudgeSent) {
289
+ // The latch holds the rung that fired; a strictly stronger rung is new
290
+ // information and may pass it. Without this the ladder went quiet from
291
+ // the first rung upward and an agent at 95% read the 45% line.
292
+ if (!lastFired || nudge.position <= lastFired.position)
295
293
  return;
296
294
  }
295
+ else if (lastFired &&
296
+ nudge.position < lastFired.position &&
297
+ !contextNudgeCrossed(nudge, prevLiveTokens, usageWindow)) {
298
+ // A weaker rung that usage merely settled at (a descent, not a
299
+ // crossing) is not news; a rung climbed back past is.
300
+ return;
301
+ }
297
302
  state.contextNudgeSent = true;
298
- sendEnforcementWhisper(pi, ctx, nudgeMessage);
303
+ state.contextNudgeRung = nudge.id;
304
+ sendEnforcementWhisper(pi, ctx, nudge.message);
299
305
  }
300
306
  }
301
307
  /**
@@ -370,7 +376,7 @@ function armHygieneAct(ctx, trigger, plan) {
370
376
  export function registerTurnEndHygiene(pi) {
371
377
  registerTurnEndHandler("turn-end-hygiene", 5, async (event, ctx) => {
372
378
  try {
373
- checkContextUsage(pi, ctx, event);
379
+ await checkContextUsage(pi, ctx, event);
374
380
  }
375
381
  catch (err) {
376
382
  log.error("turn-end-hygiene error:", err);
@@ -0,0 +1,76 @@
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
+ import type { TaskScratchpad } from "../memory/scratchpad/types.js";
21
+ /**
22
+ * How many entries of each list the resume file carries. Sized for a
23
+ * transfer, not an audit: the first open plan steps are the program a
24
+ * successor continues (later steps are usually its to rewrite), and five
25
+ * decisions/learnings cover the recent working assumptions. The uncapped
26
+ * counts travel alongside so a reader can report "20 open, 10 shown".
27
+ */
28
+ export declare const RESUME_OPEN_PLAN_LIMIT = 10;
29
+ export declare const RESUME_RECENT_DECISION_LIMIT = 5;
30
+ export declare const RESUME_RECENT_LEARNING_LIMIT = 5;
31
+ /** A plan step is live once it has been started (see `add_plan`/`mark_done`). */
32
+ export type ResumePlanStatus = "in_progress" | "pending";
33
+ export interface ResumePlanItem {
34
+ id: string;
35
+ text: string;
36
+ status: ResumePlanStatus;
37
+ }
38
+ export interface ResumeDecisionItem {
39
+ id: string;
40
+ text: string;
41
+ reason?: string;
42
+ }
43
+ export interface ResumeLearningItem {
44
+ category: string;
45
+ content: string;
46
+ }
47
+ export interface ResumeScratchpadState {
48
+ goal: string | null;
49
+ /** First RESUME_OPEN_PLAN_LIMIT unfinished steps, in plan order. */
50
+ openPlans: ResumePlanItem[];
51
+ /** Unfinished steps overall, before the display cap. */
52
+ openPlanCount: number;
53
+ recentDecisions: ResumeDecisionItem[];
54
+ recentLearnings: ResumeLearningItem[];
55
+ }
56
+ /** The projection of "no scratchpad": every section empty, never undefined. */
57
+ export declare function emptyResumeScratchpadState(): ResumeScratchpadState;
58
+ /**
59
+ * Project a loaded scratchpad onto the resume fields. Pure: the input pad is
60
+ * never mutated.
61
+ *
62
+ * Plan completion lives in `doneTurn` (mark_done stamps the turn and leaves
63
+ * the step in `plan`), so "open" is `doneTurn === 0` - the step is still in
64
+ * the plan, unfinished. A started-but-unfinished step is the live one.
65
+ */
66
+ export declare function projectResumeScratchpad(pad: TaskScratchpad | null): ResumeScratchpadState;
67
+ /**
68
+ * Read this project's scratchpad and project it onto the resume fields.
69
+ *
70
+ * Degrades to the empty projection on any read failure: a resume file with no
71
+ * prior-state section is worth less than a program, but far more than a
72
+ * handler that threw during shutdown or before a compaction. The refusal is
73
+ * logged at debug - the empty projection is the visible outcome.
74
+ */
75
+ export declare function readResumeScratchpadState(projectSlug: string): Promise<ResumeScratchpadState>;
76
+ //# sourceMappingURL=resume-state.d.ts.map
@@ -0,0 +1,90 @@
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
+ import { createLogger } from "../../lib/core/logger.js";
21
+ import { loadScratchpadFromDisk } from "../memory/scratchpad/persistence.js";
22
+ const log = createLogger("enforcement:resume-state");
23
+ /**
24
+ * How many entries of each list the resume file carries. Sized for a
25
+ * transfer, not an audit: the first open plan steps are the program a
26
+ * successor continues (later steps are usually its to rewrite), and five
27
+ * decisions/learnings cover the recent working assumptions. The uncapped
28
+ * counts travel alongside so a reader can report "20 open, 10 shown".
29
+ */
30
+ export const RESUME_OPEN_PLAN_LIMIT = 10;
31
+ export const RESUME_RECENT_DECISION_LIMIT = 5;
32
+ export const RESUME_RECENT_LEARNING_LIMIT = 5;
33
+ /** The projection of "no scratchpad": every section empty, never undefined. */
34
+ export function emptyResumeScratchpadState() {
35
+ return {
36
+ goal: null,
37
+ openPlans: [],
38
+ openPlanCount: 0,
39
+ recentDecisions: [],
40
+ recentLearnings: [],
41
+ };
42
+ }
43
+ /**
44
+ * Project a loaded scratchpad onto the resume fields. Pure: the input pad is
45
+ * never mutated.
46
+ *
47
+ * Plan completion lives in `doneTurn` (mark_done stamps the turn and leaves
48
+ * the step in `plan`), so "open" is `doneTurn === 0` - the step is still in
49
+ * the plan, unfinished. A started-but-unfinished step is the live one.
50
+ */
51
+ export function projectResumeScratchpad(pad) {
52
+ if (!pad)
53
+ return emptyResumeScratchpadState();
54
+ const openSteps = pad.plan.filter((step) => !step.doneTurn);
55
+ return {
56
+ goal: pad.goal && pad.goal.length > 0 ? pad.goal : null,
57
+ openPlans: openSteps.slice(0, RESUME_OPEN_PLAN_LIMIT).map((step) => ({
58
+ id: step.id,
59
+ text: step.text,
60
+ status: step.startTurn > 0 ? "in_progress" : "pending",
61
+ })),
62
+ openPlanCount: openSteps.length,
63
+ recentDecisions: pad.decisions.slice(-RESUME_RECENT_DECISION_LIMIT).map((decision) => ({
64
+ id: decision.id,
65
+ text: decision.text,
66
+ ...(decision.reason ? { reason: decision.reason } : {}),
67
+ })),
68
+ recentLearnings: pad.key_learnings
69
+ .slice(-RESUME_RECENT_LEARNING_LIMIT)
70
+ .map((learning) => ({ category: learning.category, content: learning.content })),
71
+ };
72
+ }
73
+ /**
74
+ * Read this project's scratchpad and project it onto the resume fields.
75
+ *
76
+ * Degrades to the empty projection on any read failure: a resume file with no
77
+ * prior-state section is worth less than a program, but far more than a
78
+ * handler that threw during shutdown or before a compaction. The refusal is
79
+ * logged at debug - the empty projection is the visible outcome.
80
+ */
81
+ export async function readResumeScratchpadState(projectSlug) {
82
+ try {
83
+ return projectResumeScratchpad(await loadScratchpadFromDisk(projectSlug));
84
+ }
85
+ catch (err) {
86
+ log.debug(`scratchpad read for resume failed: ${err}`);
87
+ return emptyResumeScratchpadState();
88
+ }
89
+ }
90
+ //# sourceMappingURL=resume-state.js.map
@@ -24,6 +24,15 @@ export declare function createScratchpadState(): ScratchpadState;
24
24
  export declare function resetScratchpadState(s: ScratchpadState): void;
25
25
  export interface ContextHygieneState {
26
26
  contextNudgeSent: boolean;
27
+ /**
28
+ * The nudge-ladder rung that armed `contextNudgeSent` (its id), or null when
29
+ * the latch was armed by something that is not a rung (the hygiene act) or
30
+ * by nothing yet. The latch re-arms in this rung's unit, and the rung is the
31
+ * floor a weaker rung has to cross to be news rather than a descent. Survives
32
+ * the re-arm; cleared when a compaction or a context tool makes a fresh
33
+ * start.
34
+ */
35
+ contextNudgeRung: string | null;
27
36
  lastContextCheckTurn: number;
28
37
  lastCompactionTurn: number;
29
38
  overflowRecently: number;