@cad0p/pi-napkin 0.2.4

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.
@@ -0,0 +1,1808 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { Napkin } from "@cad0p/napkin";
6
+ import type {
7
+ CustomEntry,
8
+ ExtensionAPI,
9
+ ExtensionContext,
10
+ ExtensionUIContext,
11
+ SessionEntry,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
14
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
15
+ import { Type } from "@sinclair/typebox";
16
+ import {
17
+ countTrackedFiles,
18
+ ensureVaultReadyForAutoDistill,
19
+ LEGACY_EMBEDDED_LAYOUT_ERROR,
20
+ } from "./auto-setup";
21
+ import {
22
+ type ActiveDistill,
23
+ cleanupDistillWorkspace,
24
+ cleanupStaleWorktrees,
25
+ DistillError,
26
+ findDistillErrorLogForBranch,
27
+ findDistillOutcomeForBranch,
28
+ getDistillState,
29
+ getDistillTouchedFilesPostSquash,
30
+ resolveDistillErrorDir,
31
+ spawnDistillInWorktree,
32
+ } from "./distill-workspace";
33
+ import { getSessionTouchedFiles } from "./session-touched-files";
34
+ import { shouldDistillOnShutdown } from "./should-distill-on-shutdown";
35
+
36
+ export interface DistillConfig {
37
+ enabled: boolean;
38
+ intervalMinutes: number;
39
+ /**
40
+ * Hard cap on how long to poll for a distill subprocess to complete
41
+ * before declaring it timed out and abandoning the worktree / tmp
42
+ * target. Defaults to 10 minutes.
43
+ *
44
+ * Primarily a testing knob (tests set this to a few ms to exercise the
45
+ * timeout branch without real-time delay), but also a legitimate vault
46
+ * config for users running distill against a slow provider. Values
47
+ * <= 0 or non-finite fall back to the 10-minute default so a bad
48
+ * config can't disable the timeout entirely.
49
+ */
50
+ maxDurationMinutes?: number;
51
+ /**
52
+ * Whether to run a final distill at session shutdown. Defaults to `true`.
53
+ *
54
+ * The shutdown handler consults this via `shouldDistillOnShutdown` — if
55
+ * false, shutdown distill is skipped even when other guards would allow it.
56
+ * Does not affect interval distill or manual `/distill`.
57
+ */
58
+ onShutdown: boolean;
59
+ model?: { provider: string; id: string };
60
+ }
61
+
62
+ export interface VaultConfig {
63
+ showStatus: boolean;
64
+ distill: DistillConfig;
65
+ }
66
+
67
+ /**
68
+ * Hard cap on how long we'll poll for a distill subprocess to complete
69
+ * before declaring it timed out and abandoning the worktree / tmp target.
70
+ *
71
+ * 10 minutes is the production default. Configurable per-vault via
72
+ * `distill.maxDurationMinutes` in `.napkin/config.json` — tests set this
73
+ * to a few milliseconds so the timeout branch is exercisable without
74
+ * waiting 10 real minutes, and users running distill against a slow
75
+ * provider can legitimately raise it. Values <= 0, NaN, or unset fall
76
+ * back to the default.
77
+ */
78
+ const DEFAULT_MAX_DISTILL_DURATION_MS = 10 * 60 * 1000;
79
+
80
+ export function getMaxDistillDurationMs(config?: DistillConfig): number {
81
+ const minutes = config?.maxDurationMinutes;
82
+ if (typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0) {
83
+ return minutes * 60 * 1000;
84
+ }
85
+ return DEFAULT_MAX_DISTILL_DURATION_MS;
86
+ }
87
+
88
+ /**
89
+ * Custom entry type used to persist `/distill-auto-this-session` state into the
90
+ * session file. CustomEntry (unlike CustomMessageEntry) does not participate in
91
+ * LLM context, so we can write freely without affecting the agent.
92
+ *
93
+ * Schema is append-only: the `suppressed: boolean` key must remain stable so
94
+ * new-version writers aren't shadowed by older valid entries.
95
+ */
96
+ const SESSION_STATE_CUSTOM_TYPE = "napkin-distill-session-state";
97
+
98
+ interface SessionPauseState {
99
+ suppressed: boolean;
100
+ }
101
+
102
+ /**
103
+ * Extension handlers receive a `ReadonlySessionManager`, but the runtime
104
+ * object is a full `SessionManager` with write methods. We use the cast
105
+ * to call `appendCustomEntry` for the `/distill-auto-this-session` pause
106
+ * state below — napkin-context applies the same pattern for
107
+ * `appendCustomMessageEntry` (a different SessionManager method, used
108
+ * for messages that DO participate in LLM context).
109
+ */
110
+ interface WritableSessionShape {
111
+ appendCustomEntry(customType: string, data?: unknown): string;
112
+ }
113
+
114
+ /**
115
+ * Read the latest persisted pause state from the current session branch.
116
+ *
117
+ * Uses `getBranch()` (canonical for state restoration — see todo, summarize,
118
+ * handoff, qna examples) so entries on abandoned branches don't leak into the
119
+ * live branch. Stops at the first matching `customType` even on malformed
120
+ * data to protect new-version writers from being shadowed by older entries.
121
+ */
122
+ function readPersistedSuppressed(sm: {
123
+ getBranch(fromId?: string): SessionEntry[];
124
+ }): boolean {
125
+ const branch = sm.getBranch();
126
+ for (let i = branch.length - 1; i >= 0; i--) {
127
+ const entry = branch[i];
128
+ if (entry.type !== "custom") continue;
129
+ const custom = entry as CustomEntry<SessionPauseState>;
130
+ if (custom.customType !== SESSION_STATE_CUSTOM_TYPE) continue;
131
+ if (custom.data && typeof custom.data.suppressed === "boolean") {
132
+ return custom.data.suppressed;
133
+ }
134
+ return false;
135
+ }
136
+ return false;
137
+ }
138
+
139
+ /** Append the current pause state as a CustomEntry in the session. */
140
+ function persistSuppressed(sm: unknown, suppressed: boolean): void {
141
+ (sm as WritableSessionShape).appendCustomEntry(SESSION_STATE_CUSTOM_TYPE, {
142
+ suppressed,
143
+ } satisfies SessionPauseState);
144
+ }
145
+
146
+ export const DEFAULT_DISTILL: DistillConfig = {
147
+ enabled: false,
148
+ intervalMinutes: 60,
149
+ maxDurationMinutes: 10,
150
+ onShutdown: true,
151
+ };
152
+
153
+ export function loadVaultConfig(vaultPath: string): VaultConfig {
154
+ const configPath = path.join(vaultPath, "config.json");
155
+ if (!fs.existsSync(configPath)) {
156
+ return { showStatus: true, distill: DEFAULT_DISTILL };
157
+ }
158
+ try {
159
+ const raw = JSON.parse(fs.readFileSync(configPath, "utf-8"));
160
+ return {
161
+ showStatus: raw.showStatus !== false,
162
+ distill: { ...DEFAULT_DISTILL, ...(raw.distill || {}) },
163
+ };
164
+ } catch {
165
+ return { showStatus: true, distill: DEFAULT_DISTILL };
166
+ }
167
+ }
168
+
169
+ const DISTILL_PROMPT = `Distill this conversation into the napkin vault.
170
+
171
+ 1. \`napkin overview\` — learn the vault structure and what exists. Read \`_about.md\` files to understand what each folder is for. These are short folder descriptions (1-2 paragraphs) explaining what kinds of notes belong there — see existing ones for style.
172
+ 2. \`napkin template list\` and \`napkin template read\` — learn the note formats.
173
+ 3. Identify what's worth capturing. The vault structure and templates tell you what kinds of notes belong.
174
+ 4. For each note:
175
+ a. \`napkin search\` for the topic — if a note already covers it, \`napkin append\` instead of creating a duplicate
176
+ b. Create new notes with \`napkin create\`, following the template format; use the relevant folder path
177
+ c. Add \`[[wikilinks]]\` to related notes
178
+ 5. Append a brief summary of key activities and decisions to today's daily note in the relevant namespace (e.g. \`{namespace}/daily/YYYY-MM-DD.md\`). Follow existing patterns. Create it if it doesn't exist.
179
+
180
+ Frontmatter convention: when you create a note that replaces an older one, add
181
+ \`supersedes: ["path/to/old/note.md"]\` to its frontmatter. A future janitor will
182
+ archive the superseded note. Leave the field empty or omit it for notes that
183
+ stand alone.
184
+
185
+ Be selective. Only capture knowledge useful to someone working on this project later. Skip meta-discussion, tool output, and chatter.`;
186
+
187
+ // Inline bash script template for the legacy (git-optional) manual
188
+ // /distill path. Tainted values flow through positional `$1..$5` argv;
189
+ // the template itself is a fixed literal, never interpolated from user
190
+ // input. Same trust boundary as the worktree wrapper, without a
191
+ // separate file.
192
+ //
193
+ // Bash (not sh) because we use arrays for optional --model splicing;
194
+ // Ubuntu's /bin/sh is dash which parse-errors on `pi_args=(...)`.
195
+ const LEGACY_SPAWN_SCRIPT = `set -u
196
+ PI_BIN="$1"; SESSION="$2"; TMPDIR_ARG="$3"; PROMPT="$4"; MODEL="$5"
197
+ pi_args=(--session "$SESSION" -p "$PROMPT")
198
+ if [ -n "$MODEL" ]; then
199
+ pi_args=(--session "$SESSION" --model "$MODEL" -p "$PROMPT")
200
+ fi
201
+ "$PI_BIN" "\${pi_args[@]}" > /dev/null 2>&1 || true
202
+ rm -rf -- "$TMPDIR_ARG"
203
+ `;
204
+
205
+ /**
206
+ * Spawn a detached pi distill process that survives parent exit.
207
+ * Runs `pi -p <prompt>` against a forked session, then removes the temp
208
+ * dir. Returns the temp dir path (used as a completion marker — when it
209
+ * disappears, distill is done).
210
+ *
211
+ * Used only by manual `/distill` on git-less, disabled, or legacy-embedded
212
+ * vaults. Manual `/distill` with git + subdir layout + enabled takes the
213
+ * worktree path. Auto-distill requires git + subdir layout unconditionally
214
+ * (Phase C1).
215
+ */
216
+ export function spawnDistill(
217
+ sessionFile: string,
218
+ cwd: string,
219
+ config: DistillConfig,
220
+ spawnFn: typeof spawn = spawn,
221
+ ): string | null {
222
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "napkin-distill-"));
223
+
224
+ try {
225
+ const forkedSm = SessionManager.forkFrom(sessionFile, cwd, tmpDir);
226
+ const forkedFile = forkedSm.getSessionFile();
227
+ if (!forkedFile) {
228
+ fs.rmSync(tmpDir, { recursive: true, force: true });
229
+ return null;
230
+ }
231
+
232
+ const modelStr = config.model
233
+ ? `${config.model.provider}/${config.model.id}`
234
+ : "";
235
+ const piBin = process.env.NAPKIN_DISTILL_PI_BIN ?? "pi";
236
+
237
+ const proc = spawnFn(
238
+ "bash",
239
+ [
240
+ "-c",
241
+ LEGACY_SPAWN_SCRIPT,
242
+ "_",
243
+ piBin,
244
+ forkedFile,
245
+ tmpDir,
246
+ DISTILL_PROMPT,
247
+ modelStr,
248
+ ],
249
+ {
250
+ cwd,
251
+ detached: true,
252
+ stdio: "ignore",
253
+ env: { ...process.env, NAPKIN_DISTILL_NO_RECURSE: "1" },
254
+ },
255
+ );
256
+ proc.unref();
257
+
258
+ return tmpDir;
259
+ } catch {
260
+ fs.rmSync(tmpDir, { recursive: true, force: true });
261
+ return null;
262
+ }
263
+ }
264
+
265
+ export default function (pi: ExtensionAPI) {
266
+ let intervalHandle: ReturnType<typeof setInterval> | null = null;
267
+ let countdownHandle: ReturnType<typeof setInterval> | null = null;
268
+ let pollHandle: ReturnType<typeof setInterval> | null = null;
269
+ let lastDistillTimestamp = Date.now();
270
+ let lastSessionSize = 0;
271
+ /**
272
+ * Byte size of the session file at the moment the most recent distill
273
+ * subprocess was successfully spawned. Separate from `lastSessionSize`
274
+ * (which updates on completion): this tracks SPAWN so that a shutdown
275
+ * firing between spawn-and-complete dedupes against the in-flight distill
276
+ * without having to wait for it to finish.
277
+ *
278
+ * Read by `shouldDistillOnShutdown` in the session_shutdown handler
279
+ * (guard #8). Written by `runDistill`, `runAutoDistill`, and the shutdown
280
+ * handler itself (after a successful shutdown spawn).
281
+ */
282
+ let lastSpawnedSize = 0;
283
+ let isRunning = false;
284
+ // Session-scoped suppression of the automatic distill timer.
285
+ // Toggled via `/distill-auto-this-session` — does NOT affect manual `/distill`.
286
+ let autoDistillSuppressed = false;
287
+ /**
288
+ * Cursor into the parent session's `getEntries()` array marking the
289
+ * point of the previous distill's completion. The next per-completion
290
+ * overlap check (R7-PERF-2) walks entries from this cursor to the
291
+ * current end and computes which files the parent has touched in that
292
+ * interval; intersection with the just-completed distill's touched
293
+ * files (`git log --name-only <startSha>..HEAD` from the main vault)
294
+ * yields the overlap set.
295
+ *
296
+ * Initialised on `session_start` to `getEntries().length` (R8-CC-3 /
297
+ * R8-PERF-3): for a fresh session this is 0; for a resumed session
298
+ * with N pre-existing entries this is N, so the first post-resume
299
+ * completion only walks entries added AFTER session_start — not the
300
+ * full pre-resume history (which would surface stale notices for
301
+ * files written in earlier pi processes whose distills already
302
+ * landed).
303
+ *
304
+ * Updated on every successful distill completion (also when overlap
305
+ * is empty) so subsequent completions only see the new slice.
306
+ *
307
+ * Closure-scoped (sync, no race): the per-completion path runs inside
308
+ * the JS-side poll callback, single-threaded with everything else in
309
+ * this extension factory.
310
+ */
311
+ let lastDistillCompletionMessageCursor = 0;
312
+
313
+ // Refs captured from session_start so `/distill-auto-this-session` can refresh
314
+ // the status bar immediately without waiting for the next countdown tick.
315
+ //
316
+ // `ExtensionUIContext` is pi's public UI surface (setStatus, theme, …). We keep
317
+ // the whole thing instead of a narrow subset so future status-bar tweaks don't
318
+ // need to widen the type — and so TS catches method renames at the pi boundary.
319
+ type DistillUIRef = {
320
+ hasUI: boolean;
321
+ ui: ExtensionUIContext;
322
+ showStatus: boolean;
323
+ intervalMs: number;
324
+ };
325
+ let uiRef: DistillUIRef | null = null;
326
+
327
+ function renderIdleStatus(): void {
328
+ if (!uiRef?.hasUI || !uiRef.showStatus) return;
329
+ // While a distill is in flight the poll loop owns the status bar; leave it alone.
330
+ if (isRunning) return;
331
+ const theme = uiRef.ui.theme;
332
+ if (autoDistillSuppressed) {
333
+ uiRef.ui.setStatus(
334
+ "napkin-distill",
335
+ theme.fg("dim", "distill: off (session)"),
336
+ );
337
+ return;
338
+ }
339
+ uiRef.ui.setStatus(
340
+ "napkin-distill",
341
+ theme.fg("dim", `distill: ${formatRemaining()}`),
342
+ );
343
+ }
344
+
345
+ /** Formatted time until the next scheduled auto-distill, or `"—"` if unknown. */
346
+ function formatRemaining(): string {
347
+ if (!uiRef) return "—";
348
+ const remaining = Math.max(
349
+ 0,
350
+ uiRef.intervalMs - (Date.now() - lastDistillTimestamp),
351
+ );
352
+ const mins = Math.floor(remaining / 60000);
353
+ const secs = Math.floor((remaining % 60000) / 1000);
354
+ return mins > 0
355
+ ? `${mins}m${secs.toString().padStart(2, "0")}s`
356
+ : `${secs}s`;
357
+ }
358
+
359
+ pi.on("session_start", async (event, ctx) => {
360
+ // Reset to default before any early-return paths below; the persisted state
361
+ // (if any) is re-read further down when distill is enabled for the session.
362
+ autoDistillSuppressed = false;
363
+
364
+ let napkinVault: { configPath: string; contentPath: string };
365
+ try {
366
+ napkinVault = new Napkin(ctx.cwd).vault;
367
+ } catch {
368
+ return;
369
+ }
370
+ const vaultConfigPath = napkinVault.configPath;
371
+
372
+ const { showStatus, distill: config } = loadVaultConfig(vaultConfigPath);
373
+ if (!config.enabled) {
374
+ if (ctx.hasUI && showStatus) {
375
+ ctx.ui.setStatus(
376
+ "napkin-distill",
377
+ ctx.ui.theme.fg("dim", "distill: off"),
378
+ );
379
+ }
380
+ return;
381
+ }
382
+
383
+ // Skip if this is a distill subprocess
384
+ if (process.env.NAPKIN_DISTILL_NO_RECURSE) return;
385
+
386
+ // Auto-init git + scaffold .gitignore/.gitattributes so subsequent
387
+ // worktree operations have the invariants they need. Idempotent and
388
+ // non-throwing — on failure we notify once and disable auto-distill for
389
+ // this session rather than retrying on every interval fire.
390
+ //
391
+ // Scope: operate on `napkinVault.contentPath` — the vault root as
392
+ // napkin resolves it from cwd. This is cwd-independent: when pi is
393
+ // launched outside the vault (e.g. in another project directory),
394
+ // findVault still resolves to the user's real vault via a global
395
+ // config fallback at `~/.config/napkin/config.json`. Using `ctx.cwd`
396
+ // here would scaffold `.git` in the WRONG directory and leave the
397
+ // real vault untouched — breaking both auto-init and later worktree
398
+ // operations that (now also correctly) target the vault.
399
+ //
400
+ // `setupFailed` is the load-bearing signal for the suppression logic
401
+ // below: once setup has failed, we MUST NOT re-read the persisted
402
+ // suppression state, because a `false` there would re-enable
403
+ // auto-distill on a vault that isn't actually usable.
404
+ const vaultContentPath = napkinVault.contentPath;
405
+ let setupFailed = false;
406
+ try {
407
+ const setup = ensureVaultReadyForAutoDistill({
408
+ contentPath: vaultContentPath,
409
+ configPath: napkinVault.configPath,
410
+ });
411
+ if (setup.error) {
412
+ setupFailed = true;
413
+ if (ctx.hasUI) {
414
+ if (setup.error === LEGACY_EMBEDDED_LAYOUT_ERROR) {
415
+ // Legacy embedded layout (`~/.napkin/` with `config.json`
416
+ // alongside notes, no `.napkin/` subdir). Worktree-based
417
+ // concurrency requires the subdir layout so napkin's
418
+ // `findVault` resolves cwd=worktree to the worktree itself.
419
+ // README has the migration steps; point there instead of
420
+ // duplicating them in the notify (keeps the notification
421
+ // short enough to render cleanly in every UI surface).
422
+ ctx.ui.notify(
423
+ "Auto-distill requires the subdir vault layout. See README for migration, or set distill.enabled: false in vault config.json.",
424
+ "error",
425
+ );
426
+ } else if (setup.conflict) {
427
+ // G7: existing `.gitattributes` already claims `*.md merge=<X>`.
428
+ // We refuse to scaffold so we don't silently override the
429
+ // user's chosen driver via last-match-wins. Explain the
430
+ // options clearly — auto-distill is off for this session, but
431
+ // manual /distill still works.
432
+ ctx.ui.notify(
433
+ [
434
+ `Auto-distill setup blocked: your .gitattributes already has a merge rule for *.md ('${setup.conflict.rule}').`,
435
+ "Auto-distill needs its own driver to handle concurrent distill merges safely. To enable:",
436
+ ` - Remove the conflicting rule from ${setup.conflict.file}, OR`,
437
+ " - Set distill.onShutdown: false in vault config.json to disable auto-distill on shutdown",
438
+ "Manual /distill still works regardless.",
439
+ ].join("\n"),
440
+ "error",
441
+ );
442
+ } else {
443
+ ctx.ui.notify(
444
+ `Auto-distill setup failed: ${setup.error}. Disabling auto-distill for this session.`,
445
+ "error",
446
+ );
447
+ }
448
+ }
449
+ } else if (setup.initialized) {
450
+ const tracked = countTrackedFiles(vaultContentPath);
451
+ const files = tracked >= 0 ? tracked : setup.scaffolded.length;
452
+ if (ctx.hasUI) {
453
+ ctx.ui.notify(
454
+ [
455
+ "Initialized git repo in your vault for auto-distill.",
456
+ `Commit: 'napkin: initial vault commit (auto-distill setup)'`,
457
+ `Files tracked: ${files}`,
458
+ `To undo: rm -rf ${path.join(vaultContentPath, ".git")} (removes history, keeps files)`,
459
+ "To opt out: set distill.enabled: false in vault config.json",
460
+ ].join("\n"),
461
+ "info",
462
+ );
463
+ }
464
+ } else if (setup.scaffolded.length > 0) {
465
+ if (ctx.hasUI) {
466
+ ctx.ui.notify(
467
+ `Added ${setup.scaffolded.join(", ")} for auto-distill.`,
468
+ "info",
469
+ );
470
+ }
471
+ }
472
+ } catch (err) {
473
+ // Truly unexpected (ensureVaultReadyForAutoDistill is supposed to not
474
+ // throw). Log + continue, worst case later operations fail gracefully.
475
+ console.error("[napkin-distill] auto-setup threw:", err);
476
+ }
477
+
478
+ // Sweep out stale distill worktrees left behind by crashed pi sessions.
479
+ // Idempotent, best-effort — never throws, never blocks session_start.
480
+ try {
481
+ cleanupStaleWorktrees({ contentPath: vaultContentPath });
482
+ } catch {
483
+ // swallow — cleanup is non-critical to session lifecycle
484
+ }
485
+
486
+ // Restore the per-session pause state from the session file so that
487
+ // resuming a session retains the `/distill-auto-this-session` setting.
488
+ //
489
+ // BUT: when setup failed above, we must keep the safety flag ON. The
490
+ // persisted value reflects USER intent (opted out for this session);
491
+ // setup failure is a VAULT-level problem that should override user
492
+ // intent for this session only — next session will re-try setup.
493
+ if (setupFailed) {
494
+ autoDistillSuppressed = true;
495
+ } else {
496
+ autoDistillSuppressed = readPersistedSuppressed(ctx.sessionManager);
497
+ }
498
+
499
+ lastDistillTimestamp = Date.now();
500
+ // Initialize the per-completion overlap cursor to the current end of
501
+ // the session entries. For a new session this is 0 (empty session);
502
+ // for a resumed session (`reason` in {`resume`,`fork`,`startup`,...})
503
+ // this is the prior entry count, so the FIRST distill completion in
504
+ // the new pi process only walks entries added AFTER session_start —
505
+ // not the full pre-resume history. Without this, a resumed session
506
+ // with N pre-existing entries would surface stale overlap notices
507
+ // for files written in earlier pi processes (whose distills already
508
+ // landed on main). R8-CC-3 / R8-PERF-3.
509
+ try {
510
+ lastDistillCompletionMessageCursor =
511
+ ctx.sessionManager.getEntries().length;
512
+ } catch {
513
+ // Best-effort: if getEntries throws (shouldn't — it's a basic
514
+ // accessor), leave the cursor at its prior value (0 on first
515
+ // session_start).
516
+ }
517
+ const intervalMs = config.intervalMinutes * 60 * 1000;
518
+
519
+ uiRef = { hasUI: ctx.hasUI, ui: ctx.ui, showStatus, intervalMs };
520
+
521
+ // Paint initial state immediately so a resumed paused session doesn't
522
+ // briefly show the countdown before the first tick.
523
+ renderIdleStatus();
524
+
525
+ // On resume, if the session is off, surface it once via notify — the
526
+ // status bar is easy to miss after a long gap between sessions. Fire for
527
+ // all reasons except `"new"` (fresh sessions never match — branch is empty
528
+ // — but explicitly exclude to keep the intent obvious) and `"reload"`
529
+ // (would fire on every in-session config reload).
530
+ if (
531
+ ctx.hasUI &&
532
+ autoDistillSuppressed &&
533
+ (event.reason === "resume" ||
534
+ event.reason === "fork" ||
535
+ event.reason === "startup")
536
+ ) {
537
+ ctx.ui.notify(
538
+ "Auto-distill is off for this session. Run /distill-auto-this-session on to turn on.",
539
+ "info",
540
+ );
541
+ }
542
+
543
+ if (ctx.hasUI && showStatus) {
544
+ countdownHandle = setInterval(() => {
545
+ // `renderIdleStatus` self-guards against in-flight distills; when off
546
+ // it paints `distill: off (session)` (pi dedupes identical status strings).
547
+ renderIdleStatus();
548
+ }, 1000);
549
+ }
550
+
551
+ intervalHandle = setInterval(() => {
552
+ if (autoDistillSuppressed) return;
553
+ runAutoDistill(ctx);
554
+ }, intervalMs);
555
+ });
556
+
557
+ pi.on("session_shutdown", async (event, ctx) => {
558
+ if (countdownHandle) {
559
+ clearInterval(countdownHandle);
560
+ countdownHandle = null;
561
+ }
562
+ if (intervalHandle) {
563
+ clearInterval(intervalHandle);
564
+ intervalHandle = null;
565
+ }
566
+ if (pollHandle) {
567
+ clearInterval(pollHandle);
568
+ pollHandle = null;
569
+ }
570
+ // Reset `isRunning` so a distill that was mid-flight at shutdown doesn't
571
+ // stick as `true` across an in-process session switch and suppress the
572
+ // next session's status-bar rendering.
573
+ isRunning = false;
574
+
575
+ // ------- Final shutdown distill (Phase B Item 8) -------------------------
576
+ //
577
+ // Spawn one last auto-distill if the session has content that hasn't been
578
+ // captured yet. Guards live in `shouldDistillOnShutdown` — this block
579
+ // only assembles inputs and calls it. Any failure logs and falls through;
580
+ // shutdown must never block.
581
+ //
582
+ // Intentionally AFTER the timer cleanup above: clearing intervalHandle
583
+ // first prevents the rare race where the interval fires during shutdown
584
+ // and we end up with two concurrent spawns on the same content.
585
+ //
586
+ // Config is re-read via loadVaultConfig rather than captured from
587
+ // session_start — handler scope keeps closures small, and the cost of
588
+ // one extra JSON parse at shutdown is negligible.
589
+ try {
590
+ let vaultInfo: { configPath: string; contentPath: string } | null = null;
591
+ try {
592
+ vaultInfo = new Napkin(ctx.cwd).vault;
593
+ } catch {
594
+ // No vault resolvable — skip spawn, proceed to final resets.
595
+ }
596
+ if (vaultInfo) {
597
+ const { distill: config } = loadVaultConfig(vaultInfo.configPath);
598
+ const sessionFile = ctx.sessionManager.getSessionFile?.();
599
+ const currentSize =
600
+ sessionFile && fs.existsSync(sessionFile)
601
+ ? fs.statSync(sessionFile).size
602
+ : 0;
603
+
604
+ if (
605
+ shouldDistillOnShutdown(
606
+ event,
607
+ config,
608
+ autoDistillSuppressed,
609
+ sessionFile,
610
+ currentSize,
611
+ lastSpawnedSize,
612
+ lastSessionSize,
613
+ )
614
+ ) {
615
+ // Guard: we require git for the worktree path, rooted at the
616
+ // vault's content directory (where auto-init placed `.git`).
617
+ // Using `ctx.cwd` here would miss the repo when pi was launched
618
+ // outside the vault — the very bug this change fixes.
619
+ if (
620
+ fs.existsSync(path.join(vaultInfo.contentPath, ".git")) &&
621
+ sessionFile
622
+ ) {
623
+ const modelStr = config.model
624
+ ? `${config.model.provider}/${config.model.id}`
625
+ : undefined;
626
+ spawnDistillInWorktree({
627
+ vault: vaultInfo.contentPath,
628
+ sessionFile,
629
+ parentCwd: ctx.cwd,
630
+ prompt: DISTILL_PROMPT,
631
+ model: modelStr,
632
+ });
633
+ // Mark this size as "spawned" so if the parent re-enters shutdown
634
+ // (unlikely but possible with session switch), we don't duplicate.
635
+ lastSpawnedSize = currentSize;
636
+ }
637
+ }
638
+ }
639
+ } catch (err) {
640
+ // Never block shutdown. stderr logging only — no UI at this point.
641
+ console.error("[napkin-distill] shutdown spawn failed:", err);
642
+ }
643
+
644
+ uiRef = null;
645
+ // No need to kill anything — detached processes survive on their own
646
+ });
647
+
648
+ // ---------------------------------------------------------------------------
649
+ // Overlap notice (R7-PERF-2 redesign): per-distill-completion via
650
+ // `appendCustomMessageEntry`.
651
+ //
652
+ // Previous design (per-turn `before_agent_start` hook returning
653
+ // `{ systemPrompt: event.systemPrompt + notice }`) silently broke
654
+ // Anthropic-style prompt caching whenever the notice fired: any byte
655
+ // change in the system block invalidates the entire cached prefix, so
656
+ // every parent turn during overlap re-encoded the full conversation
657
+ // history (~$0.50–$1/turn on long sessions). The original commit's
658
+ // "cache-friendly: notice lives at the END of the system prompt"
659
+ // rationale was based on an incorrect assumption about the cache
660
+ // boundary.
661
+ //
662
+ // The redesign moves the trigger from per-turn to per-distill-
663
+ // completion (when files actually change in the parent's view) and
664
+ // moves the channel from system-prompt mutation to a custom session
665
+ // message via `appendCustomMessageEntry`. Custom messages persist in
666
+ // session history and the cache prefix stays byte-identical between
667
+ // parent and distill subprocess turns.
668
+ //
669
+ // The actual completion check lives in `runDistillWith`'s success
670
+ // path — see `postOverlapNoticeOnCompletion` below. We track
671
+ // `lastDistillCompletionMessageCursor` in the closure to bound the
672
+ // session-touched-files walk to messages added since the last
673
+ // completion.
674
+ //
675
+ // Pure helpers (`intersectFiles`, `formatOverlapNotice`) and the
676
+ // session-side file extraction (`getSessionTouchedFiles`) are still
677
+ // load-bearing and unchanged — the new trigger reuses them.
678
+
679
+ /**
680
+ * Ctx shape shared by the two run-distill paths. Kept as a `Pick` of
681
+ * pi's real `ExtensionContext` so the four fields we care about stay
682
+ * in sync with pi at the type level (any rename upstream surfaces as
683
+ * a compile error here rather than silently widening to `any`).
684
+ */
685
+ type RunCtx = Pick<
686
+ ExtensionContext,
687
+ "sessionManager" | "hasUI" | "ui" | "cwd"
688
+ >;
689
+
690
+ /**
691
+ * Strategy bundle for the shared runner. Each caller (legacy or worktree)
692
+ * supplies a preflight check, a spawn invocation, a poll-completion
693
+ * target, and a timeout cleanup step. Everything else (config load,
694
+ * size dedup, status-bar painting, poll loop wiring, completion
695
+ * bookkeeping) is common.
696
+ *
697
+ * All strategy callbacks receive `vaultContentPath` — the vault's content
698
+ * root as resolved by napkin, NOT `ctx.cwd`. This is what makes the
699
+ * whole auto-distill pipeline cwd-independent: worktrees, git, and the
700
+ * legacy spawn all target the user's actual vault even when pi is
701
+ * launched from another directory (napkin's findVault walks up from
702
+ * `ctx.cwd` and falls back to the global config).
703
+ */
704
+ interface DistillStrategy {
705
+ /**
706
+ * Optional pre-flight check. Return `{ ok: false, errorStatus }` to
707
+ * short-circuit with a status-bar message, or `{ ok: true }` to
708
+ * continue. Invoked after config load + size dedup, before spawn.
709
+ */
710
+ preflight?: (args: {
711
+ ctx: RunCtx;
712
+ vaultContentPath: string;
713
+ theme: unknown;
714
+ }) => { ok: true } | { ok: false; errorStatus?: string };
715
+ /**
716
+ * Spawn the distill subprocess. Returns `{ target }` on success — a
717
+ * filesystem path whose disappearance marks completion. Returns null
718
+ * to signal a spawn failure (caller paints an error in the status
719
+ * bar).
720
+ *
721
+ * `onComplete` is invoked exactly once when the poller detects clean
722
+ * completion (target gone, no timeout). The strategy uses it to do
723
+ * post-completion bookkeeping that needs both the strategy-specific
724
+ * spawn state (e.g. workspace handle) and the run-time `ctx`. It
725
+ * MUST NOT throw — the caller wraps it in try/catch and swallows
726
+ * errors so completion bookkeeping never blocks the next distill.
727
+ * Not invoked on timeout (that uses `cleanup` instead).
728
+ */
729
+ spawnFn: (args: {
730
+ ctx: RunCtx;
731
+ vaultContentPath: string;
732
+ vaultConfigPath: string;
733
+ sessionFile: string;
734
+ config: DistillConfig;
735
+ }) => {
736
+ target: string;
737
+ cleanup: () => void;
738
+ onComplete?: (ctx: RunCtx) => void;
739
+ /**
740
+ * Optional probe invoked when `target` disappears. Returns the
741
+ * path to a wrapper-emitted error log when the spawn failed
742
+ * silently (i.e. the wrapper exited non-zero before timing out
743
+ * but after creating its forensic log). Returns null on success.
744
+ *
745
+ * The runner uses the result to surface a UI failure on the
746
+ * worktree path (mirrors the timeout-surfacing pattern). Legacy
747
+ * spawn doesn't produce error logs in this shape — omit or
748
+ * return null.
749
+ */
750
+ checkFailure?: () => string | null;
751
+ /**
752
+ * Optional probe invoked when `target` disappears AND `checkFailure`
753
+ * returned null (no fatal error). Returns the wrapper-emitted
754
+ * outcome sidecar (POST-CONV-5): `{ outcomeClass, outcomePath,
755
+ * partialMergeLogPath }` when present, null when missing.
756
+ *
757
+ * Missing sidecar AND missing failure log = abnormal termination
758
+ * (SIGKILL / `set -e` / disk full / race) — the runner surfaces
759
+ * a warn-level notification per the locked notification severity
760
+ * contract. Legacy spawn doesn't produce outcome sidecars — omit
761
+ * or return null.
762
+ */
763
+ checkOutcome?: () => {
764
+ outcomeClass: string;
765
+ outcomePath: string;
766
+ partialMergeLogPath: string | null;
767
+ } | null;
768
+ } | null;
769
+ }
770
+
771
+ /**
772
+ * Per-completion overlap-notice helper (R7-PERF-2). Invoked by
773
+ * `worktreeSpawnFn`'s `onComplete` after the wrapper's squash-merge has
774
+ * landed and the worktree has been removed.
775
+ *
776
+ * Algorithm:
777
+ * 1. Compute the just-completed distill's touched files via
778
+ * `git log --name-only <startSha>..HEAD` from the main vault.
779
+ * The squash commit brings every file the distill affected into
780
+ * this range. Returns [] if startSha is missing (legacy meta) or
781
+ * git fails — silent no-op.
782
+ * 2. Compute the parent session's touched files since the previous
783
+ * distill's completion. Walk `getEntries()` from
784
+ * `lastDistillCompletionMessageCursor` to current end and extract
785
+ * write-class file ops (reuses `extractFileOpsFromMessage` via a
786
+ * slice-bounded `SessionEntriesSource` adapter).
787
+ * 3. Intersect. If non-empty, post an `appendCustomMessageEntry`
788
+ * with `customType: "napkin-distill-overlap"`.
789
+ * 4. Update `lastDistillCompletionMessageCursor` to the current end
790
+ * of the entries array — even when overlap is empty — so the
791
+ * next completion only walks new entries.
792
+ *
793
+ * Cache parity (R7-PERF-2): the notice lands as a custom session
794
+ * message in conversation history. Both the parent's next turn and
795
+ * any future distill subprocess (which forks the parent's session)
796
+ * see it in identical positions in the messages array — the cached
797
+ * prefix is preserved unconditionally, unlike the previous per-turn
798
+ * `appendSystemPrompt` mechanism.
799
+ *
800
+ * Failure modes are all silent (best-effort): vault resolution fail,
801
+ * git fail, missing startSha, missing SessionManager mutation method.
802
+ * Completion bookkeeping must never block the next distill.
803
+ */
804
+ function postOverlapNoticeOnCompletion(
805
+ ctx: RunCtx,
806
+ vaultContentPath: string,
807
+ startSha: string | undefined,
808
+ ): void {
809
+ let distillTouched: string[];
810
+ try {
811
+ distillTouched = getDistillTouchedFilesPostSquash(
812
+ vaultContentPath,
813
+ startSha,
814
+ );
815
+ } catch {
816
+ // Even on error, advance the cursor below so we don't double-count
817
+ // on the next completion.
818
+ distillTouched = [];
819
+ }
820
+
821
+ let entries: readonly SessionEntry[];
822
+ try {
823
+ entries = ctx.sessionManager.getEntries();
824
+ } catch {
825
+ // Couldn't read entries — leave cursor where it is so next
826
+ // completion retries the same window.
827
+ return;
828
+ }
829
+
830
+ const { overlap, newCursor } = computeOverlapForCompletion({
831
+ distillTouchedFiles: distillTouched,
832
+ sessionEntries: entries,
833
+ cursor: lastDistillCompletionMessageCursor,
834
+ });
835
+ // Always advance the cursor (even on empty overlap) so the next
836
+ // completion only sees new entries.
837
+ lastDistillCompletionMessageCursor = newCursor;
838
+
839
+ if (overlap.length === 0) return;
840
+
841
+ // Post the notice. SessionManager's mutation methods are not on the
842
+ // public ReadonlySessionManager type that pi exposes via
843
+ // ExtensionContext, so we cast through Partial<SessionManager> the
844
+ // same way `napkin-context` does — graceful degradation if pi ever
845
+ // tightens the readonly contract at runtime.
846
+ const sm = ctx.sessionManager as Partial<SessionManager>;
847
+ if (typeof sm.appendCustomMessageEntry === "function") {
848
+ try {
849
+ sm.appendCustomMessageEntry(
850
+ "napkin-distill-overlap",
851
+ formatOverlapNotice(overlap),
852
+ true, // display: surface in TUI so the user sees what happened
853
+ );
854
+ } catch {
855
+ // best-effort; cursor was already advanced above
856
+ }
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Shared runner for the two distill paths. Encodes the full lifecycle:
862
+ * 1. Early-return if isRunning.
863
+ * 2. Resolve vault config; bail silently if cwd isn't a vault.
864
+ * 3. Read session file; size-dedup against lastSessionSize.
865
+ * 4. Run strategy.preflight; short-circuit on failure.
866
+ * 5. strategy.spawn; on failure paint error status.
867
+ * 6. Bookkeeping: lastSpawnedSize = currentSize, isRunning = true,
868
+ * start polling for target disappearance.
869
+ * 7. On completion: update lastSessionSize + lastDistillTimestamp, paint
870
+ * success status, notify.
871
+ * 8. On timeout: invoke strategy's cleanup callback and paint error.
872
+ */
873
+ function runDistillWith(ctx: RunCtx, strategy: DistillStrategy): void {
874
+ if (isRunning) return;
875
+
876
+ let vaultInfo: { configPath: string; contentPath: string };
877
+ try {
878
+ vaultInfo = new Napkin(ctx.cwd).vault;
879
+ } catch {
880
+ return;
881
+ }
882
+ const vaultContentPath = vaultInfo.contentPath;
883
+
884
+ const { showStatus, distill: config } = loadVaultConfig(
885
+ vaultInfo.configPath,
886
+ );
887
+ const sessionFile = ctx.sessionManager.getSessionFile?.();
888
+ if (!sessionFile) return;
889
+
890
+ // Skip if session hasn't changed since last distill.
891
+ const currentSize = fs.existsSync(sessionFile)
892
+ ? fs.statSync(sessionFile).size
893
+ : 0;
894
+ if (currentSize > 0 && currentSize === lastSessionSize) {
895
+ lastDistillTimestamp = Date.now();
896
+ return;
897
+ }
898
+
899
+ const theme = ctx.hasUI ? ctx.ui.theme : null;
900
+
901
+ // Strategy-specific pre-flight.
902
+ if (strategy.preflight) {
903
+ const pre = strategy.preflight({ ctx, vaultContentPath, theme });
904
+ if (!pre.ok) {
905
+ if (ctx.hasUI && theme && showStatus && pre.errorStatus) {
906
+ ctx.ui.setStatus(
907
+ "napkin-distill",
908
+ theme.fg("error", "✗") + theme.fg("dim", ` ${pre.errorStatus}`),
909
+ );
910
+ }
911
+ return;
912
+ }
913
+ }
914
+
915
+ const spawned = strategy.spawnFn({
916
+ ctx,
917
+ vaultContentPath,
918
+ vaultConfigPath: vaultInfo.configPath,
919
+ sessionFile,
920
+ config,
921
+ });
922
+ if (!spawned) {
923
+ if (ctx.hasUI && theme && showStatus) {
924
+ ctx.ui.setStatus(
925
+ "napkin-distill",
926
+ theme.fg("error", "✗") + theme.fg("dim", " distill: spawn failed"),
927
+ );
928
+ }
929
+ return;
930
+ }
931
+ const {
932
+ target,
933
+ cleanup: spawnCleanup,
934
+ onComplete,
935
+ checkFailure,
936
+ checkOutcome,
937
+ } = spawned;
938
+
939
+ // Record the size we spawned on so a shutdown firing between here and
940
+ // completion dedupes against the in-flight distill.
941
+ lastSpawnedSize = currentSize;
942
+
943
+ isRunning = true;
944
+ const startTime = Date.now();
945
+
946
+ if (ctx.hasUI && theme && showStatus) {
947
+ ctx.ui.setStatus(
948
+ "napkin-distill",
949
+ theme.fg("accent", "●") + theme.fg("dim", " distill"),
950
+ );
951
+ }
952
+
953
+ pollHandle = setInterval(() => {
954
+ const elapsed = Math.floor((Date.now() - startTime) / 1000);
955
+ const timedOut = Date.now() - startTime > getMaxDistillDurationMs(config);
956
+
957
+ if (fs.existsSync(target) && !timedOut) {
958
+ if (ctx.hasUI && theme && showStatus) {
959
+ ctx.ui.setStatus(
960
+ "napkin-distill",
961
+ theme.fg("accent", "●") + theme.fg("dim", ` distill ${elapsed}s`),
962
+ );
963
+ }
964
+ return;
965
+ }
966
+
967
+ if (pollHandle) {
968
+ clearInterval(pollHandle);
969
+ pollHandle = null;
970
+ }
971
+ isRunning = false;
972
+
973
+ if (timedOut) {
974
+ try {
975
+ spawnCleanup();
976
+ } catch {
977
+ // ignore — best-effort cleanup on timeout
978
+ }
979
+ if (ctx.hasUI && theme) {
980
+ if (showStatus) {
981
+ ctx.ui.setStatus(
982
+ "napkin-distill",
983
+ theme.fg("error", "✗") + theme.fg("dim", " distill: timeout"),
984
+ );
985
+ }
986
+ ctx.ui.notify(
987
+ `Distillation timed out (${Math.round(getMaxDistillDurationMs(config) / 60000)}m)`,
988
+ "error",
989
+ );
990
+ }
991
+ return;
992
+ }
993
+
994
+ lastDistillTimestamp = Date.now();
995
+ lastSessionSize = currentSize;
996
+
997
+ // Wrapper-failure check (R7-SC-3). Mirrors the timeout-surfacing
998
+ // pattern: target disappearance is the success condition, but the
999
+ // wrapper writes a forensic log on any non-success exit (missing
1000
+ // napkin, pi subprocess error, merge-driver 3-strike, etc.). If a
1001
+ // log file matching this distill's branch is present in the
1002
+ // error dir, the run failed even though the worktree is gone.
1003
+ // Surface the failure in the UI so the user can act on it instead
1004
+ // of the run silently disappearing.
1005
+ let failureLogPath: string | null = null;
1006
+ if (checkFailure) {
1007
+ try {
1008
+ failureLogPath = checkFailure();
1009
+ } catch {
1010
+ // best-effort — if the probe throws, treat as success
1011
+ failureLogPath = null;
1012
+ }
1013
+ }
1014
+
1015
+ if (failureLogPath) {
1016
+ if (ctx.hasUI && theme) {
1017
+ if (showStatus) {
1018
+ ctx.ui.setStatus(
1019
+ "napkin-distill",
1020
+ theme.fg("error", "✗") + theme.fg("dim", " distill: failed"),
1021
+ );
1022
+ }
1023
+ ctx.ui.notify(`Distillation failed: see ${failureLogPath}`, "error");
1024
+ }
1025
+ return;
1026
+ }
1027
+
1028
+ // Per-completion overlap notice (R7-PERF-2). Strategy-specific
1029
+ // hook fires after target disappearance + before UI notify so any
1030
+ // session-mutation it does (e.g. appendCustomMessageEntry) lands
1031
+ // before the user-visible "distill complete" message. Wrapped to
1032
+ // never throw — completion bookkeeping must not block subsequent
1033
+ // distills.
1034
+ if (onComplete) {
1035
+ try {
1036
+ onComplete(ctx);
1037
+ } catch {
1038
+ // best-effort — swallow per the strategy contract
1039
+ }
1040
+ }
1041
+
1042
+ // Outcome dispatch (POST-CONV-5). The wrapper writes a one-line
1043
+ // `*.outcome` sidecar before any successful exit-0 path; the
1044
+ // class string drives the UI severity per the locked notification
1045
+ // severity contract. See `formatOutcomeNotification` for the
1046
+ // full mapping. Strategies that don't produce sidecars (legacy
1047
+ // /distill on git-less or disabled vaults) skip this entire
1048
+ // dispatch and fall through to the default info notification.
1049
+ let outcome: {
1050
+ outcomeClass: string;
1051
+ outcomePath: string;
1052
+ partialMergeLogPath: string | null;
1053
+ } | null = null;
1054
+ if (checkOutcome) {
1055
+ try {
1056
+ outcome = checkOutcome();
1057
+ } catch {
1058
+ outcome = null;
1059
+ }
1060
+ }
1061
+
1062
+ if (ctx.hasUI && theme) {
1063
+ let level: "info" | "warning" | "error" = "info";
1064
+ let message = `Distillation complete (${elapsed}s)`;
1065
+ let statusGlyph = theme.fg("success", "✓");
1066
+ let statusText = ` distill ${elapsed}s`;
1067
+
1068
+ if (checkOutcome) {
1069
+ const dispatch = formatOutcomeNotification({
1070
+ outcome,
1071
+ elapsedSec: elapsed,
1072
+ readPartialMergeLog: (p) => {
1073
+ try {
1074
+ return fs.readFileSync(p, "utf-8");
1075
+ } catch {
1076
+ return null;
1077
+ }
1078
+ },
1079
+ });
1080
+ level = dispatch.level;
1081
+ message = dispatch.message;
1082
+ statusGlyph = theme.fg(dispatch.statusKey, dispatch.statusGlyph);
1083
+ statusText = dispatch.statusText;
1084
+ }
1085
+
1086
+ if (showStatus) {
1087
+ ctx.ui.setStatus(
1088
+ "napkin-distill",
1089
+ statusGlyph + theme.fg("dim", statusText),
1090
+ );
1091
+ }
1092
+ ctx.ui.notify(message, level);
1093
+ }
1094
+ }, 2000);
1095
+ }
1096
+
1097
+ function runDistill(ctx: RunCtx) {
1098
+ // Manual `/distill` routing: use the worktree path only when the user
1099
+ // has opted into auto-distill (`distill.enabled=true`), git is
1100
+ // available, AND the vault uses the subdir layout. Otherwise fall
1101
+ // back to the legacy tmpdir spawn, which has zero git side effects.
1102
+ //
1103
+ // `distill.enabled=false` means the user opted out of auto-distill's
1104
+ // infrastructure (including `.gitattributes` rewrites). Worktree
1105
+ // spawn calls `registerMergeDriver()` which writes git config; legacy
1106
+ // path doesn't.
1107
+ //
1108
+ // Legacy-embedded layout (`configPath === contentPath`) forces the
1109
+ // same fallback: the worktree path silently corrupts on that layout
1110
+ // because napkin's `findVault` from cwd=<worktree> walks past the
1111
+ // worktree and resolves to the real `~/.napkin/` via global config
1112
+ // fallback. Distill writes land on the real vault, worktree stays
1113
+ // empty, concurrency guarantee degrades to zero. README covers the
1114
+ // subdir migration; auto-distill refuses this layout at session_start.
1115
+ //
1116
+ // Cross-session concurrency caveat: the legacy fallback has no
1117
+ // worktree isolation — two concurrent `/distill` calls on a git-less,
1118
+ // disabled, or legacy-embedded vault race on napkin writes. With
1119
+ // git + enabled + subdir layout, both manual and auto paths serialize
1120
+ // through the merge driver.
1121
+ runDistillWith(ctx, {
1122
+ spawnFn: (args) => {
1123
+ const gitPresent = fs.existsSync(
1124
+ path.join(args.vaultContentPath, ".git"),
1125
+ );
1126
+ // Legacy-embedded detection matches the predicate in
1127
+ // `ensureVaultReadyForAutoDistill` (keep the two gates in lockstep).
1128
+ const isLegacyEmbedded = args.vaultConfigPath === args.vaultContentPath;
1129
+ if (gitPresent && args.config.enabled && !isLegacyEmbedded) {
1130
+ return worktreeSpawnFn(args);
1131
+ }
1132
+ return legacySpawnFn(args);
1133
+ },
1134
+ });
1135
+ }
1136
+
1137
+ /**
1138
+ * Worktree-backed auto-distill path — used by the interval timer and the
1139
+ * shutdown handler (Item 8). Concurrency-safe via per-distill git
1140
+ * worktrees: each call spawns a detached wrapper that operates on its
1141
+ * own branch, so overlapping distills (interval + shutdown, or multiple
1142
+ * pi sessions on the same vault) merge serially on main via the LLM
1143
+ * merge driver.
1144
+ */
1145
+ function runAutoDistill(ctx: RunCtx) {
1146
+ runDistillWith(ctx, {
1147
+ preflight: ({ vaultContentPath }) => {
1148
+ // Auto-distill requires the vault to be a git repo. Phase C1
1149
+ // auto-init wires this at session_start; we surface a one-shot
1150
+ // status-bar hint here for belt-and-braces.
1151
+ if (!fs.existsSync(path.join(vaultContentPath, ".git"))) {
1152
+ return { ok: false, errorStatus: "distill: needs git" };
1153
+ }
1154
+ return { ok: true };
1155
+ },
1156
+ spawnFn: worktreeSpawnFn,
1157
+ });
1158
+ }
1159
+
1160
+ /**
1161
+ * Legacy tmpdir spawn strategy. Forks the session under `$TMPDIR` and
1162
+ * runs `pi -p` detached; cleanup is a plain `rmSync`. No git, no
1163
+ * concurrency coordination. Only used by manual `/distill` as a
1164
+ * fallback for vaults without `.git/`.
1165
+ *
1166
+ * Vault resolution note: the spawned `pi -p` instance runs with
1167
+ * `cwd = vaultContentPath`, which is already resolved by napkin
1168
+ * (cwd-independent via `new Napkin(ctx.cwd).vault`). The distill
1169
+ * subprocess itself calls `napkin` commands that walk up from their
1170
+ * cwd, so targeting `vaultContentPath` ensures they hit the user's
1171
+ * real vault regardless of where pi was originally launched. This
1172
+ * matches the pre-worktree behavior where the session operated
1173
+ * directly on the vault root — no isolation, napkin-from-cwd only.
1174
+ */
1175
+ function legacySpawnFn(args: {
1176
+ ctx: RunCtx;
1177
+ vaultContentPath: string;
1178
+ vaultConfigPath: string;
1179
+ sessionFile: string;
1180
+ config: DistillConfig;
1181
+ }): { target: string; cleanup: () => void } | null {
1182
+ const { vaultContentPath, sessionFile, config } = args;
1183
+ const tmpDir = spawnDistill(sessionFile, vaultContentPath, config);
1184
+ if (!tmpDir) return null;
1185
+ return {
1186
+ target: tmpDir,
1187
+ cleanup: () => fs.rmSync(tmpDir, { recursive: true, force: true }),
1188
+ };
1189
+ }
1190
+
1191
+ /**
1192
+ * Worktree spawn strategy. Creates a per-distill git worktree off the
1193
+ * vault's default branch, runs the detached wrapper that merges back
1194
+ * via the LLM merge driver + squash. Concurrency-safe across sessions.
1195
+ *
1196
+ * Shared by `runDistill` (when git is available) and `runAutoDistill`.
1197
+ * A `DistillError` from the workspace layer (branch collision, fork
1198
+ * failure, invalid HEAD, merge driver missing) is caught and rendered
1199
+ * as an error status; the shared runner treats a null return as a
1200
+ * spawn failure and skips the poll loop.
1201
+ */
1202
+ function worktreeSpawnFn(args: {
1203
+ ctx: RunCtx;
1204
+ vaultContentPath: string;
1205
+ vaultConfigPath: string;
1206
+ sessionFile: string;
1207
+ config: DistillConfig;
1208
+ }): {
1209
+ target: string;
1210
+ cleanup: () => void;
1211
+ onComplete?: (ctx: RunCtx) => void;
1212
+ checkFailure?: () => string | null;
1213
+ checkOutcome?: () => {
1214
+ outcomeClass: string;
1215
+ outcomePath: string;
1216
+ partialMergeLogPath: string | null;
1217
+ } | null;
1218
+ } | null {
1219
+ const { ctx: c, vaultContentPath, sessionFile, config } = args;
1220
+ try {
1221
+ const modelStr = config.model
1222
+ ? `${config.model.provider}/${config.model.id}`
1223
+ : undefined;
1224
+ const result = spawnDistillInWorktree({
1225
+ vault: vaultContentPath,
1226
+ sessionFile,
1227
+ parentCwd: c.cwd,
1228
+ prompt: DISTILL_PROMPT,
1229
+ model: modelStr,
1230
+ });
1231
+ // Capture startSha so the completion handler can diff post-squash
1232
+ // against the main vault's HEAD. The wrapper removes the worktree
1233
+ // (including meta.json) before completion fires, so we have to
1234
+ // capture it here on the JS side.
1235
+ const startSha = result.workspace.startSha;
1236
+ // Same for the branch suffix and error dir — needed by the
1237
+ // failure-surfacing probe (R7-SC-3) since the worktree is gone
1238
+ // by the time we look.
1239
+ const branchShort = result.workspace.branchName.replace(/^distill\//, "");
1240
+ const errorDir = resolveDistillErrorDir(vaultContentPath);
1241
+ return {
1242
+ target: result.workspace.worktreePath,
1243
+ cleanup: () => {
1244
+ try {
1245
+ cleanupDistillWorkspace(vaultContentPath, result.workspace);
1246
+ } catch {
1247
+ // ignore
1248
+ }
1249
+ },
1250
+ onComplete: (rctx) => {
1251
+ postOverlapNoticeOnCompletion(rctx, vaultContentPath, startSha);
1252
+ },
1253
+ checkFailure: () => findDistillErrorLogForBranch(errorDir, branchShort),
1254
+ checkOutcome: () => findDistillOutcomeForBranch(errorDir, branchShort),
1255
+ };
1256
+ } catch (err) {
1257
+ const theme = c.hasUI ? c.ui.theme : null;
1258
+ const { showStatus } = loadVaultConfig(
1259
+ new Napkin(c.cwd).vault.configPath,
1260
+ );
1261
+ if (c.hasUI && theme && showStatus) {
1262
+ const msg =
1263
+ err instanceof DistillError
1264
+ ? "distill: setup failed"
1265
+ : "distill: spawn failed";
1266
+ c.ui.setStatus(
1267
+ "napkin-distill",
1268
+ theme.fg("error", "✗") + theme.fg("dim", ` ${msg}`),
1269
+ );
1270
+ }
1271
+ return null;
1272
+ }
1273
+ }
1274
+
1275
+ pi.registerCommand("distill", {
1276
+ description: "Distill conversation knowledge into the vault",
1277
+ handler: async (_args, ctx) => {
1278
+ if (isRunning) {
1279
+ if (ctx.hasUI) ctx.ui.notify("Distill already running", "warning");
1280
+ return;
1281
+ }
1282
+ lastSessionSize = 0; // bypass size check
1283
+ runDistill(ctx);
1284
+ },
1285
+ });
1286
+
1287
+ pi.registerCommand("distill-auto-this-session", {
1288
+ description: "Pause/resume auto-distill for this session (on|off|status)",
1289
+ getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1290
+ const needle = prefix.toLowerCase();
1291
+ const values = ["on", "off", "status"];
1292
+ const items = values
1293
+ .filter((v) => v.startsWith(needle))
1294
+ .map((v) => ({ value: v, label: v }));
1295
+ return items.length > 0 ? items : null;
1296
+ },
1297
+ handler: async (args, ctx) => {
1298
+ const arg = args.trim().toLowerCase();
1299
+
1300
+ // Detect when distill is disabled in the vault config so we can warn that
1301
+ // toggling the session flag has no effect.
1302
+ let vaultDistillEnabled = false;
1303
+ try {
1304
+ const vaultConfigPath = new Napkin(ctx.cwd).vault.configPath;
1305
+ vaultDistillEnabled = loadVaultConfig(vaultConfigPath).distill.enabled;
1306
+ } catch {
1307
+ // No vault — treat as disabled at vault level.
1308
+ }
1309
+
1310
+ const vaultDisabledHint =
1311
+ "distill is disabled in vault config — set distill.enabled=true in .napkin/config.json";
1312
+
1313
+ function describeState(suppressed: boolean): string {
1314
+ if (suppressed) return "Auto-distill is off for this session";
1315
+ return `Auto-distill is on for this session (next run in ${formatRemaining()})`;
1316
+ }
1317
+
1318
+ let nextSuppressed: boolean;
1319
+ switch (arg) {
1320
+ case "":
1321
+ nextSuppressed = !autoDistillSuppressed;
1322
+ break;
1323
+ case "on":
1324
+ nextSuppressed = false;
1325
+ break;
1326
+ case "off":
1327
+ nextSuppressed = true;
1328
+ break;
1329
+ case "status": {
1330
+ if (!ctx.hasUI) return;
1331
+ if (!vaultDistillEnabled) {
1332
+ ctx.ui.notify(vaultDisabledHint, "warning");
1333
+ return;
1334
+ }
1335
+ ctx.ui.notify(describeState(autoDistillSuppressed), "info");
1336
+ return;
1337
+ }
1338
+ default:
1339
+ if (ctx.hasUI) {
1340
+ ctx.ui.notify(
1341
+ "Usage: /distill-auto-this-session [on|off|status]",
1342
+ "warning",
1343
+ );
1344
+ }
1345
+ return;
1346
+ }
1347
+
1348
+ const wasSuppressed = autoDistillSuppressed;
1349
+ autoDistillSuppressed = nextSuppressed;
1350
+
1351
+ // Persist state changes to the session file so the setting survives pi
1352
+ // restart and session resume. No-ops don't touch the session — otherwise
1353
+ // repeated invocations would bloat the file with identical entries.
1354
+ if (wasSuppressed !== nextSuppressed) {
1355
+ persistSuppressed(ctx.sessionManager, nextSuppressed);
1356
+ }
1357
+
1358
+ // When re-enabling, reset the timer so the next run respects a full
1359
+ // interval instead of firing immediately if we were already past it.
1360
+ if (wasSuppressed && !nextSuppressed) {
1361
+ lastDistillTimestamp = Date.now();
1362
+ }
1363
+
1364
+ renderIdleStatus();
1365
+
1366
+ if (!ctx.hasUI) return;
1367
+
1368
+ if (!vaultDistillEnabled) {
1369
+ ctx.ui.notify(vaultDisabledHint, "warning");
1370
+ return;
1371
+ }
1372
+
1373
+ if (wasSuppressed === nextSuppressed) {
1374
+ ctx.ui.notify(describeState(nextSuppressed), "info");
1375
+ return;
1376
+ }
1377
+
1378
+ if (nextSuppressed) {
1379
+ ctx.ui.notify("Auto-distill off for this session", "info");
1380
+ } else {
1381
+ ctx.ui.notify(
1382
+ `Auto-distill on for this session (next run in ${formatRemaining()})`,
1383
+ "info",
1384
+ );
1385
+ }
1386
+ },
1387
+ });
1388
+
1389
+ // ---------------------------------------------------------------------------
1390
+ // /distill-status and napkin_distill_status
1391
+ //
1392
+ // Shared state: both surfaces read the exact same data (active worktrees +
1393
+ // unmerged branches) via module-level `collectDistillStatus`. The command
1394
+ // formats it for humans via `formatDistillStatus`; the tool returns the
1395
+ // JSON shape for the agent via `distillStatusToJson`. The formatters are
1396
+ // module-level + exported so tests can verify their output without wiring
1397
+ // a full mock `ExtensionAPI`.
1398
+ // ---------------------------------------------------------------------------
1399
+
1400
+ /**
1401
+ * Resolve the main vault path from a command/tool `ctx`. Returns null when
1402
+ * no vault can be resolved (ctx.cwd isn't inside a napkin vault) — callers
1403
+ * surface a user-facing message in that case.
1404
+ */
1405
+ function resolveVaultPath(cwd: string): string | null {
1406
+ try {
1407
+ return new Napkin(cwd).vault.contentPath;
1408
+ } catch {
1409
+ return null;
1410
+ }
1411
+ }
1412
+
1413
+ pi.registerCommand("distill-status", {
1414
+ description: "Show active auto-distill processes for the current vault",
1415
+ handler: async (_args, ctx) => {
1416
+ const vaultPath = resolveVaultPath(ctx.cwd);
1417
+ if (!vaultPath) {
1418
+ if (ctx.hasUI) {
1419
+ ctx.ui.notify(
1420
+ "No napkin vault resolved from current directory.",
1421
+ "warning",
1422
+ );
1423
+ }
1424
+ return;
1425
+ }
1426
+
1427
+ const { active, unmerged } = collectDistillStatus(vaultPath);
1428
+ const msg = formatDistillStatus(active, unmerged);
1429
+
1430
+ if (ctx.hasUI) {
1431
+ ctx.ui.notify(msg, "info");
1432
+ } else {
1433
+ // Headless pi: surface via stdout so `pi -p /distill-status ...` works.
1434
+ console.log(msg);
1435
+ }
1436
+ },
1437
+ });
1438
+
1439
+ // Parallel pi tool: the LLM can query the same state the human gets from
1440
+ // /distill-status. Used by agents to decide whether to back off from
1441
+ // vault edits while a background distill is in flight (see also the
1442
+ // per-distill-completion overlap notice posted via
1443
+ // `appendCustomMessageEntry` once the distill finishes).
1444
+ pi.registerTool({
1445
+ name: "napkin_distill_status",
1446
+ label: "Napkin distill status",
1447
+ description:
1448
+ "Returns JSON listing active napkin distill subprocesses and unmerged distill branches for the current vault. Useful for checking if background vault writes are in progress before the agent makes concurrent edits.",
1449
+ promptSnippet:
1450
+ "Inspect in-flight napkin distill subprocesses before editing vault files.",
1451
+ parameters: Type.Object({}),
1452
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
1453
+ const vaultPath = resolveVaultPath(ctx.cwd);
1454
+ if (!vaultPath) {
1455
+ return {
1456
+ content: [
1457
+ {
1458
+ type: "text",
1459
+ text: JSON.stringify({ error: "no vault in cwd" }),
1460
+ },
1461
+ ],
1462
+ details: { vault: null, active: [], unmerged: [] },
1463
+ };
1464
+ }
1465
+ const { active, unmerged } = collectDistillStatus(vaultPath);
1466
+ const json = distillStatusToJson(active, unmerged);
1467
+ return {
1468
+ content: [{ type: "text", text: json }],
1469
+ details: { vault: vaultPath, active, unmerged },
1470
+ };
1471
+ },
1472
+ });
1473
+ }
1474
+
1475
+ /**
1476
+ * Gather the shared status payload consumed by both `/distill-status` and
1477
+ * `napkin_distill_status`. Empty arrays on any error (no git, git failure)
1478
+ * — status surfaces must never throw.
1479
+ *
1480
+ * Exported for unit tests. Callers pass the MAIN vault content path (not a
1481
+ * worktree). Both inspectors return [] when `.git/` is absent.
1482
+ */
1483
+ export function collectDistillStatus(vaultPath: string): {
1484
+ active: ActiveDistill[];
1485
+ unmerged: string[];
1486
+ } {
1487
+ return getDistillState({ contentPath: vaultPath });
1488
+ }
1489
+
1490
+ /**
1491
+ * Format the `/distill-status` human-readable string. Pure function; exported
1492
+ * for unit tests.
1493
+ *
1494
+ * Output shape (matches the spec "Output format" block in shutdown-distill.md):
1495
+ *
1496
+ * Active distills (N):
1497
+ * [PID] Xs branch=distill/abc-123 session=<basename>
1498
+ * ...
1499
+ * Unmerged branches (M):
1500
+ * distill/xyz-456 (no active process)
1501
+ *
1502
+ * Zero-active case collapses to the single line `"No active distills."`
1503
+ * when there are also zero unmerged branches; otherwise the Unmerged block
1504
+ * still renders so the user can see lingering refs.
1505
+ */
1506
+ export function formatDistillStatus(
1507
+ active: ActiveDistill[],
1508
+ unmerged: string[],
1509
+ ): string {
1510
+ const lines: string[] = [];
1511
+ if (active.length === 0) {
1512
+ lines.push("No active distills.");
1513
+ } else {
1514
+ lines.push(`Active distills (${active.length}):`);
1515
+ for (const d of active) {
1516
+ const elapsed = `${Math.floor(d.elapsedMs / 1000)}s`;
1517
+ const session =
1518
+ d.sessionPath !== null ? path.basename(d.sessionPath) : "unknown";
1519
+ const liveness = d.alive ? "" : " (dead)";
1520
+ lines.push(
1521
+ ` [${d.pid}] ${elapsed} branch=${d.branch} session=${session}${liveness}`,
1522
+ );
1523
+ }
1524
+ }
1525
+
1526
+ if (unmerged.length > 0) {
1527
+ lines.push(`Unmerged branches (${unmerged.length}):`);
1528
+ for (const b of unmerged) {
1529
+ lines.push(` ${b} (no active process)`);
1530
+ }
1531
+ }
1532
+
1533
+ return lines.join("\n");
1534
+ }
1535
+
1536
+ /**
1537
+ * Serialise the same `(active, unmerged)` payload that `/distill-status`
1538
+ * renders to a JSON string for the `napkin_distill_status` pi tool. Pure
1539
+ * function; exported for unit tests.
1540
+ *
1541
+ * Return shape (see shutdown-distill.md — `/distill-status` command):
1542
+ * {
1543
+ * "active": [
1544
+ * {
1545
+ * pid: number, // -1 when meta.json is unreadable
1546
+ * branch: string,
1547
+ * elapsedSeconds: number,
1548
+ * session: string|null, // basename of parent session .jsonl
1549
+ * alive: boolean,
1550
+ * startedAt: string|null,
1551
+ * startSha?: string,
1552
+ * }
1553
+ * ],
1554
+ * "unmerged": ["distill/xyz-456", ...]
1555
+ * }
1556
+ *
1557
+ * `session` is the basename of the parent session file (matching the
1558
+ * human-readable formatter) — the full path isn't useful to the agent and
1559
+ * would leak $HOME. `elapsedSeconds` is an integer (floor).
1560
+ *
1561
+ * `alive` and `startSha` are retained because they materially change how
1562
+ * the agent should interpret an entry (dead distills are candidates for
1563
+ * manual cleanup; `startSha` is a forensic hint for recovery).
1564
+ *
1565
+ * Shape is stable: new keys may be added, existing keys MUST NOT be renamed
1566
+ * or repurposed without a version bump.
1567
+ */
1568
+ export function distillStatusToJson(
1569
+ active: ActiveDistill[],
1570
+ unmerged: string[],
1571
+ ): string {
1572
+ const payload = {
1573
+ active: active.map((d) => ({
1574
+ pid: d.pid,
1575
+ branch: d.branch,
1576
+ elapsedSeconds: Math.floor(d.elapsedMs / 1000),
1577
+ session: d.sessionPath !== null ? path.basename(d.sessionPath) : null,
1578
+ alive: d.alive,
1579
+ startedAt: d.startedAt,
1580
+ startSha: d.startSha,
1581
+ })),
1582
+ unmerged,
1583
+ };
1584
+ return JSON.stringify(payload, null, 2);
1585
+ }
1586
+
1587
+ /**
1588
+ * Compute the intersection of session-touched paths and distill-touched
1589
+ * paths. Matching is layered:
1590
+ * 1. Exact equality (the canonical case).
1591
+ * 2. Symmetric suffix — tolerates absolute session paths
1592
+ * (`/home/user/.napkin/notes/foo.md`) against worktree-relative
1593
+ * distill paths (`notes/foo.md`) without depending on which side
1594
+ * is which.
1595
+ * 3. Basename equality — last-resort heuristic for the rare case
1596
+ * where neither path is a suffix of the other (e.g. an absolute
1597
+ * session path against a worktree-relative distill path that
1598
+ * lives under a different subtree). This produces a known
1599
+ * false-positive shape: two unrelated `README.md`s in different
1600
+ * subtrees match. Accepted because the overlap notice is
1601
+ * non-destructive (it surfaces a warning to the agent, doesn't
1602
+ * modify files); the basename-collision test in
1603
+ * `overlap-injection.test.ts` documents the trade-off.
1604
+ *
1605
+ * Exported for unit tests. Output is sorted so the overlap notice is
1606
+ * deterministic across runs.
1607
+ */
1608
+ export function intersectFiles(
1609
+ session: ReadonlySet<string>,
1610
+ distill: ReadonlySet<string>,
1611
+ ): string[] {
1612
+ if (session.size === 0 || distill.size === 0) return [];
1613
+
1614
+ const hits = new Set<string>();
1615
+ for (const d of distill) {
1616
+ for (const s of session) {
1617
+ if (
1618
+ d === s ||
1619
+ d.endsWith(`/${s}`) ||
1620
+ s.endsWith(`/${d}`) ||
1621
+ path.basename(d) === path.basename(s)
1622
+ ) {
1623
+ // Prefer the distill-side (worktree-relative) path for display;
1624
+ // it's shorter and scoped to the vault.
1625
+ hits.add(d);
1626
+ }
1627
+ }
1628
+ }
1629
+ return [...hits].sort();
1630
+ }
1631
+
1632
+ /**
1633
+ * Format the overlap notice posted as a custom session message when
1634
+ * the parent session and a just-completed distill have written to the
1635
+ * same file(s).
1636
+ *
1637
+ * Leading `\n\n` separates it from any surrounding content so it can't
1638
+ * accidentally run into the last word of whatever the tail looks like.
1639
+ * The warning glyph (⚠️) catches the agent's attention; agents trained
1640
+ * on markdown treat it as a signal.
1641
+ *
1642
+ * Text is deliberately short (~45 tokens): the notice is posted via
1643
+ * `appendCustomMessageEntry` (R7-PERF-2 redesign) so it persists in
1644
+ * session history and forks cleanly into distill subprocess sessions.
1645
+ * Cache parity is preserved unconditionally vs the previous per-turn
1646
+ * `appendSystemPrompt` mechanism.
1647
+ */
1648
+ export function formatOverlapNotice(overlapFiles: string[]): string {
1649
+ if (overlapFiles.length === 0) return "";
1650
+ const list = overlapFiles.join(", ");
1651
+ return (
1652
+ "\n\n\u26a0\ufe0f Background napkin distill is editing files you've also " +
1653
+ `touched: ${list}. Recent writes to these files may be overwritten or ` +
1654
+ "merged automatically at distill completion; consider re-reading before " +
1655
+ "further edits."
1656
+ );
1657
+ }
1658
+
1659
+ /**
1660
+ * Pure helper for the POST-CONV-5 outcome-sidecar dispatch. Maps the
1661
+ * wrapper's exit-0 outcome class (or its absence) to the UI severity +
1662
+ * notification text. Caller (runDistillWith) applies theme styling +
1663
+ * dispatches to `ctx.ui.notify` / `ctx.ui.setStatus`.
1664
+ *
1665
+ * Inputs:
1666
+ * - `outcome`: the parsed sidecar (`{ outcomeClass, partialMergeLogPath }`)
1667
+ * or null when no sidecar exists at all (abnormal termination).
1668
+ * - `elapsedSec`: wall-clock seconds since spawn, used in the
1669
+ * default success message (`merged-content`).
1670
+ * - `readPartialMergeLog`: optional reader injected for testability.
1671
+ * Returns the log content as a string, or
1672
+ * null on read failure. Production passes
1673
+ * an `fs.readFileSync` wrapper.
1674
+ *
1675
+ * Outputs `{ level, message, statusKey, statusText }` per class:
1676
+ * merged-content → info / "Distillation complete (Ns)"
1677
+ * no-content → warn / "Distillation ran but saved no content"
1678
+ * partial-merge → warn / "Distillation: partial merge — N file(s) reverted to main; see <log>"
1679
+ * <unknown> → warn / defensive class string
1680
+ * missing sidecar → warn / "Distillation terminated abnormally — no outcome record"
1681
+ *
1682
+ * `statusKey` maps to the theme's `fg(severity, glyph)` palette:
1683
+ * success | warning | error.
1684
+ *
1685
+ * Exported for unit tests; production wiring lives in `runDistillWith`.
1686
+ */
1687
+ export function formatOutcomeNotification(args: {
1688
+ outcome: {
1689
+ outcomeClass: string;
1690
+ partialMergeLogPath: string | null;
1691
+ } | null;
1692
+ elapsedSec: number;
1693
+ readPartialMergeLog?: (path: string) => string | null;
1694
+ }): {
1695
+ level: "info" | "warning" | "error";
1696
+ message: string;
1697
+ statusKey: "success" | "warning" | "error";
1698
+ statusGlyph: string;
1699
+ statusText: string;
1700
+ } {
1701
+ const { outcome, elapsedSec, readPartialMergeLog } = args;
1702
+ if (!outcome) {
1703
+ return {
1704
+ level: "warning",
1705
+ message: "Distillation terminated abnormally — no outcome record",
1706
+ statusKey: "warning",
1707
+ statusGlyph: "⚠",
1708
+ statusText: " distill: abnormal",
1709
+ };
1710
+ }
1711
+ switch (outcome.outcomeClass) {
1712
+ case "merged-content":
1713
+ return {
1714
+ level: "info",
1715
+ message: `Distillation complete (${elapsedSec}s)`,
1716
+ statusKey: "success",
1717
+ statusGlyph: "✓",
1718
+ statusText: ` distill ${elapsedSec}s`,
1719
+ };
1720
+ case "no-content":
1721
+ return {
1722
+ level: "warning",
1723
+ message: "Distillation ran but saved no content",
1724
+ statusKey: "warning",
1725
+ statusGlyph: "⚠",
1726
+ statusText: " distill: no content",
1727
+ };
1728
+ case "partial-merge": {
1729
+ let revertedCount = 0;
1730
+ if (outcome.partialMergeLogPath && readPartialMergeLog) {
1731
+ const content = readPartialMergeLog(outcome.partialMergeLogPath);
1732
+ if (content) {
1733
+ revertedCount = content
1734
+ .split("\n")
1735
+ .filter((line) => /\breverted '/.test(line)).length;
1736
+ }
1737
+ }
1738
+ const message = outcome.partialMergeLogPath
1739
+ ? `Distillation: partial merge — ${revertedCount} file${revertedCount === 1 ? "" : "s"} reverted to main; see ${outcome.partialMergeLogPath}`
1740
+ : "Distillation: partial merge — some files reverted to main";
1741
+ return {
1742
+ level: "warning",
1743
+ message,
1744
+ statusKey: "warning",
1745
+ statusGlyph: "⚠",
1746
+ statusText: " distill: partial",
1747
+ };
1748
+ }
1749
+ default:
1750
+ return {
1751
+ level: "warning",
1752
+ message: `Distillation: unrecognised outcome '${outcome.outcomeClass}'`,
1753
+ statusKey: "warning",
1754
+ statusGlyph: "⚠",
1755
+ statusText: " distill: unknown outcome",
1756
+ };
1757
+ }
1758
+ }
1759
+
1760
+ /**
1761
+ * Pure helper for the per-distill-completion overlap-notice mechanism
1762
+ * (R7-PERF-2). Stateless: given the just-completed distill's touched
1763
+ * files, the parent session's entries, and the cursor of the previous
1764
+ * completion, returns the overlap and the new cursor value to advance
1765
+ * to.
1766
+ *
1767
+ * Caller is expected to:
1768
+ * 1. Persist the new cursor (`newCursor`) into closure state, even
1769
+ * when overlap is empty — otherwise the next completion re-walks
1770
+ * the same window.
1771
+ * 2. If overlap is non-empty, post it via `appendCustomMessageEntry`
1772
+ * (or otherwise notify the agent).
1773
+ *
1774
+ * The session walk is bounded to `entries.slice(cursor)` so each
1775
+ * completion only considers messages added since the previous
1776
+ * completion. Cursor 0 means "start of session" — the first completion
1777
+ * compares against everything the parent has done so far.
1778
+ *
1779
+ * Exported for unit tests; production wiring lives in
1780
+ * `postOverlapNoticeOnCompletion` inside the extension factory.
1781
+ */
1782
+ export function computeOverlapForCompletion(args: {
1783
+ distillTouchedFiles: readonly string[];
1784
+ sessionEntries: readonly SessionEntry[];
1785
+ cursor: number;
1786
+ }): { overlap: string[]; newCursor: number } {
1787
+ const { distillTouchedFiles, sessionEntries, cursor } = args;
1788
+ const newCursor = sessionEntries.length;
1789
+
1790
+ if (distillTouchedFiles.length === 0) {
1791
+ return { overlap: [], newCursor };
1792
+ }
1793
+
1794
+ // Slice-bounded walk: only consider entries added since the previous
1795
+ // completion's cursor. `getSessionTouchedFiles` accepts any
1796
+ // `SessionEntriesSource` (`{ getEntries(): SessionEntry[] }`) so we
1797
+ // adapt the slice on the fly.
1798
+ const slice = sessionEntries.slice(cursor);
1799
+ const sessionTouched = getSessionTouchedFiles({
1800
+ getEntries: () => slice as SessionEntry[],
1801
+ });
1802
+ if (sessionTouched.size === 0) {
1803
+ return { overlap: [], newCursor };
1804
+ }
1805
+
1806
+ const overlap = intersectFiles(sessionTouched, new Set(distillTouchedFiles));
1807
+ return { overlap, newCursor };
1808
+ }