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.
@@ -16,13 +16,20 @@ export function unavailableNotesSnapshot(openedAt) {
16
16
  * malformed note data and unrelated construction errors remain visible to the caller.
17
17
  */
18
18
  export async function loadNotesSnapshot(identity, openedAt, loadHome) {
19
- const store = createNotesStore(identity);
20
- const load = loadHome ?? ((scope) => store.list({ scope }));
21
19
  const homes = new Map();
22
20
  const unavailable = [];
21
+ if (!loadHome) {
22
+ const { rows, status } = await createNotesStore(identity).listWithStatus();
23
+ for (const home of NOTES_HOMES) {
24
+ homes.set(home.scope, rows.filter(row => row.scope === home.scope));
25
+ if (status.homesUnavailable.some(address => home.scope === "session" ? !address.startsWith("@") : address === home.label || address.startsWith(`${home.label}/`)))
26
+ unavailable.push(home);
27
+ }
28
+ return { openedAt, homes, unavailable };
29
+ }
23
30
  for (const home of NOTES_HOMES) {
24
31
  try {
25
- homes.set(home.scope, await load(home.scope));
32
+ homes.set(home.scope, await loadHome(home.scope));
26
33
  }
27
34
  catch (error) {
28
35
  if (!isFilesystemError(error))
@@ -80,8 +80,6 @@ export function assertAddress(value) {
80
80
  if (path === "" && who === undefined)
81
81
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
82
82
  }
83
- if (path.includes("@"))
84
- throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
85
83
  assertVirtualPath(path);
86
84
  return { scope, path, who };
87
85
  }
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
2
2
  /** Typed store refusal. Edit locations are exposed in camelCase. */
3
3
  export declare class NoteError extends Error {
4
4
  readonly code: NoteErrorCode;
@@ -34,17 +34,9 @@ export type EditOptions = {
34
34
  origin?: Origin;
35
35
  crumpled?: boolean;
36
36
  replaceAll?: boolean;
37
+ renameTo?: string;
37
38
  };
38
- export type NotesQuery = ({
39
- scope?: undefined;
40
- who?: never;
41
- } | {
42
- scope: "session" | "project" | "human";
43
- who?: never;
44
- } | {
45
- scope: "agent" | "model";
46
- who?: string;
47
- }) & {
39
+ export type NotesQuery = {
48
40
  glob?: string;
49
41
  crumpled?: boolean;
50
42
  };
@@ -72,6 +64,8 @@ export type NoteEditResult = {
72
64
  applied: number;
73
65
  resolvedScope: Scope;
74
66
  change: NoteChange;
67
+ moved: boolean;
68
+ replacedCrumpledTarget: boolean;
75
69
  };
76
70
  export type NoteRenameResult = {
77
71
  meta: NoteMeta;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { earliestMatchOffsetChars } from "../text-match.js";
5
5
  import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
@@ -7,7 +7,7 @@ import { isFilesystemError } from "./fs-error.js";
7
7
  import { snapshotNotesIdentity } from "./identity.js";
8
8
  import { NoteError } from "./errors.js";
9
9
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
10
- import { isOrigin, isScope, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
10
+ import { isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
11
11
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, SLUG_PATTERN } from "./paths.js";
12
12
  import { projectHomes, projectReceipt } from "./project-home.js";
13
13
  // Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
@@ -112,23 +112,6 @@ function assertWho(value) {
112
112
  }
113
113
  return value;
114
114
  }
115
- async function homesFor(identity, opts) {
116
- if (opts.scope !== undefined) {
117
- if (!isScope(opts.scope))
118
- throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
119
- const scope = opts.scope;
120
- if (opts.who !== undefined) {
121
- const who = assertWho(opts.who);
122
- if (scope !== "agent" && scope !== "model")
123
- throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
124
- return [{ scope, who }];
125
- }
126
- return [{ scope }];
127
- }
128
- if (opts.who !== undefined)
129
- throw new NoteError("invalid_scope", "who requires agent or model scope");
130
- return await homesForPattern(normalizePattern(opts.glob, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
131
- }
132
115
  /**
133
116
  * Line numbers (1-based) of every occurrence of `needle` in `body`. The scan walks forward
134
117
  * once, counting newlines as it goes, so a body that repeats one anchor thousands of times
@@ -270,30 +253,46 @@ export function createNotesStore(input) {
270
253
  async function update(address, edits, options = {}) {
271
254
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
272
255
  const stableOptions = { ...options };
273
- const destination = assertAddress(address);
256
+ const from = assertAddress(address);
257
+ const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
274
258
  assertWritablePath(destination.path);
275
259
  const scope = destination.scope;
260
+ assertWritableHome(from.scope, from.who, identity);
276
261
  assertWritableHome(scope, destination.who, identity);
277
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
278
- throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
262
+ if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
263
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
279
264
  }
265
+ const fromPath = physicalPath(from.scope, from.path, identity, from.who);
280
266
  const path = physicalPath(scope, destination.path, identity, destination.who);
281
- return withPathQueue(path, async () => {
282
- const raw = await readFileIfExists(path);
267
+ const differentPaths = resolve(fromPath) !== resolve(path);
268
+ const mutate = async () => {
269
+ const raw = await readFileIfExists(fromPath);
283
270
  if (raw === undefined)
284
271
  throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
272
+ const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
273
+ // Case and symlink aliases must not turn write-then-remove into deleting the result.
274
+ const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
275
+ const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
276
+ const moved = differentPaths && !sameFile;
277
+ if (moved && targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
278
+ throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
279
+ }
285
280
  const { meta, body } = parseNote(raw);
286
- meta.scope = scope;
287
281
  const beforeMeta = { ...meta };
282
+ meta.scope = scope;
283
+ if (from.scope !== "session" && scope === "session")
284
+ meta.project = identity.projectKey;
285
+ if (from.scope === "session" && scope !== "session")
286
+ delete meta.project;
288
287
  let next = body;
289
288
  let applied = 0;
290
289
  operations.forEach((operation, index) => {
291
290
  const oldText = operation?.oldText;
292
291
  const newText = operation?.newText;
293
292
  if (typeof oldText !== "string" || oldText.length === 0)
294
- throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
293
+ throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
295
294
  if (typeof newText !== "string")
296
- throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
295
+ throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
297
296
  const lines = matchLineNumbers(next, oldText);
298
297
  if (lines.length === 0)
299
298
  throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
@@ -318,7 +317,7 @@ export function createNotesStore(input) {
318
317
  delete meta.crumpledAt;
319
318
  const bodyChanged = body !== next;
320
319
  const originChanged = beforeMeta.origin !== meta.origin;
321
- if (bodyChanged || originChanged)
320
+ if (bodyChanged || originChanged || moved)
322
321
  meta.updatedAt = writeStamp();
323
322
  const serialized = serializeNote(meta, next);
324
323
  assertSerializedSize(serialized);
@@ -326,7 +325,7 @@ export function createNotesStore(input) {
326
325
  let change;
327
326
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
328
327
  // whole serialized file, so the frontmatter part stays visible in the diff.
329
- if (bodyChanged && metadataChanged)
328
+ if (bodyChanged && (metadataChanged || moved))
330
329
  change = { kind: "body", before: raw, after: serialized };
331
330
  else if (bodyChanged)
332
331
  change = { kind: "body", before: body, after: next };
@@ -334,50 +333,21 @@ export function createNotesStore(input) {
334
333
  change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
335
334
  else
336
335
  change = { kind: "none", before: "", after: "" };
337
- await atomicWrite(path, serialized);
338
- return { meta, applied, resolvedScope: scope, change };
339
- });
336
+ await atomicWrite(sameFile ? sourceReal : path, serialized);
337
+ if (moved)
338
+ await rm(fromPath, { force: true });
339
+ return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
340
+ };
341
+ // Exact aliases share one queue; other spellings lock both paths in stable order.
342
+ if (!differentPaths)
343
+ return withPathQueue(path, mutate);
344
+ const [first, second] = [fromPath, path].sort();
345
+ return withPathQueue(first, () => withPathQueue(second, mutate));
340
346
  }
341
- /**
342
- * Move one note to a new address with every metadata key preserved. Both ends must be
343
- * writable; a live target refuses, a crumpled target is replaced. Locks both paths in
344
- * sorted order so crossed renames cannot deadlock.
345
- */
347
+ /** Moving alone shares validation and persistence with a combined edit-and-move. */
346
348
  async function rename(fromAddress, toAddress) {
347
- const from = assertAddress(fromAddress);
348
- const to = assertAddress(toAddress);
349
- const fromScope = from.scope;
350
- const toScope = to.scope;
351
- assertWritablePath(to.path);
352
- assertWritableHome(fromScope, from.who, identity);
353
- assertWritableHome(toScope, to.who, identity);
354
- const fromPath = physicalPath(fromScope, from.path, identity, from.who);
355
- const toPath = physicalPath(toScope, to.path, identity, to.who);
356
- if (resolve(fromPath) === resolve(toPath))
357
- throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
358
- const [first, second] = [fromPath, toPath].sort();
359
- return withPathQueue(first, () => withPathQueue(second, async () => {
360
- const raw = await readFileIfExists(fromPath);
361
- if (raw === undefined)
362
- throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
363
- const targetRaw = await readFileIfExists(toPath);
364
- if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
365
- throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
366
- }
367
- const { meta, body } = parseNote(raw);
368
- meta.scope = toScope;
369
- // Project ownership only changes when the move crosses the session boundary.
370
- if (fromScope !== "session" && toScope === "session")
371
- meta.project = identity.projectKey;
372
- if (fromScope === "session" && toScope !== "session")
373
- delete meta.project;
374
- meta.updatedAt = writeStamp();
375
- const serialized = serializeNote(meta, body);
376
- assertSerializedSize(serialized);
377
- await atomicWrite(toPath, serialized);
378
- await rm(fromPath, { force: true });
379
- return { meta, replacedCrumpledTarget: targetRaw !== undefined };
380
- }));
349
+ const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
350
+ return { meta, replacedCrumpledTarget };
381
351
  }
382
352
  async function* scan(options, status) {
383
353
  const pattern = normalizePattern(options.glob, identity);
@@ -385,7 +355,7 @@ export function createNotesStore(input) {
385
355
  const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
386
356
  let homes;
387
357
  try {
388
- homes = await homesFor(identity, options);
358
+ homes = await homesForPattern(normalized, identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
389
359
  }
390
360
  catch (error) {
391
361
  if (!status || !isFilesystemError(error) || !/^@(projects|agents|models)\//.test(options.glob ?? ""))
@@ -209,7 +209,7 @@ export function registerContext(pi, settingsManager) {
209
209
  name: "empty_brain",
210
210
  label: "Empty Brain",
211
211
  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.",
212
- 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 }),
212
+ 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 }),
213
213
  async execute(_id, params, _signal, _update, ctx) {
214
214
  if (!enabled)
215
215
  return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
@@ -7,7 +7,7 @@ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, rende
7
7
  import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
8
8
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")];
9
9
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
10
- description: "(optional, default self) Who wrote it: user, self, or external.",
10
+ description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self.",
11
11
  }));
12
12
  const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
13
13
  const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
@@ -184,7 +184,7 @@ export const notesWrite = {
184
184
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
185
185
  async execute(params, identity) {
186
186
  try {
187
- const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin ?? "self" });
187
+ const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin });
188
188
  return success({ ...noteIdentity(identity, params.address), outcome });
189
189
  }
190
190
  catch (error) {
@@ -199,7 +199,7 @@ export const notesUpdateParameters = Type.Object({
199
199
  origin: ORIGIN,
200
200
  crumpled: CRUMPLED_PARAMETER,
201
201
  replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
202
- 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." })),
202
+ 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." })),
203
203
  }, { additionalProperties: false });
204
204
  function renderUpdateData(data) {
205
205
  const head = data.rename_from === undefined
@@ -235,17 +235,11 @@ export const notesUpdate = {
235
235
  const store = createNotesStore(identity);
236
236
  // Empty filler is not a request: models that pass every parameter get the edit path.
237
237
  const renameTo = params.rename_to === "" ? undefined : params.rename_to;
238
- if (renameTo !== undefined) {
239
- if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
240
- return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
241
- }
242
- await store.rename(params.address, renameTo);
243
- const from = noteIdentity(identity, params.address).address;
244
- const to = noteIdentity(identity, renameTo);
245
- return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
246
- }
247
- const { change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
248
- return boundedUpdate({ ...noteIdentity(identity, params.address), change_kind: change.kind, diff: renderDiff(change) });
238
+ const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
239
+ const from = noteIdentity(identity, params.address).address;
240
+ const to = noteIdentity(identity, renameTo ?? params.address);
241
+ const diff = renderDiff(change);
242
+ 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 });
249
243
  }
250
244
  catch (error) {
251
245
  return failureOf(error);
@@ -74,7 +74,7 @@ test("the root boot and reset boot carry durable window identity", async () => {
74
74
  assert.equal(rootText.includes(NORMAL_CONTINUATIONS[0]), false, "root startup carries no reset handoff");
75
75
  assertBootHistory(rootText, historyFromSession(ctx));
76
76
  assert.ok(rootText.includes("decisions.md"));
77
- const decisionsMeta = (await listNotes(ctx, { scope: "session" })).find((row) => row.path === "decisions.md")?.meta;
77
+ const decisionsMeta = (await listNotes(ctx)).find((row) => row.path === "decisions.md")?.meta;
78
78
  assert.ok(decisionsMeta);
79
79
  assert.match(rootText, /decisions\.md · (?:just now|\d+s ago)/, "boot note metadata carries a relative update time");
80
80
  assert.ok(rootText.includes(NOTES_PROTOCOL_OPEN_TAG));
@@ -193,6 +193,18 @@ test("shared note operations return canonical outcomes with a body-only read win
193
193
  assert.equal(updated.diff, "caller-rendered-diff");
194
194
  const defaultReceipt = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "gamma", newText: "delta" }] }, notesIdentity));
195
195
  assert.equal(defaultReceipt.diff, "note body");
196
+ await notesWrite.execute({ address: "owned.md", content: "first", origin: "user" }, notesIdentity);
197
+ await notesWrite.execute({ address: "owned.md", content: "rewritten" }, notesIdentity);
198
+ assert.equal(data(await notesRead.execute({ address: "owned.md" }, notesIdentity)).metadata.origin, "user", "tool overwrites preserve an omitted origin");
199
+ const invalid = refusal(await notesUpdate.execute({ address: "owned.md", edits: [{ oldText: "", newText: "x" }] }, notesIdentity));
200
+ assert.equal(invalid.code, "invalid_edit");
201
+ const moved = data(await notesUpdate.execute({ address: "owned.md", rename_to: "@project/renamed.md", edits: [{ oldText: "rewritten", newText: "final" }], origin: "external" }, notesIdentity));
202
+ assert.equal(moved.change_kind, "moved");
203
+ assert.equal(moved.rename_from, "owned.md");
204
+ assert.match(moved.diff, /rename owned\.md -> @project\/renamed\.md/);
205
+ const renamed = data(await notesRead.execute({ address: moved.address }, notesIdentity));
206
+ assert.equal(renamed.text, "final");
207
+ assert.equal(renamed.metadata.origin, "external");
196
208
  const unchanged = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "delta", newText: "delta" }] }, notesIdentity));
