@cad0p/pi-napkin 0.7.2 → 0.7.3

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.
@@ -463,9 +463,38 @@ export default function (pi: ExtensionAPI) {
463
463
  // at session_start after session replacement/reload — but a setInterval
464
464
  // callback already queued in the macrotask queue still fires after
465
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).
466
+ // On every TUI-side teardown path, session_shutdown handlers complete
467
+ // BEFORE invalidation (pi lifecycle), so flipping this flag there makes any
468
+ // queued tick a clean no-op (issue #84). CAVEAT (issue #100): this ordering
469
+ // is NOT universal — a raw AgentSession.dispose() from an SDK/host consumer
470
+ // invalidates the runner WITHOUT emitting session_shutdown, which is why
471
+ // session_start below also refuses to arm timers for non-interactive or
472
+ // session-less sessions at all.
468
473
  let sessionActive = false;
474
+ // Session generation (issue #93): incremented at every session_start. Each
475
+ // timer captures the generation at ARM time; a queued tick from an earlier
476
+ // session that fires after the next session_start re-armed `sessionActive`
477
+ // sees a mismatch and returns BEFORE touching its (invalidated) ctx — a
478
+ // clean no-op instead of the stale-ctx throw + `tick failed` log that #84's
479
+ // try/catch could only downgrade, not prevent.
480
+ //
481
+ // A stale ctx reaches a tick via two paths: (a) legit replacement/reload,
482
+ // where the old session's already-queued tick outruns its own shutdown
483
+ // handler, and (b) raw AgentSession.dispose() from SDK/host consumers
484
+ // (issue #100), where NO session_shutdown ever fires for the disposed
485
+ // session. Path (b) is closed upstream by the arm gate in session_start;
486
+ // this guard remains the backstop for queued ticks around either path.
487
+ let sessionGeneration = 0;
488
+ // Stale-ctx lockdown (issue #96): if a tick ever catches the stale-ctx
489
+ // error (the session_start's ctx was invalidated without the matching
490
+ // session_shutdown clearing this closure's timers — e.g. a raw
491
+ // AgentSession.dispose() from an SDK/host consumer skips the shutdown
492
+ // event entirely (issue #100); the #84/#93 guards cannot see it because
493
+ // they key off events this closure never received), the interval would
494
+ // otherwise throw + log on EVERY tick forever. On first detection we
495
+ // disarm the auto interval and log
496
+ // once; a later session_start re-arms everything cleanly.
497
+ let staleCtxDisarmed = false;
469
498
 
