pi-braid 0.40.3 → 0.40.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +116 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +178 -17
  13. package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +74 -13
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-POLICY.md +8 -0
  49. package/docs/LOCAL_DEV.md +0 -1
  50. package/docs/ROADMAP.md +5 -5
  51. package/docs/SETUP.md +19 -18
  52. package/package.json +2 -1
  53. package/skills/herdr-topology/SKILL.md +6 -1
  54. package/skills/research/SKILL.md +32 -0
  55. package/skills/subagent-orchestration/SKILL.md +2 -2
  56. package/src/extensions/core/agent-environment/index.ts +4 -3
  57. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  58. package/src/extensions/core/prompt-builder/index.ts +12 -7
  59. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  60. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  61. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  62. package/src/extensions/core/skills-tool/auto-inject.ts +350 -27
  63. package/src/extensions/core/skills-tool/index.ts +217 -15
  64. package/src/extensions/core/skills-tool/reach.ts +256 -0
  65. package/src/extensions/core/skills-tool/skill-triggers.ts +130 -23
  66. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  67. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  68. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  69. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  70. package/src/extensions/enforcement/resume-state.ts +127 -0
  71. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  72. package/src/extensions/enforcement/whisper.ts +21 -1
  73. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  74. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  75. package/src/extensions/memory/AGENTS.md +25 -1
  76. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  77. package/src/lib/config/braid-paths.ts +20 -0
  78. package/src/lib/config/braid-settings.ts +46 -0
  79. package/src/lib/detection/context-tiers.ts +186 -13
  80. package/src/lib/events/AGENTS.md +1 -0
  81. package/src/lib/events/turn-boundary.ts +115 -0
  82. package/src/lib/orchestrator/workers.ts +33 -12
  83. package/src/lib/state/global-state.ts +1 -0
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/types/extension-context.d.ts +22 -79
@@ -1,20 +1,44 @@
1
1
  /**
2
- * Frontmatter `triggers:` phrases for the suggestion matcher.
2
+ * Curated trigger phrases for the suggestion matcher.
3
3
  *
4
4
  * pi's skill objects carry a fixed shape (name, description, path, source),
5
5
  * so curated trigger phrases never reach braid through the prompt-builder
6
- * cache — read them from the SKILL.md frontmatter directly. Reads are
7
- * memoized by file mtime + size: repeated turns stat, only changed or
8
- * first-seen files parse.
6
+ * cache — read them from the SKILL.md itself. Reads are memoized by file
7
+ * mtime + size: repeated turns stat, only changed or first-seen files parse.
8
+ *
9
+ * Authors wrote the phrases in three places, and all three are read:
10
+ * 1. frontmatter, under `trigger:` (a comma-separated string) or
11
+ * `triggers:` (a YAML list) — the canonical field;
12
+ * 2. a `## trigger:` body heading, quoted or bare (9 of core's 22 skills
13
+ * carry the phrases here and nowhere else);
14
+ * 3. the description's trailing "Triggers: …" segment, the pack's older
15
+ * convention.
16
+ * A file may use any of them, and every source that yields phrases is read:
17
+ * the lists are MERGED in that order, so a phrase an author put in the body
18
+ * heading survives when frontmatter also declares some, and the frontmatter
19
+ * still outranks the rest. First-wins was the defect: agent-testing declares
20
+ * seven phrases in its description tail and five in its body heading, and
21
+ * precedence let the tail replace the heading, so the five never reached the
22
+ * matcher while the file said they had.
9
23
  *
10
24
  * A trigger hit scores like a name hit and qualifies a skill whose
11
25
  * description alone would stay under the qualification bar — the phrase is
12
26
  * the author's own signal of when the skill applies, sharper than any
13
- * description keyword.
27
+ * description keyword. Matching is case-insensitive: prompts arrive
28
+ * capitalized ("MASTERSHIP TRANSFER: …"), and a phrase that only matched
29
+ * lowercase text would be dead in production while a lowercase-only unit
30
+ * fixture kept the suite green.
14
31
  */
15
32
  import { statSync, readFileSync } from "node:fs";
16
33
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
17
- /** Max trigger phrases read per skill — a longer list is an authoring bug, not a matcher input. */
34
+ /**
35
+ * Max trigger phrases read per skill — a longer list is an authoring bug, not a
36
+ * matcher input. Three authored lists reach the cap: braid-reference (16
37
+ * phrases), pi-reference (15), and agent-testing, which fills it exactly (7 in
38
+ * the description tail + 5 in the body heading) now that the sources merge.
39
+ * The cap assertion lives in test-skill-triggers-body.mjs; raising the number
40
+ * means changing it there.
41
+ */
18
42
  export const MAX_TRIGGERS = 12;
19
43
  /** Max characters of one trigger phrase. */
20
44
  export const MAX_TRIGGER_CHARS = 64;
@@ -42,14 +66,27 @@ export function normalizeTriggers(value) {
42
66
  return cleaned;
43
67
  }
44
68
  /**
45
- * Read a skill's trigger phrases: frontmatter `triggers:` first (canonical),
46
- * then the description's trailing "Triggers: …" segment — the pack's existing
47
- * convention (7 of 32 skills carry one) predates the frontmatter field, and
48
- * the matcher should honor what authors already wrote. Missing/unreadable
49
- * file or malformed YAML → no triggers (the matcher falls back to
50
- * name/description scoring alone). Memoized: unchanged files never re-read.
69
+ * Read a skill's trigger phrases from every source the file uses, merged in
70
+ * priority order: frontmatter (`trigger` or `triggers`), then a `## trigger:`
71
+ * body heading, then the description's trailing "Triggers: …" segment.
72
+ * Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
73
+ * description tail is still read.
74
+ * Memoized: unchanged files never re-read.
51
75
  */
