@cad0p/pi-napkin 0.7.0 → 0.7.1

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.
@@ -13,11 +13,7 @@ import type {
13
13
  import { SessionManager } from "@earendil-works/pi-coding-agent";
14
14
  import type { AutocompleteItem } from "@earendil-works/pi-tui";
15
15
  import { sendCustomMessageWithFallback } from "../shared/custom-message";
16
- import {
17
- countTrackedFiles,
18
- ensureVaultReadyForDistill,
19
- LEGACY_EMBEDDED_LAYOUT_ERROR,
20
- } from "./auto-setup";
16
+ import { countTrackedFiles, ensureVaultReadyForDistill } from "./auto-setup";
21
17
  import {
22
18
  type ActiveDistill,
23
19
  cleanupDistillWorkspace,
@@ -291,7 +287,7 @@ export function loadVaultConfig(vaultPath: string): VaultConfig {
291
287
  }
292
288
 
293
289
  /**
294
- * LEGACY_DISTILL_PROMPT: used only by the legacy `spawnDistill` path
290
+ * TMPDIR_DISTILL_PROMPT: used only by the tmpdir `spawnDistill` path
295
291
  * (argv-based, pre-PR-12). The canonical agent-driven prompt lives in
296
292
  * `distill-prompt.md` (loaded via `buildDistillPrompt` from
297
293
  * `distill-prompt.ts`) and is the source of truth for steps 1–10 of
@@ -300,13 +296,13 @@ export function loadVaultConfig(vaultPath: string): VaultConfig {
300
296
  * This constant duplicates roughly steps 1–5 of the canonical prompt
301
297
  * (overview → templates → identify → search/append/create → daily
302
298
  * note + supersedes frontmatter). Do NOT add new steps here without
303
- * cross-checking distill-prompt.md — the legacy path is intentionally
304
- * retained for git-less / disabled / legacy-embedded vaults that
305
- * can't take the worktree spawn path, so drift between the two
306
- * prompts is a hazard. Phase D / a future cleanup pass may factor
307
- * the shared content into a single source.
299
+ * cross-checking distill-prompt.md — the tmpdir path is intentionally
300
+ * retained for git-less or disabled vaults that can't take the
301
+ * worktree spawn path, so drift between the two prompts is a
302
+ * hazard. Phase D / a future cleanup pass may factor the shared
303
+ * content into a single source.
308
304
  */
309
- const LEGACY_DISTILL_PROMPT = `Distill this conversation into the napkin vault.
305
+ const TMPDIR_DISTILL_PROMPT = `Distill this conversation into the napkin vault.
310
306
 
311
307
  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.
312
308
  2. \`napkin template list\` and \`napkin template read\` — learn the note formats.
@@ -324,7 +320,7 @@ stand alone.
324
320
 
325
321
  Be selective. Only capture knowledge useful to someone working on this project later. Skip meta-discussion, tool output, and chatter.`;
326
322
 
327
- // Inline bash script template for the legacy (git-optional) manual
323
+ // Inline bash script template for the tmpdir (git-optional) manual
328
324
  // /distill path. Tainted values flow through positional `$1..$5` argv;
329
325
  // the template itself is a fixed literal, never interpolated from user
330
326
  // input. Same trust boundary as the worktree wrapper, without a
@@ -332,7 +328,7 @@ Be selective. Only capture knowledge useful to someone working on this project l
332
328
  //
333
329
  // Bash (not sh) because we use arrays for optional --model splicing;
334
330
  // Ubuntu's /bin/sh is dash which parse-errors on `pi_args=(...)`.
335
- const LEGACY_SPAWN_SCRIPT = `set -u
331
+ const TMPDIR_SPAWN_SCRIPT = `set -u
336
332
  PI_BIN="$1"; SESSION="$2"; TMPDIR_ARG="$3"; PROMPT="$4"; MODEL="$5"
337
333
  pi_args=(--session "$SESSION" -p "$PROMPT")
338
334
  if [ -n "$MODEL" ]; then
@@ -348,10 +344,9 @@ rm -rf -- "$TMPDIR_ARG"
348
344
  * dir. Returns the temp dir path (used as a completion marker — when it
349
345
  * disappears, distill is done).
350
346
  *
351
- * Used only by manual `/distill` on git-less, disabled, or legacy-embedded
352
- * vaults. Manual `/distill` with git + subdir layout + enabled takes the
353
- * worktree path. Auto-distill requires git + subdir layout unconditionally
354
- * (Phase C1).
347
+ * Used only by manual `/distill` on git-less or disabled vaults. Manual
348
+ * `/distill` with git + enabled takes the worktree path. Auto-distill
349
+ * requires git unconditionally (Phase C1).
355
350
  */
356
351
  export function spawnDistill(
357
352
  sessionFile: string,
@@ -378,12 +373,12 @@ export function spawnDistill(
378
373
  "bash",
379
374
  [
380
375
  "-c",
381
- LEGACY_SPAWN_SCRIPT,
376
+ TMPDIR_SPAWN_SCRIPT,
382
377
  "_",
383
378
  piBin,
384
379
  forkedFile,
385
380
  tmpDir,
386
- LEGACY_DISTILL_PROMPT,
381
+ TMPDIR_DISTILL_PROMPT,
387
382
  modelStr,
388
383
  ],
389
384
  {
@@ -464,6 +459,14 @@ export default function (pi: ExtensionAPI) {
464
459
  };
465
460
  let uiRef: DistillUIRef | null = null;
466
461
 
462
+ // Session liveness guard for timer callbacks. pi invalidates the ctx captured
463
+ // at session_start after session replacement/reload — but a setInterval
464
+ // callback already queued in the macrotask queue still fires after
465
+ // clearInterval() (JS semantics), so a tick can observe an invalidated ctx.
466
+ // session_shutdown handlers complete BEFORE invalidation (pi lifecycle), so
467
+ // flipping this flag there makes any queued tick a clean no-op (issue #84).
468
+ let sessionActive = false;
469
+
467
470
  pi.on("before_provider_request", (event) =>
468
471
  applyDistillPromptCacheKey(event.payload),
469
472
  );
@@ -501,16 +504,17 @@ export default function (pi: ExtensionAPI) {
501
504
  }
502
505
 
503
506
  pi.on("session_start", async (event, ctx) => {
507
+ // Arm the session liveness guard FIRST — before any early-return path — so
508
+ // a tick queued from a previous session can never observe a dead session
509
+ // while this one is starting (issue #84).
510
+ sessionActive = true;
511
+
504
512
  // Reset to default before any early-return paths below; the persisted state
505
513
  // (if any) is re-read further down when distill is enabled for the session.
506
514
  autoDistillSuppressed = false;
507
515
 
508
- let napkinVault: { configPath: string; contentPath: string };
509
- try {
510
- napkinVault = new Napkin(ctx.cwd).vault;
511
- } catch {
512
- return;
513
- }
516
+ const napkinVault = resolveDistillVault(ctx.cwd);
517
+ if (!napkinVault) return;
514
518
  const vaultConfigPath = napkinVault.configPath;
515
519
 
516
520
  let showStatus: boolean;
@@ -578,43 +582,24 @@ export default function (pi: ExtensionAPI) {
578
582
  },
579
583
  "fast",
580
584
  );
581
- if (setup.error === LEGACY_EMBEDDED_LAYOUT_ERROR) {
582
- // Legacy embedded layout (`~/.napkin/` with `config.json`
583
- // alongside notes, no `.napkin/` subdir). Worktree-based
584
- // concurrency requires the subdir layout so napkin's
585
- // `findVault` resolves cwd=worktree to the worktree itself.
586
- // README has the migration steps; point there instead of
587
- // duplicating them in the notify (keeps the notification
588
- // short enough to render cleanly in every UI surface). Skip
589
- // the structured per-finding render below so the same
590
- // condition doesn't fire two error notifies.
591
- setupFailed = true;
592
- if (ctx.hasUI) {
593
- ctx.ui.notify(
594
- "Auto-distill requires the subdir vault layout. See README for migration, or set distill.enabled: false in vault config.json.",
595
- "error",
596
- );
597
- }
598
- } else {
599
- // Surface every non-legacy finding through the structured
600
- // helper so fast-level error invariants (malformed gitignore
601
- // markers, invalid `config.json`) get the same notify
602
- // treatment as the full-level call sites and so auto-recovered
603
- // findings (gitignore install / migrate / reset) reach the user
604
- // here at session_start instead of at the first interval tick.
605
- const { hasErrors } = surfaceHealthFindings(ctx, setup.findings);
606
- setupFailed = !!setup.error || hasErrors;
607
-
608
- // Generic fail-soft errors (git init / add / commit /
609
- // scaffolding-write failures) populate `setup.error` but not
610
- // `findings`; surface the underlying message so the user knows
611
- // why setup aborted on this session.
612
- if (setup.error && ctx.hasUI) {
613
- ctx.ui.notify(
614
- `Auto-distill setup failed: ${setup.error}. Disabling auto-distill for this session.`,
615
- "error",
616
- );
617
- }
585
+ // Surface every finding through the structured
586
+ // helper so fast-level error invariants (malformed gitignore
587
+ // markers, invalid `config.json`) get the same notify
588
+ // treatment as the full-level call sites and so auto-recovered
589
+ // findings (gitignore install / migrate / reset) reach the user
590
+ // here at session_start instead of at the first interval tick.
591
+ const { hasErrors } = surfaceHealthFindings(ctx, setup.findings);
592
+ setupFailed = !!setup.error || hasErrors;
593
+
594
+ // Generic fail-soft errors (git init / add / commit /
595
+ // scaffolding-write failures) populate `setup.error` but not
596
+ // `findings`; surface the underlying message so the user knows
597
+ // why setup aborted on this session.
598
+ if (setup.error && ctx.hasUI) {
599
+ ctx.ui.notify(
600
+ `Auto-distill setup failed: ${setup.error}. Disabling auto-distill for this session.`,
601
+ "error",
602
+ );
618
603
  }
619
604
 
620
605
  // Initial-run onboarding notify carries scope context (file
@@ -709,19 +694,43 @@ export default function (pi: ExtensionAPI) {
709
694
 
710
695
  if (ctx.hasUI && showStatus) {
711
696
  countdownHandle = setInterval(() => {
712
- // `renderIdleStatus` self-guards against in-flight distills; when off
713
- // it paints `distill: off (session)` (pi dedupes identical status strings).
714
- renderIdleStatus();
697
+ // Queued tick after session replacement/reload must not touch
698
+ // `uiRef.ui` (stale ctx) — skip the countdown render entirely.
699
+ if (!sessionActive) return;
700
+ try {
701
+ // `renderIdleStatus` self-guards against in-flight distills; when
702
+ // off it paints `distill: off (session)` (pi dedupes identical
703
+ // status strings).
704
+ renderIdleStatus();
705
+ } catch (err) {
706
+ // A tick must never take down pi (same invariant as the
707
+ // auto-distill interval tick): any unexpected render error logs
708
+ // and is retried on the next countdown repaint.
709
+ console.error("[napkin-distill] countdown tick failed:", err);
710
+ }
715
711
  }, IDLE_STATUS_REPAINT_INTERVAL_MS);
716
712
  }
717
713
 
718
714
  intervalHandle = setInterval(() => {
715
+ if (!sessionActive) return; // queued tick after replacement/reload → clean no-op
719
716
  if (autoDistillSuppressed) return;
720
- runAutoDistill(ctx);
717
+ try {
718
+ runAutoDistill(ctx);
719
+ } catch (err) {
720
+ // A tick must never take down pi: any unexpected error (stale ctx,
721
+ // vault config, spawn) logs and is retried on the next tick.
722
+ console.error("[napkin-distill] auto-distill tick failed:", err);
723
+ }
721
724
  }, intervalMs);
722
725
  });
723
726
 
724
727
  pi.on("session_shutdown", async (event, ctx) => {
728
+ // Drop the liveness guard BEFORE clearing the timers — both are
729
+ // synchronous, so no window exists where a tick sees `sessionActive` true
730
+ // with cleared handles. A tick already queued in the macrotask queue
731
+ // becomes a clean no-op (issue #84).
732
+ sessionActive = false;
733
+
725
734
  if (countdownHandle) {
726
735
  clearInterval(countdownHandle);
727
736
  countdownHandle = null;
@@ -754,12 +763,7 @@ export default function (pi: ExtensionAPI) {
754
763
  // session_start — handler scope keeps closures small, and the cost of
755
764
  // one extra JSON parse at shutdown is negligible.
756
765
  try {
757
- let vaultInfo: { configPath: string; contentPath: string } | null = null;
758
- try {
759
- vaultInfo = new Napkin(ctx.cwd).vault;
760
- } catch {
761
- // No vault resolvable — skip spawn, proceed to final resets.
762
- }
766
+ const vaultInfo = resolveDistillVault(ctx.cwd);
763
767
  if (vaultInfo) {
764
768
  const { distill: config } = loadVaultConfig(vaultInfo.configPath);
765
769
  const sessionFile = ctx.sessionManager.getSessionFile?.();
@@ -875,7 +879,7 @@ export default function (pi: ExtensionAPI) {
875
879
  >;
876
880
 
877
881
  /**
878
- * Strategy bundle for the shared runner. Each caller (legacy or worktree)
882
+ * Strategy bundle for the shared runner. Each caller (tmpdir or worktree)
879
883
  * supplies a preflight check, a spawn invocation, a poll-completion
880
884
  * target, and a timeout cleanup step. Everything else (config load,
881
885
  * size dedup, status-bar painting, poll loop wiring, completion
@@ -884,7 +888,7 @@ export default function (pi: ExtensionAPI) {
884
888
  * All strategy callbacks receive `vaultContentPath` — the vault's content
885
889
  * root as resolved by napkin, NOT `ctx.cwd`. This is what makes the
886
890
  * whole auto-distill pipeline cwd-independent: worktrees, git, and the
887
- * legacy spawn all target the user's actual vault even when pi is
891
+ * tmpdir spawn all target the user's actual vault even when pi is
888
892
  * launched from another directory (napkin's findVault walks up from
889
893
  * `ctx.cwd` and falls back to the global config).
890
894
  */
@@ -930,9 +934,9 @@ export default function (pi: ExtensionAPI) {
930
934
  * but after creating its forensic log). Returns null on success.
931
935
  *
932
936
  * The runner uses the result to surface a UI failure on the
933
- * worktree path (mirrors the timeout-surfacing pattern). Legacy
934
- * spawn doesn't produce error logs in this shape — omit or
935
- * return null.
937
+ * worktree path (mirrors the timeout-surfacing pattern). The
938
+ * tmpdir spawn doesn't produce error logs in this shape — omit
939
+ * or return null.
936
940
  */
937
941
  checkFailure?: () => string | null;
938
942
  /**
@@ -944,8 +948,8 @@ export default function (pi: ExtensionAPI) {
944
948
  * Missing sidecar AND missing failure log = abnormal termination
945
949
  * (SIGKILL / `set -e` / disk full / race) — the runner surfaces
946
950
  * a warn-level notification per the locked notification severity
947
- * contract. Legacy spawn doesn't produce outcome sidecars — omit
948
- * or return null.
951
+ * contract. The tmpdir spawn doesn't produce outcome sidecars —
952
+ * omit or return null.
949
953
  */
950
954
  checkOutcome?: () => DistillOutcome | null;
951
955
  } | null;
@@ -1055,12 +1059,8 @@ export default function (pi: ExtensionAPI) {
1055
1059
  function runDistillWith(ctx: RunCtx, strategy: DistillStrategy): void {
1056
1060
  if (isRunning) return;
1057
1061
 
1058
- let vaultInfo: { configPath: string; contentPath: string };
1059
- try {
1060
- vaultInfo = new Napkin(ctx.cwd).vault;
1061
- } catch {
1062
- return;
1063
- }
1062
+ const vaultInfo = resolveDistillVault(ctx.cwd);
1063
+ if (!vaultInfo) return;
1064
1064
  const vaultContentPath = vaultInfo.contentPath;
1065
1065
 
1066
1066
  let showStatus: boolean;
@@ -1151,7 +1151,12 @@ export default function (pi: ExtensionAPI) {
1151
1151
  );
1152
1152
  }
1153
1153
 
1154
- pollHandle = setInterval(() => {
1154
+ // Poll body lives in its own closure function so the timer wrapper below
1155
+ // can guard it: queued stale ticks after session replacement/reload must
1156
+ // not touch ctx.ui / ctx.sessionManager NOR reset isRunning — shutdown
1157
+ // already cleared pollHandle and reset isRunning; the next session owns
1158
+ // them.
1159
+ const pollTick = (): void => {
1155
1160
  const elapsed = Math.floor((Date.now() - startTime) / 1000);
1156
1161
  const timedOut = Date.now() - startTime > getMaxDistillDurationMs(config);
1157
1162
 
@@ -1244,9 +1249,10 @@ export default function (pi: ExtensionAPI) {
1244
1249
  // `*.outcome` sidecar before any successful exit-0 path; the
1245
1250
  // class string drives the UI severity per the locked notification
1246
1251
  // severity contract. See `formatOutcomeNotification` for the
1247
- // full mapping. Strategies that don't produce sidecars (legacy
1248
- // /distill on git-less or disabled vaults) skip this entire
1249
- // dispatch and fall through to the default info notification.
1252
+ // full mapping. Strategies that don't produce sidecars (the
1253
+ // tmpdir `/distill` on git-less or disabled vaults) skip this
1254
+ // entire dispatch and fall through to the default info
1255
+ // notification.
1250
1256
  let outcome: DistillOutcome | null = null;
1251
1257
  if (checkOutcome) {
1252
1258
  try {
@@ -1281,47 +1287,48 @@ export default function (pi: ExtensionAPI) {
1281
1287
  }
1282
1288
  ctx.ui.notify(message, level);
1283
1289
  }
1290
+ };
1291
+
1292
+ pollHandle = setInterval(() => {
1293
+ // Queued stale tick after session replacement/reload → clean no-op.
1294
+ if (!sessionActive) return;
1295
+ try {
1296
+ pollTick();
1297
+ } catch (err) {
1298
+ // A tick must never take down pi (same invariant as the auto-distill
1299
+ // interval tick): in the cached-module reload window an old-session
1300
+ // tick can pass the re-armed guard and hit the stale ctx — log and
1301
+ // drop (the next session owns all poll state).
1302
+ console.error("[napkin-distill] distill poll tick failed:", err);
1303
+ }
1284
1304
  }, DISTILL_POLL_TICK_MS);
1285
1305
  }
1286
1306
 
1287
1307
  function runDistill(ctx: RunCtx) {
1288
1308
  // Manual `/distill` routing: use the worktree path only when the user
1289
- // has opted into auto-distill (`distill.enabled=true`), git is
1290
- // available, AND the vault uses the subdir layout. Otherwise fall
1291
- // back to the legacy tmpdir spawn, which has zero git side effects.
1309
+ // has opted into auto-distill (`distill.enabled=true`) and git is
1310
+ // available. Otherwise fall back to the tmpdir spawn, which has zero
1311
+ // git side effects.
1292
1312
  //
1293
1313
  // `distill.enabled=false` means the user opted out of auto-distill's
1294
1314
  // infrastructure (worktree-based concurrency, scaffolded `.gitignore`,
1295
- // session-fork housekeeping). Legacy path bypasses all of it.
1296
- //
1297
- // Legacy-embedded layout (`configPath === contentPath`) forces the
1298
- // same fallback: the worktree path silently corrupts on that layout
1299
- // because napkin's `findVault` from cwd=<worktree> walks past the
1300
- // worktree and resolves to the real `~/.napkin/` via global config
1301
- // fallback. Distill writes land on the real vault, worktree stays
1302
- // empty, concurrency guarantee degrades to zero. README covers the
1303
- // subdir migration; auto-distill refuses this layout at session_start.
1315
+ // session-fork housekeeping). The tmpdir path bypasses all of it.
1304
1316
  //
1305
- // Cross-session concurrency caveat: the legacy fallback has no
1306
- // worktree isolation — two concurrent `/distill` calls on a git-less,
1307
- // disabled, or legacy-embedded vault race on napkin writes. With
1308
- // git + enabled + subdir layout, both manual and auto paths serialize
1309
- // through per-distill worktrees, and the agent owns merge resolution
1310
- // end-to-end (PR #12).
1317
+ // Cross-session concurrency caveat: the tmpdir fallback has no
1318
+ // worktree isolation — two concurrent `/distill` calls on a git-less
1319
+ // or disabled vault race on napkin writes. With git + enabled, both
1320
+ // manual and auto paths serialize through per-distill worktrees, and
1321
+ // the agent owns merge resolution end-to-end (PR #12).
1311
1322
  runDistillWith(ctx, {
1312
1323
  spawnFn: (args) => {
1313
1324
  const gitPresent = fs.existsSync(
1314
1325
  path.join(args.vaultContentPath, ".git"),
1315
1326
  );
1316
- // Legacy-embedded detection matches the predicate in
1317
- // `ensureVaultReadyForDistill` (keep the two gates in lockstep).
1318
- const isLegacyEmbedded = args.vaultConfigPath === args.vaultContentPath;
1319
- if (gitPresent && args.config.enabled && !isLegacyEmbedded) {
1327
+ if (gitPresent && args.config.enabled) {
1320
1328
  // Full health-check before the worktree-based spawn. Surfaces
1321
1329
  // auto-recovered findings as info notifies; aborts the spawn
1322
1330
  // when any error finding fires (corrupt config, malformed
1323
- // gitignore markers, etc.). Legacy-embedded routing skips this
1324
- // entirely — those vaults are untouched by auto-distill.
1331
+ // gitignore markers, etc.).
1325
1332
  const setup = ensureVaultReadyForDistill(
1326
1333
  {
1327
1334
  contentPath: args.vaultContentPath,
@@ -1334,7 +1341,7 @@ export default function (pi: ExtensionAPI) {
1334
1341
  if (hasErrors || setup.error) return null;
1335
1342
  return worktreeSpawnFn(args);
1336
1343
  }
1337
- return legacySpawnFn(args);
1344
+ return tmpdirSpawnFn(args);
1338
1345
  },
1339
1346
  });
1340
1347
  }
@@ -1363,8 +1370,7 @@ export default function (pi: ExtensionAPI) {
1363
1370
  // Full health-check before each tick: rewires drift in the
1364
1371
  // managed gitignore block, re-emits structured findings, aborts
1365
1372
  // the spawn on any error finding (corrupt config, malformed
1366
- // markers). Auto-distill always uses the worktree path; the
1367
- // legacy-embedded route only exists for manual `/distill`.
1373
+ // markers). Auto-distill always uses the worktree path.
1368
1374
  const setup = ensureVaultReadyForDistill(
1369
1375
  {
1370
1376
  contentPath: args.vaultContentPath,
@@ -1381,7 +1387,7 @@ export default function (pi: ExtensionAPI) {
1381
1387
  }
1382
1388
 
1383
1389
  /**
1384
- * Legacy tmpdir spawn strategy. Forks the session under `$TMPDIR` and
1390
+ * Tmpdir spawn strategy. Forks the session under `$TMPDIR` and
1385
1391
  * runs `pi -p` detached; cleanup is a plain `rmSync`. No git, no
1386
1392
  * concurrency coordination. Only used by manual `/distill` as a
1387
1393
  * fallback for vaults without `.git/`.
@@ -1391,11 +1397,9 @@ export default function (pi: ExtensionAPI) {
1391
1397
  * (cwd-independent via `new Napkin(ctx.cwd).vault`). The distill
1392
1398
  * subprocess itself calls `napkin` commands that walk up from their
1393
1399
  * cwd, so targeting `vaultContentPath` ensures they hit the user's
1394
- * real vault regardless of where pi was originally launched. This
1395
- * matches the pre-worktree behavior where the session operated
1396
- * directly on the vault root — no isolation, napkin-from-cwd only.
1400
+ * real vault regardless of where pi was originally launched.
1397
1401
  */
1398
- function legacySpawnFn(args: {
1402
+ function tmpdirSpawnFn(args: {
1399
1403
  ctx: RunCtx;
1400
1404
  vaultContentPath: string;
1401
1405
  vaultConfigPath: string;
@@ -1486,7 +1490,10 @@ export default function (pi: ExtensionAPI) {
1486
1490
  // repaint.
1487
1491
  let showStatus = true;
1488
1492
  try {
1489
- ({ showStatus } = loadVaultConfig(new Napkin(c.cwd).vault.configPath));
1493
+ const cfgVault = resolveDistillVault(c.cwd);
1494
+ if (cfgVault) {
1495
+ ({ showStatus } = loadVaultConfig(cfgVault.configPath));
1496
+ }
1490
1497
  } catch (cfgErr) {
1491
1498
  if (cfgErr instanceof MalformedVaultConfigError && c.hasUI) {
1492
1499
  c.ui.notify(
@@ -1537,9 +1544,12 @@ export default function (pi: ExtensionAPI) {
1537
1544
  // Detect when distill is disabled in the vault config so we can warn that
1538
1545
  // toggling the session flag has no effect.
1539
1546
  let vaultDistillEnabled = false;
1547
+ const cfgVault = resolveDistillVault(ctx.cwd);
1540
1548
  try {
1541
- const vaultConfigPath = new Napkin(ctx.cwd).vault.configPath;
1542
- vaultDistillEnabled = loadVaultConfig(vaultConfigPath).distill.enabled;
1549
+ if (cfgVault) {
1550
+ vaultDistillEnabled = loadVaultConfig(cfgVault.configPath).distill
1551
+ .enabled;
1552
+ }
1543
1553
  } catch {
1544
1554
  // No vault — treat as disabled at vault level.
1545
1555
  }
@@ -1641,18 +1651,38 @@ export default function (pi: ExtensionAPI) {
1641
1651
  // ---------------------------------------------------------------------------
1642
1652
 
1643
1653
  /**
1644
- * Resolve the main vault path from a command `ctx`. Returns null when
1645
- * no vault can be resolved (ctx.cwd isn't inside a napkin vault) — callers
1646
- * surface a user-facing message in that case.
1654
+ * Resolve the distill vault handle from a cwd.
1655
+ *
1656
+ * Uses napkin's own resolution (`new Napkin(cwd).vault`, which
1657
+ * includes the global-config fallback). napkin >= 0.14 refuses
1658
+ * legacy-embedded layouts and missing/unreadable `config.json` with
1659
+ * `VaultNotFoundError`; distill supports exactly what napkin
1660
+ * resolves — a refused vault is treated as no vault (silent skip;
1661
+ * napkin's own CLI surfaces the refusal with migration guidance).
1662
+ *
1663
+ * Returns null when no vault can be resolved.
1647
1664
  */
1648
- function resolveVaultPath(cwd: string): string | null {
1665
+ function resolveDistillVault(cwd: string): {
1666
+ configPath: string;
1667
+ contentPath: string;
1668
+ } | null {
1649
1669
  try {
1650
- return new Napkin(cwd).vault.contentPath;
1670
+ const vault = new Napkin(cwd).vault;
1671
+ return { configPath: vault.configPath, contentPath: vault.contentPath };
1651
1672
  } catch {
1652
1673
  return null;
1653
1674
  }
1654
1675
  }
1655
1676
 
1677
+ /**
1678
+ * Resolve the main vault path from a command `ctx`. Returns null when
1679
+ * no vault can be resolved (ctx.cwd isn't inside a napkin vault) — callers
1680
+ * surface a user-facing message in that case.
1681
+ */
1682
+ function resolveVaultPath(cwd: string): string | null {
1683
+ return resolveDistillVault(cwd)?.contentPath ?? null;
1684
+ }
1685
+
1656
1686
  pi.registerCommand("distill-status", {
1657
1687
  description: "Show active auto-distill processes for the current vault",
1658
1688
  handler: async (_args, ctx) => {
@@ -0,0 +1,90 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Part of pi-napkin.
3
+
4
+ import type { Plugin, PredicateShape } from "@cad0p/pi-steering";
5
+ import { isNapkinVault, isNapkinVaultDir } from "./predicates.ts";
6
+
7
+ declare global {
8
+ /**
9
+ * `when.isNapkinVault` — true when the effective cwd is inside a
10
+ * napkin vault (read-only `.napkin/`-marker walk-up). Registered
11
+ * by the napkin steering plugin; usable by any config that lists
12
+ * the plugin. Fail-closed: unknown cwd → `"unknown"` sentinel.
13
+ */
14
+ interface PiSteeringPredicates {
15
+ isNapkinVault: PredicateShape<boolean>;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * The napkin steering plugin for `@cad0p/pi-steering`.
21
+ *
22
+ * Subpath import: `@cad0p/pi-napkin/steering`.
23
+ *
24
+ * Registers (in the terms of `Plugin`):
25
+ *
26
+ * - `predicates` - `isNapkinVault` (see `./predicates.ts` for
27
+ * the fail-closed contract).
28
+ * - `exemptions` - carve-outs of the shipped git-plugin rules
29
+ * `no-main-commit` / `no-main-commit-github`
30
+ * when `when.isNapkinVault` matches. The
31
+ * napkin workflow legitimately commits +
32
+ * pushes to `main` inside vaults (note edits,
33
+ * the distill pipeline's scratch worktrees),
34
+ * so the guards stay ACTIVE everywhere else.
35
+ *
36
+ * This is the clean replacement for the hand-rolled global
37
+ * carve-out pattern (`...rule, not: { cwd: VAULT_DIRS }` copies +
38
+ * `disabledRules`), which did NOT compose across plugins: exemptions
39
+ * ACCUMULATE (union) across plugins and config layers, and target
40
+ * the shipped rule names — a stable public contract — so other tools
41
+ * can carve the same guards for other repo types without touching
42
+ * this plugin.
43
+ *
44
+ * Exemption clauses are STRICTLY fail-closed: `onUnknown` cannot be
45
+ * written anywhere inside them (type-level ban + load-time
46
+ * rejection), and unknown walker cwd never exempts — the target
47
+ * rule's own `onUnknown:` policy decides, so the guard still fires
48
+ * on an unresolvable cwd.
49
+ *
50
+ * No pi extension runtime involved: this module is a plain library
51
+ * with a single non-builtin runtime import (`@cad0p/napkin`, itself
52
+ * a plain library shipping compiled dist JS — all pi-steering
53
+ * imports are type-only and erased by node's type stripping), so
54
+ * the steering global config can import it without pi being
55
+ * involved.
56
+ *
57
+ * Opt-in: nothing happens until the user lists this plugin next to
58
+ * the git plugin:
59
+ *
60
+ * ```ts
61
+ * import { defineConfig } from "@cad0p/pi-steering";
62
+ * import gitPlugin from "@cad0p/pi-steering/plugins/git";
63
+ * import napkinSteeringPlugin from "@cad0p/pi-napkin/steering";
64
+ *
65
+ * export default defineConfig({
66
+ * plugins: [gitPlugin, napkinSteeringPlugin],
67
+ * });
68
+ * ```
69
+ *
70
+ * `gitPlugin` MUST be listed alongside: the exemptions target its
71
+ * rule names, and a missing target surfaces `exemption-orphan`
72
+ * warnings with no carve-out.
73
+ */
74
+ const napkinSteeringPlugin = {
75
+ name: "napkin",
76
+ predicates: {
77
+ isNapkinVault,
78
+ },
79
+ exemptions: [
80
+ { rule: "no-main-commit", when: { isNapkinVault: true } },
81
+ { rule: "no-main-commit-github", when: { isNapkinVault: true } },
82
+ ],
83
+ } as const satisfies Plugin;
84
+
85
+ export default napkinSteeringPlugin;
86
+
87
+ // Named re-exports for consumers that want to pick pieces (e.g. a
88
+ // test harness constructing a minimal config that uses only the
89
+ // predicate without the shipped exemptions).
90
+ export { isNapkinVault, isNapkinVaultDir, napkinSteeringPlugin };
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Part of pi-napkin.
3
+
4
+ import { findAncestorVault } from "@cad0p/napkin";
5
+ import type { PredicateContext } from "@cad0p/pi-steering";
6
+
7
+ /**
8
+ * Back-compat alias for napkin's canonical vault walk.
9
+ *
10
+ * The canonical implementation lives in napkin (`findAncestorVault`):
11
+ * a purely structural walk-up looking for the `.napkin/` marker (or
12
+ * `.obsidian/.napkin/` for the nested layout) at any level — no
13
+ * global-config fallback, no writes. Identical semantics to the
14
+ * mirror this package previously shipped, so the steering plugin's
15
+ * fail-closed posture is unchanged (a read-only probe that can
16
+ * never make an arbitrary cwd look like a vault). The alias
17
+ * preserves the public export name the global steering config
18
+ * imports (`isNapkinVaultDir` from `@cad0p/pi-napkin/steering`).
19
+ */
20
+ export const isNapkinVaultDir = findAncestorVault;
21
+
22
+ /**
23
+ * `isNapkinVault` predicate handler — registered by the napkin
24
+ * steering plugin under the `when.isNapkinVault` slot
25
+ * (`PredicateShape<boolean>` bare form).
26
+ *
27
+ * Fail-closed contract:
28
+ *
29
+ * - `args !== true` → `false` (only the bare `true` form asks for
30
+ * the check; the spread `{ value: ... }` form is not meaningful
31
+ * for this boolean probe).
32
+ * - `ctx.cwd === "unknown"` (walker couldn't statically resolve
33
+ * the effective cwd) → returns the `"unknown"` sentinel, NOT
34
+ * `false`. Unknown cwd is not the same as "not a vault", and the
35
+ * trinary composes with the rule's own `onUnknown:` policy when
36
+ * the predicate is used as a public `when` leaf. Inside an
37
+ * exemption clause both verdicts behave identically — exemption
38
+ * clauses are STRICTLY fail-closed (anything non-true = no
39
+ * exemption = the guard still fires), so this can never weaken
40
+ * `no-main-commit` / `no-main-commit-github`.
41
+ * - Known cwd → read-only walk-up for the `.napkin/` marker
42
+ * (see {@link isNapkinVaultDir}). No writes, no global-config
43
+ * fallback.
44
+ */
45
+ export function isNapkinVault(
46
+ args: unknown,
47
+ ctx: PredicateContext,
48
+ ): boolean | "unknown" {
49
+ if (args !== true) return false;
50
+ if (ctx.cwd === "unknown") return "unknown";
51
+ return isNapkinVaultDir(ctx.cwd) !== null;
52
+ }