@cad0p/pi-napkin 0.7.2 → 0.7.3-20261004.0

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.
package/README.md CHANGED
@@ -333,9 +333,9 @@ Successful distill lifecycles produce exactly one squash commit on `main`, with
333
333
  When a background distill completes a squash-merge that touches files you've also written this session, pi-napkin posts a one-line notice into the conversation as a custom session message so the agent knows its recent writes may have been merged or overwritten:
334
334
 
335
335
  ```
336
- ⚠️ Background napkin distill is editing files you've also touched: notes/foo.md.
337
- Recent writes to these files may be overwritten or merged automatically at distill
338
- completion; consider re-reading before further edits.
336
+ ⚠️ Background napkin distill has edited files you've also touched: notes/foo.md.
337
+ Recent writes to these files may have been overwritten or merged; re-read before
338
+ further edits.
339
339
  ```
340
340
 
341
341
  Key properties:
@@ -374,6 +374,8 @@ If your vault IS already a git repo (common for "vault as project"), pi-napkin j
374
374
 
375
375
  Every time pi starts a session in an auto-distill-enabled vault, pi-napkin runs a **health check** that confirms the vault is in a state the worktree-based distill can actually run against. The check is layered into two cadences so the cost of routine checks stays near-zero while the rare expensive checks only fire on the manual `/distill` path.
376
376
 
