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.
@@ -13,7 +13,7 @@ import { join } from "node:path";
13
13
  import test from "node:test";
14
14
  import { Check } from "typebox/value";
15
15
  import { parseNote } from "../src/notes/frontmatter.js";
16
- import { projectKey } from "../src/notes/index.js";
16
+ import { createNotesStore, projectKey } from "../src/notes/index.js";
17
17
  import { globToRegExp } from "../src/notes/address.js";
18
18
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
19
19
  import { notesList, notesSearch } from "../src/tools/notes.js";
@@ -163,7 +163,7 @@ test("session-note project ownership is per note, persistent across sessions, an
163
163
  assert.equal(parseNote(readFileSync(physicalPath("session", "new-from-project-b.md", movedContext), "utf8")).meta.project, projectB, "only a newly-created session note uses the current project key");
164
164
  await call(firstCaptured, "notes_write", { address: "@project/project-note.md", content: "project home note" }, movedContext);
165
165
  assert.equal(parseNote(readFileSync(physicalPath("project", "project-note.md", movedContext), "utf8")).meta.project, undefined, "project-home notes do not receive session ownership metadata");
166
- assert.equal((await listNotes(movedContext, { scope: "session" })).length, 2, "project ownership remains frontmatter, not a separate note");
166
+ assert.equal((await listNotes(movedContext)).filter(row => row.scope === "session").length, 2, "project ownership remains frontmatter, not a separate note");
167
167
  });
