notesoup 0.48.0 → 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.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/snapshot.js +10 -3
  3. package/dist/src/boot/text.js +1 -2
  4. package/dist/src/budget/constants.d.ts +2 -4
  5. package/dist/src/budget/constants.js +2 -4
  6. package/dist/src/budget/policy.d.ts +2 -2
  7. package/dist/src/budget/policy.js +3 -3
  8. package/dist/src/budget/text.js +1 -1
  9. package/dist/src/dsh/budget.js +1 -1
  10. package/dist/src/dsh/tools.js +1 -1
  11. package/dist/src/notes/address.js +0 -2
  12. package/dist/src/notes/errors.d.ts +1 -1
  13. package/dist/src/notes/store.d.ts +4 -10
  14. package/dist/src/notes/store.js +42 -72
  15. package/dist/src/pi/budget.d.ts +1 -1
  16. package/dist/src/pi/budget.js +7 -8
  17. package/dist/src/pi/runtime.js +4 -3
  18. package/dist/src/tools/notes.js +8 -14
  19. package/dist/test/agent-loop.test.js +1 -1
  20. package/dist/test/boot.integration.test.js +10 -2
  21. package/dist/test/budget-settings.integration.test.js +6 -4
  22. package/dist/test/dsh.test.js +1 -1
  23. package/dist/test/host-neutral.test.js +12 -0
  24. package/dist/test/model-facing-text.test.js +1 -1
  25. package/dist/test/notes-library.test.js +67 -10
  26. package/dist/test/notes.integration.test.js +9 -9
  27. package/dist/test/notes.test.js +46 -13
  28. package/dist/test/reset-lifecycle.test.js +23 -1
  29. package/docs/dsh.md +1 -1
  30. package/docs/notes-library.md +7 -7
  31. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  32. package/mods/notesoup/dist/claude/helper.js +51 -76
  33. package/package.json +1 -1
  34. package/src/boot/snapshot.ts +9 -3
  35. package/src/boot/text.ts +1 -2
  36. package/src/budget/constants.ts +2 -4
  37. package/src/budget/policy.ts +3 -3
  38. package/src/budget/text.ts +1 -1
  39. package/src/dsh/budget.ts +1 -1
  40. package/src/dsh/tools.ts +1 -1
  41. package/src/notes/address.ts +0 -1
  42. package/src/notes/errors.ts +1 -1
  43. package/src/notes/store.ts +41 -73
  44. package/src/pi/budget.ts +7 -8
  45. package/src/pi/runtime.ts +4 -3
  46. package/src/tools/notes.ts +8 -14
@@ -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.0",
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, []);
package/src/boot/text.ts CHANGED
@@ -21,8 +21,7 @@ export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in t
21
21
  * notesoup's tool names. It lives once per window in the persisted boot block;
22
22
  * it is never re-injected, so it stays cache-stable at the head of the window.
23
23
  *
24
- * Deliberate fiction: the countdown ends at the warning line, and the runway below
25
- * stays hidden (budget/constants.ts). Keep "zero = wiped" — do not make this honest.
24
+ * The reported room reaches zero at the hard-reserve wipe line.
26
25
  */
27
26
  const PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
28
27
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
@@ -1,9 +1,7 @@
1
1
  export const DEFAULT_RESERVE_TOKENS = 16_384;
2
2
  export const DEFAULT_REMINDER_MARGIN_TOKENS = 24_576;
3
3
  /**
4
- * The runway: the budget between the final warning and the wipe, deliberately
5
- * invisible to the model. get_context_remaining counts down to zero at the warning
6
- * line (reserve + WARNING_RUNWAY_TOKENS); what lies below is overdraft the model
7
- * never sees — Codex's fallback buffer, relocated above the line.
4
+ * The runway between the final warning and the hard-reserve wipe.
5
+ * get_context_remaining includes this room; zero is the hard-reserve line.
8
6
  */
9
7
  export const WARNING_RUNWAY_TOKENS = 16_384;
@@ -26,7 +26,7 @@ export function deriveThresholds(reserveTokens: number, margins: NotesoupSetting
26
26
  return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
27
27
  }
28
28
 
29
- /** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
30
- export function remainingBudget(remaining: number | null, warning: number): number | null {
31
- return remaining === null ? null : Math.max(0, remaining - warning);
29
+ /** Room before the hard-reserve wipe; unknown usage stays unknown. */
30
+ export function remainingBudget(remaining: number | null, reserve: number): number | null {
31
+ return remaining === null ? null : Math.max(0, remaining - reserve);
32
32
  }
@@ -81,5 +81,5 @@ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready,
81
81
  * at write time; get_context_remaining remains the live source for the current figure.
82
82
  */
83
83
  export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
84
- return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens left. Then this brain is emptied.\nYour notes don't go anywhere — no wipe reaches the shelves. History has it too, already written down, though digging it back out is on you.\nWhat lives only in this brain leaves with it.\nA decent moment to put down where you are, while you still remember why.\nReady when you are: \`${wipeTool}\`.\n${GUIDANCE_CLOSE_TAG}`;
84
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens of room left in your brain.\nYour notes don't go anywhere — no wipe reaches the shelves. History has it too, already written down, though digging it back out is on you.\nWhat lives only in this brain leaves with it.\nA decent moment to put down where you are, while you still remember why.\nReady when you are: \`${wipeTool}\`.\n${GUIDANCE_CLOSE_TAG}`;
85
85
  }