377
+ The full check also verifies that the [`napkin` CLI](#install) is resolvable and runnable on PATH, because the worktree wrapper installs a per-distill shim that shells out to it. If the CLI is missing, session start injects a `<napkin-distill-setup>` notice into the agent context (alongside the vault-context block) with the exact install command, so an agent can repair the prerequisite on its next turn; every full-level health check (interval tick, shutdown, manual `/distill`) additionally smoke-tests the binary with `napkin --version` and, if it is missing or broken, surfaces a loud error and refuses to spawn the wrapper.
378
+
377
379
  ### The managed `.gitignore` block
378
380
 
379
381
  pi-napkin owns a single contiguous block in the vault's `.gitignore`, delimited by these exact marker lines:
@@ -524,6 +526,8 @@ Exits 0 on PASS, 1 on FAIL. Manual-only — not in CI; cost is roughly $0.50 per
524
526
 
525
527
  This replaces the earlier prompt-only gate. The strict superset matters because the wrapper↔JS-poller seam — where worktree-teardown and outcome-write race — is invisible to a prompt-only harness.
526
528
 
529
+ For the full change-class checklist — including the session forge/replay procedure for LLM-facing text changes — see [`docs/verification.md`](docs/verification.md).
530
+
527
531
  ## Future: builder-deleter
528
532
 
529
533
  Next major feature: a "builder-deleter" janitor that acts on the `supersedes:` frontmatter convention that auto-distill already writes. When a note lists `supersedes: ["old/note.md"]`, the janitor archives the superseded file. Threshold-triggered to avoid running on every distill, git gc as the safety net. Design pending.
@@ -283,6 +283,13 @@ export interface SetupOptions {
283
283
  * race the real `Date.now()`.
284
284
  */
285
285
  now?: () => number;
286
+ /**
287
+ * Probe whether the `napkin` CLI is resolvable and runnable on PATH.
288
+ * Defaults to {@link probeNapkinCli}. Tests inject a stub to pin the
289
+ * `napkin-cli-available` loud-error path without depending on the
290
+ * ambient PATH (which contains a real `napkin` under `pnpm`).
291
+ */
292
+ probeNapkin?: (options: { smokeTest: boolean }) => NapkinCliProbeResult;
286
293
  }
287
294
 
288
295
  /**
@@ -382,6 +389,15 @@ const INVARIANT_NAPKIN_DISTILL_NOT_TRACKED = "napkin-distill-not-tracked";
382
389
  */
383
390
  const INVARIANT_CACHE_ROOT_WRITABLE = "cache-root-writable";
384
391
 
392
+ /**
393
+ * Stable invariant ID for the `napkin` CLI availability check. The
394
+ * worktree wrapper installs a per-distill napkin shim and smoke-tests
395
+ * `napkin --version` before the agent runs; a missing or unrunnable
396
+ * CLI fails every distill before any content is produced. Loud-error:
397
+ * the user must install the CLI (no safe auto-recovery here).
398
+ */
399
+ const INVARIANT_NAPKIN_CLI_AVAILABLE = "napkin-cli-available";
400
+
385
401
  /**
386
402
  * Stable invariant ID for the vault HEAD pointing at a real commit.
387
403
  * Auto-recovered by seeding an empty initial commit when the vault
@@ -670,6 +686,116 @@ export function probeWritable(dir: string): WritableProbeResult {
670
686
  return { writable: true };
671
687
  }
672
688
 
689
+ /**
690
+ * Result of {@link probeNapkinCli}.
691
+ *
692
+ * `ok: true` is the healthy path; `ok: false` carries a short
693
+ * human-readable `error` suitable for embedding in a loud-error
694
+ * finding. `path` is the resolved binary path whenever PATH resolution
695
+ * succeeded, even if the smoke test then failed — so diagnostics can
696
+ * tell "not installed" apart from "installed but broken".
697
+ */
698
+ export interface NapkinCliProbeResult {
699
+ ok: boolean;
700
+ path?: string;
701
+ version?: string;
702
+ error?: string;
703
+ }
704
+
705
+ /**
706
+ * Timeout for the `napkin --version` smoke test. The CLI is a Node
707
+ * program; a healthy cold start is well under a second. A longer
708
+ * budget would stall the full-level health check (and therefore the
709
+ * distill spawn) on a hung binary without trading for real
710
+ * reliability. The timeout escalates straight to SIGKILL because
711
+ * `spawnSync` only sends `killSignal` once and waits — the default
712
+ * SIGTERM is trappable, which would let a hung binary block pi's main
713
+ * thread indefinitely.
714
+ */
715
+ const NAPKIN_CLI_PROBE_TIMEOUT_MS = 5_000;
716
+
717
+ /**
718
+ * Resolve `name` against the PATH in `env` without spawning a child
719
+ * process. Returns the first candidate that is an executable regular
720
+ * file, or `null`.
721
+ *
722
+ * `fs.accessSync(X_OK)` also succeeds for directories, so the
723
+ * `isFile()` guard is load-bearing: a `node_modules/.bin`-style
724
+ * directory named `napkin` must not shadow a real binary later in
725
+ * PATH. Symlinks are followed (`statSync` semantics) — the same
726
+ * behavior a POSIX shell's path search has. Empty PATH entries (which
727
+ * a POSIX shell treats as the current directory) are skipped: a
728
+ * vault-controlled `./napkin` is not a supported install layout.
729
+ */
730
+ export function resolveExecutableOnPath(
731
+ name: string,
732
+ env: NodeJS.ProcessEnv = process.env,
733
+ ): string | null {
734
+ const pathValue = env.PATH ?? "";
735
+ for (const dir of pathValue.split(path.delimiter)) {
736
+ if (dir.length === 0) continue;
737
+ const candidate = path.join(dir, name);
738
+ let stat: fs.Stats;
739
+ try {
740
+ stat = fs.statSync(candidate);
741
+ } catch {
742
+ continue;
743
+ }
744
+ if (!stat.isFile()) continue;
745
+ try {
746
+ fs.accessSync(candidate, fs.constants.X_OK);
747
+ } catch {
748
+ continue;
749
+ }
750
+ return candidate;
751
+ }
752
+ return null;
753
+ }
754
+
755
+ /**
756
+ * Probe that the `napkin` CLI is available to the distill wrapper.
757
+ *
758
+ * `smokeTest: false` only resolves the binary on PATH (sub-millisecond;
759
+ * used by the session-start LLM notice). The default `smokeTest: true`
760
+ * additionally spawns `napkin --version`, mirroring the wrapper's own
761
+ * smoke test so the full-level health check agrees with what the
762
+ * wrapper will do.
763
+ *
764
+ * Never throws: spawn failures are translated into `ok: false` +
765
+ * `error` so callers can surface a structured finding.
766
+ */
767
+ export function probeNapkinCli(
768
+ options: { smokeTest?: boolean; env?: NodeJS.ProcessEnv } = {},
769
+ ): NapkinCliProbeResult {
770
+ const env = options.env ?? process.env;
771
+ const resolved = resolveExecutableOnPath("napkin", env);
772
+ if (!resolved) {
773
+ return { ok: false, error: "not found on PATH" };
774
+ }
775
+ if (options.smokeTest === false) {
776
+ return { ok: true, path: resolved };
777
+ }
778
+ const r = spawnSync("napkin", ["--version"], {
779
+ encoding: "utf-8",
780
+ timeout: NAPKIN_CLI_PROBE_TIMEOUT_MS,
781
+ killSignal: "SIGKILL",
782
+ env,
783
+ });
784
+ if (r.error) {
785
+ return { ok: false, path: resolved, error: r.error.message };
786
+ }
787
+ if (r.status !== 0) {
788
+ const detail = (r.stderr || "").trim();
789
+ return {
790
+ ok: false,
791
+ path: resolved,
792
+ error:
793
+ detail.length > 0 ? detail : `\`napkin --version\` exited ${r.status}`,
794
+ };
795
+ }
796
+ return { ok: true, path: resolved, version: (r.stdout || "").trim() };
797
+ }
798
+
673
799
  /**
674
800
  * Internal result of {@link mergeManagedBlock}.
675
801
  *
@@ -921,12 +1047,19 @@ function mergeManagedBlock(
921
1047
  * read-only cache root would fail the worktree spawn at
922
1048
  * `mkdir -p`; surfacing here gives the user a fixable error
923
1049
  * before any git work commits to a worktree.
924
- * 7. fast + full: if anything in steps 1–3 changed:
1050
+ * 7. full only: probe that the `napkin` CLI is resolvable AND
1051
+ * runnable on PATH via {@link probeNapkinCli}
1052
+ * (`napkin-cli-available`, loud-error). The worktree wrapper
1053
+ * installs a per-distill napkin shim and smoke-tests
1054
+ * `napkin --version` before the agent runs; failing here gives
1055
+ * the user one actionable install command instead of a stream
1056
+ * of failed distill logs.
1057
+ * 8. fast + full: if anything in steps 1–3 changed:
925
1058
  * - fresh init -> `git add .` + commit `"napkin: initial vault
926
1059
  * commit (auto-distill setup)"`
927
1060
  * - existing repo with scaffolded changes -> `git add ...scaffolded`
928
1061
  * + commit `"napkin: scaffold auto-distill git config"`
929
- * 8. full only: ensure HEAD resolves to a commit; seed an empty
1062
+ * 9. full only: ensure HEAD resolves to a commit; seed an empty
930
1063
  * initial commit when an existing-but-empty repo would leave
931
1064
  * `git worktree add HEAD` unable to pin a ref
932
1065
  * (`vault-head-on-branch`, auto-recovered). Fast-level skips
@@ -934,12 +1067,12 @@ function mergeManagedBlock(
934
1067
  * seed an unsolicited commit; the next full-level call (tick,
935
1068
  * shutdown, or manual `/distill`) seeds lazily when a worktree
936
1069
  * spawn is imminent.
937
- * 9. full only: prune orphaned distill worktree registry entries
1070
+ * 10. full only: prune orphaned distill worktree registry entries
938
1071
  * via `git worktree prune --expire=now`
939
1072
  * (`no-orphaned-distill-worktrees`, auto-recovered). Cleans up
940
1073
  * registry entries whose worktree directories were removed
941
1074
  * (typically a crashed pi session) so they don't accumulate.
942
- * 10. full only: delete `distill/*` branches whose committerdate is
1075
+ * 11. full only: delete `distill/*` branches whose committerdate is
943
1076
  * older than {@link STALE_DISTILL_BRANCH_GRACE_MS} AND have no
944
1077
  * live worktree (`no-stale-distill-branches-over-grace`,
945
1078
  * auto-recovered). The grace gives the user a `git reflog`
@@ -1140,6 +1273,24 @@ export function ensureVaultReadyForDistill(
1140
1273
  message: `Cache root parent ${probeDir} is not writable: ${probeResult.error ?? "unknown error"}. Set XDG_CACHE_HOME to a writable directory or fix the permissions.`,
1141
1274
  });
1142
1275
  }
1276
+
1277
+ // The worktree wrapper installs a per-distill `napkin` shim and
1278
+ // smoke-tests the binary with `napkin --version` before the agent
1279
+ // runs; a missing or unrunnable CLI fails every distill before any
1280
+ // content is produced. Surface it as a hard error here so the user
1281
+ // gets one actionable install command instead of a stream of
1282
+ // failed distill logs. The session-start path additionally injects
1283
+ // the same failure into LLM context via `setup-notice.ts` so an
1284
+ // agent can self-heal on its next turn.
1285
+ const probeNapkin = options.probeNapkin ?? probeNapkinCli;
1286
+ const napkinProbe = probeNapkin({ smokeTest: true });
1287
+ if (!napkinProbe.ok) {
1288
+ findings.push({
1289
+ kind: "error",
1290
+ invariant: INVARIANT_NAPKIN_CLI_AVAILABLE,
1291
+ message: `The \`napkin\` CLI is required for auto-distill but is not runnable: ${napkinProbe.error ?? "unknown error"}. Install it with \`npm install -g @cad0p/napkin\` (or \`pnpm add -g @cad0p/napkin\`), then re-run the distill.`,
1292
+ });
1293
+ }
1143
1294
  }
1144
1295
 
1145
1296
  if (initialized) {
@@ -13,7 +13,11 @@ 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 { countTrackedFiles, ensureVaultReadyForDistill } from "./auto-setup";
16
+ import {
17
+ countTrackedFiles,
18
+ ensureVaultReadyForDistill,
19
+ probeNapkinCli,
20
+ } from "./auto-setup";
17
21
  import {
18
22
  type ActiveDistill,
19
23
  cleanupDistillWorkspace,
@@ -30,6 +34,7 @@ import {
30
34
  } from "./distill-workspace";
31
35
  import { surfaceHealthFindings, surfaceSetupError } from "./health-notify";
32
36
  import { getSessionTouchedFiles } from "./session-touched-files";
37
+ import { maybeInjectNapkinSetupNotice } from "./setup-notice";
33
38
  import { shouldDistillOnShutdown } from "./should-distill-on-shutdown";
34
39
 
35
40
  /**
@@ -463,9 +468,38 @@ export default function (pi: ExtensionAPI) {
463
468
  // at session_start after session replacement/reload — but a setInterval
464
469
  // callback already queued in the macrotask queue still fires after
465
470
  // 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).
471
+ // On every TUI-side teardown path, session_shutdown handlers complete
472
+ // BEFORE invalidation (pi lifecycle), so flipping this flag there makes any
473
+ // queued tick a clean no-op (issue #84). CAVEAT (issue #100): this ordering
474
+ // is NOT universal — a raw AgentSession.dispose() from an SDK/host consumer
475
+ // invalidates the runner WITHOUT emitting session_shutdown, which is why
476
+ // session_start below also refuses to arm timers for non-interactive or
477
+ // session-less sessions at all.
468
478
  let sessionActive = false;
479
+ // Session generation (issue #93): incremented at every session_start. Each
480
+ // timer captures the generation at ARM time; a queued tick from an earlier
481
+ // session that fires after the next session_start re-armed `sessionActive`
482
+ // sees a mismatch and returns BEFORE touching its (invalidated) ctx — a
483
+ // clean no-op instead of the stale-ctx throw + `tick failed` log that #84's
484
+ // try/catch could only downgrade, not prevent.
485
+ //
486
+ // A stale ctx reaches a tick via two paths: (a) legit replacement/reload,
487
+ // where the old session's already-queued tick outruns its own shutdown
488
+ // handler, and (b) raw AgentSession.dispose() from SDK/host consumers
489
+ // (issue #100), where NO session_shutdown ever fires for the disposed
490
+ // session. Path (b) is closed upstream by the arm gate in session_start;
491
+ // this guard remains the backstop for queued ticks around either path.
492
+ let sessionGeneration = 0;
493
+ // Stale-ctx lockdown (issue #96): if a tick ever catches the stale-ctx
494
+ // error (the session_start's ctx was invalidated without the matching
495
+ // session_shutdown clearing this closure's timers — e.g. a raw
496
+ // AgentSession.dispose() from an SDK/host consumer skips the shutdown
497
+ // event entirely (issue #100); the #84/#93 guards cannot see it because
498
+ // they key off events this closure never received), the interval would
499
+ // otherwise throw + log on EVERY tick forever. On first detection we
500
+ // disarm the auto interval and log
501
+ // once; a later session_start re-arms everything cleanly.
502
+ let staleCtxDisarmed = false;
469
503
 
470
504
  pi.on("before_provider_request", (event) =>
471
505
  applyDistillPromptCacheKey(event.payload),
@@ -503,15 +537,62 @@ export default function (pi: ExtensionAPI) {
503
537
  : `${secs}s`;
504
538
  }
505
539
 
540
+ /**
541
+ * True when `err` is pi's stale-ctx error (the ctx captured at
542
+ * session_start was invalidated by a session replacement/reload).
543
+ * Matched by the message pi's ExtensionRunner throws — deliberately
544
+ * substring-based so it survives minor wording drift and stays
545
+ * independent of the internal stack frames.
546
+ */
547
+ function isStaleCtxError(err: unknown): boolean {
548
+ return (
549
+ err instanceof Error &&
550
+ err.message.includes("stale after session replacement")
551
+ );
552
+ }
553
+
554
+ /**
555
+ * One-time stale-ctx lockdown (issue #96). If a tick catches the
556
+ * stale-ctx error, the closure's session_start ctx is dead and the
557
+ * #84/#93 event-keyed guards can't see it (the matching
558
+ * session_shutdown never reached this closure — most commonly because
559
+ * an SDK/host consumer tore the session down via a raw
560
+ * AgentSession.dispose(), which invalidates the runner WITHOUT emitting
561
+ * session_shutdown, issue #100). The interval would otherwise throw +
562
+ * log on EVERY tick until the next session_start. Disarm the auto
563
+ * interval on first detection and log once; the next session_start
564
+ * clears the flag and re-arms cleanly.
565
+ */
566
+ function handleStaleCtxInTick(kind: "auto" | "poll" | "countdown"): void {
567
+ if (staleCtxDisarmed) return;
568
+ staleCtxDisarmed = true;
569
+ if (intervalHandle) {
570
+ clearInterval(intervalHandle);
571
+ intervalHandle = null;
572
+ }
573
+ console.error(
574
+ `[napkin-distill] ${kind} tick hit a stale session ctx; auto-distill disarmed until the next session_start (raw AgentSession.dispose() from an SDK/host consumer skipped session_shutdown)`,
575
+ );
576
+ }
577
+
506
578
  pi.on("session_start", async (event, ctx) => {
507
579
  // Arm the session liveness guard FIRST — before any early-return path — so
508
580
  // a tick queued from a previous session can never observe a dead session
509
581
  // while this one is starting (issue #84).
510
582
  sessionActive = true;
583
+ // Increment the session generation BEFORE any early return (issue #93): a
584
+ // previous session's tick already queued in the macrotask queue must see
585
+ // a generation mismatch even when this session_start bails on vault/
586
+ // config below.
587
+ sessionGeneration += 1;
511
588
 
512
589
  // Reset to default before any early-return paths below; the persisted state
513
590
  // (if any) is re-read further down when distill is enabled for the session.
514
591
  autoDistillSuppressed = false;
592
+ // A fresh session_start means this closure has a live session again —
593
+ // clear the stale-ctx lockdown so the new session's timers can run
594
+ // (issue #96).
595
+ staleCtxDisarmed = false;
515
596
 
516
597
  const napkinVault = resolveDistillVault(ctx.cwd);
517
598
  if (!napkinVault) return;
@@ -627,6 +708,30 @@ export default function (pi: ExtensionAPI) {
627
708
  console.error("[napkin-distill] auto-setup threw:", err);
628
709
  }
629
710
 
711
+ // LLM-visible prerequisite notice: `surfaceHealthFindings` above is
712
+ // TUI-only. When the `napkin` CLI is missing, also inject a custom
713
+ // message into session context so the agent can repair it on its next
714
+ // turn (the full-level gate blocks the wrapper spawn until then).
715
+ // The resolution-only probe keeps session_start latency low, and the
716
+ // notice is deliberately NOT folded into `setupFailed` — auto-distill
717
+ // stays armed, so installing the CLI mid-session repairs the next
718
+ // tick without a pi restart.
719
+ maybeInjectNapkinSetupNotice({
720
+ poster: pi,
721
+ sm: ctx.sessionManager as Partial<SessionManager>,
722
+ probe: probeNapkinCli({ smokeTest: false }),
723
+ onFallbackFailure: (err) => {
724
+ if (ctx.hasUI) {
725
+ ctx.ui.notify(
726
+ `napkin-distill: could not inject the missing-napkin setup notice (${
727
+ err instanceof Error ? err.message : String(err)
728
+ })`,
729
+ "warning",
730
+ );
731
+ }
732
+ },
733
+ });
734
+
630
735
  // Sweep out stale distill worktrees left behind by crashed pi sessions.
631
736
  // Idempotent, best-effort — never throws, never blocks session_start.
632
737
  try {
@@ -666,6 +771,11 @@ export default function (pi: ExtensionAPI) {
666
771
  // accessor), leave the cursor at its prior value (0 on first
667
772
  // session_start).
668
773
  }
774
+ // Sidechain/SDK sessions bind no UI (ctx.hasUI === false); ephemeral runs
775
+ // (--no-session) have no session file to fork. Nothing can ever be distilled:
776
+ // arm nothing, paint nothing.
777
+ if (!ctx.hasUI || !ctx.sessionManager.getSessionFile()) return;
778
+
669
779
  const intervalMs = config.intervalMinutes * 60 * 1000;
670
780
 
671
781
  uiRef = { hasUI: ctx.hasUI, ui: ctx.ui, showStatus, intervalMs };
@@ -692,11 +802,20 @@ export default function (pi: ExtensionAPI) {
692
802
  );
693
803
  }
694
804
 
805
+ // Generation seen by the timers armed by THIS session_start. A queued
806
+ // tick from an earlier session that fires after the next session_start
807
+ // re-armed the flag sees a mismatch and no-ops (issue #93).
808
+ const armedGeneration = sessionGeneration;
809
+
695
810
  if (ctx.hasUI && showStatus) {
696
811
  countdownHandle = setInterval(() => {
697
- // Queued tick after session replacement/reload must not touch
698
- // `uiRef.ui` (stale ctx) — skip the countdown render entirely.
812
+ // Queued tick from a dead session must not touch `uiRef.ui`
813
+ // (stale ctx): either a replacement/reload where the tick outran
814
+ // its own shutdown handler, or a raw-dispose SDK session whose
815
+ // shutdown never fired at all (issue #100). Skip the countdown
816
+ // render entirely.
699
817
  if (!sessionActive) return;
818
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
700
819
  try {
701
820
  // `renderIdleStatus` self-guards against in-flight distills; when
702
821
  // off it paints `distill: off (session)` (pi dedupes identical
@@ -705,21 +824,40 @@ export default function (pi: ExtensionAPI) {
705
824
  } catch (err) {
706
825
  // A tick must never take down pi (same invariant as the
707
826
  // 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);
827
+ // and is retried on the next countdown repaint. A stale-ctx
828
+ // error means the session was replaced under us — disarm once
829
+ // instead of spamming (issue #96).
830
+ if (isStaleCtxError(err)) {
831
+ handleStaleCtxInTick("countdown");
832
+ } else {
833
+ console.error("[napkin-distill] countdown tick failed:", err);
834
+ }
710
835
  }
711
836
  }, IDLE_STATUS_REPAINT_INTERVAL_MS);
712
837
  }
713
838
 
714
839
  intervalHandle = setInterval(() => {
715
- if (!sessionActive) return; // queued tick after replacement/reload → clean no-op
840
+ // Queued tick from a dead session (replacement/reload, or a
841
+ // raw-dispose SDK session whose shutdown never fired — issue #100)
842
+ // → clean no-op.
843
+ if (!sessionActive) return;
844
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
716
845
  if (autoDistillSuppressed) return;
717
846
  try {
718
847
  runAutoDistill(ctx);
719
848
  } catch (err) {
720
849
  // 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);
850
+ // vault config, spawn) logs and is retried on the next tick. A
851
+ // stale-ctx error means this closure's session died without its
852
+ // shutdown reaching us — a replacement/reload racing the handler,
853
+ // or a raw AgentSession.dispose() from an SDK/host consumer, which
854
+ // never emits session_shutdown at all (issue #100). Disarm once
855
+ // instead of throwing+logging on every tick (issue #96).
856
+ if (isStaleCtxError(err)) {
857
+ handleStaleCtxInTick("auto");
858
+ } else {
859
+ console.error("[napkin-distill] auto-distill tick failed:", err);
860
+ }
723
861
  }
724
862
  }, intervalMs);
725
863
  });
@@ -1289,17 +1427,27 @@ export default function (pi: ExtensionAPI) {
1289
1427
  }
1290
1428
  };
1291
1429
 
1430
+ // Capture the generation at ARM time so a queued poll tick from an
1431
+ // earlier session that fires after the next session_start re-armed the
1432
+ // flag no-ops before touching its stale ctx (issue #93).
1433
+ const armedGeneration = sessionGeneration;
1292
1434
  pollHandle = setInterval(() => {
1293
1435
  // Queued stale tick after session replacement/reload → clean no-op.
1294
1436
  if (!sessionActive) return;
1437
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
1295
1438
  try {
1296
1439
  pollTick();
1297
1440
  } catch (err) {
1298
1441
  // A tick must never take down pi (same invariant as the auto-distill
1299
1442
  // interval tick): in the cached-module reload window an old-session
1300
1443
  // 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);
1444
+ // drop (the next session owns all poll state). A stale-ctx error
1445
+ // disarms the auto interval once instead of spamming (issue #96).
1446
+ if (isStaleCtxError(err)) {
1447
+ handleStaleCtxInTick("poll");
1448
+ } else {
1449
+ console.error("[napkin-distill] distill poll tick failed:", err);
1450
+ }
1303
1451
  }
1304
1452
  }, DISTILL_POLL_TICK_MS);
1305
1453
  }
