notesoup 0.48.1 → 0.49.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.
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { Dirent } from "node:fs";
3
- import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
@@ -8,7 +8,7 @@ import { isFilesystemError } from "./fs-error.js";
8
8
  import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
9
  import { NoteError } from "./errors.js";
10
10
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
- import { isOrigin, isScope, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
11
+ import { isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
12
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, SLUG_PATTERN, type Scope } from "./paths.js";
13
13
  import { projectHomes, projectReceipt, type ProjectReceipt } from "./project-home.js";
14
14
 
@@ -27,19 +27,15 @@ export type NoteMatch = { line: number; text: string; /** Code-point offset into
27
27
  export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; matches: NoteMatch[] };
28
28
  export type EditOperation = { oldText: string; newText: string };
29
29
  export type WriteOptions = { origin?: Origin };
30
- export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: boolean };
31
- export type NotesQuery = (
32
- | { scope?: undefined; who?: never }
33
- | { scope: "session" | "project" | "human"; who?: never }
34
- | { scope: "agent" | "model"; who?: string }
35
- ) & { glob?: string; crumpled?: boolean };
30
+ export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
31
+ export type NotesQuery = { glob?: string; crumpled?: boolean };
36
32
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
37
33
  export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
38
34
  export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
39
35
  export type NoteChange =
40
36
  | { kind: "none"; before: ""; after: "" }
41
37
  | { kind: "body" | "metadata"; before: string; after: string };
42
- export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
38
+ export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange; moved: boolean; replacedCrumpledTarget: boolean };
43
39
  export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
44
40
  /** A home, or one unreadable note inside it, that a status-reporting query could not read. */
45
41
  export type NoteQueryStatus = { homesUnavailable: string[] };
@@ -151,21 +147,6 @@ function assertWho(value: unknown): string {
151
147
  return value;
152
148
  }
153
149
 
154
- async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<HomeRef[]> {
155
- if (opts.scope !== undefined) {
156
- if (!isScope(opts.scope)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
157
- const scope = opts.scope;
158
- if (opts.who !== undefined) {
159
- const who = assertWho(opts.who);
160
- if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
161
- return [{ scope, who }];
162
- }
163
- return [{ scope }];
164
- }
165
- if (opts.who !== undefined) throw new NoteError("invalid_scope", "who requires agent or model scope");
166
- return await homesForPattern(normalizePattern(opts.glob, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
167
- }
168
-
169
150
  /**
170
151
  * Line numbers (1-based) of every occurrence of `needle` in `body`. The scan walks forward
171
152
  * once, counting newlines as it goes, so a body that repeats one anchor thousands of times
@@ -305,27 +286,41 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
305
286
  async function update(address: string, edits?: EditOperation[], options: EditOptions = {}): Promise<NoteEditResult> {
306
287
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
307
288
  const stableOptions = { ...options };
308
- const destination = assertAddress(address);
289
+ const from = assertAddress(address);
290
+ const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
309
291
  assertWritablePath(destination.path);
310
292
  const scope = destination.scope;
293
+ assertWritableHome(from.scope, from.who, identity);
311
294
  assertWritableHome(scope, destination.who, identity);
312
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
313
- throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
295
+ if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
296
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
314
297
  }
298
+ const fromPath = physicalPath(from.scope, from.path, identity, from.who);
315
299
  const path = physicalPath(scope, destination.path, identity, destination.who);
316
- return withPathQueue(path, async () => {
317
- const raw = await readFileIfExists(path);
300
+ const differentPaths = resolve(fromPath) !== resolve(path);
301
+ const mutate = async (): Promise<NoteEditResult> => {
302
+ const raw = await readFileIfExists(fromPath);
318
303
  if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
304
+ const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
305
+ // Case and symlink aliases must not turn write-then-remove into deleting the result.
306
+ const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
307
+ const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
308
+ const moved = differentPaths && !sameFile;
309
+ if (moved && targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
310
+ throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo!).address} already holds a note; crumple it first or pick another address.`);
311
+ }
319
312
  const { meta, body } = parseNote(raw);
320
- meta.scope = scope;
321
313
  const beforeMeta: NoteMeta = { ...meta };
314
+ meta.scope = scope;
315
+ if (from.scope !== "session" && scope === "session") meta.project = identity.projectKey;
316
+ if (from.scope === "session" && scope !== "session") delete meta.project;
322
317
  let next = body;
323
318
  let applied = 0;
324
319
  operations.forEach((operation, index) => {
325
320
  const oldText = operation?.oldText;
326
321
  const newText = operation?.newText;
327
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
328
- if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
322
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
323
+ if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
329
324
  const lines = matchLineNumbers(next, oldText);
330
325
  if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
331
326
  if (lines.length > 1 && !stableOptions.replaceAll) {
@@ -344,58 +339,31 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
344
339
  if (stableOptions.crumpled === false) delete meta.crumpledAt;
345
340
  const bodyChanged = body !== next;
346
341
  const originChanged = beforeMeta.origin !== meta.origin;
347
- if (bodyChanged || originChanged) meta.updatedAt = writeStamp();
342
+ if (bodyChanged || originChanged || moved) meta.updatedAt = writeStamp();
348
343
  const serialized = serializeNote(meta, next);
349
344
  assertSerializedSize(serialized);
350
345
  const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
351
346
  let change: NoteChange;
352
347
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
353
348
  // whole serialized file, so the frontmatter part stays visible in the diff.
354
- if (bodyChanged && metadataChanged) change = { kind: "body", before: raw, after: serialized };
349
+ if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
355
350
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
356
351
  else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
357
352
  else change = { kind: "none", before: "", after: "" };
358
- await atomicWrite(path, serialized);
359
- return { meta, applied, resolvedScope: scope, change };
360
- });
353
+ await atomicWrite(sameFile ? sourceReal! : path, serialized);
354
+ if (moved) await rm(fromPath, { force: true });
355
+ return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
356
+ };
357
+ // Exact aliases share one queue; other spellings lock both paths in stable order.
358
+ if (!differentPaths) return withPathQueue(path, mutate);
359
+ const [first, second] = [fromPath, path].sort();
360
+ return withPathQueue(first!, () => withPathQueue(second!, mutate));
361
361
  }
362
362
 
363
- /**
364
- * Move one note to a new address with every metadata key preserved. Both ends must be
365
- * writable; a live target refuses, a crumpled target is replaced. Locks both paths in
366
- * sorted order so crossed renames cannot deadlock.
367
- */
363
+ /** Moving alone shares validation and persistence with a combined edit-and-move. */
368
364
  async function rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult> {
369
- const from = assertAddress(fromAddress);
370
- const to = assertAddress(toAddress);
371
- const fromScope = from.scope;
372
- const toScope = to.scope;
373
- assertWritablePath(to.path);
374
- assertWritableHome(fromScope, from.who, identity);
375
- assertWritableHome(toScope, to.who, identity);
376
- const fromPath = physicalPath(fromScope, from.path, identity, from.who);
377
- const toPath = physicalPath(toScope, to.path, identity, to.who);
378
- if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
379
- const [first, second] = [fromPath, toPath].sort();
380
- return withPathQueue(first!, () => withPathQueue(second!, async () => {
381
- const raw = await readFileIfExists(fromPath);
382
- if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
383
- const targetRaw = await readFileIfExists(toPath);
384
- if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
385
- throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
386
- }
387
- const { meta, body } = parseNote(raw);
388
- meta.scope = toScope;
389
- // Project ownership only changes when the move crosses the session boundary.
390
- if (fromScope !== "session" && toScope === "session") meta.project = identity.projectKey;
391
- if (fromScope === "session" && toScope !== "session") delete meta.project;
392
- meta.updatedAt = writeStamp();
393
- const serialized = serializeNote(meta, body);
394
- assertSerializedSize(serialized);
395
- await atomicWrite(toPath, serialized);
396
- await rm(fromPath, { force: true });
397
- return { meta, replacedCrumpledTarget: targetRaw !== undefined };
398
- }));
365
+ const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
366
+ return { meta, replacedCrumpledTarget };
399
367
  }
400
368
 
401
369
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
@@ -404,7 +372,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
404
372
  const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
405
373
  let homes: HomeRef[];
406
374
  try {
407
- homes = await homesFor(identity, options);
375
+ homes = await homesForPattern(normalized, identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
408
376
  } catch (error) {
409
377
  if (!status || !isFilesystemError(error) || !/^@(projects|agents|models)\//.test(options.glob ?? "")) throw error;
410
378
  status.homesUnavailable.push(options.glob!.split("/")[0]!);
package/src/pi/runtime.ts CHANGED
@@ -205,7 +205,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
205
205
  name: "empty_brain",
206
206
  label: "Empty Brain",
207
207
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
208
- parameters: Type.Object({ last_word: Type.Optional(Type.String({ maxLength: MAX_LAST_WORD_CHARS, description: `A tiny sticky note, at most ${MAX_LAST_WORD_CHARS} characters. After the wipe it is slapped on your forehead; longer notes are refused.` })) }, { additionalProperties: false }),
208
+ parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: `A tiny sticky note, at most ${MAX_LAST_WORD_CHARS} characters. After the wipe it is slapped on your forehead; longer notes are refused.` })) }, { additionalProperties: false }),
209
209
  async execute(_id, params, _signal, _update, ctx) {
210
210
  if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
211
211
  const lastWord = sanitizeLastWord(params.last_word);
@@ -9,7 +9,7 @@ import { nullableString, InvalidQueryError, searchQueries, searchQuery } from ".
9
9
 
10
10
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
11
11
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
12
- description: "(optional, default self) Who wrote it: user, self, or external.",
12
+ description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self.",
13
13
  }));
