@narumitw/pi-notes 0.0.0 → 0.1.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/src/menu.ts CHANGED
@@ -7,22 +7,23 @@ interface NotesMenuState {
7
7
  templates: DiscoveryResult;
8
8
  }
9
9
 
10
- type NotesScreen = "notes" | "templates" | "path";
11
- type NotesAction = "chooseNote" | "chooseTemplate" | "createNote";
10
+ type NotesScreen = "notes" | "openNote" | "templates" | "pastePath" | "manageTemplates";
11
+ type NotesAction = "chooseRoute" | "chooseNote" | "chooseTemplate" | "pastePath" | "editTemplate";
12
12
 
13
- export interface NotesManagerResult {
14
- kind: "open" | "closed";
15
- notePath?: string;
16
- }
13
+ export type NotesManagerResult =
14
+ | { kind: "open"; notePath: string }
15
+ | { kind: "pastePath"; notePath: string }
16
+ | { kind: "editTemplate"; templatePath: string }
17
+ | { kind: "closed" };
17
18
 
18
19
  export function createNotesMenu(storage: NotesStorage) {
19
- let selectedTemplate: string | undefined;
20
- let selectedNote: string | undefined;
20
+ let result: Exclude<NotesManagerResult, { kind: "closed" }> | undefined;
21
21
 
22
22
  const getState = async ({ signal }: { signal: AbortSignal }): Promise<NotesMenuState> => {
23
23
  const notes = await storage.discoverNotes(signal);
24
24
  if (signal.aborted) throw signal.reason;
25
25
  const templates = await storage.discoverTemplates(signal);
26
+ if (signal.aborted) throw signal.reason;
26
27
  return { notes, templates };
27
28
  };
28
29
 
@@ -34,23 +35,49 @@ export function createNotesMenu(storage: NotesStorage) {
34
35
  title: `Pi Notes · ${state.notes.entries.length} note${state.notes.entries.length === 1 ? "" : "s"}`,
35
36
  lines: discoveryLines(state.notes, "note"),
36
37
  items: [
38
+ {
39
+ id: "open",
40
+ label: "Open a note…",
41
+ description: "Choose an existing Markdown note.",
42
+ searchText: "open browse existing note",
43
+ },
37
44
  {
38
45
  id: "create",
39
46
  label: "Create a note…",
40
- description: "Start blank or copy a user template.",
41
- searchText: "new create blank template",
47
+ description: "Open an automatically named blank note or user template.",
48
+ searchText: "new create blank template automatic filename",
49
+ },
50
+ {
51
+ id: "paste-path",
52
+ label: "Paste a note path…",
53
+ description: "Insert a note's absolute path into the parent editor.",
54
+ searchText: "paste insert absolute path",
55
+ },
56
+ {
57
+ id: "manage-templates",
58
+ label: "Manage templates…",
59
+ description: "Edit existing Markdown templates.",
60
+ searchText: "manage edit templates",
42
61
  },
43
- ...state.notes.entries.map((note, index) => ({
44
- id: `note:${index}`,
45
- label: note.displayPath,
46
- description: `${note.size} bytes`,
47
- searchText: note.displayPath,
48
- })),
49
62
  ],
63
+ action: "chooseRoute",
64
+ viewportSize: 12,
65
+ hint: "close",
66
+ }),
67
+ openNote: ({ state }) => ({
68
+ kind: "choice",
69
+ title: "Open a note",
70
+ lines: discoveryLines(state.notes, "note"),
71
+ items: state.notes.entries.map((note, index) => ({
72
+ id: `note:${index}`,
73
+ label: note.displayPath,
74
+ description: `${note.size} bytes`,
75
+ searchText: note.displayPath,
76
+ })),
50
77
  action: "chooseNote",
51
78
  enableSearch: state.notes.entries.length > 8,
52
79
  viewportSize: 12,
53
- hint: "close",
80
+ hint: "back",
54
81
  }),