@@ -1830,15 +1978,20 @@ export function intersectFiles(
1830
1978
  * session history and forks cleanly into distill subprocess sessions.
1831
1979
  * Cache parity is preserved unconditionally vs the previous per-turn
1832
1980
  * `appendSystemPrompt` mechanism.
1981
+ *
1982
+ * Wording is past tense ("has edited … may have been overwritten"): this
1983
+ * notice is only posted from `onComplete`, after the wrapper's squash-merge
1984
+ * has landed and the worktree is gone (see `postOverlapNoticeOnCompletion`).
1985
+ * Present tense previously misled agents into waiting on an already-finished
1986
+ * distill (issue #104).
1833
1987
  */
1834
1988
  export function formatOverlapNotice(overlapFiles: string[]): string {
1835
1989
  if (overlapFiles.length === 0) return "";
1836
1990
  const list = overlapFiles.join(", ");
1837
1991
  return (
1838
- "\n\n\u26a0\ufe0f Background napkin distill is editing files you've also " +
1839
- `touched: ${list}. Recent writes to these files may be overwritten or ` +
1840
- "merged automatically at distill completion; consider re-reading before " +
1841
- "further edits."
1992
+ "\n\n\u26a0\ufe0f Background napkin distill has edited files you've also " +
1993
+ `touched: ${list}. Recent writes to these files may have been overwritten ` +
1994
+ "or merged; re-read before further edits."
1842
1995
  );
1843
1996
  }
1844
1997
 
@@ -83,9 +83,10 @@
83
83
  # main, pushes if origin, cleans
84
84
  # up worktree+branch — see
85
85
  # extensions/distill/distill-prompt.md)
86
- # 4. validate agent output (markers, HEAD on default,
86
+ # 4. validate agent output (unresolved conflicts,
87
+ # HEAD on default,
87
88
  # commit count; see
88
- # validate_no_markers /
89
+ # validate_no_unresolved_conflicts /
89
90
  # validate_head_on_default /
90
91
  # validate_commit_count below)
91
92
  # 5. salvage if validation fails (force-cleanup worktree+
@@ -294,12 +295,13 @@ ERROR_LOG="$ERROR_DIR/${TIMESTAMP}-$$-${BRANCH_SHORT}.log"
294
295
  # failed:<reason> → error.
295
296
  OUTCOME_PATH="$ERROR_DIR/${TIMESTAMP}-$$-${BRANCH_SHORT}.outcome"
296
297
 
297
- # Pre-distill marker snapshot tmp file (CORR-1). Captured right before
298
+ # Pre-distill unresolved-conflict snapshot (CORR-1). Captured right before
298
299
  # the agent runs (after START_SHA is recovered from meta.json) so the
299
- # post-agent validate_no_markers can distinguish agent-induced markers
300
- # from pre-existing ones. Empty string until the snapshot is
301
- # captured. Cleaned up in the EXIT trap.
302
- PRE_DISTILL_MARKER_FILES_FILE=""
300
+ # post-agent validate_no_unresolved_conflicts can distinguish
301
+ # agent-induced conflicts from pre-existing ones. A plain shell variable
302
+ # (no tmp file) — `git ls-files -u` output is small and the EXIT trap has
303
+ # nothing to clean up.
304
+ PRE_DISTILL_CONFLICT_FILES=""
303
305
 
304
306
  # Lazy-create error log on first write. Empty file is the "no error" signal.
305
307
  ERROR_LOG_TOUCHED=0
@@ -546,13 +548,13 @@ salvage() {
546
548
  local hint
547
549
  case "$reason" in
548
550
  markers-after-agent-exit)
549
- hint="Conflict markers landed in the vault. Inspect '$vault', then 'git -C $vault revert HEAD --no-edit' to undo the corrupt commit. Distill content is recoverable from 'git -C $vault reflog' for ~90 days."
551
+ hint="Unresolved merge conflicts landed in the vault. Inspect '$vault' and resolve them with 'git -C $vault mergetool' (or edit the conflicted files + 'git add' them), then commit the resolution. Distill content is recoverable from 'git -C $vault reflog' for ~90 days."
550
552
  ;;
551
553
  pre-existing-markers)
552
- hint="Conflict markers were already present in the vault before this distill ran (likely from a prior failed merge or a hand-edit). The agent did NOT introduce them, so this distill was rejected to avoid compounding the corruption. Inspect '$vault' (the error log lists the affected files) and resolve manually — delete the marker lines, keep the desired content, and commit. Once clean, re-run distill."
554
+ hint="Unresolved merge conflicts were already present in the vault before this distill ran (likely from a prior failed merge or an in-progress manual merge). The agent did NOT introduce them, so this distill was rejected to avoid compounding the corruption. Inspect '$vault' (the error log lists the affected files) and resolve the merge manually — edit the conflicted files, 'git add' them, and commit. Once clean, re-run distill."
553
555
  ;;
554
556
  internal-validator-error)
555
- hint="The post-distill conflict-marker validator could NOT run (mktemp failed to allocate a tempfile — likely a full disk or locked-down TMPDIR). The vault was NOT scanned for markers after the agent exited, so the wrapper cannot say whether the squash commit introduced corruption. Inspect '$vault' manually for unresolved '<<<<<<< / ======= / >>>>>>>' markers; if clean, the squash is keepable, otherwise 'git -C $vault revert HEAD --no-edit'. Distill content is recoverable from 'git -C $vault reflog' for ~90 days."
557
+ hint="The post-distill conflict validator could NOT run (git ls-files failed — likely a corrupt or unreadable vault git dir). The vault was NOT scanned for unresolved conflicts after the agent exited, so the wrapper cannot say whether the squash commit introduced a conflict state. Inspect '$vault' manually with 'git -C $vault status' and 'git -C $vault ls-files -u'; if clean, the squash is keepable, otherwise resolve the conflicts. Distill content is recoverable from 'git -C $vault reflog' for ~90 days."
556
558
  ;;
557
559
  head-not-on-default)
558
560
  hint="Vault HEAD is not on '$DEFAULT_BRANCH'. Run 'git -C $vault checkout $DEFAULT_BRANCH' before the next distill. Distill content is recoverable from 'git -C $vault reflog'."
@@ -622,184 +624,96 @@ salvage() {
622
624
  # beyond logging — the salvage path (A4) is the only thing that mutates
623
625
  # the worktree/branch on validation failure.
624
626
 
625
- # list_marker_files <vault> <output_file>
626
- #
627
- # Scan the vault's tracked `*.md` files and write the relative path of
628
- # every file that contains a complete conflict-marker triple to
629
- # <output_file>, one per line. Empty output file = no conflict-marked
630
- # files in the vault. Idempotent: caller is responsible for
631
- # truncating <output_file> first.
632
- #
633
- # Marker triple definition (CORR-A-1, SEC-A-7): a real merge conflict
634
- # always emits ALL THREE marker types (`<<<<<<< `, `======= `, `>>>>>>> `)
635
- # in the same file. The any-of-three rule false-positives on Setext
636
- # H1 underlines and on documentation prose that quotes one or two
637
- # markers; co-presence eliminates those classes. The acknowledged
638
- # tradeoff (a vault that genuinely documents the full triple inside
639
- # a single file) is documented at validate_no_markers below.
640
- #
641
- # Restricted to `*.md` because that's the only file class the agent
642
- # touches; scanning the entire vault would false-positive on user
643
- # scripts that legitimately discuss markers.
644
- #
645
- # Why a `git ls-files` enumeration: gitignored content (e.g. the
646
- # per-distill `.napkin/distill/` shim dir) is skipped automatically.
647
- # Per-file `grep -q` invocations are O(N) in tracked .md files; the
648
- # prior single-pass `xargs grep` was O(1) but couldn't express the
649
- # per-file all-three-co-present predicate. For vaults with thousands
650
- # of .md files this is slower but still well under wall-clock
651
- # budget. CLEAN-A-15 tracks the optimisation opportunity.
652
- #
653
- # bash 3.2 portability (macOS default): `while read -d ''` with array
654
- # `+=` is supported. Process substitution `< <(...)` is also bash 3.2.
655
- #
656
- # Used by:
657
- # - The pre-distill snapshot capture (right before the agent runs)
658
- # to record which files already had markers, so post-distill
659
- # validation can distinguish agent-induced markers from
660
- # pre-existing ones (CORR-1).
661
- # - validate_no_markers (post-distill), which calls this helper
662
- # against the same vault and diffs the two snapshots.
663
- list_marker_files() {
664
- local vault="$1"
665
- local output_file="$2"
666
- local file
667
- while IFS= read -r -d '' file; do
668
- # All three markers must appear in the same file. `grep -q`
669
- # short-circuits on first match, and the `&&` chain stops as
670
- # soon as one marker type is absent — minimising work in the
671
- # common no-conflict case.
672
- if grep -qE '^<{7} ' -- "$vault/$file" 2>/dev/null \
673
- && grep -qE '^={7}$' -- "$vault/$file" 2>/dev/null \
674
- && grep -qE '^>{7} ' -- "$vault/$file" 2>/dev/null; then
675
- printf '%s\n' "$file" >> "$output_file"
676
- fi
677
- done < <(git -C "$vault" ls-files -z -- '*.md' 2>/dev/null)
678
- }
679
-
680
- # validate_no_markers <vault> <pre_distill_marker_files>
681
- #
682
- # Searches the vault's tracked `*.md` files for unresolved git conflict
683
- # markers and classifies any matches against the pre-distill snapshot
684
- # captured just before the agent ran:
685
- #
686
- # pass (rc 0) — no marker-bearing files post-distill
687
- # fail rc 1 — at least one NEW marker-bearing file (agent-induced)
688
- # fail rc 2 — only pre-existing marker-bearing files (NOT
689
- # agent-induced — the user's vault was already in this
690
- # state; the agent didn't make it worse)
691
- #
692
- # rc 1 takes priority when both new and pre-existing markers are
627
+ # validate_no_unresolved_conflicts <vault> <pre_conflict_files>
628
+ #
629
+ # Checks the vault for UNRESOLVED MERGE CONFLICTS via the authoritative
630
+ # git index state (`git ls-files -u`: entries with stages 1/2/3 exist
631
+ # only during an unresolved merge) and classifies any conflicts against
632
+ # the pre-distill snapshot captured just before the agent ran:
633
+ #
634
+ # pass (rc 0) — no unresolved conflicts post-distill
635
+ # fail rc 1 — at least one NEW conflict path (agent-induced)
636
+ # fail rc 2 — only pre-existing conflict paths (NOT agent-induced —
637
+ # the user's vault was already mid-merge; the agent
638
+ # didn't make it worse)
639
+ # fail rc 3 — validator could not run (git ls-files failed);
640
+ # internal-validator-error (graceful degradation; do
641
+ # NOT blame the agent for state nobody observed)
642
+ #
643
+ # rc 1 takes priority when both new and pre-existing conflicts are
693
644
  # present: the agent's run made things worse, which is the dominant
694
- # signal even if it didn't touch the pre-existing files. Only rc 2
695
- # fires when EVERY marker-bearing file post-distill was already
696
- # marker-bearing pre-distill.
697
- #
698
- # Caller dispatches on the rc to choose the right salvage reason
699
- # code:
700
- # rc 1 → markers-after-agent-exit (agent-induced; existing reason)
701
- # rc 2 → pre-existing-markers (NOT agent-induced; new reason
702
- # code with a recovery hint that
703
- # points the user at fixing the
704
- # listed files manually)
705
- # rc 3 → internal-validator-error (validator could NOT run because
706
- # its post-distill mktemp failed;
707
- # surfaced as its own reason so the
708
- # user is NOT told markers were
709
- # found post-agent-exit when the
710
- # validator never observed the
711
- # vault state — CORR-1 R3 / SEC-1 R3)
712
- #
713
- # CORR-1: pre-existing markers (from a prior failed run, user error,
714
- # leftover state from a botched manual merge) used to classify as
715
- # `markers-after-agent-exit` because the wrapper had no
716
- # pre-distill marker snapshot. That misled the user into blaming the
717
- # agent for state it didn't create. Capturing the snapshot at
718
- # wrapper start lets us differentiate.
719
- #
720
- # Marker triple definition (CORR-A-1, SEC-A-7): a real merge conflict
721
- # always emits ALL THREE marker types in the same file. See
722
- # list_marker_files for the per-file predicate.
723
- #
724
- # Acknowledged tradeoff: a vault that genuinely documents a complete
725
- # `<<<<<<<` / `=======` / `>>>>>>>` example INSIDE A SINGLE FILE will
726
- # trip the validator post-distill — but if it ALSO tripped
727
- # pre-distill, this code path classifies it as `pre-existing-markers`
728
- # (rc 2) instead of as agent-induced. Users who hit this can escape
729
- # the markers in their docs (leading space, HTML comments) once and
730
- # subsequent distills see no markers either pre or post.
731
- #
732
- # Why scan post-squash on the vault: the agent merges into its branch
733
- # inside the worktree, then squashes onto the default branch in the
734
- # vault. Markers in the agent's branch get squashed into the vault's
735
- # default branch — they become committed corruption in the vault. The
736
- # vault working tree is the canonical post-condition.
737
- validate_no_markers() {
645
+ # signal even if it didn't touch the pre-existing files.
646
+ #
647
+ # Why the index state instead of scanning file contents (CORR-A-1,
648
+ # SEC-A-7, issue #95): a REAL merge conflict is recorded in the index
649
+ # by git itself — no regex can beat that signal. A documented conflict
650
+ # EXAMPLE inside a fenced code block is ordinary committed content, not
651
+ # an unmerged index entry, so it can never false-positive a distill.
652
+ # The old content scan needed fence-aware parsing precisely because it
653
+ # grepped marker TEXT anywhere in tracked *.md files, which is
654
+ # inherently ambiguous with documentation.
655
+ #
656
+ # `git ls-files -u` emits three entries per conflicted path (stages
657
+ # 1/2/3); `cut -f2` isolates the path column and `sort -u` dedupes.
658
+ # The caller passes the pre-distill snapshot as a newline-separated
659
+ # path list (empty string when none was captured), and /dev/null when
660
+ # the pre-capture failed, which collapses to "every post conflict is
661
+ # NEW" and routes to failed:markers-after-agent-exit.
662
+ validate_no_unresolved_conflicts() {
738
663
  local vault="$1"
739
- local pre_file="$2"
740
- if [ -z "$vault" ] || [ -z "$pre_file" ]; then
741
- log_error "validate_no_markers: both <vault> and <pre_distill_marker_files> are required (caller passes /dev/null when no pre-distill snapshot is available)"
664
+ local pre_files="$2"
665
+ if [ -z "$vault" ]; then
666
+ log_error "validate_no_unresolved_conflicts: <vault> is required"
742
667
  return 3
743
668
  fi
744
669
 
745
- local post_file
746
- post_file="$(mktemp -t napkin-distill-post-marker.XXXXXX 2>/dev/null || true)"
747
- if [ -z "$post_file" ]; then
748
- # CORR-1 R3 / SEC-1 R3: post-distill mktemp failure (full disk,
749
- # locked-down TMPDIR, etc.) USED to return 1 — which the caller
750
- # mapped to `failed:markers-after-agent-exit`. That misled the
751
- # user into reverting a possibly-correct squash commit on the
752
- # claim that markers had landed in the vault, even though the
753
- # validator never actually scanned the vault. Return a distinct
754
- # rc 3 so the caller routes to `failed:internal-validator-error`
755
- # whose recovery hint truthfully tells the user the validator
756
- # couldn't run — inspect the vault before relying on the squash.
757
- log_error "validate_no_markers: mktemp failed for post-distill snapshot — cannot scan vault for conflict markers; routing to internal-validator-error (NOT markers-after-agent-exit) to avoid misattributing unobserved state to the agent"
670
+ local post_files post_rc
671
+ # `ls-files -u` exit status is load-bearing: a git failure must route
672
+ # to rc 3 (internal-validator-error), NOT be mistaken for "no
673
+ # conflicts" (empty output). The pipe to cut/sort would mask git's
674
+ # exit code (the last command's status wins), so capture it first.
675
+ post_files="$(git -C "$vault" ls-files -u 2>/dev/null)"
676
+ post_rc=$?
677
+ if [ "$post_rc" -ne 0 ]; then
678
+ log_error "validate_no_unresolved_conflicts: git ls-files failed (rc $post_rc) — cannot scan vault for unresolved conflicts; routing to internal-validator-error (NOT markers-after-agent-exit) to avoid misattributing unobserved state to the agent"
758
679
  return 3
759
680
  fi
760
- list_marker_files "$vault" "$post_file"
761
-
762
- # Empty post-distill snapshot = no marker-bearing files = pass.
763
- if [ ! -s "$post_file" ]; then
764
- rm -f "$post_file" 2>/dev/null || true
681
+ post_files="$(printf '%s\n' "$post_files" | cut -f2 | sort -u)"
682
+ if [ -z "$post_files" ]; then
683
+ # No unresolved conflicts post-distill = pass.
765
684
  return 0
766
685
  fi
767
686
 
768
- # Compute set difference: files in post but NOT in pre = NEW (agent-induced).
769
- # `comm` requires sorted input. The caller passes /dev/null as pre_file
770
- # when no pre-distill snapshot is available (mktemp failed at startup),
771
- # which collapses to "every post-marker file is NEW" and routes to
772
- # failed:markers-after-agent-exit.
773
- local new_marker_files pre_existing_marker_files
774
- new_marker_files="$(comm -23 <(sort -u "$post_file") <(sort -u "$pre_file" 2>/dev/null) 2>/dev/null || cat "$post_file")"
775
- pre_existing_marker_files="$(comm -12 <(sort -u "$post_file") <(sort -u "$pre_file" 2>/dev/null) 2>/dev/null || true)"
776
-
777
- rm -f "$post_file" 2>/dev/null || true
687
+ # Diff against the pre-distill snapshot. `comm` requires sorted input;
688
+ # /dev/null as pre collapses to "every post conflict is NEW".
689
+ local new_conflicts pre_existing_conflicts
690
+ new_conflicts="$(comm -23 <(printf '%s\n' "$post_files") <(printf '%s\n' "$pre_files" 2>/dev/null | sort -u) 2>/dev/null || printf '%s\n' "$post_files")"
691
+ pre_existing_conflicts="$(comm -12 <(printf '%s\n' "$post_files") <(printf '%s\n' "$pre_files" 2>/dev/null | sort -u) 2>/dev/null || true)"
778
692
 
779
- if [ -n "$new_marker_files" ]; then
780
- # Agent-induced markers present (alone or alongside pre-existing).
693
+ if [ -n "$new_conflicts" ]; then
694
+ # Agent-induced conflicts present (alone or alongside pre-existing).
781
695
  # Dominant signal: the run made things worse.
782
- log_error "validate_no_markers: NEW conflict markers (agent-induced) in vault \`$vault\`:"
696
+ log_error "validate_no_unresolved_conflicts: NEW unresolved merge conflicts (agent-induced) in vault \`$vault\`:"
783
697
  while IFS= read -r file; do
784
698
  [ -n "$file" ] && log_error " $vault/$file"
785
- done <<< "$new_marker_files"
786
- if [ -n "$pre_existing_marker_files" ]; then
787
- log_error "validate_no_markers: also pre-existing conflict markers (present before agent ran) in:"
699
+ done <<< "$new_conflicts"
700
+ if [ -n "$pre_existing_conflicts" ]; then
701
+ log_error "validate_no_unresolved_conflicts: also pre-existing conflicts (present before agent ran) in:"
788
702
  while IFS= read -r file; do
789
703
  [ -n "$file" ] && log_error " $vault/$file"
790
- done <<< "$pre_existing_marker_files"
704
+ done <<< "$pre_existing_conflicts"
791
705
  fi
792
706
  return 1
793
707
  fi
794
708
 
795
- # Only pre-existing markers post-distill — the agent didn't touch
709
+ # Only pre-existing conflicts post-distill — the agent didn't touch
796
710
  # those files (or touched them but didn't make things worse). Not
797
711
  # agent-induced; route to a different reason code so the user can
798
- # fix the underlying files manually.
799
- log_error "validate_no_markers: pre-existing conflict markers (NOT agent-induced) in vault \`$vault\`:"
712
+ # resolve the merge manually.
713
+ log_error "validate_no_unresolved_conflicts: pre-existing unresolved merge conflicts (NOT agent-induced) in vault \`$vault\`:"
800
714
  while IFS= read -r file; do
801
715
  [ -n "$file" ] && log_error " $vault/$file"
802
- done <<< "$pre_existing_marker_files"
716
+ done <<< "$pre_existing_conflicts"
803
717
  return 2
804
718
  }
805
719
 
@@ -987,13 +901,9 @@ cleanup() {
987
901
  # was the last distill for the vault. ENOTEMPTY (other concurrent
988
902
  # distills) and ENOENT (race) are both expected and benign.
989
903
  rmdir "$(dirname "$WORKTREE")" 2>/dev/null || true
990
- # CORR-1: the pre-distill marker snapshot tmp file is the wrapper's
991
- # internal scratch state. Empty string when the snapshot was never
992
- # captured (NAPKIN_DISTILL_SKIP_PI=1, early-exit before snapshot,
993
- # mktemp failed). `rm -f` is idempotent on missing paths.
994
- if [ -n "${PRE_DISTILL_MARKER_FILES_FILE:-}" ]; then
995
- rm -f "$PRE_DISTILL_MARKER_FILES_FILE" 2>/dev/null || true
996
- fi
904
+ # The pre-distill conflict snapshot is a plain variable — nothing to
905
+ # clean up on exit (the old mktemp-backed marker snapshot file is gone;
906
+ # issue #95 simplification).
997
907
  # SEC-2 R3: pi_stderr is the agent's stderr capture file (allocated
998
908
  # via mktemp before invoking pi). Normal-path cleanup happens inline
999
909
  # at the post-agent block, but a SIGTERM-on-grace, OOM kill, or any
@@ -1193,35 +1103,39 @@ if [ "${NAPKIN_DISTILL_FORCE_CLEANUP:-}" = "1" ]; then
1193
1103
  exit 1
1194
1104
  fi
1195
1105
 
1196
- # --- Pre-distill marker snapshot (CORR-1) -----------------------------------
1106
+ # --- Pre-distill conflict snapshot (CORR-1) -------------------------------
1197
1107
  #
1198
- # Capture which tracked `*.md` files in the vault already contain a
1199
- # complete conflict-marker triple BEFORE the agent runs. Used by
1200
- # validate_no_markers post-agent to differentiate:
1108
+ # Capture the vault's UNRESOLVED MERGE CONFLICTS (index stage entries)
1109
+ # BEFORE the agent runs. Used by validate_no_unresolved_conflicts
1110
+ # post-agent to differentiate:
1201
1111
  #
1202
- # - Files marker-bearing post-distill but NOT pre-distill
1112
+ # - Conflict paths post-distill but NOT pre-distill
1203
1113
  # → NEW (agent-induced) → failed:markers-after-agent-exit
1204
- # - Files marker-bearing pre-distill AND post-distill
1114
+ # - Conflict paths pre-distill AND post-distill
1205
1115
  # → pre-existing (NOT agent-induced) → failed:pre-existing-markers
1206
1116
  #
1207
- # Without this snapshot, every post-agent marker classified as
1208
- # agent-induced — misleading users when the markers came from a prior
1209
- # failed run, a botched manual merge, or user editing.
1210
- #
1211
- # Best-effort: if mktemp fails (very rare), set PRE_DISTILL_MARKER_FILES_FILE
1212
- # to /dev/null so the call site always passes a concrete pre-snapshot
1213
- # path. validate_no_markers treats /dev/null as "no pre-existing markers
1214
- # observed", collapsing every post-agent marker to NEW (agent-induced)
1215
- # and routing to failed:markers-after-agent-exit. The wrapper does NOT
1216
- # hard-fail on snapshot failure — the worst-case is the pre-PR-12-Pass-2B
1217
- # behaviour.
1218
- PRE_DISTILL_MARKER_FILES_FILE="$(mktemp -t napkin-distill-pre-marker.XXXXXX 2>/dev/null || true)"
1219
- if [ -n "$PRE_DISTILL_MARKER_FILES_FILE" ]; then
1220
- list_marker_files "$VAULT" "$PRE_DISTILL_MARKER_FILES_FILE"
1117
+ # `git ls-files -u` is the authoritative "is this file in a conflicted
1118
+ # merge state" signal: it lists index entries with stages 1/2/3, which
1119
+ # git only writes during an unresolved merge. Documented conflict-marker
1120
+ # EXAMPLES inside fenced code blocks are ordinary committed content, not
1121
+ # unmerged index entries — they never appear here, so they can never
1122
+ # false-positive a distill (issue #95). This replaces the old
1123
+ # marker-text scan (which grepped file contents and needed fence-aware
1124
+ # parsing to avoid flagging documentation).
1125
+ #
1126
+ # Best-effort: if the command fails, the variable is empty and any
1127
+ # post-agent conflict routes to markers-after-agent-exit (treating the
1128
+ # state as unobserved rather than pre-existing). Capture git's exit
1129
+ # status before the pipe masks it (same load-bearing pattern as the
1130
+ # post-distill validator).
1131
+ PRE_DISTILL_CONFLICT_FILES_RAW="$(git -C "$VAULT" ls-files -u 2>/dev/null)"
1132
+ if [ $? -ne 0 ]; then
1133
+ log_error "pre-distill conflict snapshot: git ls-files failed; treating vault as conflict-free (any post-agent conflict will route to markers-after-agent-exit)"
1134
+ PRE_DISTILL_CONFLICT_FILES=""
1221
1135
  else
1222
- log_error "pre-distill marker snapshot: mktemp failed; passing /dev/null to validate_no_markers (any post-agent markers will route to failed:markers-after-agent-exit)"
1223
- PRE_DISTILL_MARKER_FILES_FILE="/dev/null"
1136
+ PRE_DISTILL_CONFLICT_FILES="$(printf '%s\n' "$PRE_DISTILL_CONFLICT_FILES_RAW" | cut -f2 | sort -u)"
1224
1137
  fi
1138
+ unset PRE_DISTILL_CONFLICT_FILES_RAW
1225
1139
 
1226
1140
  # --- Step: run the agent under a hard timeout (PR #12 architecture) --------
1227
1141
  #
@@ -1295,11 +1209,13 @@ fi
1295
1209
  #
1296
1210
  # Validates the agent's output and writes the appropriate outcome class.
1297
1211
  # A3 wires:
1298
- # - validate_no_markers (markers-after-agent-exit when NEW markers
1299
- # post-agent; pre-existing-markers when
1300
- # only pre-existing markers — CORR-1;
1301
- # internal-validator-error when post-
1302
- # distill mktemp fails — CORR-1 R3 /
1212
+ # - validate_no_unresolved_conflicts
1213
+ # (markers-after-agent-exit when NEW
1214
+ # conflict paths post-agent;
1215
+ # pre-existing-markers when only
1216
+ # pre-existing conflicts — CORR-1;
1217
+ # internal-validator-error when the
1218
+ # validator cannot run — CORR-1 R3 /
1303
1219
  # SEC-1 R3)
1304
1220
  # - validate_head_on_default (head-not-on-default on fail)
1305
1221
  # - validate_commit_count (no-content when 0 commits since startSha)
@@ -1312,14 +1228,16 @@ fi
1312
1228
  # outcome sidecar.
1313
1229
  #
1314
1230
  # Reason codes (from the V3 verification report):
1315
- # markers-after-agent-exit — V1 fail, NEW conflict markers in vault
1316
- # *.md introduced by the agent's run
1317
- # pre-existing-markers — V1 fail, ONLY pre-existing markers in
1318
- # vault *.md (present before agent ran;
1319
- # not the agent's fault — CORR-1)
1320
- # internal-validator-error — V1 fail, post-distill mktemp failed so
1321
- # the marker validator could NOT scan
1322
- # the vault. Distinct from
1231
+ # markers-after-agent-exit — V1 fail, NEW unresolved merge conflicts
1232
+ # in the vault introduced by the agent's
1233
+ # run (git ls-files -u)
1234
+ # pre-existing-markers — V1 fail, ONLY pre-existing unresolved
1235
+ # conflicts in the vault (present before
1236
+ # agent ran; not the agent's fault —
1237
+ # CORR-1)
1238
+ # internal-validator-error — V1 fail, the conflict validator could
1239
+ # NOT scan the vault (git ls-files
1240
+ # failed). Distinct from
1323
1241
  # markers-after-agent-exit so the user
1324
1242
  # isn't blamed-via-agent for state
1325
1243
  # nobody observed (CORR-1 R3 / SEC-1 R3)
@@ -1371,23 +1289,22 @@ if ! validate_head_on_default "$VAULT" "$DEFAULT_BRANCH"; then
1371
1289
  exit 1
1372
1290
  fi
1373
1291
 
1374
- # Marker validation (CORR-A-1, SEC-A-7, CORR-1, CORR-1 R3 / SEC-1 R3).
1375
- # Four rc paths:
1376
- # 0 → no markers post-distill, pass
1377
- # 1 → NEW marker-bearing files (agent-induced) → markers-after-agent-exit
1378
- # 2 → only pre-existing marker files → pre-existing-markers (NOT
1379
- # agent-induced; user must fix manually before next distill)
1380
- # 3 → post-distill mktemp failed; validator could not scan →
1292
+ # Conflict validation (CORR-A-1, SEC-A-7, CORR-1, CORR-1 R3 / SEC-1 R3).
1293
+ # Three rc paths (plus rc 3 for validator failure):
1294
+ # 0 → no unresolved conflicts post-distill, pass
1295
+ # 1 → NEW conflict paths (agent-induced) → markers-after-agent-exit
1296
+ # 2 → only pre-existing conflict paths → pre-existing-markers (NOT
1297
+ # agent-induced; user must resolve the merge manually before next
1298
+ # distill)
1299
+ # 3 → git ls-files failed; validator could not scan →
1381
1300
  # internal-validator-error (graceful degradation; do NOT
1382
1301
  # blame the agent for state nobody observed — CORR-1 R3 /
1383
1302
  # SEC-1 R3)
1384
1303
  #
1385
- # Pass the pre-distill snapshot file so validate_no_markers can do the
1386
- # diff. PRE_DISTILL_MARKER_FILES_FILE is set to /dev/null upstream when
1387
- # mktemp failed; validate_no_markers treats /dev/null as "no pre-existing
1388
- # markers observed" and routes every post-agent marker to
1389
- # failed:markers-after-agent-exit.
1390
- validate_no_markers "$VAULT" "$PRE_DISTILL_MARKER_FILES_FILE"
1304
+ # Pass the pre-distill snapshot (newline-separated conflict paths, empty
1305
+ # when none were captured) so validate_no_unresolved_conflicts can do
1306
+ # the diff.
1307
+ validate_no_unresolved_conflicts "$VAULT" "$PRE_DISTILL_CONFLICT_FILES"
1391
1308
  MARKER_RC=$?
1392
1309
  if [ "$MARKER_RC" -eq 1 ]; then
1393
1310
  record_dangling_sha
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Session-start setup notice: when the `napkin` CLI is missing, inject a
3
+ * custom message into the session so the *LLM* — not only the TUI — sees
4
+ * the blocking prerequisite. The TUI notify from
5
+ * `surfaceHealthFindings` is human-facing only; without this message the
6
+ * agent has no way to know auto-distill is broken and cannot repair it on
7
+ * its next turn.
8
+ *
9
+ * Deliberately separate from `ensureVaultReadyForDistill`'s finding
10
+ * channel: the notice uses the cheap PATH-resolution probe (no child
11
+ * process) and does NOT count as a setup failure, so auto-distill stays
12
+ * armed. Once the agent installs the CLI, the next full-level health
13
+ * check passes and the next tick works without a pi restart. If the agent
14
+ * does not repair it, the full-level gate blocks the wrapper spawn and
15
+ * keeps surfacing the loud error.
16
+ *
17
+ * Delivery uses the shared `sendCustomMessageOnce` helper
18
+ * (`pi.sendMessage` primary, direct session append fallback, deduped by
19
+ * customType) so the custom message participates in LLM context exactly
20
+ * like the `<napkin-context>` overview block, and a resumed session does
21
+ * not accumulate duplicate notices.
22
+ */
23
+
24
+ import type {
25
+ ExtensionAPI,
26
+ SessionManager,
27
+ } from "@earendil-works/pi-coding-agent";
28
+ import { sendCustomMessageOnce } from "../shared/custom-message";
29
+ import type { NapkinCliProbeResult } from "./auto-setup";
30
+
31
+ /** customType identifying the session-start setup notice message. */
32
+ export const NAPKIN_SETUP_NOTICE_CUSTOM_TYPE = "napkin-distill-setup";
33
+
34
+ /**
35
+ * Render the agent-facing notice. The install command is the documented
36
+ * prerequisite (README "Install"); the trailing instruction tells the
37
+ * agent to repair it proactively on its next turn instead of merely
38
+ * describing the problem to the user.
39
+ */
40
+ export function formatNapkinSetupNotice(error: string | undefined): string {
41
+ return [
42
+ "<napkin-distill-setup>",
43
+ `Auto-distill is blocked: the \`napkin\` CLI required by the distill wrapper is not available on PATH (${error ?? "unknown error"}).`,
44
+ "Repair it when you next act: run `pnpm add -g @cad0p/napkin` (or `npm install -g @cad0p/napkin`), verify with `napkin --version`, then tell the user auto-distill was repaired. No pi restart is needed when the install bin directory is already on PATH.",
45
+ "</napkin-distill-setup>",
46
+ ].join("\n");
47
+ }
48
+
49
+ export interface MaybeInjectNapkinSetupNoticeOptions {
50
+ /** The extension API whose `sendMessage` is fire-and-forget (void). */
51
+ poster: Pick<ExtensionAPI, "sendMessage">;
52
+ /** Captured session manager (fallback append + notice dedupe). */
53
+ sm: Partial<SessionManager> | undefined;
54
+ /** Result of the cheap (no smoke test) napkin CLI probe. */
55
+ probe: NapkinCliProbeResult;
56
+ /** Invoked when the fallback append itself throws. */
57
+ onFallbackFailure?: (err: unknown) => void;
58
+ }
59
+
60
+ /**
61
+ * Inject {@link formatNapkinSetupNotice} when the probe failed.
62
+ * `sendCustomMessageOnce` handles the resume dedupe (one notice per
63
+ * session). No-op on the healthy path. Never throws.
64
+ */
65
+ export function maybeInjectNapkinSetupNotice(
66
+ options: MaybeInjectNapkinSetupNoticeOptions,
67
+ ): void {
68
+ const { poster, sm, probe, onFallbackFailure } = options;
69
+ if (probe.ok) return;
70
+ sendCustomMessageOnce({
71
+ poster,
72
+ sm,
73
+ customType: NAPKIN_SETUP_NOTICE_CUSTOM_TYPE,
74
+ content: formatNapkinSetupNotice(probe.error),
75
+ onFallbackFailure,
76
+ });
77
+ }
@@ -11,7 +11,7 @@ import {
11
11
  } from "@earendil-works/pi-coding-agent";
12
12
  import { Markdown, Text } from "@earendil-works/pi-tui";
13
13
  import { Type } from "@sinclair/typebox";
14
- import { sendCustomMessageWithFallback } from "../shared/custom-message";
14
+ import { sendCustomMessageOnce } from "../shared/custom-message";
15
15
 
16
16
  function loadShowStatus(vaultPath: string): boolean {
17
17
  const configPath = path.join(vaultPath, "config.json");
@@ -170,16 +170,6 @@ function getNapkin(cwd: string): Napkin {
170
170
  return new Napkin(cwd);
171
171
  }
172
172
 
173
- function hasInjectedContext(sm: Pick<SessionManager, "getEntries">): boolean {
174
- return sm
175
- .getEntries()
176
- .some(
177
- (e) =>
178
- e.type === "custom_message" &&
179
- (e as { customType?: string }).customType === "napkin-context",
180
- );
181
- }
182
-
183
173
  function getOverview(n: Napkin): { text: string; root: string } | null {
184
174
  try {
185
175
  // napkin >= 0.12.3 ships the fork's defaults (collapseDepth 2, maxRows
@@ -291,24 +281,22 @@ export default function (pi: ExtensionAPI) {
291
281
  // that never calls them never learns a vault is expected or how to
292
282
  // create/configure one.
293
283
  if (e instanceof Error && e.name === "VaultNotFoundError") {
294
- if (!hasInjectedContext(ctx.sessionManager)) {
295
- sendCustomMessageWithFallback({
296
- poster: pi,
297
- sm: ctx.sessionManager as Partial<SessionManager>,
298
- customType: "napkin-context",
299
- content: e.message,
300
- onFallbackFailure: (err) => {
301
- if (ctx.hasUI) {
302
- ctx.ui.notify(
303
- `napkin-context: could not surface no-vault guidance (${
304
- err instanceof Error ? err.message : String(err)
305
- })`,
306
- "warning",
307
- );
308
- }
309
- },
310
- });
311
- }
284
+ sendCustomMessageOnce({
285
+ poster: pi,
286
+ sm: ctx.sessionManager as Partial<SessionManager>,
287
+ customType: "napkin-context",
288
+ content: e.message,
289
+ onFallbackFailure: (err) => {
290
+ if (ctx.hasUI) {
291
+ ctx.ui.notify(
292
+ `napkin-context: could not surface no-vault guidance (${
293
+ err instanceof Error ? err.message : String(err)
294
+ })`,
295
+ "warning",
296
+ );
297
+ }
298
+ },
299
+ });
312
300
  if (ctx.hasUI) {
313
301
  // Unconditional on purpose — unlike the success path it cannot
314
302
  // consult loadShowStatus(): no vault exists, so there is no vault
@@ -329,38 +317,37 @@ export default function (pi: ExtensionAPI) {
329
317
  vaultRoot = overview?.root ?? null;
330
318
 
331
319
  if (overview) {
332
- // Check if we already injected context in this session
333
- const alreadyInjected = hasInjectedContext(ctx.sessionManager);
334
-
335
- if (!alreadyInjected) {
336
- // Send via the public message event path (message_start) so the TUI
337
- // renders the custom message live. A direct sessionManager append is
338
- // only picked up by the next full chat rebuild — on /new the chat is
339
- // rebuilt BEFORE session_start handlers run, so a direct append would
340
- // leave the vault overview invisible in the new session's chat (the
341
- // stale line survives as terminal pixels until the next repaint).
342
- // pi.sendMessage is fire-and-forget (void). In the idle path it
343
- // appends the entry to the session manager synchronously AND pushes
344
- // the message into agent state — the overview participates in LLM
345
- // context by design, even where the TUI event is not subscribed yet
346
- // (startup path).
347
- sendCustomMessageWithFallback({
348
- poster: pi,
349
- sm: ctx.sessionManager as Partial<SessionManager>,
350
- customType: "napkin-context",
351
- content: overview.text,
352
- onFallbackFailure: (err) => {
353
- if (ctx.hasUI) {
354
- ctx.ui.notify(
355
- `napkin-context: could not inject vault overview (${
356
- err instanceof Error ? err.message : String(err)
357
- })`,
358
- "warning",
359
- );
360
- }
361
- },
362
- });
363
- }
320
+ // Send via the public message event path (message_start) so the TUI
321
+ // renders the custom message live. A direct sessionManager append is
322
+ // only picked up by the next full chat rebuild — on /new the chat is
323
+ // rebuilt BEFORE session_start handlers run, so a direct append would
324
+ // leave the vault overview invisible in the new session's chat (the
325
+ // stale line survives as terminal pixels until the next repaint).
326
+ // pi.sendMessage is fire-and-forget (void). In the idle path it
327
+ // appends the entry to the session manager synchronously AND pushes
328
+ // the message into agent state — the overview participates in LLM
329
+ // context by design, even where the TUI event is not subscribed yet
330
+ // (startup path).
331
+ //
332
+ // `sendCustomMessageOnce` dedupes by customType: a resumed session
333
+ // already replays the prior overview in its history, so re-injecting
334
+ // would only duplicate it.
335
+ sendCustomMessageOnce({
336
+ poster: pi,
337
+ sm: ctx.sessionManager as Partial<SessionManager>,
338
+ customType: "napkin-context",
339
+ content: overview.text,
340
+ onFallbackFailure: (err) => {
341
+ if (ctx.hasUI) {
342
+ ctx.ui.notify(
343
+ `napkin-context: could not inject vault overview (${
344
+ err instanceof Error ? err.message : String(err)
345
+ })`,
346
+ "warning",
347
+ );
348
+ }
349
+ },
350
+ });
364
351
  }
365
352
 
366
353
  if (ctx.hasUI && loadShowStatus(n.vault.configPath)) {
@@ -77,3 +77,48 @@ export function sendCustomMessageWithFallback(
77
77
  }
78
78
  }
79
79
  }
80
+
81
+ /**
82
+ * Whether the session history already contains a custom message of
83
+ * `customType`. Session-start injections replay on resumed sessions (the
84
+ * prior message is already in LLM context), so callers use this to dedupe
85
+ * rather than injecting a duplicate copy of the same guidance.
86
+ *
87
+ * Unreadable histories (`getEntries` absent or throwing) report `false`:
88
+ * the caller proceeds with the send and at worst produces one duplicate.
89
+ */
90
+ export function hasCustomMessage(
91
+ sm: Partial<SessionManager> | undefined,
92
+ customType: string,
93
+ ): boolean {
94
+ if (!sm || typeof sm.getEntries !== "function") return false;
95
+ try {
96
+ return sm
97
+ .getEntries()
98
+ .some(
99
+ (e) =>
100
+ e.type === "custom_message" &&
101
+ (e as { customType?: string }).customType === customType,
102
+ );
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * {@link sendCustomMessageWithFallback}, deduped against session history:
110
+ * sends only when no custom message of `customType` is present yet, so a
111
+ * resumed session does not accumulate duplicate session-start guidance.
112
+ *
113
+ * Returns whether delivery was attempted (`false` = already present).
114
+ * Best-effort like the underlying helper: a failed primary path falls
115
+ * back to a direct append, and a double failure is reported through
116
+ * `onFallbackFailure` without throwing.
117
+ */
118
+ export function sendCustomMessageOnce(
119
+ options: SendCustomMessageWithFallbackOptions,
120
+ ): boolean {
121
+ if (hasCustomMessage(options.sm, options.customType)) return false;
122
+ sendCustomMessageWithFallback(options);
123
+ return true;
124
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cad0p/pi-napkin",
3
- "version": "0.7.2",
3
+ "version": "0.7.3-20261004.0",
4
4
  "description": "📜 Napkin integration for pi — vault context, knowledge tools, and automatic distillation with git-worktree concurrency safety",
5
5
  "type": "module",
6
6
  "exports": {
@@ -74,7 +74,7 @@
74
74
  "vitest": "^2.1.0"
75
75
  },
76
76
  "dependencies": {
77
- "@cad0p/napkin": "0.14.0-20260814.2"
77
+ "@cad0p/napkin": "0.14.0-20260820.1"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "@earendil-works/pi-coding-agent": ">=0.74.0",