168
168
  test("linked git worktrees share the main checkout's project key", () => {
169
169
  freshRoot();
@@ -204,7 +204,7 @@ legacy body`);
204
204
  const parsed = parseNote(readFileSync(legacyFile, "utf8"), Date.parse("2026-02-01T00:00:00Z"));
205
205
  assert.equal(parsed.meta.createdAt, Date.parse("2026-02-01T00:00:00Z"), "missing canonical timestamp takes the normal default");
206
206
  assert.equal(parsed.meta.created_at, "2026-01-01T00:00:00.000+00:00", "unrecognized fields remain ordinary extras");
207
- assert.equal((await listNotes(ctx, { scope: "session" }))[0]?.address, "legacy.md");
207
+ assert.equal((await listNotes(ctx))[0]?.address, "legacy.md");
208
208
  assert.match(resultRead(await call(captured, "notes_read", { address: "legacy.md" }, ctx)).content, /legacy body$/);
209
209
  await call(captured, "notes_update", { address: "legacy.md", edits: [{ oldText: "legacy body", newText: "edited body" }] }, ctx);
210
210
  await call(captured, "notes_write", { address: "legacy.md", content: "overwritten body" }, ctx);
@@ -279,25 +279,28 @@ test("nothing-to-do, not-found, atomic batches, and replace_all zero-match are n
279
279
  const zero = resultError(await call(captured, "notes_update", { address: "edit.md", edits: [{ oldText: "zzz", newText: "y" }], replace_all: true }, ctx));
280
280
  assert.match(zero.message, /edits\[0\]/, "replace_all with zero matches is the same zero-match error, not a silent no-op");
281
281
  });
282
- test("notes_update rename_to moves a note and refuses combinations and live targets", async () => {
282
+ test("notes_update combines rename_to with edits and metadata but protects live targets", async () => {
283
283
  freshRoot();
284
284
  const session = manager();
285
285
  const captured = makeExtension(session);
286
286
  const ctx = context(session);
287
287
  await call(captured, "notes_write", { address: "move-me.md", content: "body" }, ctx);
288
- const combined = resultError(await call(captured, "notes_update", { address: "move-me.md", rename_to: "moved.md", edits: [{ oldText: "body", newText: "x" }] }, ctx));
289
- assert.match(combined.message, /rename_to is used alone/, "rename_to rejects being combined with edits");
288
+ const failed = resultError(await call(captured, "notes_update", { address: "move-me.md", rename_to: "moved.md", edits: [{ oldText: "absent", newText: "x" }] }, ctx));
289
+ assert.equal(failed.code, "no_match", "a failed edit does not move the note");
290
290
  await call(captured, "notes_write", { address: "occupied.md", content: "live target" }, ctx);
291
291
  const conflict = resultError(await call(captured, "notes_update", { address: "move-me.md", rename_to: "occupied.md" }, ctx));
292
292
  assert.match(conflict.message, /occupied\.md/, "a live target refuses the move");
293
- const renamed = resultData(await call(captured, "notes_update", { address: "move-me.md", rename_to: "moved.md" }, ctx));
293
+ const renamed = resultData(await call(captured, "notes_update", { address: "move-me.md", rename_to: "moved.md", edits: [{ oldText: "body", newText: "x" }], origin: "external", crumpled: true }, ctx));
294
294
  assertReceiptIdentity(renamed, "moved.md", "session", ctx);
295
295
  assert.equal(renamed.rename_from, "move-me.md");
296
296
  assert.equal(renamed.change_kind, "moved");
297
297
  assert.equal(renamed.address, "moved.md");
298
298
  const gone = resultError(await call(captured, "notes_read", { address: "move-me.md" }, ctx));
299
299
  assert.equal(gone.code, "not_found", "the old address is gone");
300
- assert.equal(resultRead(await call(captured, "notes_read", { address: "moved.md" }, ctx)).content, "body");
300
+ assert.equal(resultRead(await call(captured, "notes_read", { address: "moved.md" }, ctx)).content, "x");
301
+ const movedMeta = (await listNotes(ctx, { crumpled: true }))[0].meta;
302
+ assert.equal(movedMeta.origin, "external");
303
+ assert.ok(movedMeta.crumpledAt);
301
304
  // Empty filler values are not a combination: a model passing every parameter still gets its crumple.
302
305
  const crumpled = resultData(await call(captured, "notes_update", { address: "moved.md", crumpled: true, edits: [], origin: "self", rename_to: "", replace_all: false }, ctx));
303
306
  assert.equal(crumpled.address, "moved.md", "an empty rename_to is ignored as if omitted");
@@ -305,8 +308,8 @@ test("notes_update rename_to moves a note and refuses combinations and live targ
305
308
  assert.equal(listedCrumpled.files.some((file) => file.address === "moved.md"), true, "the note was crumpled");
306
309
  const fillerRename = resultData(await call(captured, "notes_update", { address: "moved.md", rename_to: "moved-again.md", edits: [], replace_all: false }, ctx));
307
310
  assert.equal(fillerRename.address, "moved-again.md", "empty edits and replace_all: false ride along with a rename");
308
- const realCombo = resultError(await call(captured, "notes_update", { address: "moved-again.md", rename_to: "nope.md", replace_all: true }, ctx));
309
- assert.match(realCombo.message, /rename_to is used alone/, "replace_all: true is a real combination and refuses");
311
+ const realCombo = resultData(await call(captured, "notes_update", { address: "moved-again.md", rename_to: "final.md", replace_all: true, crumpled: false }, ctx));
312
+ assert.equal(realCombo.address, "final.md", "replace_all is harmless without edits, and restoration can accompany the move");
310
313
  });
311
314
  test("write and update receipts distinguish outcomes and no-op edits", async () => {
312
315
  freshRoot();
@@ -465,7 +468,7 @@ test("a read keeps its body window verbatim under the new presentation", async (
465
468
  assert.equal(wholeText.endsWith("\n\n0123456789"), true, "a complete window carries no continuation footer");
466
469
  assert.equal(wholeText.includes("more characters"), false);
467
470
  });
468
- test("@ addresses select one home, reject illegal sigils, and never fall back", async () => {
471
+ test("@ addresses select one home, keep boundaries, and never fall back", async () => {
469
472
  const root = freshRoot();
470
473
  const session = manager();
471
474
  const captured = makeExtension(session);
@@ -478,8 +481,38 @@ test("@ addresses select one home, reject illegal sigils, and never fall back",
478
481
  assert.match(resultRead(await call(captured, "notes_read", { address: "same.md" }, ctx)).content, /session$/);
479
482
  assert.equal(resultError(await call(captured, "notes_read", { address: "@project/missing.md" }, ctx)).code, "not_found");
480
483
  assert.match(resultError(await call(captured, "notes_read", { address: "@glboal/same.md" }, ctx)).message, /isn't a note address.*@project\/.*@human\//);
481
- assert.equal(resultError(await call(captured, "notes_write", { address: "bad@name.md", content: "no" }, ctx)).code, "invalid_address");
482
- assert.equal(existsSync(join(root, "human", "bad@name.md")), false, "a bad sigil creates nothing anywhere");
484
+ assert.equal(resultError(await call(captured, "notes_write", { address: "@glboal/same.md", content: "no" }, ctx)).code, "invalid_address", "an unknown leading head is still not a note address");
485
+ assert.equal(resultError(await call(captured, "notes_write", { address: "@project/../escape.md", content: "no" }, ctx)).code, "invalid_address", "traversal never hides behind a known head");
486
+ assert.equal(existsSync(join(root, "human", "escape.md")), false, "a refused address creates nothing anywhere");
487
+ });
488
+ test("interior @ in a note path round-trips through write, list, search, read, update and rename", async () => {
489
+ const root = freshRoot();
490
+ const session = manager();
491
+ const captured = makeExtension(session);
492
+ const ctx = context(session);
493
+ assertReceiptIdentity(resultData(await call(captured, "notes_write", { address: "release@v1.md", content: "release needle" }, ctx)), "release@v1.md", "session", ctx);
494
+ assertReceiptIdentity(resultData(await call(captured, "notes_write", { address: "@project/mail/alice@example.com.md", content: "mail needle" }, ctx)), "@project/mail/alice@example.com.md", "project", ctx);
495
+ assert.ok(existsSync(join(root, "pi", "session", session.getSessionId(), "release@v1.md")), "the session file keeps its interior @");
496
+ assert.ok(existsSync(physicalPath("project", "mail/alice@example.com.md", ctx)), "the project file keeps its interior @ inside a folder");
497
+ const listed = resultData(await call(captured, "notes_list", {}, ctx));
498
+ assert.deepEqual(listed.files.map((row) => row.address).sort(), ["@project/mail/alice@example.com.md", "release@v1.md"], "both addresses list in canonical form");
499
+ const globbed = resultData(await call(captured, "notes_list", { glob: "@project/**" }, ctx));
500
+ assert.deepEqual(globbed.files.map((row) => row.address), ["@project/mail/alice@example.com.md"], "a home glob still narrows to that home");
501
+ const searched = resultData(await call(captured, "notes_search", { query: "needle" }, ctx));
502
+ assert.deepEqual(searched.files.map((row) => row.address).sort(), ["@project/mail/alice@example.com.md", "release@v1.md"], "searched addresses carry the interior @ back out");
503
+ assert.match(resultRead(await call(captured, "notes_read", { address: "@project/mail/alice@example.com.md" }, ctx)).content, /mail needle$/);
504
+ await call(captured, "notes_update", { address: "release@v1.md", edits: [{ oldText: "release", newText: "shipped" }] }, ctx);
505
+ assert.match(resultRead(await call(captured, "notes_read", { address: "release@v1.md" }, ctx)).content, /shipped needle$/);
506
+ const store = createNotesStore(notesIdentityFromPi(ctx));
507
+ await store.rename("release@v1.md", "shipped@v2.md");
508
+ assert.match((await store.read("shipped@v2.md")).body, /shipped needle$/);
509
+ assert.equal(await store.read("release@v1.md"), undefined, "the rename leaves no old name behind");
510
+ // A file dropped on disk (before any address change) still lists and reads under its full address.
511
+ mkdirSync(join(root, "human"), { recursive: true });
512
+ writeFileSync(join(root, "human", "pre@existing.md"), "---\norigin: user\n---\n\nlegacy needle\n");
513
+ const legacy = resultData(await call(captured, "notes_list", { glob: "@human/**" }, ctx));
514
+ assert.deepEqual(legacy.files.map((row) => row.address), ["@human/pre@existing.md"]);
515
+ assert.match(resultRead(await call(captured, "notes_read", { address: "@human/pre@existing.md" }, ctx)).content, /legacy needle/);
483
516
  });
484
517
  test("Pi adapter defaults to anonymous agent identity", async () => {
485
518
  const root = freshRoot();
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import test from "node:test";
6
+ import { Check } from "typebox/value";
6
7
  import { SessionManager as Manager } from "@earendil-works/pi-coding-agent";
7
8
  import notesoup from "../src/pi/extension.js";
8
9
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
@@ -80,7 +81,12 @@ function harness() {
80
81
  // Pi 1.0 hands a tool the session context plus the nested-call surface; toolContext builds it.
81
82
  return tool.execute("call", params, new AbortController().signal, () => { }, toolContext(ctx));
82
83
  };
83
- return { sessionManager, handlers, sent, notices, emit, runCommand, callTool };
84
+ const toolParameters = (name) => {
85
+ const tool = tools.get(name);
86
+ assert.ok(tool, `${name} is registered`);
87
+ return tool.parameters;
88
+ };
89
+ return { sessionManager, handlers, sent, notices, emit, runCommand, callTool, toolParameters };
84
90
  }
85
91
  function resultEntries(results) {
86
92
  let entries = [];
@@ -708,6 +714,9 @@ test("empty_brain trims the last word, refuses an oversized one, and a blank per
708
714
  over.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
709
715
  const refused = await over.callTool("empty_brain", { last_word: "x".repeat(MAX_LAST_WORD_CHARS + 1) });
710
716
  assert.match(JSON.stringify(refused), /error/, "an oversized note is refused, not truncated");
717
+ assert.match(JSON.stringify(refused), new RegExp(`${MAX_LAST_WORD_CHARS + 1} characters`), "the refusal names the actual size and the limit");
718
+ const refusedAstral = await over.callTool("empty_brain", { last_word: "\u{1F41F}".repeat(MAX_LAST_WORD_CHARS + 1) });
719
+ assert.match(JSON.stringify(refusedAstral), new RegExp(`${MAX_LAST_WORD_CHARS + 1} characters`), "the guard counts code points, not UTF-16 units");
711
720
  const untouched = resultEntries(await over.emit("turn_end", fakeBoundaryEvent()));
712
721
  assert.equal(untouched.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a refused call requests no reset");
713
722
  const h = harness();
@@ -716,6 +725,19 @@ test("empty_brain trims the last word, refuses an oversized one, and a blank per
716
725
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
717
726
  assert.equal(boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a blank last word persists no entry");
718
727
  });
728
+ test("empty_brain's schema admits whitespace-wrapped notes and leaves length to the handler", async () => {
729
+ const parameters = harness().toolParameters("empty_brain");
730
+ const padded = " ".repeat(300) + "x";
731
+ assert.equal(Check(parameters, { last_word: padded }), true, "300 spaces plus x is admitted by the schema");
732
+ assert.equal(Check(parameters, { last_word: "x".repeat(MAX_LAST_WORD_CHARS + 1) }), true, "the schema does not pre-empt the handler's code-point limit");
733
+ assert.equal(Check(parameters, { last_word: 42 }), false, "a genuine type violation is still refused by the schema");
734
+ const h = harness();
735
+ h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
736
+ await h.callTool("empty_brain", { last_word: padded });
737
+ const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
738
+ const lastWords = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE);
739
+ assert.deepEqual(lastWords[0], { type: "custom_message", customType: RESET_LAST_WORD_TYPE, content: `${LAST_WORD_PREFIX}x`, display: true }, "the handler records the trimmed note");
740
+ });
719
741
  test("reset-control: a tool request carries its last word to the turn-end commit", () => {
720
742
  const windowId = "pcw:test:window";
721
743
  const armed = reduceResetControl(initialResetControl(), { type: "tool_request", windowId, lastWord: "the shoes were loyal" });
@@ -32,18 +32,18 @@ const matches = await notes.search(["library"]);
32
32
 
33
33
  `createNotesStore(identity)` snapshots the five required identity fields; changing the supplied object afterward does not retarget the store. It resolves `home` once, validates identity components, and creates no files until an operation needs to write. Create a new store to change identity. Multiple stores can use independent roots and identities without changing process environment.
34
34
 
35
- - `write(address, content, { origin? }?)` returns `Promise<{ meta, outcome }>` (`created`, `overwritten` or `uncrumpled`). Default origin is `self`; overwriting preserves creation time, existing project ownership, and unknown metadata, and always produces an uncrumpled note (it clears any `crumpledAt`).
35
+ - `write(address, content, { origin? }?)` returns `Promise<{ meta, outcome }>` (`created`, `overwritten` or `uncrumpled`). New notes default to origin `self`; overwriting preserves the existing origin unless explicitly supplied, creation time, project ownership, and unknown metadata, and always produces an uncrumpled note (it clears any `crumpledAt`).
36
36
  - `read(address)` returns `Promise<{ meta, body, resolvedScope } | undefined>`. **Reads update** `lastAccessed` and `accessCount` on disk. The body is separate from metadata; the serialized frontmatter is not part of the read API.
37
- - `update(address, edits?, { origin?, crumpled?, replaceAll? }?)` returns `Promise<{ meta, applied, resolvedScope, change }>`. Edits affect the body; metadata-only changes need no edits, but must supply `origin` or `crumpled`. `crumpled: true` records `crumpledAt` (keeping the original time if already set); `crumpled: false` removes it; omitted leaves it unchanged. Crumpling and smoothing never change `updatedAt`, which tracks body or origin changes only. Each replacement uses the evolving body in array order; the complete batch is written atomically only after every edit succeeds. `change` is a typed `{ kind, before, after }`: `kind` is `body`, `metadata`, or `none` with empty strings when neither body, origin, nor `crumpledAt` changed. A body change that also rewrites frontmatter is still `body`, and its diff inputs then span the whole serialized file. It is not a rendered diff.
38
- - `rename(fromAddress, toAddress)` returns `Promise<{ meta, replacedCrumpledTarget }>`. The note moves with every metadata key preserved (`updatedAt` is bumped); a live note at the target refuses with `already_exists`, a crumpled target is replaced, and renaming onto the same resolved path is `nothing_to_do`.
39
- - `list({ glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteRow[]>`, sorted by update time descending with address tie-breaking. Rows contain address, scope, virtual path, metadata, body, and body byte size. `scope` narrows the five-home view; `who` names a concrete agent/model home. By default crumpled notes are excluded; `crumpled: true` returns only crumpled notes instead.
40
- - `search(queries: string[], { glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same crumpled-note rule as `list`. An empty queries array disables filtering and returns scoped notes with empty `matches`. Otherwise matching is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and `offsetChars` into the body, excluding frontmatter. Neither listing nor search increments access metadata.
37
+ - `update(address, edits?, { origin?, crumpled?, replaceAll?, renameTo? }?)` returns `Promise<{ meta, applied, resolvedScope, change, moved, replacedCrumpledTarget }>`. Body edits, origin, crumpled state and a move can be combined. Every edit, destination and size check passes before saving; a live target refuses with `already_exists`, while a crumpled target can be replaced. Cross-session moves update project ownership. Each replacement uses the evolving body in array order. `crumpled: true` keeps an existing `crumpledAt` or adds it; false removes it; omitted preserves it. `updatedAt` advances for body/origin changes and actual moves, not crumpling alone. `change` contains `{ kind, before, after }`, with kind `body`, `metadata` or `none`; a body edit that also changes metadata or moves includes the whole serialized file in its diff inputs. Moves lock both paths in stable order, atomically write the destination, then remove the source; this is not a crash-atomic two-file transaction.
38
+ - `rename(fromAddress, toAddress)` returns `Promise<{ meta, replacedCrumpledTarget }>`. It delegates to the same update path with `renameTo`, preserving metadata. A same-file destination, including a case or symlink alias resolved by the filesystem, applies accompanying edits without removing the source. An exact path alias needs only one lock.
39
+ - `list({ glob?, crumpled? }?)` returns `Promise<NoteRow[]>`, sorted by update time descending with address tie-breaking. Rows contain address, scope, virtual path, metadata, body, and body byte size. Crumpled notes are excluded by default; `crumpled: true` returns only crumpled notes.
40
+ - `search(queries: string[], { glob?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same selection and crumpled-note rules. An empty queries array returns matching notes with empty `matches`. Otherwise search is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and code-point `offsetChars` into the body. Neither listing nor search increments access metadata.
41
41
 
42
- `list` and `search` share the `NotesQuery` type. A merged query uses `{ glob?, crumpled? }`; a single-home query adds `scope`. Only `scope: "agent" | "model"` accepts `who`. TypeScript rejects combinations such as `{ scope: "project", who: "root" }`, and JavaScript callers receive a runtime refusal.
42
+ `list` and `search` share `NotesQuery`: **glob is the only home/path selector**. Omit it for the five current homes; use `@project/**`, `@self/**`, or `@projects/<name>/**` to select a home. The former `scope`/`who` query parameters are removed, without compatibility aliases. Row metadata still includes scope.
43
43
 
44
44
  The library returns full data, not tool envelopes or paginated/truncated output. `NoteError` exposes the existing named store refusals through `code`, with `lineNumbers` for ambiguous edits and `editIndex` for a failed edit. Runtime API fields and known persisted note metadata use camelCase; Pi tool wire fields such as `updated_at`, `offset_chars`, and `replace_all` retain their established names. Unrecognized frontmatter keys, including old snake_case metadata, are preserved as ordinary extras; they are not interpreted as current camelCase fields or migrated automatically. Invalid addresses/identities and filesystem failures reject; only a missing `read` returns `undefined`. Notes remain markdown files with the existing size limits and same-directory atomic rename. Same-file read/modify/write work is serialized by absolute physical filename across all store instances in this process (including `.md` address aliases); symlink/case aliases and cross-process locking are not guaranteed. `list` and `search` asynchronously traverse homes and serialize each discovered file read against pending mutations, but are not global snapshots and may not discover a file created after traversal. Foreign named homes can be read (including the access-metadata update), but their bodies cannot be written or edited through the store. These are cooperative address rules, not an OS security sandbox.
45
45
 
46
- Addresses are a path with no `@` (a session note), `@project/`, `@human/`, `@self/`, `@model/`, or explicit `@agents/<slug>/` and `@models/<slug>/`. Relative self/model addresses resolve to the supplied identity. Results show the current agent's and model's notes as `@self/` and `@model/`; only other agents' or models' notes carry an explicit `@agents/<slug>/` or `@models/<slug>/`. Globs accept either form. The disk layout remains `pi/session/<sessionId>/`, `project/<projectKey>/`, `human/`, `agents/<agent>/`, and `models/<model>/`. No data migration happens on library import or construction. Notes already using camelCase metadata retain their metadata; old snake_case keys are preserved as unrecognized extras, not interpreted or migrated. New session notes record the supplied project key.
46
+ Addresses are a relative path (a session note), `@project/`, `@human/`, `@self/`, `@model/`, or explicit `@agents/<slug>/` and `@models/<slug>/`. Only the first character of an address is sigil-position: an unknown leading `@head` refuses, while `@` inside the path (`release@v1.md`, `@project/mail/alice@example.com.md`) is an ordinary character. Relative self/model addresses resolve to the supplied identity. Results show the current agent's and model's notes as `@self/` and `@model/`; only other agents' or models' notes carry an explicit `@agents/<slug>/` or `@models/<slug>/`. Globs accept either form. The disk layout remains `pi/session/<sessionId>/`, `project/<projectKey>/`, `human/`, `agents/<agent>/`, and `models/<model>/`. No data migration happens on library import or construction. Notes already using camelCase metadata retain their metadata; old snake_case keys are preserved as unrecognized extras, not interpreted or migrated. New session notes record the supplied project key.
47
47
 
48
48
  ## Library and plugin boundary
49
49
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.48.1",
3
+ "version": "0.49.0",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -7975,7 +7975,7 @@ function isFilesystemError(error) {
7975
7975
 
7976
7976
  // src/notes/store.ts
7977
7977
  import { randomUUID as randomUUID2 } from "node:crypto";
7978
- import { mkdir, readdir as readdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
7978
+ import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
7979
7979
  import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
7980
7980
 
7981
7981
  // src/text-match.ts
@@ -8106,7 +8106,6 @@ function assertAddress(value) {
8106
8106
  if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8107
8107
  if (path === "" && who === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8108
8108
  }
8109
- if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8110
8109
  assertVirtualPath(path);
8111
8110
  return { scope, path, who };
8112
8111
  }
@@ -8427,20 +8426,6 @@ function assertWho(value) {
8427
8426
  }
8428
8427
  return value;
8429
8428
  }
8430
- async function homesFor(identity2, opts) {
8431
- if (opts.scope !== void 0) {
8432
- if (!isScope(opts.scope)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
8433
- const scope = opts.scope;
8434
- if (opts.who !== void 0) {
8435
- const who = assertWho(opts.who);
8436
- if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
8437
- return [{ scope, who }];
8438
- }
8439
- return [{ scope }];
8440
- }
8441
- if (opts.who !== void 0) throw new NoteError("invalid_scope", "who requires agent or model scope");
8442
- return await homesForPattern(normalizePattern(opts.glob, identity2), identity2) ?? SCOPE_ORDER.map((scope) => ({ scope }));
8443
- }
8444
8429
  function matchLineNumbers(body, needle) {
8445
8430
  const lines = [];
8446
8431
  let line = 1;
@@ -8552,27 +8537,40 @@ function createNotesStore(input) {
8552
8537
  async function update(address, edits, options = {}) {
8553
8538
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
8554
8539
  const stableOptions = { ...options };
8555
- const destination = assertAddress(address);
8540
+ const from = assertAddress(address);
8541
+ const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
8556
8542
  assertWritablePath(destination.path);
8557
8543
  const scope = destination.scope;
8544
+ assertWritableHome(from.scope, from.who, identity2);
8558
8545
  assertWritableHome(scope, destination.who, identity2);
8559
- if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0) {
8560
- throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
8546
+ if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0) {
8547
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
8561
8548
  }
8549
+ const fromPath = physicalPath(from.scope, from.path, identity2, from.who);
8562
8550
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8563
- return withPathQueue(path, async () => {
8564
- const raw = await readFileIfExists(path);
8551
+ const differentPaths = resolve3(fromPath) !== resolve3(path);
8552
+ const mutate = async () => {
8553
+ const raw = await readFileIfExists(fromPath);
8565
8554
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8555
+ const targetRaw = differentPaths ? await readFileIfExists(path) : void 0;
8556
+ const sourceReal = targetRaw === void 0 ? void 0 : await realpath(fromPath);
8557
+ const sameFile = sourceReal !== void 0 && sourceReal === await realpath(path);
8558
+ const moved = differentPaths && !sameFile;
8559
+ if (moved && targetRaw !== void 0 && parseNote(targetRaw).meta.crumpledAt === void 0) {
8560
+ throw new NoteError("already_exists", `${noteIdentity(identity2, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
8561
+ }
8566
8562
  const { meta, body } = parseNote(raw);
8567
- meta.scope = scope;
8568
8563
  const beforeMeta = { ...meta };
8564
+ meta.scope = scope;
8565
+ if (from.scope !== "session" && scope === "session") meta.project = identity2.projectKey;
8566
+ if (from.scope === "session" && scope !== "session") delete meta.project;
8569
8567
  let next = body;
8570
8568
  let applied = 0;
8571
8569
  operations.forEach((operation, index) => {
8572
8570
  const oldText = operation?.oldText;
8573
8571
  const newText = operation?.newText;
8574
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
8575
- if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
8572
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
8573
+ if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
8576
8574
  const lines = matchLineNumbers(next, oldText);
8577
8575
  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 });
8578
8576
  if (lines.length > 1 && !stableOptions.replaceAll) {
@@ -8590,49 +8588,26 @@ function createNotesStore(input) {
8590
8588
  if (stableOptions.crumpled === false) delete meta.crumpledAt;
8591
8589
  const bodyChanged = body !== next;
8592
8590
  const originChanged = beforeMeta.origin !== meta.origin;
8593
- if (bodyChanged || originChanged) meta.updatedAt = writeStamp();
8591
+ if (bodyChanged || originChanged || moved) meta.updatedAt = writeStamp();
8594
8592
  const serialized = serializeNote(meta, next);
8595
8593
  assertSerializedSize(serialized);
8596
8594
  const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
8597
8595
  let change;
8598
- if (bodyChanged && metadataChanged) change = { kind: "body", before: raw, after: serialized };
8596
+ if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
8599
8597
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
8600
8598
  else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
8601
8599
  else change = { kind: "none", before: "", after: "" };
8602
- await atomicWrite(path, serialized);
8603
- return { meta, applied, resolvedScope: scope, change };
8604
- });
8600
+ await atomicWrite(sameFile ? sourceReal : path, serialized);
8601
+ if (moved) await rm(fromPath, { force: true });
8602
+ return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
8603
+ };
8604
+ if (!differentPaths) return withPathQueue(path, mutate);
8605
+ const [first, second] = [fromPath, path].sort();
8606
+ return withPathQueue(first, () => withPathQueue(second, mutate));
8605
8607
  }
8606
8608
  async function rename2(fromAddress, toAddress) {
8607
- const from = assertAddress(fromAddress);
8608
- const to = assertAddress(toAddress);
8609
- const fromScope = from.scope;
8610
- const toScope = to.scope;
8611
- assertWritablePath(to.path);
8612
- assertWritableHome(fromScope, from.who, identity2);
8613
- assertWritableHome(toScope, to.who, identity2);
8614
- const fromPath = physicalPath(fromScope, from.path, identity2, from.who);
8615
- const toPath = physicalPath(toScope, to.path, identity2, to.who);
8616
- if (resolve3(fromPath) === resolve3(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
8617
- const [first, second] = [fromPath, toPath].sort();
8618
- return withPathQueue(first, () => withPathQueue(second, async () => {
8619
- const raw = await readFileIfExists(fromPath);
8620
- if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, fromAddress).address}.`);
8621
- const targetRaw = await readFileIfExists(toPath);
8622
- if (targetRaw !== void 0 && parseNote(targetRaw).meta.crumpledAt === void 0) {
8623
- throw new NoteError("already_exists", `${noteIdentity(identity2, toAddress).address} already holds a note; crumple it first or pick another address.`);
8624
- }
8625
- const { meta, body } = parseNote(raw);
8626
- meta.scope = toScope;
8627
- if (fromScope !== "session" && toScope === "session") meta.project = identity2.projectKey;
8628
- if (fromScope === "session" && toScope !== "session") delete meta.project;
8629
- meta.updatedAt = writeStamp();
8630
- const serialized = serializeNote(meta, body);
8631
- assertSerializedSize(serialized);
8632
- await atomicWrite(toPath, serialized);
8633
- await rm(fromPath, { force: true });
8634
- return { meta, replacedCrumpledTarget: targetRaw !== void 0 };
8635
- }));
8609
+ const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
8610
+ return { meta, replacedCrumpledTarget };
8636
8611
  }
8637
8612
  async function* scan(options, status) {
8638
8613
  const pattern = normalizePattern(options.glob, identity2);
@@ -8640,7 +8615,7 @@ function createNotesStore(input) {
8640
8615
  const matcher = normalized === void 0 ? void 0 : globToRegExp(normalized);
8641
8616
  let homes;
8642
8617
  try {
8643
- homes = await homesFor(identity2, options);
8618
+ homes = await homesForPattern(normalized, identity2) ?? SCOPE_ORDER.map((scope) => ({ scope }));
8644
8619
  } catch (error) {
8645
8620
  if (!status || !isFilesystemError(error) || !/^@(projects|agents|models)\//.test(options.glob ?? "")) throw error;
8646
8621
  status.homesUnavailable.push(options.glob.split("/")[0]);
@@ -9004,7 +8979,7 @@ function searchQueries(query) {
9004
8979
  // src/tools/notes.ts
9005
8980
  var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("self"), typebox_exports.Literal("external")];
9006
8981
  var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
9007
- description: "(optional, default self) Who wrote it: user, self, or external."
8982
+ description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
9008
8983
  }));
9009
8984
  var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
9010
8985
  var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
@@ -9161,7 +9136,7 @@ var notesWrite = {
9161
9136
  executionMode: "sequential",
9162
9137
  async execute(params, identity2) {
9163
9138
  try {
9164
- const { outcome } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin ?? "self" });
9139
+ const { outcome } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin });
9165
9140
  return success({ ...noteIdentity(identity2, params.address), outcome });
9166
9141
  } catch (error) {
9167
9142
  return failureOf(error);
@@ -9175,7 +9150,7 @@ var notesUpdateParameters = typebox_exports.Object({
9175
9150
  origin: ORIGIN,
9176
9151
  crumpled: CRUMPLED_PARAMETER,
9177
9152
  replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
9178
- rename_to: typebox_exports.Optional(typebox_exports.String({ description: "(optional) Move to this address, keeping metadata. Use alone. Won't overwrite a live note; references aren't updated." }))
9153
+ rename_to: typebox_exports.Optional(typebox_exports.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." }))
9179
9154
  }, { additionalProperties: false });
9180
9155
  function renderUpdateData(data) {
9181
9156
  const head = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
@@ -9208,17 +9183,11 @@ var notesUpdate = {
9208
9183
  try {
9209
9184
  const store = createNotesStore(identity2);
9210
9185
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
9211
- if (renameTo !== void 0) {
9212
- if ((params.edits?.length ?? 0) > 0 || params.origin !== void 0 || params.crumpled !== void 0 || params.replace_all === true) {
9213
- return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
9214
- }
9215
- await store.rename(params.address, renameTo);
9216
- const from = noteIdentity(identity2, params.address).address;
9217
- const to = noteIdentity(identity2, renameTo);
9218
- return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
9219
- }
9220
- const { change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
9221
- return boundedUpdate({ ...noteIdentity(identity2, params.address), change_kind: change.kind, diff: renderDiff(change) });
9186
+ const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9187
+ const from = noteIdentity(identity2, params.address).address;
9188
+ const to = noteIdentity(identity2, renameTo ?? params.address);
9189
+ const diff = renderDiff(change);
9190
+ 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 });
9222
9191
  } catch (error) {
9223
9192
  return failureOf(error);
9224
9193
  }
@@ -9864,13 +9833,19 @@ var NOTES_HOMES = [
9864
9833
  { scope: "model", label: "@model" }
9865
9834
  ];
9866
9835
  async function loadNotesSnapshot(identity2, openedAt, loadHome) {
9867
- const store = createNotesStore(identity2);
9868
- const load = loadHome ?? ((scope) => store.list({ scope }));
9869
9836
  const homes = /* @__PURE__ */ new Map();
9870
9837
  const unavailable = [];
9838
+ if (!loadHome) {
9839
+ const { rows, status } = await createNotesStore(identity2).listWithStatus();
9840
+ for (const home of NOTES_HOMES) {
9841
+ homes.set(home.scope, rows.filter((row) => row.scope === home.scope));
9842
+ if (status.homesUnavailable.some((address) => home.scope === "session" ? !address.startsWith("@") : address === home.label || address.startsWith(`${home.label}/`))) unavailable.push(home);
9843
+ }
9844
+ return { openedAt, homes, unavailable };
9845
+ }
9871
9846
  for (const home of NOTES_HOMES) {
9872
9847
  try {
9873
- homes.set(home.scope, await load(home.scope));
9848
+ homes.set(home.scope, await loadHome(home.scope));
9874
9849
  } catch (error) {
9875
9850
  if (!isFilesystemError(error)) throw error;
9876
9851
  homes.set(home.scope, []);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.48.1",
3
+ "version": "0.49.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -29,13 +29,19 @@ export function unavailableNotesSnapshot(openedAt: number): NotesSnapshot {
29
29
  * malformed note data and unrelated construction errors remain visible to the caller.
30
30
  */
31
31
  export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot> {
32
- const store = createNotesStore(identity);
33
- const load = loadHome ?? ((scope: Scope) => store.list({ scope }));
34
32
  const homes = new Map<Scope, readonly NoteRow[]>();
35
33
  const unavailable: NotesHome[] = [];
34
+ if (!loadHome) {
35
+ const { rows, status } = await createNotesStore(identity).listWithStatus();
36
+ for (const home of NOTES_HOMES) {
37
+ homes.set(home.scope, rows.filter(row => row.scope === home.scope));
38
+ if (status.homesUnavailable.some(address => home.scope === "session" ? !address.startsWith("@") : address === home.label || address.startsWith(`${home.label}/`))) unavailable.push(home);
39
+ }
40
+ return { openedAt, homes, unavailable };
41
+ }
36
42
  for (const home of NOTES_HOMES) {
37
43
  try {
38
- homes.set(home.scope, await load(home.scope));
44
+ homes.set(home.scope, await loadHome(home.scope));
39
45
  } catch (error) {
40
46
  if (!isFilesystemError(error)) throw error;
41
47
  homes.set(home.scope, []);
@@ -76,7 +76,6 @@ export function assertAddress(value: unknown): NoteAddress {
76
76
  if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
77
77
  if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
78
78
  }
79
- if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
80
79
  assertVirtualPath(path);
81
80
  return { scope, path, who };
82
81
  }
@@ -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
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {