@cad0p/pi-napkin 0.2.4 → 0.3.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
@@ -19,6 +19,13 @@ Then install the pi-napkin extension:
19
19
  pi install npm:@cad0p/pi-napkin
20
20
  ```
21
21
 
22
+ ### Requirements
23
+
24
+ - **bash 4+** — the auto-distill wrapper uses bash arrays, `local -n`, and other bash-4 features. macOS ships bash 3.2 by default; install a newer one via `brew install bash` (the wrapper resolves bash via its `#!/usr/bin/env bash` shebang, so it picks up homebrew's bash if `brew` is on `PATH`).
25
+ - **`timeout(1)` from coreutils** — used to bound the agent's wall-clock budget (`distill.maxDurationMinutes`). Linux distros ship it as `timeout`; macOS ships it as `gtimeout` after `brew install coreutils`. The wrapper detects either binary and falls back fast with a helpful error if neither is present.
26
+ - **git 2.20+** — needed for `git worktree`, `merge-base --is-ancestor`, and `symbolic-ref --short HEAD`.
27
+ - **A `pi` configured with at least one model provider** — auto-distill spawns `pi -p` against the model in `distill.model.{provider,id}`. Manual `/distill` reuses the parent session's provider.
28
+
22
29
  <details>
23
30
  <summary>Pre-release / dev installs</summary>
24
31
 
@@ -206,7 +213,7 @@ Or edit `<vault>/.napkin/config.json` directly:
206
213
 
207
214
  When enabled, on session start the extension:
208
215
 
209
- 1. Runs `ensureVaultReadyForAutoDistill` on the vault (see below) — git-inits if needed and scaffolds `.gitignore` / `.gitattributes`.
216
+ 1. Runs `ensureVaultReadyForAutoDistill` on the vault (see below) — git-inits if needed and scaffolds `.gitignore`.
210
217
  2. Sweeps stale distill worktrees left by crashed pi instances (`cleanupStaleWorktrees`).
211
218
  3. Arms a timer (`intervalMinutes`) that spawns a detached `pi -p` subprocess on tick.
212
219
  4. On shutdown (unless `distill.onShutdown` is false or the session file is already captured), spawns one final distill.
@@ -226,7 +233,7 @@ The distill subprocess runs a prompt that asks the model to:
226
233
  When you enable `distill.enabled: true` on a vault that isn't a git repo, pi-napkin auto-initializes it on the next session start:
227
234
 
228
235
  1. Runs `git init`.