52
76
  export function readSkillTriggers(filePath, description) {
77
+ return readSkillTriggerEntries(filePath, description).map((entry) => entry.phrase);
78
+ }
79
+ /**
80
+ * Read a skill's authored phrases WITH their provenance, merged in priority
81
+ * order: frontmatter (`trigger` or `triggers`), then a `## trigger:` body
82
+ * heading, then the description's trailing "Triggers: …" segment.
83
+ * Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
84
+ * description tail is still read.
85
+ * Memoized: unchanged files never re-read (a different description argument is
86
+ * a miss, because the merged list depends on it).
87
+ */
88
+ export function readSkillTriggerEntries(filePath, description) {
89
+ const desc = description ?? "";
53
90
  let st;
54
91
  try {
55
92
  st = statSync(filePath);
@@ -59,20 +96,63 @@ export function readSkillTriggers(filePath, description) {
59
96
  return [];
60
97
  }
61
98
  const cached = cache.get(filePath);
62
- if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size)
63
- return cached.triggers;
64
- let triggers;
99
+ if (cached &&
100
+ cached.mtimeMs === st.mtimeMs &&
101
+ cached.size === st.size &&
102
+ cached.description === desc) {
103
+ return cached.entries;
104
+ }
105
+ const sources = [];
65
106
  try {
66
- const { frontmatter } = parseFrontmatter(readFileSync(filePath, "utf-8"));
67
- triggers = normalizeTriggers(frontmatter.triggers);
107
+ const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
108
+ const fm = frontmatter;
109
+ const label = (source) => (phrase) => ({ phrase, source });
110
+ sources.push(normalizeTriggers(fm.trigger).map(label("frontmatter")), normalizeTriggers(fm.triggers).map(label("frontmatter")), parseBodyTriggers(body).map(label("heading")));
68
111
  }
69
112
  catch {
70
- triggers = []; // malformed frontmatter — score on name/description only
113
+ // Malformed frontmatter: the file sources yield nothing, and the
114
+ // description tail below is still read.
115
+ }
116
+ if (desc)
117
+ sources.push(parseDescriptionTriggers(desc).map((phrase) => ({ phrase, source: "description" })));
118
+ const entries = mergeTriggerEntries(sources);
119
+ cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, description: desc, entries });
120
+ return entries;
121
+ }
122
+ /**
123
+ * Merge authored phrase sources into one bounded list, in priority order.
124
+ *
125
+ * The cap is a budget spent down the list, so when it binds the LOWEST
126
+ * priority source is the one that loses phrases — a higher-priority source is
127
+ * never cut to make room for a later one. A phrase repeated by two sources
128
+ * keeps its first (highest-priority) source. Pure.
129
+ */
130
+ export function mergeTriggerEntries(sources) {
131
+ const merged = [];
132
+ for (const source of sources) {
133
+ for (const entry of source) {
134
+ if (merged.length >= MAX_TRIGGERS)
135
+ return merged;
136
+ if (!merged.some((kept) => kept.phrase === entry.phrase))
137
+ merged.push(entry);
138
+ }
139
+ }
140
+ return merged;
141
+ }
142
+ /** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
143
+ const BODY_TRIGGER_HEADING = /^##\s*triggers?\s*:\s*(.*)$/i;
144
+ /**
145
+ * Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
146
+ * heading is the whole input: a body with several is an authoring error, not
147
+ * extra matcher input. Quotes around the value are stripped. Pure.
148
+ */
149
+ export function parseBodyTriggers(body) {
150
+ for (const line of body.split(/\r?\n/)) {
151
+ const match = BODY_TRIGGER_HEADING.exec(line);
152
+ if (match)
153
+ return normalizeTriggers(match[1].trim().replace(/^["']|["']$/g, ""));
71
154
  }
72
- if (!triggers.length && description)
73
- triggers = parseDescriptionTriggers(description);
74
- cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, triggers });
75
- return triggers;
155
+ return [];
76
156
  }
77
157
  /**
78
158
  * Trigger phrases from a description's trailing "Triggers: …" segment —
@@ -99,7 +179,8 @@ export function clearSkillTriggerCache() {
99
179
  /**
100
180
  * True when the phrase occurs in the prompt on word boundaries ("pane" does
101
181
  * not match "paneled"). Multi-word phrases match literally; hyphenated
102
- * prompt tokens count as boundaries.
182
+ * prompt tokens count as boundaries. Phrases are normalized to lowercase, so
183
+ * the prompt is folded to match: the boundary classes stay lowercase-only.
103
184
  */
104
185
  export function triggerMatches(phrase, promptText) {
105
186
  let re = regexCache.get(phrase);
@@ -108,6 +189,6 @@ export function triggerMatches(phrase, promptText) {
108
189
  re = new RegExp(`(?:^|[^a-z0-9])${escaped}(?:$|[^a-z0-9])`);
109
190
  regexCache.set(phrase, re);
110
191
  }
111
- return re.test(promptText);
192
+ return re.test(promptText.toLowerCase());
112
193
  }
113
194
  //# sourceMappingURL=skill-triggers.js.map
@@ -191,12 +191,23 @@ export function registerSessionCompactHandler(pi) {
191
191
  // resume-vs-advisory delivery differs. A mid-work turn stays
192
192
  // triggerTurn:true (compaction aborted the loop; it must be handed
193
193
  // back to the agent).
194
+ //
195
+ // bypassFloodCap: this whisper is the resume. It is the only thing that
196
+ // restarts a turn the context_compress tool aborted, so dropping it
197
+ // halts the session instead of losing a nudge. Every enforcement
198
+ // whisper shares the `enforcement/whisper` per-source bucket (cap 3),
199
+ // so three ordinary advisories earlier in the same turn are enough to
200
+ // spend it and swallow the wake. The exemption is granted here, at the
201
+ // one call site that cannot afford to lose the message - not in the
202
+ // wrapper's default and not in the funnel.
194
203
  setTimeout(() => {
195
204
  sendEnforcementWhisper(pi, ctx, `Context compacted at turn ${compactTurn}. ` +
196
205
  `Re-orient: read scratchpad for goal/plan/learnings, then check next pending task. ` +
197
206
  `Note: compaction summaries may lack speaker labels — use the scratchpad ` +
198
207
  `(which preserves speaker context) to distinguish who said what. ` +
199
- `These surfaces survive compaction - continue from there.`, false, naturalStop && !agentRequestedResume ? { delivery: "park" } : { triggerTurn: true });
208
+ `These surfaces survive compaction - continue from there.`, false, naturalStop && !agentRequestedResume
209
+ ? { delivery: "park", bypassFloodCap: true }
210
+ : { triggerTurn: true, bypassFloodCap: true });
200
211
  }, 0);
201
212
  }