470
499
  pi.on("before_provider_request", (event) =>
471
500
  applyDistillPromptCacheKey(event.payload),
@@ -503,15 +532,62 @@ export default function (pi: ExtensionAPI) {
503
532
  : `${secs}s`;
504
533
  }
505
534
 
535
+ /**
536
+ * True when `err` is pi's stale-ctx error (the ctx captured at
537
+ * session_start was invalidated by a session replacement/reload).
538
+ * Matched by the message pi's ExtensionRunner throws — deliberately
539
+ * substring-based so it survives minor wording drift and stays
540
+ * independent of the internal stack frames.
541
+ */
542
+ function isStaleCtxError(err: unknown): boolean {
543
+ return (
544
+ err instanceof Error &&
545
+ err.message.includes("stale after session replacement")
546
+ );
547
+ }
548
+
549
+ /**
550
+ * One-time stale-ctx lockdown (issue #96). If a tick catches the
551
+ * stale-ctx error, the closure's session_start ctx is dead and the
552
+ * #84/#93 event-keyed guards can't see it (the matching
553
+ * session_shutdown never reached this closure — most commonly because
554
+ * an SDK/host consumer tore the session down via a raw
555
+ * AgentSession.dispose(), which invalidates the runner WITHOUT emitting
556
+ * session_shutdown, issue #100). The interval would otherwise throw +
557
+ * log on EVERY tick until the next session_start. Disarm the auto
558
+ * interval on first detection and log once; the next session_start
559
+ * clears the flag and re-arms cleanly.
560
+ */
561
+ function handleStaleCtxInTick(kind: "auto" | "poll" | "countdown"): void {
562
+ if (staleCtxDisarmed) return;
563
+ staleCtxDisarmed = true;
564
+ if (intervalHandle) {
565
+ clearInterval(intervalHandle);
566
+ intervalHandle = null;
567
+ }
568
+ console.error(
569
+ `[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)`,
570
+ );
571
+ }
572
+
506
573
  pi.on("session_start", async (event, ctx) => {
507
574
  // Arm the session liveness guard FIRST — before any early-return path — so
508
575
  // a tick queued from a previous session can never observe a dead session
509
576
  // while this one is starting (issue #84).
510
577
  sessionActive = true;
578
+ // Increment the session generation BEFORE any early return (issue #93): a
579
+ // previous session's tick already queued in the macrotask queue must see
580
+ // a generation mismatch even when this session_start bails on vault/
581
+ // config below.
582
+ sessionGeneration += 1;
511
583
 
512
584
  // Reset to default before any early-return paths below; the persisted state
513
585
  // (if any) is re-read further down when distill is enabled for the session.
514
586
  autoDistillSuppressed = false;
587
+ // A fresh session_start means this closure has a live session again —
588
+ // clear the stale-ctx lockdown so the new session's timers can run
589
+ // (issue #96).
590
+ staleCtxDisarmed = false;
515
591
 
516
592
  const napkinVault = resolveDistillVault(ctx.cwd);
517
593
  if (!napkinVault) return;
@@ -666,6 +742,11 @@ export default function (pi: ExtensionAPI) {
666
742
  // accessor), leave the cursor at its prior value (0 on first
667
743
  // session_start).
668
744
  }
745
+ // Sidechain/SDK sessions bind no UI (ctx.hasUI === false); ephemeral runs
746
+ // (--no-session) have no session file to fork. Nothing can ever be distilled:
747
+ // arm nothing, paint nothing.
748
+ if (!ctx.hasUI || !ctx.sessionManager.getSessionFile()) return;
749
+
669
750
  const intervalMs = config.intervalMinutes * 60 * 1000;
670
751
 
671
752
  uiRef = { hasUI: ctx.hasUI, ui: ctx.ui, showStatus, intervalMs };
@@ -692,11 +773,20 @@ export default function (pi: ExtensionAPI) {
692
773
  );
693
774
  }
694
775
 
776
+ // Generation seen by the timers armed by THIS session_start. A queued
777
+ // tick from an earlier session that fires after the next session_start
778
+ // re-armed the flag sees a mismatch and no-ops (issue #93).
779
+ const armedGeneration = sessionGeneration;
780
+
695
781
  if (ctx.hasUI && showStatus) {
696
782
  countdownHandle = setInterval(() => {
697
- // Queued tick after session replacement/reload must not touch
698
- // `uiRef.ui` (stale ctx) — skip the countdown render entirely.
783
+ // Queued tick from a dead session must not touch `uiRef.ui`
784
+ // (stale ctx): either a replacement/reload where the tick outran
785
+ // its own shutdown handler, or a raw-dispose SDK session whose
786
+ // shutdown never fired at all (issue #100). Skip the countdown
787
+ // render entirely.
699
788
  if (!sessionActive) return;
789
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
700
790
  try {
701
791
  // `renderIdleStatus` self-guards against in-flight distills; when
702
792
  // off it paints `distill: off (session)` (pi dedupes identical
@@ -705,21 +795,40 @@ export default function (pi: ExtensionAPI) {
705
795
  } catch (err) {
706
796
  // A tick must never take down pi (same invariant as the
707
797
  // 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);
798
+ // and is retried on the next countdown repaint. A stale-ctx
799
+ // error means the session was replaced under us — disarm once
800
+ // instead of spamming (issue #96).
801
+ if (isStaleCtxError(err)) {
802
+ handleStaleCtxInTick("countdown");
803
+ } else {
804
+ console.error("[napkin-distill] countdown tick failed:", err);
805
+ }
710
806
  }
711
807
  }, IDLE_STATUS_REPAINT_INTERVAL_MS);
712
808
  }
713
809
 
714
810
  intervalHandle = setInterval(() => {
715
- if (!sessionActive) return; // queued tick after replacement/reload → clean no-op
811
+ // Queued tick from a dead session (replacement/reload, or a
812
+ // raw-dispose SDK session whose shutdown never fired — issue #100)
813
+ // → clean no-op.
814
+ if (!sessionActive) return;
815
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
716
816
  if (autoDistillSuppressed) return;
717
817
  try {
718
818
  runAutoDistill(ctx);
719
819
  } catch (err) {
720
820
  // 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);
821
+ // vault config, spawn) logs and is retried on the next tick. A
822
+ // stale-ctx error means this closure's session died without its
823
+ // shutdown reaching us — a replacement/reload racing the handler,
824
+ // or a raw AgentSession.dispose() from an SDK/host consumer, which
825
+ // never emits session_shutdown at all (issue #100). Disarm once
826
+ // instead of throwing+logging on every tick (issue #96).
827
+ if (isStaleCtxError(err)) {
828
+ handleStaleCtxInTick("auto");
829
+ } else {
830
+ console.error("[napkin-distill] auto-distill tick failed:", err);
831
+ }
723
832
  }
724
833
  }, intervalMs);
725
834
  });
@@ -1289,17 +1398,27 @@ export default function (pi: ExtensionAPI) {
1289
1398
  }
1290
1399
  };
1291
1400
 
1401
+ // Capture the generation at ARM time so a queued poll tick from an
1402
+ // earlier session that fires after the next session_start re-armed the
1403
+ // flag no-ops before touching its stale ctx (issue #93).
1404
+ const armedGeneration = sessionGeneration;
1292
1405
  pollHandle = setInterval(() => {
1293
1406
  // Queued stale tick after session replacement/reload → clean no-op.
1294
1407
  if (!sessionActive) return;
1408
+ if (armedGeneration !== sessionGeneration) return; // old-session tick → clean no-op (#93)
1295
1409
  try {
1296
1410
  pollTick();
1297
1411
  } catch (err) {
1298
1412
  // A tick must never take down pi (same invariant as the auto-distill
1299
1413
  // interval tick): in the cached-module reload window an old-session
1300
1414
  // 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);
1415
+ // drop (the next session owns all poll state). A stale-ctx error
1416
+ // disarms the auto interval once instead of spamming (issue #96).
1417
+ if (isStaleCtxError(err)) {
1418
+ handleStaleCtxInTick("poll");
1419
+ } else {
1420
+ console.error("[napkin-distill] distill poll tick failed:", err);
1421
+ }
1303
1422
  }
1304
1423
  }, DISTILL_POLL_TICK_MS);
1305
1424
  }
@@ -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
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",
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",