package/src/dsh/budget.ts CHANGED
@@ -31,5 +31,5 @@ export async function measureBudget(ctx: Context, agent: CompactionAgentContext,
31
31
  if (event.type === "user/message" && event.data.source.kind === "compact-checkpoint") { used = measured.surfaceTokens + estimateToolsTokens(agent.session.requestHeader()); break; }
32
32
  }
33
33
  const remaining = Math.max(0, contextWindow - used);
34
- return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, thresholds.warning)!, warning: thresholds.warning, reminder: thresholds.reminder };
34
+ return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, reserve)!, warning: thresholds.warning, reminder: thresholds.reminder };
35
35
  }
package/src/dsh/tools.ts CHANGED
@@ -93,7 +93,7 @@ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): v
93
93
  }));
94
94
  ctx.tools.register(defineTool({
95
95
  name: "get_context_remaining",
96
- description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
96
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
97
97
  parameters: {},
98
98
  output: { schema: { type: "object", properties: { remaining_tokens: { oneOf: [{ type: "integer" }, { type: "null" }], required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
99
99
  async execute(_args, exec) {
@@ -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 {
@@ -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/budget.ts CHANGED
@@ -93,7 +93,7 @@ export function registerBudget(
93
93
  const remaining = remainingTokens(ctx);
94
94
  if (remaining === null) return result();
95
95
  const windowId = currentWindowId(ctx);
96
- const { reminder, warning } = thresholdsFor(ctx);
96
+ const { reminder, warning, reserve } = thresholdsFor(ctx);
97
97
  if (remaining <= warning) {
98
98
  if (hasWindowMessage(ctx, WARNING_TYPE)) return result();
99
99
  // The critical close-out starts at reserve + runway, not at the hard reserve.
@@ -112,7 +112,7 @@ export function registerBudget(
112
112
  if (hasWindowMessage(ctx, GUIDANCE_TYPE)) return result();
113
113
  if (pendingGuidance?.windowId !== windowId) {
114
114
  if (remaining > reminder) return result();
115
- pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
115
+ pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, reserve) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
116
116
  }
117
117
  return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
118
118
  });
@@ -120,13 +120,12 @@ export function registerBudget(
120
120
  pi.registerTool(defineTool({
121
121
  name: "get_context_remaining",
122
122
  label: "Get context remaining",
123
- description: "Return estimated context tokens left before your memory is wiped; null when Pi cannot estimate usage.",
123
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
124
124
  parameters: Type.Object({}, { additionalProperties: false }),
125
125
  async execute(_id, _params, _signal, _update, ctx) {
126
- // The countdown the model sees ends at the warning line (reserve + runway);
127
- // the runway below it is overdraft the model never sees. See budget/constants.ts.
126
+ // Report room to the hard-reserve wipe, including the warning runway.
128
127
  const remaining = remainingTokens(ctx);
129
- return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx as ExtensionContext).warning) });
128
+ return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx as ExtensionContext).reserve) });
130
129
  },
131
130
  }));
132
131
 
@@ -134,8 +133,8 @@ export function registerBudget(
134
133
  automaticResetEnabled,
135
134
  hardReserveDue,
136
135
  consumeTurnEnd,
137
- /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
138
- statusFor: (ctx: ExtensionContext): { remaining: number | null } => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
136
+ /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
137
+ statusFor: (ctx: ExtensionContext): { remaining: number | null } => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).reserve) }),
139
138
  clear: () => { clearStaged(); notifiedWindows.clear(); },
140
139
  };
141
140
  }
package/src/pi/runtime.ts CHANGED
@@ -4,7 +4,7 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type SettingsManager } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
- import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
7
+ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
9
  import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE, RESET_LAST_WORD_TYPE } from "./entries.js";
@@ -75,7 +75,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
75
75
  const tail = branch.slice(branch.indexOf(marker) + 1);
76
76
  const lastWordEntry = tail.find((entry) => (entry as { customType?: string }).customType === RESET_LAST_WORD_TYPE) as { content?: string } | undefined;
77
77
  const lastWord = lastWordEntry?.content?.startsWith(LAST_WORD_PREFIX) ? lastWordEntry.content.slice(LAST_WORD_PREFIX.length) : undefined;
78
- ctx.ui.notify(`🥣 Brain emptied${lastWord ? ` · last word: “${lastWord}”` : ""}`, "info");
78
+ const forced = markerResetOrigin(marker) === "forced";
79
+ ctx.ui.notify(`🥣 Brain emptied${forced ? " forcibly: overflow" : ""}${lastWord ? ` · last word: “${lastWord}”` : ""}`, forced ? "warning" : "info");
79
80
  }
80
81
  };
81
82
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -204,7 +205,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
204
205
  name: "empty_brain",
205
206
  label: "Empty Brain",
206
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.",
207
- 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 }),
208
209
  async execute(_id, params, _signal, _update, ctx) {
209
210
  if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
210
211
  const lastWord = sanitizeLastWord(params.last_word);