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,31 +1,70 @@
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
 
16
33
  import { statSync, readFileSync } from "node:fs";
17
34
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
18
35
 
19
- /** Max trigger phrases read per skill — a longer list is an authoring bug, not a matcher input. */
36
+ /**
37
+ * Max trigger phrases read per skill — a longer list is an authoring bug, not a
38
+ * matcher input. Three authored lists reach the cap: braid-reference (16
39
+ * phrases), pi-reference (15), and agent-testing, which fills it exactly (7 in
40
+ * the description tail + 5 in the body heading) now that the sources merge.
41
+ * The cap assertion lives in test-skill-triggers-body.mjs; raising the number
42
+ * means changing it there.
43
+ */
20
44
  export const MAX_TRIGGERS = 12;
21
45
 
22
46
  /** Max characters of one trigger phrase. */
23
47
  export const MAX_TRIGGER_CHARS = 64;
24
48
 
49
+ /**
50
+ * Where an authored phrase came from. Precedence (frontmatter, heading,
51
+ * description) orders the merged list and decides which source the cap cuts
52
+ * last; the label itself is what a ranking row reports as its evidence.
53
+ */
54
+ export type TriggerSource = "frontmatter" | "heading" | "description";
55
+
56
+ /** One authored phrase and the source that declared it. */
57
+ export interface TriggerEntry {
58
+ phrase: string;
59
+ source: TriggerSource;
60
+ }
61
+
25
62
  interface TriggerCacheEntry {
26
63
  mtimeMs: number;
27
64
  size: number;
28
- triggers: string[];
65
+ /** The description the entries were merged with: a different one is a miss. */
66
+ description: string;
67
+ entries: TriggerEntry[];
29
68
  }
30
69
 
31
70
  const cache = new Map<string, TriggerCacheEntry>();
@@ -52,14 +91,28 @@ export function normalizeTriggers(value: unknown): string[] {
52
91
  }
53
92
 
54
93
  /**
55
- * Read a skill's trigger phrases: frontmatter `triggers:` first (canonical),
56
- * then the description's trailing "Triggers: …" segment — the pack's existing
57
- * convention (7 of 32 skills carry one) predates the frontmatter field, and
58
- * the matcher should honor what authors already wrote. Missing/unreadable
59
- * file or malformed YAML → no triggers (the matcher falls back to
60
- * name/description scoring alone). Memoized: unchanged files never re-read.
94
+ * Read a skill's trigger phrases from every source the file uses, merged in
95
+ * priority order: frontmatter (`trigger` or `triggers`), then a `## trigger:`
96
+ * body heading, then the description's trailing "Triggers: …" segment.
97
+ * Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
98
+ * description tail is still read.
99
+ * Memoized: unchanged files never re-read.
61
100
  */