197
209
  assert.equal(unchanged.change_kind, "none");
198
210
  assert.equal(unchanged.diff, "");
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import test from "node:test";
@@ -77,7 +77,7 @@ test("same-file read/modify/write operations serialize across stores and markdow
77
77
  const before = (await notes.read("shared")).meta.accessCount;
78
78
  const [readA, readB] = await Promise.all([notes.read("shared.md"), other.read("shared")]);
79
79
  assert.ok(readA && readB);
80
- assert.equal((await notes.list({ scope: "session" }))[0]?.meta.accessCount, before + 2, "parallel reads do not lose access-counter updates");
80
+ assert.equal((await notes.list())[0]?.meta.accessCount, before + 2, "parallel reads do not lose access-counter updates");
81
81
  const file = join(home, "pi/session/session-a/shared.md");
82
82
  const stableEdits = [{ oldText: "A", newText: "first" }];
83
83
  const operation = notes.update("shared", stableEdits);
@@ -131,7 +131,7 @@ test("search offsets address the body and never move when access metadata grows"
131
131
  // would shift by one character here, because the rewrite adds a digit to the frontmatter.
132
132
  for (let read = 0; read < 12; read++)
133
133
  await notes.read("counted.md");
134
- assert.equal((await notes.list({ scope: "session" })).find((row) => row.address === "counted.md").meta.accessCount, 12);
134
+ assert.equal((await notes.list()).find((row) => row.address === "counted.md").meta.accessCount, 12);
135
135
  assert.equal(await offsetOf(), 0, "reads that rewrite access metadata do not move the match");
136
136
  await notes.write("front.md", `---\nbig: ${"x".repeat(200)}\n---\n\nneedle later`);
137
137
  const frontMatch = (await notes.search(["needle"])).find((row) => row.address === "front.md").matches[0];
@@ -145,15 +145,15 @@ test("invalid addressing and failed edits leave stored bytes untouched without p
145
145
  const { home, context, notes } = fixture(t);
146
146
  assert.throws(() => createNotesStore({ ...context, sessionId: "../escape" }));
147
147
  await assert.rejects(() => notes.write("@project/../escape", "bad"), (error) => error instanceof NoteError && error.code === "invalid_address");
148
- await assert.rejects(() => notes.list({ scope: "agent", who: "../escape" }));
149
- // The typed API disallows this; JavaScript callers must still receive a refusal.
150
- // @ts-expect-error who cannot accompany project scope
151
- await assert.rejects(() => notes.list({ scope: "project", who: "root" }), (error) => error instanceof NoteError && error.code === "invalid_scope");
148
+ await assert.rejects(() => notes.list({ glob: "@agents/../escape/**" }));
152
149
  await notes.write("edit", "alpha\nbeta\nbeta");
153
150
  const path = join(home, "pi/session/session-a/edit.md");
154
151
  const before = readFileSync(path, "utf8");
155
152
  await assert.rejects(() => notes.update("edit", [{ oldText: "beta", newText: "B" }]), (error) => error instanceof NoteError && error.code === "ambiguous_edit" && error.lineNumbers?.join(",") === "2,3");
156
153
  await assert.rejects(() => notes.update("edit", [{ oldText: "alpha", newText: "A" }, { oldText: "absent", newText: "X" }]), (error) => error instanceof NoteError && error.code === "no_match" && error.editIndex === 1);
154
+ await assert.rejects(() => notes.update("edit", [{ oldText: "", newText: "X" }]), (error) => error instanceof NoteError && error.code === "invalid_edit");
155
+ // @ts-expect-error malformed JavaScript callers receive a parameter error, not no_match
156
+ await assert.rejects(() => notes.update("edit", [{ oldText: "alpha", newText: 5 }]), (error) => error instanceof NoteError && error.code === "invalid_edit");
157
157
  assert.equal(readFileSync(path, "utf8"), before);
158
158
  await assert.rejects(() => notes.update("absent", undefined, { crumpled: true }), (error) => error instanceof NoteError && error.code === "not_found");
159
159
  await notes.update("edit", [{ oldText: "alpha", newText: "A" }]);
@@ -183,11 +183,68 @@ test("rename moves a note with metadata intact across scopes and refuses live ta
183
183
  const replaced = await notes.rename("still-back.md", "occupied.md");
184
184
  assert.equal(replaced.replacedCrumpledTarget, true, "a crumpled target is replaced");
185
185
  assert.equal((await notes.read("occupied.md"))?.meta.createdAt, written.meta.createdAt, "the moved note keeps its identity, not the target's");
186
- await assert.rejects(() => notes.rename("occupied", "occupied.md"), (error) => error instanceof NoteError && error.code === "nothing_to_do");
186
+ const beforeAlias = (await notes.read("occupied")).meta.updatedAt;
187
+ assert.equal((await notes.rename("occupied", "occupied.md")).meta.updatedAt, beforeAlias, "a same-file move is a successful no-op");
187
188
  await assert.rejects(() => notes.rename("occupied.md", "@models/other-model/stolen.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
188
189
  await assert.rejects(() => notes.rename("@agents/someone-else/private.md", "mine.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
189
190
  await assert.rejects(() => notes.rename("absent.md", "anywhere.md"), (error) => error instanceof NoteError && error.code === "not_found");
190
191
  });
192
+ test("combined moves validate everything before saving either endpoint", async (t) => {
193
+ const { home, notes } = fixture(t);
194
+ await notes.write("source", "alpha alpha", { origin: "user" });
195
+ await notes.write("target", "keep me");
196
+ const sourcePath = join(home, "pi/session/session-a/source.md");
197
+ const targetPath = join(home, "pi/session/session-a/target.md");
198
+ const sourceBefore = readFileSync(sourcePath, "utf8");
199
+ const targetBefore = readFileSync(targetPath, "utf8");
200
+ await assert.rejects(() => notes.update("source", [{ oldText: "alpha", newText: "A" }], { replaceAll: true, renameTo: "target" }), (error) => error instanceof NoteError && error.code === "already_exists");
201
+ await notes.update("target", undefined, { crumpled: true });
202
+ const crumpledBefore = readFileSync(targetPath, "utf8");
203
+ await assert.rejects(() => notes.update("source", [{ oldText: "missing", newText: "A" }], { renameTo: "target", origin: "external", crumpled: false }), (error) => error instanceof NoteError && error.code === "no_match");
204
+ assert.equal(readFileSync(sourcePath, "utf8"), sourceBefore);
205
+ assert.notEqual(crumpledBefore, targetBefore);
206
+ assert.equal(readFileSync(targetPath, "utf8"), crumpledBefore, "a failed edit does not consume a crumpled destination");
207
+ const result = await notes.update("source", [{ oldText: "alpha", newText: "A" }], { renameTo: "@project/moved", replaceAll: true, origin: "external", crumpled: true });
208
+ assert.equal(result.moved, true);
209
+ assert.equal(result.meta.origin, "external");
210
+ assert.ok(result.meta.crumpledAt);
211
+ assert.equal(result.meta.project, undefined);
212
+ assert.equal(existsSync(sourcePath), false);
213
+ assert.equal((await notes.read("@project/moved")).body, "A A");
214
+ const same = await notes.update("@project/moved", [{ oldText: "A A", newText: "B" }], { renameTo: "@project/moved.md", crumpled: false });
215
+ assert.equal(same.moved, false);
216
+ assert.equal(same.change.kind, "body");
217
+ assert.equal(same.meta.crumpledAt, undefined);
218
+ });
219
+ test("same-file case and directory aliases cannot delete a moved note", async (t) => {
220
+ const { home, notes } = fixture(t);
221
+ await notes.write("Mixed.md", "precious", { origin: "user" });
222
+ await notes.update("Mixed.md", undefined, { crumpled: true });
223
+ const directory = join(home, "pi/session/session-a");
224
+ symlinkSync(directory, join(directory, "linked"), "dir");
225
+ const result = await notes.update("Mixed.md", [{ oldText: "precious", newText: "saved" }], { renameTo: "linked/Mixed.md", crumpled: false });
226
+ assert.equal(result.moved, false);
227
+ assert.equal(result.replacedCrumpledTarget, false);
228
+ assert.equal((await notes.read("Mixed.md"))?.body, "saved");
229
+ assert.equal((await notes.read("linked/Mixed.md"))?.body, "saved");
230
+ // The host filesystem decides whether these two case spellings alias.
231
+ if (existsSync(join(directory, "mixed.md"))) {
232
+ await notes.update("Mixed.md", undefined, { crumpled: true });
233
+ const caseResult = await notes.update("Mixed.md", [{ oldText: "saved", newText: "still here" }], { renameTo: "mixed.md" });
234
+ assert.equal(caseResult.moved, false);
235
+ assert.equal((await notes.read("Mixed.md"))?.body, "still here");
236
+ assert.equal((await notes.read("mixed.md"))?.body, "still here");
237
+ }
238
+ });
239
+ test("glob is the single query selector for a named project home", async (t) => {
240
+ const { home, notes } = fixture(t);
241
+ mkdirSync(join(home, "project/other"), { recursive: true });
242
+ writeFileSync(join(home, "project/other/decision.md"), "needle");
243
+ const rows = await notes.list({ glob: "@projects/other/**" });
244
+ assert.deepEqual(rows.map(row => row.address), ["@projects/other/decision.md"]);
245
+ assert.equal((await notes.search(["needle"], { glob: "@projects/other/**" }))[0]?.matches[0]?.text, "needle");
246
+ await assert.rejects(() => notes.write(rows[0].address, "overwrite"), (error) => error instanceof NoteError && error.code === "invalid_scope", "named project queries do not grant writes");
247
+ });
191
248
  test("ambiguous multiline anchors report each starting line", async (t) => {
192
249
  const { notes } = fixture(t);
193
250
  await notes.write("multiline", "a\nb\na\nb\na\nb");
@@ -219,10 +276,10 @@ test("one unreadable note is named without hiding its readable siblings", async
219
276
  await notes.write("@project/bad.md", "bad body");
220
277
  await notes.write("@project/good.md", "good body");
221
278
  chmodSync(join(home, "project", "project-12345678", "bad.md"), 0o000);
222
- const result = await notes.listWithStatus({ scope: "project" });
279
+ const result = await notes.listWithStatus({ glob: "@project/**" });
223
280
  assert.deepEqual(result.rows.map((row) => row.address), ["@project/good.md"], "the readable sibling still lists");
224
281
  assert.deepEqual(result.status.homesUnavailable, ["@project/bad.md"], "the unreadable note is named on its own");
225
- await assert.rejects(() => notes.list({ scope: "project" }), (error) => error.code === "EACCES", "a caller that asked for no status still sees the failure");
282
+ await assert.rejects(() => notes.list({ glob: "@project/**" }), (error) => error.code === "EACCES", "a caller that asked for no status still sees the failure");
226
283
  });
227
284
  test("a hand-written quoted numeric extra survives a rewrite as a string", async (t) => {
228
285
  const { home, notes } = fixture(t);
@@ -135,26 +135,26 @@ test("crumple lifecycle: metadata-only edits close and smooth a note without tou
135
135
  const captured = makeExtension(sm);
136
136
  const ctx = context(sm);
137
137
  await call(captured, "notes_write", { address: "journal.md", content: "log line" }, ctx);
138
- const updatedBefore = (await listNotes(ctx, { scope: "session" }))[0].meta.updatedAt;
138
+ const updatedBefore = (await listNotes(ctx))[0].meta.updatedAt;
139
139
  // metadata-only: content unchanged, and the recorded time is the original one
140
140
  const markOnly = resultData(await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx));
141
141
  assert.equal(markOnly.change_kind, "metadata");
142
142
  assert.match(markOnly.diff, /^\+\s*\d+\s+crumpledAt: \d{4}-\d{2}-\d{2}T/m);
143
- assert.deepEqual(await listNotes(ctx, { scope: "session" }), [], "a crumpled note leaves the live list");
144
- const basket = (await listNotes(ctx, { scope: "session", crumpled: true }))[0];
143
+ assert.deepEqual(await listNotes(ctx), [], "a crumpled note leaves the live list");
144
+ const basket = (await listNotes(ctx, { crumpled: true }))[0];
145
145
  assert.ok(basket.meta.crumpledAt);
146
146
  assert.equal(basket.meta.updatedAt, updatedBefore, "crumpling does not change updatedAt");
147
147
  assert.equal(resultRead(await call(captured, "notes_read", { address: "journal.md" }, ctx)).content.endsWith("log line"), true, "read still reaches a crumpled note");
148
148
  // re-crumpling keeps the first time; smoothing empties the basket
149
149
  await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx);
150
- assert.equal((await listNotes(ctx, { scope: "session", crumpled: true }))[0]?.meta.crumpledAt, basket.meta.crumpledAt);
150
+ assert.equal((await listNotes(ctx, { crumpled: true }))[0]?.meta.crumpledAt, basket.meta.crumpledAt);
151
151
  await call(captured, "notes_update", { address: "journal.md", crumpled: false }, ctx);
152
- assert.deepEqual(await listNotes(ctx, { scope: "session", crumpled: true }), []);
153
- assert.equal((await listNotes(ctx, { scope: "session" }))[0]?.meta.crumpledAt, undefined);
152
+ assert.deepEqual(await listNotes(ctx, { crumpled: true }), []);
153
+ assert.equal((await listNotes(ctx))[0]?.meta.crumpledAt, undefined);
154
154
  // writing to a crumpled address always produces an uncrumpled note
155
155
  await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx);
156
156
  await call(captured, "notes_write", { address: "journal.md", content: "reopened" }, ctx);
157
- assert.equal((await listNotes(ctx, { scope: "session" }))[0]?.meta.crumpledAt, undefined, "writing always produces an uncrumpled note");
157
+ assert.equal((await listNotes(ctx))[0]?.meta.crumpledAt, undefined, "writing always produces an uncrumpled note");
158
158
  // metadata-only on a missing path is the typed not-found arm
159
159
  const missing = resultError(await call(captured, "notes_update", { address: "missing.md", crumpled: true }, ctx));
160
160
  assert.equal(missing.code, "not_found");
@@ -162,10 +162,10 @@ test("crumple lifecycle: metadata-only edits close and smooth a note without tou
162
162
  test("the filesystem notes loader treats an absent home as empty but surfaces a real directory read failure", async () => {
163
163
  const sm = manager();
164
164
  const ctx = context(sm);
165
- assert.deepEqual(await listNotes(ctx, { scope: "human" }), [], "a home that has not been created is empty");
165
+ assert.deepEqual(await listNotes(ctx, { glob: "@human/**" }), [], "a home that has not been created is empty");
166
166
  const blockedHome = scopeDir("human", ctx);
167
167
  writeFileSync(blockedHome, "not a directory");
168
- await assert.rejects(() => listNotes(ctx, { scope: "human" }), (error) => error.code === "ENOTDIR", "a non-ENOENT directory failure is not swallowed as an empty home");
168
+ await assert.rejects(() => listNotes(ctx, { glob: "@human/**" }), (error) => error.code === "ENOTDIR", "a non-ENOENT directory failure is not swallowed as an empty home");
169
169
  });
170
170
  test("boot note acquisition is one closed snapshot and isolates one or all failed homes", async () => {
171
171
  const sm = manager();