14
14
  const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
15
15
  const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
@@ -211,7 +211,7 @@ export const notesWrite = {
211
211
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
212
212
  async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
213
213
  try {
214
- const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin ?? "self" });
214
+ const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin });
215
215
  return success({ ...noteIdentity(identity, params.address), outcome });
216
216
  } catch (error) { return failureOf(error); }
217
217
  },
@@ -224,7 +224,7 @@ export const notesUpdateParameters = Type.Object({
224
224
  origin: ORIGIN,
225
225
  crumpled: CRUMPLED_PARAMETER,
226
226
  replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
227
- rename_to: Type.Optional(Type.String({ description: "(optional) Move to this address, keeping metadata. Use alone. Won't overwrite a live note; references aren't updated." })),
227
+ rename_to: Type.Optional(Type.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." })),
228
228
  }, { additionalProperties: false });
229
229
 
230
230
  function renderUpdateData(data: NotesUpdateData): string {
@@ -263,17 +263,11 @@ export const notesUpdate = {
263
263
  const store = createNotesStore(identity);
264
264
  // Empty filler is not a request: models that pass every parameter get the edit path.
265
265
  const renameTo = params.rename_to === "" ? undefined : params.rename_to;
266
- if (renameTo !== undefined) {
267
- if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
268
- return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
269
- }
270
- await store.rename(params.address, renameTo);
271
- const from = noteIdentity(identity, params.address).address;
272
- const to = noteIdentity(identity, renameTo);
273
- return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
274
- }
275
- const { change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
276
- return boundedUpdate({ ...noteIdentity(identity, params.address), change_kind: change.kind, diff: renderDiff(change) });
266
+ const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
267
+ const from = noteIdentity(identity, params.address).address;
268
+ const to = noteIdentity(identity, renameTo ?? params.address);
269
+ const diff = renderDiff(change);
270
+ return boundedUpdate({ ...to, ...(moved ? { rename_from: from } : {}), change_kind: moved ? "moved" : change.kind, diff: moved ? [`rename ${from} -> ${to.address}`, diff].filter(Boolean).join("\n") : diff });
277
271
  } catch (error) { return failureOf(error); }
278
272
  },
279
273
  render: renderUpdate,