202
213
  finally {
@@ -13,15 +13,17 @@
13
13
  *
14
14
  * File location: <braidDir()>/sessions/<projectSlug>/resume.json
15
15
  */
16
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
16
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
17
17
  import * as path from "node:path";
18
18
  import { execSync } from "node:child_process";
19
19
  import { createLogger } from "../../../lib/core/logger.js";
20
20
  import { onEvent } from "../../../lib/events/event-types.js";
21
21
  import { getState } from "../state.js";
22
- import { scratchpadDir, braidDir } from "../../../lib/config/braid-paths.js";
22
+ import { braidDir } from "../../../lib/config/braid-paths.js";
23
23
  import { SESSION_SHUTDOWN } from "../../../lib/core/event-names.js";
24
24
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
25
+ import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
26
+ import { readResumeScratchpadState, } from "../resume-state.js";
25
27
  const log = createLogger("enforcement:session-shutdown-resumption");
26
28
  /**
27
29
  * Register the SESSION_SHUTDOWN resumption writer.
@@ -31,38 +33,17 @@ export function registerSessionShutdownResumption(pi) {
31
33
  try {
32
34
  const cwd = ctx.cwd ?? "";
33
35
  const slug = projectSlugFromCwd(cwd);
34
- let goal = null;
35
- let openPlans = [];
36
- let recentDecisions = [];
37
- let recentLearnings = [];
38
- // Prior state is a READ: the scratchpad root is resolved on every call,
39
- // so a pinned run reads the tree the scratchpad writer wrote to. A
40
- // refused root (no absolute braid home) degrades to no prior-state
41
- // section instead of failing the resume write below.
42
- try {
43
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
44
- if (existsSync(scratchpadFile)) {
45
- const content = readFileSync(scratchpadFile, "utf-8");
46
- const parsed = JSON.parse(content);
47
- goal = parsed.goal ?? null;
48
- openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
49
- .filter((p) => !p.done)
50
- .slice(0, 10)
51
- .map((p) => ({ id: p.id ?? "", text: p.text ?? "" }));
52
- recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
53
- .slice(-5)
54
- .map((d) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
55
- recentLearnings = (Array.isArray(parsed.learnings) ? parsed.learnings : [])
56
- .slice(-5)
57
- .map((l) => ({
58
- category: l.category ?? "",
59
- content: l.content ?? l.text ?? "",
60
- }));
61
- }
62
- }
63
- catch (err) {
64
- log.debug(`scratchpad prior-state read failed: ${err}`);
65
- }
36
+ // Flush the debounced scratchpad write queue first: at shutdown the
37
+ // in-memory pad may hold the session's last mutations and the read
38
+ // below only sees what reached the checkpoint log.
39
+ await flushPendingScratchpadWrites().catch(() => { });
40
+ // Prior state is a READ through the scratchpad store's own loader (the
41
+ // checkpoint log, not a hand-built path), so a schema or storage change
42
+ // in the store moves this reader with it. A refused root (no absolute
43
+ // braid home) degrades to an empty prior-state section instead of
44
+ // failing the resume write below.
45
+ const resumeState = await readResumeScratchpadState(slug);
46
+ const { goal, openPlans, recentDecisions, recentLearnings } = resumeState;
66
47
  let uncommittedFiles = [];
67
48
  try {
68
49
  // Scope to the project dir only. When ctx.cwd is missing, `cwd` is "" and
@@ -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)
@@ -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