55
82
  templates: ({ state }) => ({
56
83
  kind: "choice",
@@ -74,43 +101,74 @@ export function createNotesMenu(storage: NotesStorage) {
74
101
  viewportSize: 12,
75
102
  hint: "back",
76
103
  }),
77
- path: () => ({
78
- kind: "input",
79
- title: "New note path",
80
- lines: [
81
- "Enter a relative Markdown path below pi-notes/notes.",
82
- selectedTemplate ? `Template: ${sanitizeTerminalText(selectedTemplate)}` : "Template: Blank",
83
- ],
84
- placeholder: "topic.md or folder/topic.md",
85
- action: "createNote",
104
+ pastePath: ({ state }) => ({
105
+ kind: "choice",
106
+ title: "Paste a note path",
107
+ lines: discoveryLines(state.notes, "note"),
108
+ items: state.notes.entries.map((note, index) => ({
109
+ id: `paste:${index}`,
110
+ label: note.displayPath,
111
+ description: `${note.size} bytes`,
112
+ searchText: note.displayPath,
113
+ })),
114
+ action: "pastePath",
115
+ enableSearch: state.notes.entries.length > 8,
116
+ viewportSize: 12,
117
+ hint: "back",
118
+ }),
119
+ manageTemplates: ({ state }) => ({
120
+ kind: "choice",
121
+ title: "Manage templates",
122
+ lines: discoveryLines(state.templates, "template"),
123
+ items: state.templates.entries.map((template, index) => ({
124
+ id: `manage-template:${index}`,
125
+ label: template.displayPath,
126
+ description: `${template.size} bytes`,
127
+ searchText: template.displayPath,
128
+ })),
129
+ action: "editTemplate",
130
+ enableSearch: state.templates.entries.length > 8,
131
+ viewportSize: 12,
86
132
  hint: "back",
87
133
  }),
88
134
  },
89
135
  actions: {
90
- chooseNote: ({ state, itemId }) => {
136
+ chooseRoute: ({ itemId }) => {
137
+ if (itemId === "open") return { kind: "to", screen: "openNote" };
91
138
  if (itemId === "create") return { kind: "to", screen: "templates" };
139
+ if (itemId === "paste-path") return { kind: "to", screen: "pastePath" };
140
+ if (itemId === "manage-templates") return { kind: "to", screen: "manageTemplates" };
141
+ return { kind: "rejected", error: new Error("The selected notes action is no longer available") };
142
+ },
143
+ chooseNote: ({ state, itemId }) => {
92
144
  const note = indexedEntry(state.notes.entries, itemId, "note:");
93
145
  if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
94
- selectedNote = note.relativePath;
146
+ result = { kind: "open", notePath: note.relativePath };
95
147
  return { kind: "close" };
96
148
  },
97
- chooseTemplate: ({ state, itemId }) => {
98
- if (itemId === "blank") {
99
- selectedTemplate = undefined;
100
- return { kind: "to", screen: "path" };
149
+ chooseTemplate: async ({ state, itemId, signal }) => {
150
+ const templatePath =
151
+ itemId === "blank" ? undefined : indexedEntry(state.templates.entries, itemId, "template:")?.relativePath;
152
+ if (itemId !== "blank" && !templatePath) {
153
+ return { kind: "rejected", error: new Error("The selected template is no longer available") };
101
154
  }
102
- const template = indexedEntry(state.templates.entries, itemId, "template:");
155
+ const note = await storage.createAutomaticNote({ ...(templatePath ? { templatePath } : {}), signal });
156
+ if (signal.aborted) return { kind: "close" };
157
+ result = { kind: "open", notePath: note.relativePath };
158
+ return { kind: "close" };
159
+ },
160
+ pastePath: ({ state, itemId }) => {
161
+ const note = indexedEntry(state.notes.entries, itemId, "paste:");
162
+ if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
163
+ result = { kind: "pastePath", notePath: note.relativePath };
164
+ return { kind: "close" };
165
+ },
166
+ editTemplate: ({ state, itemId }) => {
167
+ const template = indexedEntry(state.templates.entries, itemId, "manage-template:");
103
168
  if (!template) {
104
169
  return { kind: "rejected", error: new Error("The selected template is no longer available") };
105
170
  }
106
- selectedTemplate = template.relativePath;
107
- return { kind: "to", screen: "path" };
108
- },
109
- createNote: async ({ value, signal }) => {
110
- if (typeof value !== "string") return { kind: "rejected", error: new Error("Note path is required") };
111
- const note = await storage.createNote(value, { templatePath: selectedTemplate, signal });
112
- if (signal.aborted) return { kind: "close" };
113
- selectedNote = note.relativePath;
171
+ result = { kind: "editTemplate", templatePath: template.relativePath };
114
172
  return { kind: "close" };
115
173
  },
116
174
  },
@@ -119,7 +177,7 @@ export function createNotesMenu(storage: NotesStorage) {
119
177
  return {
120
178
  menu,
121
179
  getState,
122
- getSelectedNote: () => selectedNote,
180
+ getResult: () => result,
123
181
  };
124
182
  }
125
183
 
@@ -140,10 +198,8 @@ export async function showNotesManager(
140
198
  },
141
199
  });
142
200
  if (result.kind === "error") throw result.error;
143
- const selected = controller.getSelectedNote();
144
- return selected && ownership.isCurrent() && !ownership.signal.aborted
145
- ? { kind: "open", notePath: selected }
146
- : { kind: "closed" };
201
+ const selected = controller.getResult();
202
+ return selected && ownership.isCurrent() && !ownership.signal.aborted ? selected : { kind: "closed" };
147
203
  }
148
204
 
149
205
  function indexedEntry(entries: readonly MarkdownEntry[], itemId: string, prefix: string): MarkdownEntry | undefined {
@@ -4,8 +4,9 @@ import {
4
4
  type ExtensionContext,
5
5
  getAgentDir,
6
6
  } from "@earendil-works/pi-coding-agent";
7
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
7
8
  import type { NotesManagerResult } from "./menu.js";
8
- import { NotesStorage } from "./storage.js";
9
+ import { NotesStorage, type TemplateSnapshot } from "./storage.js";
9
10
  import type { OpenNotesWorkspaceOptions } from "./workspace.js";
10
11
 
11
12
  interface NotesExtensionDependencies {
@@ -16,6 +17,11 @@ interface NotesExtensionDependencies {
16
17
  storage: NotesStorage,
17
18
  ownership: { signal: AbortSignal; isCurrent(): boolean },
18
19
  ): Promise<NotesManagerResult>;
20
+ editTemplate(
21
+ ctx: ExtensionCommandContext,
22
+ template: TemplateSnapshot,
23
+ ownership: { signal: AbortSignal; isCurrent(): boolean },
24
+ ): Promise<string | undefined>;
19
25
  openWorkspace(options: OpenNotesWorkspaceOptions): Promise<void>;
20
26
  }
21
27
 
@@ -32,6 +38,13 @@ export function createNotesExtension(
32
38
  if (ownership.signal.aborted || !ownership.isCurrent()) return { kind: "closed" };
33
39
  return showNotesManager(ctx, storage, ownership);
34
40
  }),
41
+ editTemplate:
42
+ dependencies.editTemplate ??
43
+ (async (ctx, template, ownership) => {
44
+ const { showTemplateEditor } = await import("./template-editor.js");
45
+ if (ownership.signal.aborted || !ownership.isCurrent()) return undefined;
46
+ return showTemplateEditor(ctx, template, ownership);
47
+ }),
35
48
  openWorkspace:
36
49
  dependencies.openWorkspace ??
37
50
  (async (options) => {
@@ -67,25 +80,76 @@ export function createNotesExtension(
67
80
  const signal = ctx.signal ? AbortSignal.any([ctx.signal, ownerController.signal]) : ownerController.signal;
68
81
  const isCurrent = () =>
69
82
  activeSessionManager === owner && generation === ownerGeneration && !ownerController.signal.aborted;
70
- if (!isCurrent()) throw new Error("Pi Notes session is no longer active.");
83
+ const isOwned = () => isCurrent() && !signal.aborted;
84
+ if (!isOwned()) throw new Error("Pi Notes session is no longer active.");
71
85
 
72
86
  const agentDir = deps.getAgentDir();
73
87
  const storage = deps.createStorage(agentDir);
74
88
  await storage.initialize(signal);
75
- if (!isCurrent() || signal.aborted) return;
76
- const selected = await deps.showManager(ctx, storage, { signal, isCurrent });
77
- if (!isCurrent() || signal.aborted || selected.kind !== "open" || !selected.notePath) return;
78
- const thinkingLevel = pi.getThinkingLevel();
79
- if (!isCurrent() || signal.aborted) return;
80
- await deps.openWorkspace({
81
- ctx,
82
- agentDir,
83
- storage,
84
- notePath: selected.notePath,
85
- thinkingLevel,
86
- signal,
87
- isCurrent,
88
- });
89
+ if (!isOwned()) return;
90
+
91
+ while (isOwned()) {
92
+ const selected = await deps.showManager(ctx, storage, { signal, isCurrent });
93
+ if (!isOwned()) return;
94
+ if (selected.kind === "closed") return;
95
+
96
+ if (selected.kind === "pastePath") {
97
+ let absolutePath: string;
98
+ try {
99
+ absolutePath = await storage.resolveCanonicalNotePath(selected.notePath, signal);
100
+ } catch (error) {
101
+ if (!isOwned()) return;
102
+ safeNotify(ctx, `Pi Notes failed to resolve the selected note: ${safeErrorMessage(error)}`, "error");
103
+ continue;
104
+ }
105
+ if (!isOwned()) return;
106
+ if (sanitizeTerminalText(absolutePath) !== absolutePath) {
107
+ safeNotify(ctx, "Pi Notes cannot paste a path that contains terminal or direction controls.", "error");
108
+ continue;
109
+ }
110
+ ctx.ui.pasteToEditor(absolutePath);
111
+ return;
112
+ }
113
+
114
+ if (selected.kind === "editTemplate") {
115
+ let template: TemplateSnapshot;
116
+ try {
117
+ template = await storage.readTemplate(selected.templatePath, signal);
118
+ } catch (error) {
119
+ if (!isOwned()) return;
120
+ safeNotify(ctx, `Pi Notes failed to read the selected template: ${safeErrorMessage(error)}`, "error");
121
+ continue;
122
+ }
123
+ if (!isOwned()) return;
124
+ const content = await deps.editTemplate(ctx, template, { signal, isCurrent });
125
+ if (!isOwned()) return;
126
+ if (content === undefined || content === template.content) continue;
127
+ try {
128
+ await storage.replaceTemplate(template.relativePath, template.revision, content, signal);
129
+ } catch (error) {
130
+ if (!isOwned()) return;
131
+ safeNotify(ctx, `Pi Notes failed to save template: ${safeErrorMessage(error)}`, "error");
132
+ continue;
133
+ }
134
+ if (!isOwned()) return;
135
+ safeNotify(ctx, `Saved template: ${template.relativePath}`, "info");
136
+ continue;
137
+ }
138
+
139
+ const thinkingLevel = pi.getThinkingLevel();
140
+ if (!isOwned()) return;
141
+ await deps.openWorkspace({
142
+ ctx,
143
+ agentDir,
144
+ storage,
145
+ notePath: selected.notePath,
146
+ thinkingLevel,
147
+ signal,
148
+ isCurrent,
149
+ });
150
+ if (!isOwned()) return;
151
+ return;
152
+ }
89
153
  };
90
154
 
91
155
  pi.registerCommand("notes", {
@@ -119,6 +183,18 @@ export function createNotesExtension(
119
183
  };
120
184
  }
121
185
 
186
+ function safeNotify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error"): void {
187
+ try {
188
+ ctx.ui.notify(sanitizeTerminalText(message), level);
189
+ } catch {
190
+ // A replaced session can invalidate the old UI immediately.
191
+ }
192
+ }
193
+
194
+ function safeErrorMessage(error: unknown): string {
195
+ return sanitizeTerminalText(error instanceof Error ? error.message : String(error)).slice(0, 500);
196
+ }
197
+
122
198
  function rejectCommand(ctx: ExtensionContext, message: string): void {
123
199
  if (ctx.hasUI) {
124
200
  try {
package/src/storage.ts CHANGED
@@ -48,6 +48,13 @@ export interface NoteSnapshot {
48
48
  size: number;
49
49
  }
50
50
 
51
+ export interface TemplateSnapshot {
52
+ relativePath: string;
53
+ content: string;
54
+ revision: string;
55
+ size: number;
56
+ }
57
+
51
58
  export interface NotesStorageOptions {
52
59
  /** Test seam invoked after a complete temporary file is synced and before publication. */
53
60
  beforePublish?(targetPath: string, temporaryPath: string): Promise<void> | void;
@@ -88,14 +95,19 @@ export class NotesStorage {
88
95
  }
89
96
 
90
97
  async readNote(relativePath: string, signal?: AbortSignal): Promise<NoteSnapshot> {
91
- const resolved = await resolveExistingMarkdown(this.paths.notes, relativePath, signal);
98
+ const resolved = await resolveExistingMarkdown(this.paths.notes, relativePath, "Note", signal);
92
99
  const content = await readBoundedMarkdown(resolved.absolutePath, "Note", signal);
93
100
  return snapshot(resolved.relativePath, content);
94
101
  }
95
102
 
96
- async readTemplate(relativePath: string, signal?: AbortSignal): Promise<string> {
97
- const resolved = await resolveExistingMarkdown(this.paths.templates, relativePath, signal);
98
- return readBoundedMarkdown(resolved.absolutePath, "Template", signal);
103
+ async resolveCanonicalNotePath(relativePath: string, signal?: AbortSignal): Promise<string> {
104
+ return (await resolveExistingMarkdown(this.paths.notes, relativePath, "Note", signal)).absolutePath;
105
+ }
106
+
107
+ async readTemplate(relativePath: string, signal?: AbortSignal): Promise<TemplateSnapshot> {
108
+ const resolved = await resolveExistingMarkdown(this.paths.templates, relativePath, "Template", signal);
109
+ const content = await readBoundedMarkdown(resolved.absolutePath, "Template", signal);
110
+ return snapshot(resolved.relativePath, content);
99
111
  }
100
112
 
101
113
  async createNote(
@@ -103,12 +115,13 @@ export class NotesStorage {
103
115
  options: { templatePath?: string; signal?: AbortSignal } = {},
104
116
  ): Promise<NoteSnapshot> {
105
117
  const normalized = normalizeRelativeMarkdownPath(relativePath);
106
- const content = options.templatePath ? await this.readTemplate(options.templatePath, options.signal) : "";
118
+ const content = options.templatePath ? (await this.readTemplate(options.templatePath, options.signal)).content : "";
107
119
  validateMarkdownContent(content, "Note");
108
120
  const root = await canonicalDirectory(this.paths.notes, options.signal);
109
121
  const target = resolve(root, ...normalized.split("/"));
110
122
  assertContained(root, target);
111
- return withFileMutationQueue(target, async () => {
123
+ // One canonical root key serializes destination aliases on case-insensitive filesystems.
124
+ return withFileMutationQueue(root, async () => {
112
125
  await ensureSafeParent(root, dirname(target), options.signal);
113
126
  throwIfAborted(options.signal);
114
127
  await assertMissingNote(target, normalized, options.signal);
@@ -117,6 +130,71 @@ export class NotesStorage {
117
130
  });
118
131
  }
119
132
 
133
+ async createAutomaticNote(options: { templatePath?: string; signal?: AbortSignal } = {}): Promise<NoteSnapshot> {
134
+ const content = options.templatePath ? (await this.readTemplate(options.templatePath, options.signal)).content : "";
135
+ validateMarkdownContent(content, "Note");
136
+ const root = await canonicalDirectory(this.paths.notes, options.signal);
137
+ const sessionsRoot = await canonicalDirectory(this.paths.sessions, options.signal);
138
+ return withFileMutationQueue(root, async () => {
139
+ const createIfAvailable = async (relativePath: string): Promise<NoteSnapshot | undefined> => {
140
+ const target = resolve(root, relativePath);
141
+ if (await entryExists(join(sessionsRoot, noteSessionKey(relativePath)), options.signal)) return undefined;
142
+ try {
143
+ await assertMissingNote(target, relativePath, options.signal);
144
+ await atomicCreate(root, target, relativePath, content, options.signal, this.beforePublish);
145
+ return snapshot(relativePath, content);
146
+ } catch (error) {
147
+ if (!(error instanceof NoteAlreadyExistsError)) throw error;
148
+ return undefined;
149
+ }
150
+ };
151
+
152
+ for (let index = 1; index <= MAX_DISCOVERED_FILES + 1; index += 1) {
153
+ throwIfAborted(options.signal);
154
+ const note = await createIfAvailable(index === 1 ? "untitled.md" : `untitled-${index}.md`);
155
+ if (note) return note;
156
+ }
157
+ while (true) {
158
+ throwIfAborted(options.signal);
159
+ const note = await createIfAvailable(`untitled-${randomUUID()}.md`);
160
+ if (note) return note;
161
+ }
162
+ });
163
+ }
164
+
165
+ async renameNote(
166
+ relativePath: string,
167
+ expectedRevision: string,
168
+ newRelativePath: string,
169
+ signal?: AbortSignal,
170
+ ): Promise<NoteSnapshot> {
171
+ const normalized = normalizeExistingMarkdownPath(relativePath);
172
+ const renamed = normalizeRelativeMarkdownPath(newRelativePath);
173
+ if (renamed.split("/").length - 1 > MAX_SCAN_DEPTH) {
174
+ throw new Error(`Rename destination must contain at most ${MAX_SCAN_DEPTH} parent directories`);
175
+ }
176
+ if (renamed === normalized) throw new Error(`The current note is already named ${renamed}`);
177
+ const root = await canonicalDirectory(this.paths.notes, signal);
178
+ const source = resolve(root, ...normalized.split("/"));
179
+ const target = resolve(root, ...renamed.split("/"));
180
+ assertContained(root, source);
181
+ assertContained(root, target);
182
+ return withFileMutationQueue(root, async () => {
183
+ throwIfAborted(signal);
184
+ const current = await this.readNote(normalized, signal);
185
+ assertRevision(current, expectedRevision);
186
+ await ensureSafeParent(root, dirname(target), signal);
187
+ await assertMissingNote(target, renamed, signal);
188
+ await revalidateCanonicalParent(root, target, signal);
189
+ const latest = await this.readNote(normalized, signal);
190
+ assertRevision(latest, expectedRevision);
191
+ await assertMissingNote(target, renamed, signal);
192
+ throwIfAborted(signal);
193
+ await rename(source, target);
194
+ return snapshot(renamed, latest.content);
195
+ });
196
+ }
197
+
120
198
  async editNote(
121
199
  relativePath: string,
122
200
  expectedRevision: string,
@@ -126,8 +204,10 @@ export class NotesStorage {
126
204
  ): Promise<NoteSnapshot> {
127
205
  if (!oldText) throw new Error("oldText must not be empty; use replace_current_note for a full replacement");
128
206
  const normalized = normalizeExistingMarkdownPath(relativePath);
129
- const queuePath = resolve(this.paths.notes, ...normalized.split("/"));
130
- return withFileMutationQueue(queuePath, async () => {
207
+ const root = await canonicalDirectory(this.paths.notes, signal);
208
+ const target = resolve(root, ...normalized.split("/"));
209
+ assertContained(root, target);
210
+ return withFileMutationQueue(root, async () => {
131
211
  throwIfAborted(signal);
132
212
  const current = await this.readNote(normalized, signal);
133
213
  assertRevision(current, expectedRevision);
@@ -138,7 +218,7 @@ export class NotesStorage {
138
218
  }
139
219
  const content = `${current.content.slice(0, index)}${newText}${current.content.slice(index + oldText.length)}`;
140
220
  validateMarkdownContent(content, "Note");
141
- await atomicReplace(this.paths.notes, queuePath, content, current.revision, signal, this.beforePublish);
221
+ await atomicReplace(root, target, content, current.revision, "Note", signal, this.beforePublish);
142
222
  return snapshot(normalized, content);
143
223
  });
144
224
  }
@@ -151,12 +231,34 @@ export class NotesStorage {
151
231
  ): Promise<NoteSnapshot> {
152
232
  const normalized = normalizeExistingMarkdownPath(relativePath);
153
233
  validateMarkdownContent(content, "Note");
154
- const queuePath = resolve(this.paths.notes, ...normalized.split("/"));
155
- return withFileMutationQueue(queuePath, async () => {
234
+ const root = await canonicalDirectory(this.paths.notes, signal);
235
+ const target = resolve(root, ...normalized.split("/"));
236
+ assertContained(root, target);
237
+ return withFileMutationQueue(root, async () => {
156
238
  throwIfAborted(signal);
157
239
  const current = await this.readNote(normalized, signal);
158
240
  assertRevision(current, expectedRevision);
159
- await atomicReplace(this.paths.notes, queuePath, content, current.revision, signal, this.beforePublish);
241
+ await atomicReplace(root, target, content, current.revision, "Note", signal, this.beforePublish);
242
+ return snapshot(normalized, content);
243
+ });
244
+ }
245
+
246
+ async replaceTemplate(
247
+ relativePath: string,
248
+ expectedRevision: string,
249
+ content: string,
250
+ signal?: AbortSignal,
251
+ ): Promise<TemplateSnapshot> {
252
+ const normalized = normalizeExistingMarkdownPath(relativePath);
253
+ validateMarkdownContent(content, "Template");
254
+ const root = await canonicalDirectory(this.paths.templates, signal);
255
+ const target = resolve(root, ...normalized.split("/"));
256
+ assertContained(root, target);
257
+ return withFileMutationQueue(root, async () => {
258
+ throwIfAborted(signal);
259
+ const current = await this.readTemplate(normalized, signal);
260
+ assertRevision(current, expectedRevision, "Template");
261
+ await atomicReplace(root, target, content, current.revision, "Template", signal, this.beforePublish);
160
262
  return snapshot(normalized, content);
161
263
  });
162
264
  }
@@ -198,6 +300,10 @@ export function revisionFor(content: string): string {
198
300
  return createHash("sha256").update(content).digest("hex");
199
301
  }
200
302
 
303
+ export function noteSessionKey(notePath: string): string {
304
+ return createHash("sha256").update(notePath).digest("hex");
305
+ }
306
+
201
307
  export function validateMarkdownContent(content: string, label: string): void {
202
308
  const bytes = Buffer.byteLength(content, "utf8");
203
309
  if (bytes > MAX_MARKDOWN_BYTES) {
@@ -300,6 +406,7 @@ async function discoverMarkdown(rootPath: string, signal?: AbortSignal): Promise
300
406
  async function resolveExistingMarkdown(
301
407
  rootPath: string,
302
408
  relativePath: string,
409
+ label: string,
303
410
  signal?: AbortSignal,
304
411
  ): Promise<{ relativePath: string; absolutePath: string }> {
305
412
  const normalized = normalizeExistingMarkdownPath(relativePath);
@@ -309,12 +416,12 @@ async function resolveExistingMarkdown(
309
416
  throwIfAborted(signal);
310
417
  const linkInfo = await lstat(candidate);
311
418
  throwIfAborted(signal);
312
- if (linkInfo.isSymbolicLink()) throw new Error(`Symbolic-link notes are not supported: ${normalized}`);
313
- if (!linkInfo.isFile()) throw new Error(`Note is not a regular file: ${normalized}`);
419
+ if (linkInfo.isSymbolicLink()) throw new Error(`${label} path is a symbolic link: ${normalized}`);
420
+ if (!linkInfo.isFile()) throw new Error(`${label} is not a regular file: ${normalized}`);
314
421
  const canonical = await realpath(candidate);
315
422
  throwIfAborted(signal);
316
423
  assertContained(root, canonical);
317
- if (canonical !== candidate) throw new Error(`Note path is not canonical: ${normalized}`);
424
+ if (canonical !== candidate) throw new Error(`${label} path is not canonical: ${normalized}`);
318
425
  return { relativePath: normalized, absolutePath: canonical };
319
426
  }
320
427
 
@@ -403,29 +510,45 @@ async function atomicCreate(
403
510
  }
404
511
  }
405
512
 
513
+ class NoteAlreadyExistsError extends Error {}
514
+
406
515
  async function assertMissingNote(targetPath: string, relativePath: string, signal?: AbortSignal): Promise<void> {
407
516
  throwIfAborted(signal);
408
517
  try {
409
518
  await lstat(targetPath);
410
- throw new Error(`Note already exists: ${relativePath}`);
519
+ throw new NoteAlreadyExistsError(`Note already exists: ${relativePath}`);
411
520
  } catch (error) {
412
521
  if (!isNodeError(error, "ENOENT")) throw error;
413
522
  }
414
523
  throwIfAborted(signal);
415
524
  }
416
525
 
526
+ async function entryExists(path: string, signal?: AbortSignal): Promise<boolean> {
527
+ throwIfAborted(signal);
528
+ try {
529
+ await lstat(path);
530
+ throwIfAborted(signal);
531
+ return true;
532
+ } catch (error) {
533
+ if (!isNodeError(error, "ENOENT")) throw error;
534
+ throwIfAborted(signal);
535
+ return false;
536
+ }
537
+ }
538
+
417
539
  async function atomicReplace(
418
540
  rootPath: string,
419
541
  targetPath: string,
420
542
  content: string,
421
543
  expectedRevision: string,
544
+ label: string,
422
545
  signal?: AbortSignal,
423
546
  beforePublish?: NotesStorageOptions["beforePublish"],
424
547
  ): Promise<void> {
425
548
  const relativePath = relative(rootPath, targetPath).split(sep).join("/");
426
- const resolved = await resolveExistingMarkdown(rootPath, relativePath, signal);
427
- const current = await readBoundedMarkdown(resolved.absolutePath, "Note", signal);
428
- if (revisionFor(current) !== expectedRevision) throw new Error("Note changed before publication; read it again");
549
+ const resolved = await resolveExistingMarkdown(rootPath, relativePath, label, signal);
550
+ const current = await readBoundedMarkdown(resolved.absolutePath, label, signal);
551
+ if (revisionFor(current) !== expectedRevision) throw new Error(`${label} changed before publication; read it again`);
429
552
  const info = await stat(resolved.absolutePath);
430
553
  throwIfAborted(signal);
431
554
  const temporaryPath = temporaryName(targetPath);
@@ -434,12 +557,14 @@ async function atomicReplace(
434
557
  throwIfAborted(signal);
435
558
  await beforePublish?.(targetPath, temporaryPath);
436
559
  throwIfAborted(signal);
437
- const latestResolved = await resolveExistingMarkdown(rootPath, relativePath, signal);
560
+ const latestResolved = await resolveExistingMarkdown(rootPath, relativePath, label, signal);
438
561
  if (latestResolved.absolutePath !== resolved.absolutePath) {
439
- throw new Error("Note path changed before publication; read it again");
562
+ throw new Error(`${label} path changed before publication; read it again`);
563
+ }
564
+ const latest = await readBoundedMarkdown(latestResolved.absolutePath, label, signal);
565
+ if (revisionFor(latest) !== expectedRevision) {
566
+ throw new Error(`${label} changed before publication; read it again`);
440
567
  }
441
- const latest = await readBoundedMarkdown(latestResolved.absolutePath, "Note", signal);
442
- if (revisionFor(latest) !== expectedRevision) throw new Error("Note changed before publication; read it again");
443
568
  throwIfAborted(signal);
444
569
  await rename(temporaryPath, latestResolved.absolutePath);
445
570
  } catch (error) {
@@ -481,9 +606,10 @@ function snapshot(relativePath: string, content: string): NoteSnapshot {
481
606
  };
482
607
  }
483
608
 
484
- function assertRevision(current: NoteSnapshot, expectedRevision: string): void {
485
- if (current.revision !== expectedRevision)
486
- throw new Error("Note revision is stale; read the current note before editing");
609
+ function assertRevision(current: NoteSnapshot | TemplateSnapshot, expectedRevision: string, label = "Note"): void {
610
+ if (current.revision !== expectedRevision) {
611
+ throw new Error(`${label} revision is stale; read the current ${label.toLowerCase()} before editing`);
612
+ }
487
613
  }
488
614
 
489
615
  function assertContained(root: string, candidate: string): void {