62
101
  export function readSkillTriggers(filePath: string, description?: string): string[] {
102
+ return readSkillTriggerEntries(filePath, description).map((entry) => entry.phrase);
103
+ }
104
+
105
+ /**
106
+ * Read a skill's authored phrases WITH their provenance, merged in priority
107
+ * order: frontmatter (`trigger` or `triggers`), then a `## trigger:` body
108
+ * heading, then the description's trailing "Triggers: …" segment.
109
+ * Missing/unreadable file or malformed YAML → no frontmatter phrases, and the
110
+ * description tail is still read.
111
+ * Memoized: unchanged files never re-read (a different description argument is
112
+ * a miss, because the merged list depends on it).
113
+ */
114
+ export function readSkillTriggerEntries(filePath: string, description?: string): TriggerEntry[] {
115
+ const desc = description ?? "";
63
116
  let st;
64
117
  try {
65
118
  st = statSync(filePath);
@@ -68,17 +121,70 @@ export function readSkillTriggers(filePath: string, description?: string): strin
68
121
  return [];
69
122
  }
70
123
  const cached = cache.get(filePath);
71
- if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size) return cached.triggers;
72
- let triggers: string[];
124
+ if (
125
+ cached &&
126
+ cached.mtimeMs === st.mtimeMs &&
127
+ cached.size === st.size &&
128
+ cached.description === desc
129
+ ) {
130
+ return cached.entries;
131
+ }
132
+ const sources: TriggerEntry[][] = [];
73
133
  try {
74
- const { frontmatter } = parseFrontmatter(readFileSync(filePath, "utf-8"));
75
- triggers = normalizeTriggers((frontmatter as Record<string, unknown>).triggers);
134
+ const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
135
+ const fm = frontmatter as Record<string, unknown>;
136
+ const label = (source: TriggerSource) => (phrase: string) => ({ phrase, source });
137
+ sources.push(
138
+ normalizeTriggers(fm.trigger).map(label("frontmatter")),
139
+ normalizeTriggers(fm.triggers).map(label("frontmatter")),
140
+ parseBodyTriggers(body).map(label("heading")),
141
+ );
76
142
  } catch {
77
- triggers = []; // malformed frontmatter — score on name/description only
143
+ // Malformed frontmatter: the file sources yield nothing, and the
144
+ // description tail below is still read.
145
+ }
146
+ if (desc)
147
+ sources.push(
148
+ parseDescriptionTriggers(desc).map((phrase) => ({ phrase, source: "description" })),
149
+ );
150
+ const entries = mergeTriggerEntries(sources);
151
+ cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, description: desc, entries });
152
+ return entries;
153
+ }
154
+
155
+ /**
156
+ * Merge authored phrase sources into one bounded list, in priority order.
157
+ *
158
+ * The cap is a budget spent down the list, so when it binds the LOWEST
159
+ * priority source is the one that loses phrases — a higher-priority source is
160
+ * never cut to make room for a later one. A phrase repeated by two sources
161
+ * keeps its first (highest-priority) source. Pure.
162
+ */
163
+ export function mergeTriggerEntries(sources: TriggerEntry[][]): TriggerEntry[] {
164
+ const merged: TriggerEntry[] = [];
165
+ for (const source of sources) {
166
+ for (const entry of source) {
167
+ if (merged.length >= MAX_TRIGGERS) return merged;
168
+ if (!merged.some((kept) => kept.phrase === entry.phrase)) merged.push(entry);
169
+ }
170
+ }
171
+ return merged;
172
+ }
173
+
174
+ /** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
175
+ const BODY_TRIGGER_HEADING = /^##\s*triggers?\s*:\s*(.*)$/i;
176
+
177
+ /**
178
+ * Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
179
+ * heading is the whole input: a body with several is an authoring error, not
180
+ * extra matcher input. Quotes around the value are stripped. Pure.
181
+ */
182
+ export function parseBodyTriggers(body: string): string[] {
183
+ for (const line of body.split(/\r?\n/)) {
184
+ const match = BODY_TRIGGER_HEADING.exec(line);
185
+ if (match) return normalizeTriggers(match[1].trim().replace(/^["']|["']$/g, ""));
78
186
  }
79
- if (!triggers.length && description) triggers = parseDescriptionTriggers(description);
80
- cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, triggers });
81
- return triggers;
187
+ return [];
82
188
  }
83
189
 
84
190
  /**
@@ -106,7 +212,8 @@ export function clearSkillTriggerCache(): void {
106
212
  /**
107
213
  * True when the phrase occurs in the prompt on word boundaries ("pane" does
108
214
  * not match "paneled"). Multi-word phrases match literally; hyphenated
109
- * prompt tokens count as boundaries.
215
+ * prompt tokens count as boundaries. Phrases are normalized to lowercase, so
216
+ * the prompt is folded to match: the boundary classes stay lowercase-only.
110
217
  */
111
218
  export function triggerMatches(phrase: string, promptText: string): boolean {
112
219
  let re = regexCache.get(phrase);
@@ -115,5 +222,5 @@ export function triggerMatches(phrase: string, promptText: string): boolean {
115
222
  re = new RegExp(`(?:^|[^a-z0-9])${escaped}(?:$|[^a-z0-9])`);
116
223
  regexCache.set(phrase, re);
117
224
  }
118
- return re.test(promptText);
225
+ return re.test(promptText.toLowerCase());
119
226
  }
@@ -228,6 +228,15 @@ export function registerSessionCompactHandler(pi: ExtensionAPI): void {
228
228
  // resume-vs-advisory delivery differs. A mid-work turn stays
229
229
  // triggerTurn:true (compaction aborted the loop; it must be handed
230
230
  // back to the agent).
231
+ //
232
+ // bypassFloodCap: this whisper is the resume. It is the only thing that
233
+ // restarts a turn the context_compress tool aborted, so dropping it
234
+ // halts the session instead of losing a nudge. Every enforcement
235
+ // whisper shares the `enforcement/whisper` per-source bucket (cap 3),
236
+ // so three ordinary advisories earlier in the same turn are enough to
237
+ // spend it and swallow the wake. The exemption is granted here, at the
238
+ // one call site that cannot afford to lose the message - not in the
239
+ // wrapper's default and not in the funnel.
231
240
  setTimeout(() => {
232
241
  sendEnforcementWhisper(
233
242
  pi,
@@ -238,7 +247,9 @@ export function registerSessionCompactHandler(pi: ExtensionAPI): void {
238
247
  `(which preserves speaker context) to distinguish who said what. ` +
239
248
  `These surfaces survive compaction - continue from there.`,
240
249
  false,
241
- naturalStop && !agentRequestedResume ? { delivery: "park" } : { triggerTurn: true },
250
+ naturalStop && !agentRequestedResume
251
+ ? { delivery: "park", bypassFloodCap: true }
252
+ : { triggerTurn: true, bypassFloodCap: true },
242
253
  );
243
254
  }, 0);
244
255
  } finally {
@@ -15,15 +15,22 @@
15
15
  */
16
16
 
17
17
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
18
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
19
19
  import * as path from "node:path";
20
20
  import { execSync } from "node:child_process";
21
21
  import { createLogger } from "../../../lib/core/logger.js";
22
22
  import { onEvent } from "../../../lib/events/event-types.js";
23
23
  import { getState } from "../state.js";
24
- import { scratchpadDir, braidDir } from "../../../lib/config/braid-paths.js";
24
+ import { braidDir } from "../../../lib/config/braid-paths.js";
25
25
  import { SESSION_SHUTDOWN } from "../../../lib/core/event-names.js";
26
26
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
27
+ import { flushPendingScratchpadWrites } from "../../memory/scratchpad/utils.js";
28
+ import {
29
+ readResumeScratchpadState,
30
+ type ResumeDecisionItem,
31
+ type ResumeLearningItem,
32
+ type ResumePlanItem,
33
+ } from "../resume-state.js";
27
34
 
28
35
  const log = createLogger("enforcement:session-shutdown-resumption");
29
36
 
@@ -31,9 +38,9 @@ interface ResumptionFile {
31
38
  writtenAt: string;
32
39
  cwd: string;
33
40
  goal: string | null;
34
- openPlans: Array<{ id: string; text: string }>;
35
- recentDecisions: Array<{ id: string; text: string }>;
36
- recentLearnings: Array<{ category: string; content: string }>;
41
+ openPlans: ResumePlanItem[];
42
+ recentDecisions: ResumeDecisionItem[];
43
+ recentLearnings: ResumeLearningItem[];
37
44
  uncommittedFiles: string[];
38
45
  toolCallCount: number;
39
46
  verificationCount: number;
@@ -48,38 +55,18 @@ export function registerSessionShutdownResumption(pi: ExtensionAPI): void {
48
55
  const cwd = (ctx as { cwd?: string }).cwd ?? "";
49
56
  const slug = projectSlugFromCwd(cwd);
50
57
 
51
- let goal: string | null = null;
52
- let openPlans: Array<{ id: string; text: string }> = [];
53
- let recentDecisions: Array<{ id: string; text: string }> = [];
54
- let recentLearnings: Array<{ category: string; content: string }> = [];
58
+ // Flush the debounced scratchpad write queue first: at shutdown the
59
+ // in-memory pad may hold the session's last mutations and the read
60
+ // below only sees what reached the checkpoint log.
61
+ await flushPendingScratchpadWrites().catch(() => {});
55
62
 
56
- // Prior state is a READ: the scratchpad root is resolved on every call,
57
- // so a pinned run reads the tree the scratchpad writer wrote to. A
58
- // refused root (no absolute braid home) degrades to no prior-state
59
- // section instead of failing the resume write below.
60
- try {
61
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
62
- if (existsSync(scratchpadFile)) {
63
- const content = readFileSync(scratchpadFile, "utf-8");
64
- const parsed = JSON.parse(content);
65
- goal = parsed.goal ?? null;
66
- openPlans = (Array.isArray(parsed.plans) ? parsed.plans : [])
67
- .filter((p: any) => !p.done)
68
- .slice(0, 10)
69
- .map((p: any) => ({ id: p.id ?? "", text: p.text ?? "" }));
70
- recentDecisions = (Array.isArray(parsed.decisions) ? parsed.decisions : [])
71
- .slice(-5)
72
- .map((d: any) => ({ id: d.id ?? "", text: d.text ?? d.content ?? "" }));
73
- recentLearnings = (Array.isArray(parsed.learnings) ? parsed.learnings : [])
74
- .slice(-5)
75
- .map((l: any) => ({
76
- category: l.category ?? "",
77
- content: l.content ?? l.text ?? "",
78
- }));
79
- }
80
- } catch (err) {
81
- log.debug(`scratchpad prior-state read failed: ${err}`);
82
- }
63
+ // Prior state is a READ through the scratchpad store's own loader (the
64
+ // checkpoint log, not a hand-built path), so a schema or storage change
65
+ // in the store moves this reader with it. A refused root (no absolute
66
+ // braid home) degrades to an empty prior-state section instead of
67
+ // failing the resume write below.
68
+ const resumeState = await readResumeScratchpadState(slug);
69
+ const { goal, openPlans, recentDecisions, recentLearnings } = resumeState;
83
70
 
84
71
  let uncommittedFiles: string[] = [];
85
72
  try {
@@ -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)
@@ -43,14 +44,15 @@ import {
43
44
  type DiscoverySignalType,
44
45
  } from "../../../lib/state/global-state.js";
45
46
  import {
46
- scratchpadDir,
47
47
  episodesFilePath,
48
48
  semanticMemoryFilePath,
49
49
  AGENT,
50
50
  braidDir,
51
+ journalFilePath,
51
52
  tagsSlugFromCwd,
52
53
  } from "../../../lib/config/braid-paths.js";
53
54
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
55
+ import { readResumeScratchpadState } from "../resume-state.js";
54
56
 
55
57
  const log = createLogger("enforcement:session-start-discoverability");
56
58
 
@@ -91,30 +93,23 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
91
93
  delete (enforcementSignals as Record<string, EnforcementSignalEntry>)[key];
92
94
  }
93
95
 
94
- // 1. Scratchpad. The store root is resolved on every call, never a
95
- // module-load constant: a pinned run must read the tree the writers
96
- // wrote to, and a refused root (no absolute braid home) degrades.
96
+ // 1. Scratchpad. Read through the store's own loader (the checkpoint
97
+ // log), never a hand-built snapshot path: the snapshot file this
98
+ // branch used to open has not been written for years, so the signal
99
+ // was armed against a file that never existed. The store root is
100
+ // resolved on every call, never a module-load constant, so a pinned
101
+ // run reads the tree the writers wrote to.
97
102
  try {
98
103
  const slug = projectSlugFromCwd(cwd);
99
- const scratchpadFile = path.join(scratchpadDir(), slug, "latest.json");
100
- if (existsSync(scratchpadFile)) {
101
- const stat = statSync(scratchpadFile);
102
- if (stat.size > 10) {
103
- const content = readFileSync(scratchpadFile, "utf-8");
104
- const parsed = JSON.parse(content);
105
- const hasGoal = parsed.goal && parsed.goal.length > 0;
106
- const openPlans = Array.isArray(parsed.plans)
107
- ? parsed.plans.filter((p: any) => !p.done).length
108
- : 0;
109
- if (hasGoal || openPlans > 0) {
110
- signals.push({
111
- type: "scratchpad_prior",
112
- text:
113
- `Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
114
- `Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
115
- });
116
- }
117
- }
104
+ const prior = await readResumeScratchpadState(slug);
105
+ const openPlans = prior.openPlanCount;
106
+ if (prior.goal || openPlans > 0) {
107
+ signals.push({
108
+ type: "scratchpad_prior",
109
+ text:
110
+ `Prior scratchpad data exists for this project (${openPlans} open plan items). ` +
111
+ `Use \`scratchpad action=continue\` to resume -- it returns goal + open plan + recent context in one call.`,
112
+ });
118
113
  }
119
114
  } catch (err) {
120
115
  log.debug(`scratchpad discoverability check failed: ${err}`);
@@ -227,7 +222,33 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
227
222
  // ignore
228
223
  }
229
224
 
230
- // 7. Context hygiene & state preservation tip: forward-looking
225
+ // 7. The owner-input journal. The path comes from the constant the
226
+ // writer appends through, never a hand-built shape: two spellings for
227
+ // one file is how the scratchpad pointer armed itself against a file
228
+ // nothing writes (see step 1).
229
+ try {
230
+ const slug = projectSlugFromCwd(cwd);
231
+ const journalFile = journalFilePath(slug);
232
+ if (existsSync(journalFile)) {
233
+ const count = readFileSync(journalFile, "utf-8")
234
+ .split("\n")
235
+ .filter((line) => line.trim()).length;
236
+ if (count > 0) {
237
+ signals.push({
238
+ type: "journal_prior",
239
+ text:
240
+ `The project journal holds ${count} entr${count === 1 ? "y" : "ies"} at ${journalFile} -- ` +
241
+ `what earlier seats decided and why, readable without their sessions. ` +
242
+ `Read the open program before acting (digest printer: packages/core/scripts/check-journal.mjs --digest), ` +
243
+ `so a decision gets superseded, not rediscovered.`,
244
+ });
245
+ }
246
+ }
247
+ } catch {
248
+ // ignore
249
+ }
250
+
251
+ // 8. Context hygiene & state preservation tip: forward-looking
231
252
  // guidance — when prior state exists, remind the agent how to manage
232
253
  // context and preserve state against crashes.
233
254
  // Shown only when there's prior state to manage (other signals exist).
@@ -246,14 +267,23 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
246
267
  // persistence (via `projectSlugFromCwd`) lets `pi --session <id>` (a new
247
268
  // process) read previously shown signals from disk and skip them, so the
248
269
  // discoverability bundle doesn't re-fire on session resume.
270
+ // Signal types that must reach every seat, not only the first. The
271
+ // dedupe below -- and the branch entries it writes -- exists so a
272
+ // resumed session is not told what it already saw. A journal pointer is
273
+ // aimed at a seat that has never seen this project, so a mark left by an
274
+ // earlier seat is exactly the one-shot failure it exists to repair.
275
+ const alwaysShown: ReadonlySet<DiscoverySignalType> = new Set(["journal_prior"]);
276
+
249
277
  const slug = signals.length > 0 && (cwd ? projectSlugFromCwd(cwd) : "");
250
- const unseenSignals = slug
251
- ? signals.filter((s) => !isProjectSignalShown(slug, s.type))
252
- : signals.filter((s) => !isProjectSignalShown("default", s.type));
278
+ const projectKey = slug || "default";
279
+ const unseenSignals = signals.filter(
280
+ (s) => alwaysShown.has(s.type) || !isProjectSignalShown(projectKey, s.type),
281
+ );
253
282
  if (unseenSignals.length > 0) {
254
283
  const bundled = unseenSignals.map((s) => s.text).join("\n");
255
284
  for (const s of unseenSignals) {
256
- markProjectSignalShown(slug || "default", s.type, pi);
285
+ if (alwaysShown.has(s.type)) continue;
286
+ markProjectSignalShown(projectKey, s.type, pi);
257
287
  }
258
288
  // Informational pointers to prior state: park (no forced turn).
259
289
  sendEnforcementWhisper(pi, ctx, bundled, false, { delivery: "park" });