@cad0p/pi-napkin 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * File-write detection for the distill overlap-notice mechanism.
3
+ *
4
+ * Adapted from pi's internal `extractFileOpsFromMessage`:
5
+ * @earendil-works/pi-coding-agent@0.74.0
6
+ * dist/core/compaction/utils.js — `extractFileOpsFromMessage`
7
+ *
8
+ * That function is not exported from pi's public API, so we reimplement
9
+ * the small subset we need (just the file-mutation part). Sync with pi
10
+ * upstream when the tool catalog changes — if pi adds a new write-class
11
+ * tool (or renames "write"/"edit"), update WRITE_CLASS_TOOLS accordingly.
12
+ *
13
+ * A companion sanity test (session-touched-files.version-check.test.ts)
14
+ * asserts the upstream function is still present at the expected path, so
15
+ * a regression is caught at test time rather than silently diverging.
16
+ *
17
+ * // Reimplemented from pi's internal extractFileOpsFromMessage
18
+ * // Original: @earendil-works/pi-coding-agent ^0.74.0
19
+ * // dist/core/compaction/utils.js — extractFileOpsFromMessage / computeFileLists
20
+ * // Not exported; sync with pi upstream when tool catalog changes.
21
+ *
22
+ * Used by `postOverlapNoticeOnCompletion` in extensions/distill/index.ts
23
+ * (per-distill-completion trigger, R7-PERF-2 redesign): walks the
24
+ * parent session's entries since the previous distill's completion to
25
+ * compute which files the parent has written, then intersects with the
26
+ * just-completed distill's touched files (`git log --name-only
27
+ * <startSha>..HEAD` from the main vault).
28
+ *
29
+ * Responsibility split:
30
+ * - `extractFileOpsFromMessage`: pure, per-message, returns paths. No
31
+ * I/O, no state — friendly for unit tests.
32
+ * - `getSessionTouchedFiles`: walks a SessionEntriesSource's entries,
33
+ * unions the per-message paths, returns a deduped `Set<string>`.
34
+ * Callers can pass a slice-bounded source to scope the walk to a
35
+ * subrange of entries.
36
+ */
37
+
38
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
39
+
40
+ /**
41
+ * Tool names that mutate files, as used by pi's built-in tools. Kept in one
42
+ * place so the version-pin test can assert it matches upstream.
43
+ *
44
+ * Pi's `extractFileOpsFromMessage` tracks "read" separately from write/edit
45
+ * for a context-aware truncation pass; for overlap detection we only care
46
+ * about files that were *written*, so "read" is intentionally excluded.
47
+ *
48
+ * Exported so tests can round-trip the set.
49
+ */
50
+ export const WRITE_CLASS_TOOLS: ReadonlySet<string> = new Set([
51
+ "write",
52
+ "edit",
53
+ ]);
54
+
55
+ /**
56
+ * Minimal tool-call shape used here. Intentionally structural so this file
57
+ * doesn't need a tight coupling to pi-ai's AssistantMessage internals —
58
+ * those types evolve across pi minor versions and we want the version-
59
+ * check test (not the compiler) to be the pin signal.
60
+ */
61
+ interface ToolCallLike {
62
+ type: "toolCall";
63
+ name: string;
64
+ arguments?: unknown;
65
+ }
66
+
67
+ function isToolCall(block: unknown): block is ToolCallLike {
68
+ return (
69
+ typeof block === "object" &&
70
+ block !== null &&
71
+ "type" in block &&
72
+ (block as { type?: unknown }).type === "toolCall" &&
73
+ typeof (block as { name?: unknown }).name === "string"
74
+ );
75
+ }
76
+
77
+ /**
78
+ * Assistant-message shape this file actually depends on.
79
+ */
80
+ interface AssistantMessageShape {
81
+ role: string;
82
+ content?: unknown;
83
+ }
84
+
85
+ /**
86
+ * Walk an assistant message's content blocks and return the file paths
87
+ * referenced by any write-class tool call. Best-effort:
88
+ * - Only looks at blocks with `type === "toolCall"`.
89
+ * - Only considers tool names in `WRITE_CLASS_TOOLS`.
90
+ * - Extracts `arguments.path` when it's a string (pi's Write/Edit both
91
+ * use `path` as the canonical key).
92
+ * - Also detects a narrow class of bash redirection patterns
93
+ * (`> path`, `>> path`, `tee path`) so an agent that shells out for
94
+ * writes isn't invisible to overlap detection.
95
+ *
96
+ * Duplicates ARE NOT deduped here — callers union with a Set.
97
+ *
98
+ * Returns an empty array for non-assistant messages and for assistant
99
+ * messages without any qualifying tool calls.
100
+ */
101
+ export function extractFileOpsFromMessage(
102
+ msg: AssistantMessageShape,
103
+ ): string[] {
104
+ if (msg.role !== "assistant") return [];
105
+ if (!Array.isArray(msg.content)) return [];
106
+
107
+ const paths: string[] = [];
108
+ for (const block of msg.content) {
109
+ if (!isToolCall(block)) continue;
110
+ const args = block.arguments;
111
+ if (!args || typeof args !== "object") continue;
112
+
113
+ // Write/Edit class: extract `path` if it's a string.
114
+ if (WRITE_CLASS_TOOLS.has(block.name)) {
115
+ const p = (args as { path?: unknown }).path;
116
+ if (typeof p === "string" && p.length > 0) paths.push(p);
117
+ continue;
118
+ }
119
+
120
+ // Bash: try to pick out common redirection targets. Deliberately
121
+ // conservative — a bash command can do anything, so overlap detection
122
+ // for bash-driven writes is a best-effort heuristic, not a promise.
123
+ if (block.name === "bash") {
124
+ const cmd = (args as { command?: unknown }).command;
125
+ if (typeof cmd !== "string") continue;
126
+ for (const p of extractBashRedirectionTargets(cmd)) paths.push(p);
127
+ }
128
+ }
129
+ return paths;
130
+ }
131
+
132
+ /**
133
+ * Very narrow heuristic: spot shell commands that write to a file via
134
+ * `>`, `>>`, or `tee`. Only captures the FIRST target on each operator to
135
+ * keep false-positives low. Quoted paths are stripped of their outer
136
+ * single or double quotes; shell escapes are left alone (caller treats
137
+ * paths as opaque identifiers).
138
+ *
139
+ * Examples that match:
140
+ * echo hi > foo.txt → ["foo.txt"]
141
+ * cat a.md >> log.txt → ["log.txt"]
142
+ * make 2>&1 | tee /tmp/build.log → ["/tmp/build.log"]
143
+ * echo x > "path with spaces.md" → ["path with spaces.md"]
144
+ *
145
+ * Does NOT match (returns empty):
146
+ * ls -la → []
147
+ *
148
+ * Exported for unit tests; not part of the public API of this module.
149
+ */
150
+ export function extractBashRedirectionTargets(command: string): string[] {
151
+ const out: string[] = [];
152
+ // Matches `>` or `>>` not preceded by `2` or `&` (to skip 2>&1 style fd
153
+ // duplication) followed by optional whitespace and a bare word / quoted
154
+ // string. The bare-word form excludes shell separators (`;`, `|`, `&`) so
155
+ // `echo a > one.md; echo b >> two.md` captures two distinct targets
156
+ // instead of swallowing the separator. Pathological shell is not our
157
+ // target — these are heuristics for overlap detection, not a parser.
158
+ const redirRe = /(?<![2&])>>?\s*("([^"]+)"|'([^']+)'|([^\s;|&]+))/g;
159
+ let m = redirRe.exec(command);
160
+ while (m !== null) {
161
+ let target = m[2] ?? m[3] ?? m[4];
162
+ // Strip trailing shell terminators (;, &, |, `) that greedy \S+ matched.
163
+ target = target.replace(/[;&|`]+$/, "");
164
+ if (target && target.length > 0) out.push(target);
165
+ m = redirRe.exec(command);
166
+ }
167
+
168
+ // `tee <file>` — `tee -a <file>` also matches. Skip `tee` options like
169
+ // `-a`, `--append`, `-i`, `--ignore-interrupts`, `--`.
170
+ const teeRe = /\btee\s+((?:-\w+\s+|--\w+\s+)*)(\S+)/g;
171
+ let t = teeRe.exec(command);
172
+ while (t !== null) {
173
+ // Strip matching outer quotes off the target, if any.
174
+ let target = t[2];
175
+ const q = target[0];
176
+ if ((q === '"' || q === "'") && target.endsWith(q)) {
177
+ target = target.slice(1, -1);
178
+ }
179
+ if (target.length > 0) out.push(target);
180
+ t = teeRe.exec(command);
181
+ }
182
+
183
+ return out;
184
+ }
185
+
186
+ /**
187
+ * SessionManager read surface the overlap injector actually needs. Accepting
188
+ * a structural type (not the full class) keeps tests lightweight.
189
+ */
190
+ export interface SessionEntriesSource {
191
+ getEntries(): SessionEntry[];
192
+ }
193
+
194
+ /**
195
+ * Union all file paths touched by assistant messages in the source.
196
+ * Deduped via Set. Returns an empty Set for a source that hasn't
197
+ * mutated any files (including fresh sessions / empty slices).
198
+ *
199
+ * Walks `getEntries()` rather than `getBranch()`: the per-completion
200
+ * overlap mechanism (R7-PERF-2) cares about "has the parent written
201
+ * X since the previous distill completion?" Caller bounds the walk by
202
+ * passing a slice-of-entries source (e.g.
203
+ * `{ getEntries: () => allEntries.slice(cursor) }`).
204
+ */
205
+ export function getSessionTouchedFiles(sm: SessionEntriesSource): Set<string> {
206
+ const out = new Set<string>();
207
+ for (const entry of sm.getEntries()) {
208
+ if (entry.type !== "message") continue;
209
+ const msg = (entry as { message?: AssistantMessageShape }).message;
210
+ if (!msg || msg.role !== "assistant") continue;
211
+ for (const p of extractFileOpsFromMessage(msg)) {
212
+ out.add(p);
213
+ }
214
+ }
215
+ return out;
216
+ }
@@ -0,0 +1,68 @@
1
+ import type { SessionShutdownEvent } from "@earendil-works/pi-coding-agent";
2
+
3
+ /**
4
+ * Pure predicate that decides whether a distill subprocess should be spawned
5
+ * at session shutdown. No I/O, no side effects \u2014 callers assemble the inputs.
6
+ *
7
+ * Guard order matches the spec ("Guard order in shutdown handler"):
8
+ * 1. NAPKIN_DISTILL_NO_RECURSE set \u2192 false (inside a distill subprocess)
9
+ * 2. event.reason === "reload" \u2192 false (session continues; pi 0.74+ fires
10
+ * session_shutdown before a reload-triggered
11
+ * session_start, so we avoid double-distill)
12
+ * 3. autoDistillSuppressed === true \u2192 false (/distill-auto-this-session off)
13
+ * 4. !config.enabled \u2192 false (vault-level master switch)
14
+ * 5. config.onShutdown === false \u2192 false (per-vault shutdown opt-out)
15
+ * 6. !sessionFile \u2192 false (ephemeral session, nothing to fork)
16
+ * 7. currentSize === 0 \u2192 false (nothing happened)
17
+ * 8. currentSize === lastSpawnedSize \u2192 false (interval distill just took this exact content)
18
+ * 9. currentSize === lastSessionSize \u2192 false (previous distill completed on this exact size)
19
+ * otherwise \u2192 true
20
+ *
21
+ * @param event Shutdown event from pi (SessionShutdownEvent). `reason` is
22
+ * a discriminated string present in pi >= 0.68.0 (the peer
23
+ * dep floor). Earlier versions are unsupported.
24
+ * @param config Vault distill config.
25
+ * @param autoDistillSuppressed Session-scoped toggle from /distill-auto-this-session.
26
+ * @param sessionFile Path to the current session .jsonl, or undefined/empty
27
+ * for ephemeral sessions.
28
+ * @param currentSize Byte size of sessionFile right now.
29
+ * @param lastSpawnedSize Byte size captured at the last successful distill SPAWN
30
+ * (set before completion poll). Dedupes "shutdown just after
31
+ * interval fired" without blocking new-content shutdowns.
32
+ * @param lastSessionSize Byte size captured at the last successful distill COMPLETION.
33
+ */
34
+ export interface ShouldDistillOnShutdownConfig {
35
+ enabled: boolean;
36
+ onShutdown: boolean;
37
+ }
38
+
39
+ export function shouldDistillOnShutdown(
40
+ event: Pick<SessionShutdownEvent, "reason">,
41
+ config: ShouldDistillOnShutdownConfig,
42
+ autoDistillSuppressed: boolean,
43
+ sessionFile: string | undefined | null,
44
+ currentSize: number,
45
+ lastSpawnedSize: number,
46
+ lastSessionSize: number,
47
+ ): boolean {
48
+ // 1. Recursion guard \u2014 we're inside a distill subprocess.
49
+ if (process.env.NAPKIN_DISTILL_NO_RECURSE) return false;
50
+ // 2. Session is just reloading; it'll pick up again momentarily.
51
+ if (event.reason === "reload") return false;
52
+ // 3. Per-session /distill-auto-this-session off.
53
+ if (autoDistillSuppressed) return false;
54
+ // 4. Master switch.
55
+ if (!config.enabled) return false;
56
+ // 5. Per-vault shutdown opt-out.
57
+ if (config.onShutdown === false) return false;
58
+ // 6. Ephemeral session (nothing to fork).
59
+ if (!sessionFile) return false;
60
+ // 7. Nothing happened.
61
+ if (currentSize === 0) return false;
62
+ // 8. Interval distill just grabbed this exact content (race).
63
+ if (currentSize === lastSpawnedSize) return false;
64
+ // 9. Previous distill completed on this exact content.
65
+ if (currentSize === lastSessionSize) return false;
66
+
67
+ return true;
68
+ }
@@ -0,0 +1,259 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { Napkin } from "@cad0p/napkin";
4
+ import {
5
+ type AgentToolResult,
6
+ type ExtensionAPI,
7
+ keyHint,
8
+ type SessionManager,
9
+ type Theme,
10
+ type ToolRenderResultOptions,
11
+ } from "@earendil-works/pi-coding-agent";
12
+ import { Markdown, Text } from "@earendil-works/pi-tui";
13
+ import { Type } from "@sinclair/typebox";
14
+
15
+ function loadShowStatus(vaultPath: string): boolean {
16
+ const configPath = path.join(vaultPath, "config.json");
17
+ if (!fs.existsSync(configPath)) return true;
18
+ try {
19
+ const raw = JSON.parse(fs.readFileSync(configPath, "utf-8"));
20
+ return raw.showStatus !== false;
21
+ } catch {
22
+ return true;
23
+ }
24
+ }
25
+
26
+ function formatKbResult(
27
+ result: AgentToolResult<unknown>,
28
+ options: ToolRenderResultOptions,
29
+ theme: Theme,
30
+ maxCollapsedLines: number,
31
+ ): string {
32
+ const output = result.content
33
+ .flatMap((c) => (c.type === "text" ? [c.text] : []))
34
+ .join("\n")
35
+ .trimEnd();
36
+ if (!output) return "";
37
+ const lines = output.split(/\r?\n/);
38
+ const maxLines = options.expanded ? lines.length : maxCollapsedLines;
39
+ const displayLines = lines.slice(0, maxLines);
40
+ const remaining = lines.length - maxLines;
41
+ let text = `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`;
42
+ if (remaining > 0) {
43
+ text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")})`;
44
+ }
45
+ return text;
46
+ }
47
+
48
+ function getNapkin(cwd: string): Napkin {
49
+ return new Napkin(cwd);
50
+ }
51
+
52
+ function getOverview(n: Napkin): string | null {
53
+ try {
54
+ const overview = n.overview();
55
+ if (!overview) return null;
56
+
57
+ let text = overview.context || "";
58
+ if (overview.overview && overview.overview.length > 0) {
59
+ text += "\n\n";
60
+ for (const folder of overview.overview) {
61
+ text += `${folder.path}/\n`;
62
+ if (folder.keywords && folder.keywords.length > 0) {
63
+ text += ` keywords: ${folder.keywords.join(", ")}\n`;
64
+ }
65
+ text += ` notes: ${folder.notes}\n`;
66
+ }
67
+ }
68
+ return text.trim() || null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ export default function (pi: ExtensionAPI) {
75
+ let hasVault = false;
76
+
77
+ pi.registerMessageRenderer(
78
+ "napkin-context",
79
+ (message, { expanded }, theme) => {
80
+ if (!expanded) {
81
+ const label = theme.fg("customMessageLabel", "🧻 napkin vault context");
82
+ const hint = theme.fg("dim", " — Ctrl+O to expand");
83
+ return new Text(label + hint, 1, 0);
84
+ }
85
+ // pi typed message.content as `string | (TextContent | ImageContent)[]`;
86
+ // we only ever set string content via appendCustomMessageEntry so just
87
+ // narrow here. Fallback to empty string if an image-bearing custom
88
+ // message sneaks in — the Markdown renderer can't represent images.
89
+ const body =
90
+ typeof message.content === "string"
91
+ ? message.content
92
+ : message.content
93
+ .filter(
94
+ (c): c is { type: "text"; text: string } => c.type === "text",
95
+ )
96
+ .map((c) => c.text)
97
+ .join("");
98
+ return new Markdown(
99
+ body,
100
+ 1,
101
+ 0,
102
+ {
103
+ heading: (t) => theme.fg("mdHeading", t),
104
+ link: (t) => theme.fg("mdLink", t),
105
+ linkUrl: (t) => theme.fg("mdLinkUrl", t),
106
+ code: (t) => theme.fg("mdCode", t),
107
+ codeBlock: (t) => theme.fg("mdCodeBlock", t),
108
+ codeBlockBorder: (t) => theme.fg("mdCodeBlockBorder", t),
109
+ quote: (t) => theme.fg("mdQuote", t),
110
+ quoteBorder: (t) => theme.fg("mdQuoteBorder", t),
111
+ hr: (t) => theme.fg("mdHr", t),
112
+ listBullet: (t) => theme.fg("mdListBullet", t),
113
+ bold: (t) => theme.bold(t),
114
+ italic: (t) => theme.italic(t),
115
+ strikethrough: (t) => theme.strikethrough(t),
116
+ underline: (t) => theme.underline(t),
117
+ },
118
+ { color: (t) => theme.fg("customMessageText", t) },
119
+ );
120
+ },
121
+ );
122
+
123
+ pi.on("session_start", async (_event, ctx) => {
124
+ let n: Napkin;
125
+ try {
126
+ n = getNapkin(ctx.cwd);
127
+ } catch {
128
+ return;
129
+ }
130
+
131
+ const overview = getOverview(n);
132
+ hasVault = !!overview;
133
+
134
+ if (overview) {
135
+ // Check if we already injected context in this session
136
+ const alreadyInjected = ctx.sessionManager
137
+ .getEntries()
138
+ .some(
139
+ (e) =>
140
+ e.type === "custom_message" &&
141
+ (e as { customType?: string }).customType === "napkin-context",
142
+ );
143
+
144
+ if (!alreadyInjected) {
145
+ // pi's ExtensionContext narrows sessionManager to
146
+ // ReadonlySessionManager, which omits mutation methods. At runtime
147
+ // it's always the full SessionManager, but if pi ever wraps the
148
+ // instance in a genuine readonly proxy the mutation method will
149
+ // either be absent or throw. Guard both the duck-type and the
150
+ // call so the worst-case is a degraded (no context injection)
151
+ // session, not a fatal extension error. (R2-2)
152
+ const sm = ctx.sessionManager as Partial<SessionManager>;
153
+ if (typeof sm.appendCustomMessageEntry === "function") {
154
+ try {
155
+ sm.appendCustomMessageEntry(
156
+ "napkin-context",
157
+ "## Napkin vault context\n" +
158
+ "You have access to a napkin vault (Obsidian-compatible knowledge base). " +
159
+ "Here is the vault overview. Use the kb_search tool to find specific content, " +
160
+ "and the kb_read tool to read files.\n\n" +
161
+ overview,
162
+ true,
163
+ );
164
+ } catch (err) {
165
+ // Graceful degradation: pi may have tightened the readonly
166
+ // contract at runtime. Surface once, then proceed without
167
+ // context injection.
168
+ if (ctx.hasUI) {
169
+ ctx.ui.notify(
170
+ `napkin-context: could not inject vault overview (${
171
+ err instanceof Error ? err.message : String(err)
172
+ })`,
173
+ "warning",
174
+ );
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+
181
+ if (ctx.hasUI && loadShowStatus(n.vault.configPath)) {
182
+ const theme = ctx.ui.theme;
183
+ if (hasVault) {
184
+ ctx.ui.setStatus("napkin", `🧻${theme.fg("dim", " napkin")}`);
185
+ } else {
186
+ ctx.ui.setStatus("napkin", theme.fg("dim", "napkin: no NAPKIN.md"));
187
+ }
188
+ }
189
+ });
190
+
191
+ // ── Tools ───────────────────────────────────────────────────────
192
+
193
+ pi.registerTool({
194
+ name: "kb_search",
195
+ label: "KB Search",
196
+ description: "Search the knowledge base for notes matching a query",
197
+ promptSnippet: "Search the napkin vault for notes by keyword or topic",
198
+ parameters: Type.Object({
199
+ query: Type.String({ description: "Search query" }),
200
+ }),
201
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
202
+ const n = getNapkin(ctx.cwd);
203
+ const results = n.search(params.query);
204
+
205
+ if (results.length === 0) {
206
+ return {
207
+ content: [{ type: "text", text: "No results found." }],
208
+ details: { results: [] },
209
+ };
210
+ }
211
+
212
+ const text = results
213
+ .map((r) => {
214
+ let entry = `**${r.file}**`;
215
+ if (r.snippets && r.snippets.length > 0) {
216
+ entry += `\n${r.snippets.map((s) => ` ${s.text}`).join("\n")}`;
217
+ }
218
+ return entry;
219
+ })
220
+ .join("\n\n");
221
+
222
+ return {
223
+ content: [{ type: "text", text }],
224
+ details: { results },
225
+ };
226
+ },
227
+ renderResult(result, options, theme, context) {
228
+ const t =
229
+ (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
230
+ t.setText(formatKbResult(result, options, theme, 15));
231
+ return t;
232
+ },
233
+ });
234
+
235
+ pi.registerTool({
236
+ name: "kb_read",
237
+ label: "KB Read",
238
+ description: "Read a file from the knowledge base",
239
+ promptSnippet: "Read a note from the napkin vault by name or path",
240
+ parameters: Type.Object({
241
+ file: Type.String({ description: "File name or path to read" }),
242
+ }),
243
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
244
+ const n = getNapkin(ctx.cwd);
245
+ const result = n.read(params.file);
246
+
247
+ return {
248
+ content: [{ type: "text", text: result.content }],
249
+ details: { path: result.path },
250
+ };
251
+ },
252
+ renderResult(result, options, theme, context) {
253
+ const t =
254
+ (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
255
+ t.setText(formatKbResult(result, options, theme, 10));
256
+ return t;
257
+ },
258
+ });
259
+ }
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@cad0p/pi-napkin",
3
+ "version": "0.2.4",
4
+ "description": "🧻 Napkin integration for pi — vault context, knowledge tools, and automatic distillation with git-worktree concurrency safety",
5
+ "publishConfig": {
6
+ "access": "public",
7
+ "registry": "https://registry.npmjs.org"
8
+ },
9
+ "keywords": [
10
+ "pi",
11
+ "pi-package",
12
+ "pi-extension",
13
+ "napkin",
14
+ "obsidian",
15
+ "knowledge-vault",
16
+ "markdown",
17
+ "session-distill",
18
+ "llm",
19
+ "agent-memory"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/cad0p/pi-napkin.git"
24
+ },
25
+ "homepage": "https://github.com/cad0p/pi-napkin#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/cad0p/pi-napkin/issues"
28
+ },
29
+ "files": [
30
+ "extensions/**/*.ts",
31
+ "!extensions/**/*.test.ts",
32
+ "!extensions/**/_test-helpers.ts",
33
+ "extensions/**/scripts/**",
34
+ "extensions/**/README.md",
35
+ "skills",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "pi": {
40
+ "extensions": [
41
+ "extensions/napkin-context",
42
+ "extensions/distill"
43
+ ],
44
+ "skills": [
45
+ "skills"
46
+ ]
47
+ },
48
+ "scripts": {
49
+ "lint": "bunx biome check extensions/",
50
+ "lint:fix": "bunx biome check --write extensions/",
51
+ "typecheck": "bunx tsc --noEmit",
52
+ "test": "bun test"
53
+ },
54
+ "devDependencies": {
55
+ "@biomejs/biome": "^2.3.14",
56
+ "@types/bun": "^1.3.0",
57
+ "typescript": "^5.8.0"
58
+ },
59
+ "dependencies": {
60
+ "@cad0p/napkin": "^0.8.1"
61
+ },
62
+ "peerDependencies": {
63
+ "@earendil-works/pi-coding-agent": ">=0.74.0",
64
+ "@earendil-works/pi-tui": ">=0.74.0",
65
+ "@sinclair/typebox": "^0.34.49"
66
+ },
67
+ "license": "MIT"
68
+ }
@@ -0,0 +1,44 @@
1
+ ---
2
+ name: napkin
3
+ description: Read, create, search, and manage notes in Obsidian vaults using the napkin CLI. Works directly on markdown files and canvas files — no Obsidian app required. Use when the user asks to interact with their Obsidian vault, manage notes, search vault content, work with tasks, tags, properties, daily notes, templates, bases, bookmarks, aliases, or canvas files from the command line.
4
+ ---
5
+
6
+ # napkin
7
+
8
+ CLI for Obsidian vaults. Operates directly on markdown files — no Obsidian app, no Electron, no Catalyst license.
9
+
10
+ See: **[README.md](../../README.md)** for full documentation — install, config, auto-distill, concurrency, commands, tools, agent visibility, vault setup, and troubleshooting.
11
+
12
+ The single piece of agent-critical operational info we keep in the SKILL itself is vault resolution, since misresolution silently creates a bare vault (which is a data-loss hazard).
13
+
14
+ ## Vault Resolution
15
+
16
+ Before any command runs, napkin picks a vault in this order:
17
+
18
+ 1. **`--vault <path>`** flag, if supplied.
19
+ 2. **Nearest ancestor with `.napkin/`** (or `.obsidian/.napkin/`) walking up from cwd.
20
+ 3. **Global fallback** — `vault` field in `$XDG_CONFIG_HOME/napkin/config.json` (defaults to `~/.config/napkin/config.json`).
21
+ 4. **Bare vault auto-created at cwd** — last resort. napkin silently creates `.napkin/` + `NAPKIN.md` + `.obsidian/` in the current directory with no prompt.
22
+
23
+ > **Warning:** Step 4 is a footgun at first setup. Running `napkin vault` (or any command that resolves the vault) from a random directory with no ancestor `.napkin/` and no global config will silently create an empty vault there. Always confirm the resolved vault before running commands that might trigger this fallback.
24
+
25
+ ### First-time setup
26
+
27
+ Configure the global fallback so commands never accidentally create bare vaults:
28
+
29
+ ```json
30
+ // ~/.config/napkin/config.json
31
+ {
32
+ "vault": "~/path/to/vault"
33
+ }
34
+ ```
35
+
36
+ Supports `~` expansion; paths without `~` are resolved relative to the config file's directory. Override the default config location with `XDG_CONFIG_HOME`.
37
+
38
+ Confirm resolution before first use:
39
+
40
+ ```bash
41
+ napkin vault --json | jq -r .path # Should print the expected vault path
42
+ ```
43
+
44
+ If it prints a path that shouldn't be a vault (e.g. your cwd or `$HOME`), napkin just created a bare vault there — either delete the stray `.napkin/`/`NAPKIN.md`/`.obsidian/` it generated and configure the global fallback, or re-run with `--vault <path>`.