229
- 2. Scaffolds `.gitignore` (excludes `.napkin/distill/` — the per-worktree session fork) and `.gitattributes` (routes `*.md` through the LLM merge driver). Distill worktrees themselves live outside the vault (see [Where worktrees live](#where-worktrees-live)), so `.gitignore` doesn't need to exclude them.
236
+ 2. Scaffolds `.gitignore` (excludes `.napkin/distill/` — the per-worktree session fork). Distill worktrees themselves live outside the vault (see [Where worktrees live](#where-worktrees-live)), so `.gitignore` doesn't need to exclude them. No `.gitattributes` is written — the agent-driven merge architecture has no driver to register.
230
237
  3. Commits everything as `napkin: initial vault commit (auto-distill setup)`.
231
238
  4. Notifies you once, with instructions to undo (`rm -rf <vault>/.git`) or opt out (`distill.enabled: false`).
232
239
 
@@ -250,23 +257,61 @@ Running multiple pi sessions against the same vault (for example, autonomous age
250
257
 
251
258
  ### Worktree per distill
252
259
 
253
- Each auto-distill invocation (interval fire or shutdown) creates its own temporary branch and worktree under `$XDG_CACHE_HOME/napkin-distill/<vault-hash>/<branch-suffix>/` (typically `~/.cache/napkin-distill/…`). pi runs at the **parent session's cwd** (not the worktree) so the system prompt's `Current working directory:` line stays byte-identical to the parent's, preserving prompt-cache hits. Vault writes from the agent's bash tool are routed back to the worktree by a per-distill napkin shim at `<worktree>/.napkin/distill/bin/napkin` that injects `--vault <worktree>` into every napkin invocation. The wrapper's own git operations (`git add` / `commit` / `merge --squash`) all run with `git -C <worktree>` against the isolated checkout. See [Where worktrees live](#where-worktrees-live) for why the worktree dir is external to the vault.
260
+ Each auto-distill invocation (interval fire or shutdown) creates its own temporary branch and worktree under `$XDG_CACHE_HOME/napkin-distill/<vault-hash>/<branch-suffix>/` (typically `~/.cache/napkin-distill/…`). pi runs at the **parent session's cwd** (not the worktree) so the system prompt's `Current working directory:` line stays byte-identical to the parent's, preserving prompt-cache hits. Vault writes from the agent's bash tool are routed back to the worktree by a per-distill napkin shim at `<worktree>/.napkin/distill/bin/napkin` that injects `--vault <worktree>` into every napkin invocation. See [Where worktrees live](#where-worktrees-live) for why the worktree dir is external to the vault.
261
+
262
+ ### How distill resolves conflicts
263
+
264
+ The distill agent owns the full lifecycle: produce content → merge default branch into the distill branch → squash to default → push to origin (if configured) → clean up. The wrapper does NOT invoke a per-file merge driver; the model that wrote the content also resolves any conflicts that surface when the worktree is reconciled with main.
254
265
 
255
- ### LLM merge driver
266
+ Flow:
256
267
 
257
- When the distill commits its changes and merges back to main, conflicts are resolved by a custom git merge driver (`.napkin-distill-merge`) that calls the same model as the distill itself. The driver is registered per-worktree via `git config --local` and routed at the file level by an `*.md merge=napkin-distill-merge` entry in `.gitattributes`.
268
+ 1. **Wrapper** sets up the worktree, installs the per-distill napkin shim, and spawns one `pi -p $PROMPT` invocation under `timeout ${maxDurationMinutes}m`. The prompt instructs the agent to walk steps 1–10 (distill → merge → squash → push → cleanup).
269
+ 2. **Agent** distills content into the worktree, then runs `git -C <worktree> merge --no-edit <default>`. If conflicts surface, it edits each file in place using the conversation history as context.
270
+ 3. **Agent** squash-merges into the vault's default branch (`git -C <vault> merge --squash <distill-branch>` then `git commit`).
271
+ 4. **Agent** pushes to `origin/<default>` if origin is configured. On non-fast-forward failures it recovers via `git pull --no-rebase origin <default>` then re-pushes. It NEVER uses `--force` or `--force-with-lease`.
272
+ 5. **Wrapper** post-validates: no conflict markers in tracked `*.md`, vault HEAD on default branch, push (if attempted) didn't rewrite shared history. Writes an outcome sidecar and force-cleans the worktree + distill branch.
258
273
 
259
- The driver makes three attempts per conflict. After three strikes, the driver exits 1 and git leaves conflict markers — handled by the next step.
274
+ The full prompt template lives at `extensions/distill/distill-prompt.md`. The wrapper bounds the agent's wall-clock with `timeout(1)`; everything else (retry policy, network handling, conflict-resolution shape) is the agent's call.
260
275
 
261
- ### Partial-merge salvage
276
+ ### Outcome classes
262
277
 
263
- If the LLM merge driver fails on some files, we don't abort the whole merge. Files that merged cleanly keep the distill's content; files that failed fall back to main's version via `git checkout main -- <file>`.
278
+ Each distill produces a sidecar at `<vault>/.napkin/distill/errors/<timestamp>-<pid>-<branch>.outcome` whose first line is a machine-readable class:
264
279
 
265
- Think of it as: "save what you can, log what you lost." A per-failure entry is written to `<vault>/.napkin/distill/errors/` so you can inspect what was discarded, and the dangling distill commit SHA is kept for ~2 weeks of git gc grace in case you want to recover it manually.
280
+ | Class | When | UI severity |
281
+ |---|---|---|
282
+ | `merged-content` | Agent produced content, integrated, squashed, and pushed to origin (or origin not configured). | info ✓ |
283
+ | `merged-local` | Agent integrated + squashed, but origin/`<default>` is configured AND local `<default>` is ahead of `origin/<default>` (push didn't land). | warning ⚠ — "distilled but not pushed" |
284
+ | `no-content` | Agent produced nothing (genuine no-op — selective filter), or committed to the distill branch but skipped squash (default branch never moved). | warning ⚠ |
285
+ | `failed:<reason>` | Wrapper validation rejected the agent's output, or the agent didn't complete. | error ✗ |
286
+
287
+ Known `failed:<reason>` codes:
288
+
289
+ | Reason | Meaning | Recovery |
290
+ |---|---|---|
291
+ | `markers-after-agent-exit` | Conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`) found in tracked `*.md` files that the agent did not have at distill start. The agent left an unfinished merge. | The squash commit may already be on `<default>`. Inspect with `git show HEAD`, then `git revert HEAD --no-edit` to undo cleanly. The dangling distill branch is recoverable from `git reflog` for ~2 weeks. |
292
+ | `pre-existing-markers` | Markers were present in the same files BEFORE the agent ran. Validation refuses to misattribute them. | Resolve the pre-existing markers in the vault yourself, then re-run distill. |
293
+ | `internal-validator-error` | The wrapper's post-distill marker validator could NOT run (e.g. `mktemp` failed because of a full disk or locked-down `TMPDIR`), so the vault was never scanned after the agent exited. | Inspect the vault manually for unresolved `<<<<<<< / ======= / >>>>>>>` markers before relying on the squash commit. If clean, the squash is keepable; otherwise `git -C <vault> revert HEAD --no-edit`. Distill content is recoverable from `git reflog` for ~90 days. |
294
+ | `head-not-on-default` | Vault HEAD is not on the default branch after the agent exited (detached HEAD or different branch). | Manually `git checkout <default>` after confirming nothing is in flight. The distill branch lives in `git reflog` if you want to recover its content. |
295
+ | `divergent-history` | After the agent's push, `origin/<default>` and local `<default>` diverged in a way that doesn't look like a fast-forward (unexpected; benign third-party push or — defensively — a force-push). | Inspect `origin/<default>` vs local. If a teammate landed a commit during distill, `git pull --no-rebase` to integrate. |
296
+ | `agent-exit-nonzero` | The agent's `pi -p` invocation exited non-zero with no other diagnostic. | See the error log next to the sidecar for the agent's stderr. |
297
+ | `agent-timeout` | `timeout(1)` killed the agent after `distill.maxDurationMinutes` minutes. | Bump `distill.maxDurationMinutes` if your conversations routinely produce long distills, or check the error log for what the agent was doing when it timed out. |
298
+
299
+ A missing sidecar AND missing error log means the wrapper itself was killed before writing either (SIGKILL, OOM). The JS-side poller surfaces this as "distill terminated abnormally".
300
+
301
+ ### Salvage when validation fails
302
+
303
+ The salvage path is deliberately narrow: the wrapper janitors the **worktree and distill branch**, never the main vault's commit history. If validation fails:
304
+
305
+ - Force-remove the worktree (`git worktree remove --force` + path-safety guard, falling back to `rm -rf` only if the worktree path is a descendant of the resolved cache root).
306
+ - Force-delete the distill branch (`git branch -D`).
307
+ - Write a `failed:<reason>` sidecar with a recovery hint that points at the corrupt squash commit if one landed on `<default>`.
308
+ - Exit 1.
309
+
310
+ The wrapper deliberately does NOT `git reset --hard` or otherwise rewrite the vault's commit history. If the agent's squash landed corrupt content, the user's `git revert HEAD --no-edit` (forward-only) is preferred over a destructive reset that could clobber concurrent edits the user made between distill spawn and validation. The recovery hint in the failed sidecar names the exact command.
266
311
 
267
312
  ### Linear history
268
313
 
269
- Successful distill lifecycles produce exactly one squash commit on `main`, with an LLM-generated summary message. This keeps history clean and makes it easy to revert a bad distill with `git revert <sha>`.
314
+ Successful distill lifecycles produce exactly one squash commit on `main`, with a one-line summary the agent generates from the distill content. This keeps history clean and makes it easy to revert a bad distill with `git revert <sha>`.
270
315
 
271
316
  ## Agent visibility
272
317
 
@@ -308,7 +353,7 @@ If you want auto-distill on an existing Obsidian vault:
308
353
  2. Start a pi session in the vault.
309
354
  3. On session start, pi-napkin prompts to auto-init git if the vault isn't already one.
310
355
 
311
- If your vault IS already a git repo (common for "vault as project"), pi-napkin just adds the `.gitignore` / `.gitattributes` scaffolds and moves on.
356
+ If your vault IS already a git repo (common for "vault as project"), pi-napkin just adds the `.gitignore` scaffold and moves on.
312
357
 
313
358
  ## Troubleshooting
314
359
 
@@ -331,15 +376,18 @@ rm -rf ~/.cache/napkin-distill/
331
376
 
332
377
  Safe — anything valuable is either already committed to main or was never going to commit.
333
378
 
334
- ### Merge driver fails repeatedly
379
+ ### Distill keeps failing (`failed:<reason>`)
380
+
381
+ Outcome sidecar: `<vault>/.napkin/distill/errors/<ISO-timestamp>-<pid>-<branch-hash>.outcome`. First line is the class string (`failed:<reason>`); remaining lines are a human-readable recovery hint.
335
382
 
336
- Error log: `<vault>/.napkin/distill/errors/<ISO-timestamp>-<pid>-<branch-hash>.log`.
383
+ Companion error log (if produced): `<ISO-timestamp>-<pid>-<branch-hash>.log` — wrapper diagnostics + the agent's stderr.
337
384
 
338
- Each log has the conflicted files, the last LLM response, and an optional one-liner describing the failure. Common causes:
385
+ See the [Outcome classes](#outcome-classes) table for what each `<reason>` means and the recommended recovery action. Common patterns:
339
386
 
340
- - Model is rate-limited → retry later.
341
- - LLM returned empty / tiny / huge output → driver sanity-check rejects it. Usually a transient provider issue.
342
- - Conflicted content is genuinely unmergeable (same line added with different content) → the partial-merge salvage falls back to main's version; the distill commit SHA is kept in reflog for ~2 weeks if you want to recover it.
387
+ - `agent-timeout` recurring → bump `distill.maxDurationMinutes` (default 10) or investigate what's taking the agent so long. Log shows the last tool calls before SIGTERM.
388
+ - `markers-after-agent-exit` → the agent's squash commit may already be on `<default>` with literal `<<<<<<<` markers in tracked files. The recovery hint in the sidecar names the exact `git revert HEAD --no-edit` command.
389
+ - `agent-exit-nonzero` → check the model provider (rate limits, auth refresh, network). The agent's stderr is in the `.log` file.
390
+ - `divergent-history` → a teammate likely landed a commit on `origin/<default>` while the agent's distill ran. `git pull --no-rebase` to integrate.
343
391
 
344
392
  ### "vault not a git repo" / "legacy embedded layout"
345
393
 
@@ -356,21 +404,47 @@ The distill wrapper (`extensions/distill/scripts/distill-wrapper.sh`) reads seve
356
404
 
357
405
  | Variable | Purpose |
358
406
  |---|---|
359
- | `NAPKIN_DISTILL_PI_BIN` | Override the `pi` binary path. Tests point this at `/usr/bin/true` (exits 0 quickly) or a stub script so the wrapper completes its lifecycle without contacting a real LLM. |
360
- | `NAPKIN_DISTILL_MERGE_MOCK` | Forwarded to `napkin-distill-merge` (the LLM driver). Set to `fail` to force every conflict to 3-strike, or `ok-after-N` to succeed after N attempts. Used to exercise the partial-merge salvage path. |
361
- | `NAPKIN_DISTILL_SKIP_PI=1` | Skip BOTH the napkin shim install AND the `pi` invocation. Used by tests that pre-stage file changes manually and only want to exercise the wrapper's git lifecycle (commit/merge/squash). |
407
+ | `NAPKIN_DISTILL_PI_BIN` | Override the `pi` binary path. Integration tests under `extensions/distill/test-fixtures/agent-stubs/` point this at a bash stub that simulates a specific agent behavior class (clean-distill, conflict-resolve-clean, agent-timeout, etc.) so the wrapper completes its lifecycle without contacting a real LLM. |
408
+ | `NAPKIN_DISTILL_SKIP_PI=1` | Skip BOTH the napkin shim install AND the `pi` invocation. Used by tests that pre-stage file changes manually and only want to exercise the wrapper's lifecycle (validation, salvage, sidecar emission). |
409
+ | `NAPKIN_DISTILL_NO_RECURSE=1` | Exported by the wrapper into the agent's environment so a nested `pi` won't auto-distill recursively. Tests sometimes set it directly to suppress recursion when invoking the wrapper from inside another distill. |
362
410
  | `NAPKIN_DISTILL_HALT_AFTER_META=1` | Halt right after rewriting `meta.json`'s pid to the wrapper's pid. Lets tests inspect the updated meta without the cleanup trap wiping the worktree. Clears the `EXIT` trap so cleanup is skipped — caller is responsible for tearing down the worktree afterwards. |
363
411
  | `NAPKIN_DISTILL_HALT_AFTER_SHIM=1` | Halt right after the per-distill napkin shim is installed at `<worktree>/.napkin/distill/bin/napkin`. Lets tests inspect the shim contents and PATH injection without the cleanup trap firing. |
364
- | `NAPKIN_DISTILL_FORCE_MERGE_HEAD=1` | Force `MERGE_HEAD` to exist right before the escape-hatch check. Lets tests cover the belt-and-braces "merge did not complete" bail-out path, which isn't reliably triggerable via real driver output (git clears `MERGE_HEAD` on driver exit 0). |
365
- | `NAPKIN_DISTILL_FORCE_MERGE_RC=<n>` | Override the captured merge exit code. Lets tests cover the unexpected-exit-code branch (128 etc.) without contriving a real git failure of that shape. |
412
+ | `NAPKIN_DISTILL_FORCE_CLEANUP=1` | Force the salvage / cleanup path to run unconditionally (even on success). Used to test salvage idempotency. |
413
+ | `NAPKIN_DISTILL_TIMEOUT_KILL_GRACE_SECS=<n>` | Override the `timeout(1) -k` grace window (default 30s) — the delay between SIGTERM and SIGKILL when the agent exceeds `distill.maxDurationMinutes`. Used to keep timeout tests fast. |
366
414
 
367
415
  Production never sets any of these. If you find one in your environment by accident, `unset` it and re-run — the wrapper falls back to its normal behaviour automatically.
368
416
 
369
- ## Future: builder-deleter
417
+ ## Migration from PR #11
370
418
 
371
- 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.
419
+ pi-napkin v0.1.x shipped an LLM-backed git merge driver (`.napkin-distill-merge`). PR #12 (v0.2.x) deleted the driver entirely; the agent now resolves its own conflicts as part of the distill task. New vaults set up by v0.2+ never see the driver. Existing v0.1.x vaults retain inert fragments that are safe to leave in place but cleaner to remove:
420
+
421
+ ```bash
422
+ # In each existing vault that ran v0.1.x distill:
423
+ git config --local --remove-section merge.napkin-distill-merge 2>/dev/null || true
424
+
425
+ # Edit <vault>/.gitattributes and remove this line if present:
426
+ # *.md merge=napkin-distill-merge
427
+ ```
428
+
429
+ Why manual: PR #12 deliberately avoids automatic migration. The orphaned `.gitattributes` rule falls back to git's built-in merge driver once the script is gone (the rule becomes inert, not harmful), so the cost of automating cleanup outweighs the benefit for a project with a small user base. New vaults aren't affected.
430
+
431
+ ## Maintenance
432
+
433
+ ### Verifying the distill flow end-to-end against a real LLM
434
+
435
+ CI uses bash-stub fixtures (`extensions/distill/test-fixtures/agent-stubs/`) to cover the agent-behavior space without burning tokens. For ad-hoc re-validation that the full runtime — wrapper subprocess + agent + JS-side polling — still walks cleanly through a real model, run:
436
+
437
+ ```bash
438
+ bun run verify:e2e
439
+ ```
440
+
441
+ The script (`scripts/verify-e2e.ts`) creates a tmpdir vault with a bare-repo origin, registers the distill extension against a captured mock `ExtensionAPI`, triggers the `/distill` command handler so the production `runDistillWith` path runs (real wrapper subprocess, real 2-second `setInterval` poller), and asserts on the dispatched UI notification's severity + message together with filesystem post-conditions: no conflict markers, HEAD on default branch, agent's squash commit landed, distill branch removed, worktree removed, outcome sidecar with class `merged-content`, and origin advanced. Exits 0 on PASS, 1 on FAIL. Manual-only — not in CI; cost is roughly $0.50 per run.
442
+
443
+ 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.
444
+
445
+ ## Future: builder-deleter
372
446
 
373
- See [features/pi-napkin-distill/builder-deleter](https://github.com/cad0p/pi-napkin/blob/main/features/) (design pending) for the full design.
447
+ 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.
374
448
 
375
449
  ## License
376
450
 
@@ -3,15 +3,24 @@
3
3
  *
4
4
  * Auto-distill needs the vault to be a git repo with a `.gitignore` that
5
5
  * excludes its ephemeral state (distill worktrees, Obsidian workspace-local
6
- * caches) and a `.gitattributes` that registers the LLM merge driver for
7
- * concurrent distill runs. Vaults typically ship without any of this — we
8
- * scaffold it at `session_start` when `distill.enabled` is true.
6
+ * caches). Vaults typically ship without any of this — we scaffold it at
7
+ * `session_start` when `distill.enabled` is true.
8
+ *
9
+ * PR #12 (agent-driven merge): pre-PR-12 auto-distill also installed an
10
+ * `*.md merge=napkin-distill-merge` rule in `.gitattributes` to route
11
+ * concurrent-distill conflicts through an LLM merge driver. PR #12 deleted
12
+ * that driver — the distill agent now resolves merges itself in its
13
+ * worktree, so the rule is no longer needed. New vaults never get the rule
14
+ * installed. Existing vaults that already have it are left alone (manual
15
+ * cleanup; the rule becomes inert once the driver script is gone — git
16
+ * silently falls back to its built-in merge driver). See design.md
17
+ * "Migration" for rationale.
9
18
  *
10
19
  * Design contract:
11
20
  * - Idempotent: re-running on an already-set-up vault is a no-op (returns
12
21
  * `{ initialized: false, scaffolded: [] }`).
13
- * - Non-destructive: never clobbers existing `.gitignore` /
14
- * `.gitattributes` content; only appends missing lines.
22
+ * - Non-destructive: never clobbers existing `.gitignore` content; only
23
+ * appends missing lines.
15
24
  * - Fail-soft: returns `{ error }` instead of throwing so the caller can
16
25
  * surface a notify() and keep the session alive.
17
26
  */
@@ -20,6 +29,8 @@ import { spawnSync } from "node:child_process";
20
29
  import * as fs from "node:fs";
21
30
  import * as path from "node:path";
22
31
 
32
+ import { GIT_SUBCOMMAND_TIMEOUT_MS } from "./distill-workspace";
33
+
23
34
  /**
24
35
  * Lines appended to `<vault>/.gitignore` when scaffolding. Order is stable so
25
36
  * diff noise stays minimal on re-runs. Each group has a section-comment
@@ -55,16 +66,6 @@ export const GITIGNORE_LINES: readonly string[] = [
55
66
  ".aws/credentials",
56
67
  ];
57
68
 
58
- /**
59
- * Lines appended to `<vault>/.gitattributes` when scaffolding. Registers the
60
- * `napkin-distill-merge` driver for every `.md` file so parallel distill
61
- * runs hit the LLM merge path on conflict.
62
- */
63
- export const GITATTRIBUTES_LINES: readonly string[] = [
64
- "# napkin-distill: LLM merge driver for concurrent auto-distill",
65
- "*.md merge=napkin-distill-merge",
66
- ];
67
-
68
69
  /**
69
70
  * Result of {@link ensureVaultReadyForAutoDistill}.
70
71
  *
@@ -74,11 +75,6 @@ export const GITATTRIBUTES_LINES: readonly string[] = [
74
75
  * - `error`: populated on fail-soft paths (git init failed, filesystem
75
76
  * errors writing the scaffolding, legacy-layout refusal). If set, other
76
77
  * fields reflect partial progress.
77
- * - `conflict`: populated when auto-setup refused to scaffold because the
78
- * existing `.gitattributes` already claims `*.md merge=<something-else>`.
79
- * `error` is also set with a short `"conflicting merge rule…"` message so
80
- * existing fail-soft callers keep working; `conflict` carries the
81
- * diagnostic details (rule text, file path) for a precise notify.
82
78
  * - `legacyLayout`: populated when auto-setup refused to scaffold because
83
79
  * the vault is using napkin's legacy embedded layout (`configPath ===
84
80
  * contentPath`). The worktree-based concurrency architecture relies on
@@ -91,14 +87,6 @@ export interface SetupResult {
91
87
  initialized: boolean;
92
88
  scaffolded: string[];
93
89
  error?: string;
94
- conflict?: {
95
- /** The full offending line as it appears in `.gitattributes`. */
96
- rule: string;
97
- /** Absolute path to the `.gitattributes` that contains the conflict. */
98
- file: string;
99
- /** Just the `<driver>` captured from `*.md merge=<driver>`. */
100
- driver: string;
101
- };
102
90
  legacyLayout?: {
103
91
  /** Absolute path to the vault's `.napkin/` (= contentPath for legacy). */
104
92
  configPath: string;
@@ -155,7 +143,7 @@ function runGit(
155
143
  const r = spawnSync("git", args, {
156
144
  cwd,
157
145
  encoding: "utf-8",
158
- timeout: 30_000,
146
+ timeout: GIT_SUBCOMMAND_TIMEOUT_MS,
159
147
  env: process.env,
160
148
  });
161
149
  return {
@@ -221,61 +209,8 @@ function mergeLines(filePath: string, newLines: readonly string[]): boolean {
221
209
  }
222
210
 
223
211
  /**
224
- * Expected driver name set by {@link GITATTRIBUTES_LINES}. Exported so tests
225
- * can assert the symmetric pair without re-parsing the scaffold string.
226
- */
227
- export const NAPKIN_MERGE_DRIVER = "napkin-distill-merge";
228
-
229
- /**
230
- * If the vault's `.gitattributes` already contains an `*.md merge=<driver>`
231
- * rule whose driver is NOT our `napkin-distill-merge`, return its details.
232
- * Returns `null` when there's no conflict (no rule, or the existing rule is
233
- * already ours).
234
- *
235
- * Scope: deliberately narrow. We only check for the EXACT pattern `*.md`
236
- * with a `merge=` attribute — pattern-overlap cases (e.g. `notes/** merge=
237
- * union` + our `*.md merge=napkin-distill-merge` both matching
238
- * `notes/x.md`) are not flagged. Those would need a full gitattributes
239
- * parser and are rare enough in practice that the noise of false positives
240
- * outweighs the value of catching them. The common case is a user who has
241
- * `*.md merge=union` globally and would silently get our driver layered on
242
- * top via last-match-wins; that case is what this catches.
243
- *
244
- * Pattern matching is case-insensitive (`*.MD` is detected too). On macOS
245
- * (APFS default) and Windows (NTFS default) filesystems, git's pattern
246
- * matching respects `core.ignorecase=true`, so `*.MD merge=union` DOES
247
- * apply to `foo.md` files — silently overriding our driver via
248
- * last-match-wins is exactly the scenario this detector exists to
249
- * prevent.
250
- *
251
- * The returned `rule` preserves the full original line (for accurate error
252
- * messages) and `driver` is just the captured driver name.
253
- */
254
- export function detectConflictingMdMergeRule(
255
- gaPath: string,
256
- ): { rule: string; driver: string } | null {
257
- if (!fs.existsSync(gaPath)) return null;
258
- const contents = fs.readFileSync(gaPath, "utf-8");
259
- for (const rawLine of contents.split("\n")) {
260
- const line = rawLine.trim();
261
- if (line.length === 0 || line.startsWith("#")) continue;
262
- // Match: `*.md` (exactly) followed by whitespace, with a `merge=<name>`
263
- // attribute somewhere on the line. Other attributes on the same line
264
- // (diff=..., text, etc.) are ignored — only the merge driver conflicts
265
- // with ours. Case-insensitive to honor `core.ignorecase=true` on
266
- // APFS/NTFS (default on macOS and Windows).
267
- const m = line.match(/^\*\.md\s+(?:.*\s+)?merge=([A-Za-z0-9_.-]+)/i);
268
- if (!m) continue;
269
- const driver = m[1];
270
- if (driver === NAPKIN_MERGE_DRIVER) continue; // Our own rule, idempotent.
271
- return { rule: line, driver };
272
- }
273
- return null;
274
- }
275
-
276
- /**
277
- * Ensure `<vaultPath>` is a git repo with a `.gitignore` / `.gitattributes`
278
- * that cover auto-distill's needs. Called once per `session_start` when
212
+ * Ensure `<vaultPath>` is a git repo with a `.gitignore` that covers
213
+ * auto-distill's needs. Called once per `session_start` when
279
214
  * `distill.enabled` is true.
280
215
  *
281
216
  * Lifecycle:
@@ -285,16 +220,12 @@ export function detectConflictingMdMergeRule(
285
220
  * subdir that findVault could resolve to. Returns `{ error:
286
221
  * "legacy-embedded-layout", legacyLayout }` without touching git.
287
222
  * 1. If `.git/` is missing → `git init`. Failure here aborts with `error`.
288
- * 2. Detect a conflicting `*.md merge=<other>` in an existing
289
- * `.gitattributes`. If present, return `{ error, conflict }` WITHOUT
290
- * writing our rule — gitattributes is last-match-wins and silently
291
- * layering our driver on top would override the user's chosen one.
292
- * 3. Merge scaffolding lines into `.gitignore` and `.gitattributes`
293
- * (idempotent; no-op if already present).
294
- * 4. If anything changed:
223
+ * 2. Merge scaffolding lines into `.gitignore` (idempotent; no-op if
224
+ * already present).
225
+ * 3. If anything changed:
295
226
  * - fresh init → `git add .` + commit `"napkin: initial vault commit
296
227
  * (auto-distill setup)"`
297
- * - existing repo → `git add .gitignore .gitattributes` + commit
228
+ * - existing repo → `git add .gitignore` + commit
298
229
  * `"napkin: scaffold auto-distill git config"`
299
230
  *
300
231
  * Returned `scaffolded` always uses vault-relative paths so notify messages
@@ -344,33 +275,14 @@ export function ensureVaultReadyForAutoDistill(vault: SetupVault): SetupResult {
344
275
  initialized = true;
345
276
  }
346
277
 
347
- // Guard against silently overriding a user-chosen `*.md merge=...` rule.
348
- // gitattributes is last-match-wins, so appending our driver without
349
- // warning would bypass their choice the next time they edit a .md file.
350
- // Refuse to scaffold and surface a `conflict` so the caller can prompt
351
- // the user to resolve it explicitly.
352
- const gaPath = path.join(vaultPath, ".gitattributes");
353
- const conflict = detectConflictingMdMergeRule(gaPath);
354
- if (conflict) {
355
- return {
356
- initialized,
357
- scaffolded: [],
358
- error: `conflicting merge rule in .gitattributes: '${conflict.rule}'`,
359
- conflict: {
360
- rule: conflict.rule,
361
- file: gaPath,
362
- driver: conflict.driver,
363
- },
364
- };
365
- }
366
-
367
278
  const scaffolded: string[] = [];
368
279
 
369
280
  try {
370
281
  const giPath = path.join(vaultPath, ".gitignore");
371
282
  if (mergeLines(giPath, GITIGNORE_LINES)) scaffolded.push(".gitignore");
372
- if (mergeLines(gaPath, GITATTRIBUTES_LINES))
373
- scaffolded.push(".gitattributes");
283
+ // PR #12: no `.gitattributes` scaffolding. Pre-PR-12 we wrote an
284
+ // `*.md merge=napkin-distill-merge` line; the agent-driven merge
285
+ // architecture has no driver to register.
374
286
  } catch (err) {
375
287
  const msg = err instanceof Error ? err.message : String(err);
376
288
  return {
@@ -441,9 +353,9 @@ export function ensureVaultReadyForAutoDistill(vault: SetupVault): SetupResult {
441
353
  // hand and never committed leaves HEAD unresolvable. Seed an empty
442
354
  // initial commit so `git worktree add ... HEAD` has something to pin to.
443
355
  // This also covers the narrow window where `git init` succeeded above
444
- // (we set `initialized = true`) but scaffolding wrote zero lines (both
445
- // .gitignore and .gitattributes already present with our exact content)
446
- // — that would fall into neither branch and leave a commit-less repo.
356
+ // (we set `initialized = true`) but scaffolding wrote zero lines
357
+ // (`.gitignore` already present with our exact content) — that would
358
+ // fall into neither branch and leave a commit-less repo.
447
359
  let seededCommit: SetupResult["seededCommit"];
448
360
  const headAfter = runGit(vaultPath, ["rev-parse", "--verify", "HEAD"]);
449
361
  if (headAfter.status !== 0) {
@@ -0,0 +1,58 @@
1
+ Your distill content lives in the git worktree at {{worktreePath}}. Use `git -C {{worktreePath}}` for all git operations there — your shell cwd is NOT the worktree. Edit files in the worktree by absolute path under `{{worktreePath}}/...` (or `cd {{worktreePath}}` first if your tool supports it).
2
+
3
+ For the distill-content phase (steps 1-6), edit files only inside `{{worktreePath}}`; do not edit files under `{{vaultPath}}`. Writing distill content to `{{vaultPath}}` directly bypasses the worktree's isolation and causes the merge in steps 7-8 to silently include none of your changes. The integration phase (steps 7-9) explicitly runs `git -C {{vaultPath}}` commands to squash and push — those are correct and required, not a violation of this rule.
4
+
5
+ Distill this conversation into the napkin vault, then integrate your changes back into the main vault yourself. The wrapper that invoked you will only validate the result; it will NOT run merge, squash, push, or cleanup on your behalf.
6
+
7
+ 1. `napkin overview` — learn the vault structure and what exists. Read `_about.md` files to understand what each folder is for. These are short folder descriptions (1-2 paragraphs) explaining what kinds of notes belong there — see existing ones for style.
8
+ 2. `napkin template list` and `napkin template read` — learn the note formats.
9
+ 3. Identify what's worth capturing. The vault structure and templates tell you what kinds of notes belong.
10
+ 4. For each note:
11
+ a. `napkin search` for the topic — if a note already covers it, `napkin append` instead of creating a duplicate
12
+ b. Create new notes with `napkin create`, following the template format; use the relevant folder path
13
+ c. Add `[[wikilinks]]` to related notes
14
+ 5. Append a brief summary of key activities and decisions to today's daily note in the relevant namespace (e.g. `{namespace}/daily/YYYY-MM-DD.md`). Follow existing patterns. Create it if it doesn't exist.
15
+ 6. Frontmatter convention: when you create a note that replaces an older one, add `supersedes: ["path/to/old/note.md"]` to its frontmatter. A future janitor will archive the superseded note. Leave the field empty or omit it for notes that stand alone.
16
+
17
+ Be selective. Only capture knowledge useful to someone working on this project later. Skip meta-discussion, tool output, and chatter.
18
+
19
+ 7. Integrate with main. If you decided nothing in this conversation merits capturing (per "Be selective" above), skip steps 7-9 entirely and exit — the wrapper will classify this as `no-content` and surface a warning to the user. Otherwise, from the worktree at {{worktreePath}}, commit your distilled content first if you haven't already:
20
+
21
+ git -C {{worktreePath}} add -A
22
+ git -C {{worktreePath}} commit -m "distill: <one-line summary>"
23
+
24
+ Then merge {{defaultBranch}} into your distill branch:
25
+
26
+ git -C {{worktreePath}} merge --no-edit {{defaultBranch}}
27
+
28
+ `--no-edit` accepts git's auto-generated merge commit message non-interactively; without it, git would open `core.editor` on a clean auto-merge and your bash tool (which has no TTY) would hang or fail.
29
+
30
+ If conflicts arise, you will see files with standard `<<<<<<<`, `=======`, `>>>>>>>` markers. Resolve each by editing the file in place to produce the correct merged content. Use the conversation history above to inform your choices — you have full context on what content you intended to add. Once all markers are gone:
31
+
32
+ git -C {{worktreePath}} add .
33
+ git -C {{worktreePath}} commit --no-edit
34
+
35
+ If `git -C {{worktreePath}} merge --no-edit {{defaultBranch}}` reports "Already up to date" (no merge commit), that's fine — proceed.
36
+
37
+ 8. Squash to main. From the main vault at {{vaultPath}}, switch to the default branch and squash-merge your branch:
38
+
39
+ git -C {{vaultPath}} checkout {{defaultBranch}}
40
+ git -C {{vaultPath}} merge --squash {{branchName}}
41
+ git -C {{vaultPath}} commit -m "distill: <one-line summary of what you captured>"
42
+
43
+ Use `--squash` to keep main's history linear (one commit per distill). If `git merge --squash` produces no staged changes (e.g. your distill content was already on main), skip the commit step — there's nothing new to land.
44
+
45
+ 9. Push if origin exists. Check `git -C {{vaultPath}} remote -v`. If `origin/{{defaultBranch}}` is configured, push your changes:
46
+
47
+ git -C {{vaultPath}} push origin {{defaultBranch}}
48
+
49
+ If push fails because the remote moved, recover with pull-merge-push (NOT pull-rebase):
50
+
51
+ git -C {{vaultPath}} pull --no-rebase origin {{defaultBranch}}
52
+ git -C {{vaultPath}} push origin {{defaultBranch}}
53
+
54
+ `--no-rebase` forces merge semantics regardless of any global `pull.rebase` config the user may have set.
55
+
56
+ NEVER use `--force` or `--force-with-lease`. If push fails for any reason and you cannot recover, stop — do not loop indefinitely. The wrapper will detect local-only state and surface a warning to the user.
57
+
58
+ Report progress concisely as you go. Stop when steps 1-9 are complete.