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
package/README.md CHANGED
@@ -30,7 +30,7 @@ pi -e npm:notesoup
30
30
 
31
31
  - **Durable context windows.** `/fresh-window` (alias `/empty-brain`) clears and stops; `/fresh-window Continue reviewing the implementation` clears and continues. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
32
32
  - **A boot block at every window head.** Static once-per-window content (cache-stable) with the window identity, the recent-notes index, and a short protocol teaching the model how to recover: notes for its own bookkeeping, history tools for everything before the reset.
33
- - **`get_context_remaining`** — the live countdown to the close-out line, so the agent can see the cliff before it drives off it.
33
+ - **`get_context_remaining`** — how much room the brain has left before the hard-reserve wipe, including the warning runway.
34
34
  - **Eight history/notes tools**, flattened from the original Codex actions:
35
35
 
36
36
  | Codex action | Pi tool |
@@ -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))
@@ -20,8 +20,7 @@ export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in t
20
20
  * notesoup's tool names. It lives once per window in the persisted boot block;
21
21
  * it is never re-injected, so it stays cache-stable at the head of the window.
22
22
  *
23
- * Deliberate fiction: the countdown ends at the warning line, and the runway below
24
- * stays hidden (budget/constants.ts). Keep "zero = wiped" — do not make this honest.
23
+ * The reported room reaches zero at the hard-reserve wipe line.
25
24
  */
26
25
  const PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
27
26
  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 declare const DEFAULT_RESERVE_TOKENS = 16384;
2
2
  export declare const DEFAULT_REMINDER_MARGIN_TOKENS = 24576;
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 declare const WARNING_RUNWAY_TOKENS = 16384;
@@ -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;
@@ -15,5 +15,5 @@ export declare function deriveThresholds(reserveTokens: number, margins: Notesou
15
15
  thresholds: ResolvedThresholds;
16
16
  warnings: string[];
17
17
  };
18
- /** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
19
- export declare function remainingBudget(remaining: number | null, warning: number): number | null;
18
+ /** Room before the hard-reserve wipe; unknown usage stays unknown. */
19
+ export declare function remainingBudget(remaining: number | null, reserve: number): number | null;
@@ -25,7 +25,7 @@ export function deriveThresholds(reserveTokens, margins) {
25
25
  }
26
26
  return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
27
27
  }
28
- /** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
29
- export function remainingBudget(remaining, warning) {
30
- return remaining === null ? null : Math.max(0, remaining - warning);
28
+ /** Room before the hard-reserve wipe; unknown usage stays unknown. */
29
+ export function remainingBudget(remaining, reserve) {
30
+ return remaining === null ? null : Math.max(0, remaining - reserve);
31
31
  }
@@ -63,5 +63,5 @@ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready,
63
63
  * at write time; get_context_remaining remains the live source for the current figure.
64
64
  */
65
65
  export function tokenBudgetGuidance(remaining, wipeTool) {
66
- 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}`;
66
+ 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}`;
67
67
  }
@@ -30,5 +30,5 @@ export async function measureBudget(ctx, agent, config, signal) {
30
30
  }
31
31
  }
32
32
  const remaining = Math.max(0, contextWindow - used);
33
- return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, thresholds.warning), warning: thresholds.warning, reminder: thresholds.reminder };
33
+ return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, reserve), warning: thresholds.warning, reminder: thresholds.reminder };
34
34
  }
@@ -98,7 +98,7 @@ export function registerTools(ctx, engine) {
98
98
  }));
99
99
  ctx.tools.register(defineTool({
100
100
  name: "get_context_remaining",
101
- description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
101
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
102
102
  parameters: {},
103
103
  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) }] },
104
104
  async execute(_args, exec) {
@@ -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 ?? ""))
@@ -3,7 +3,7 @@ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolea
3
3
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
4
4
  hardReserveDue: (ctx: ExtensionContext) => boolean;
5
5
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
6
- /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
6
+ /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
7
7
  statusFor: (ctx: ExtensionContext) => {
8
8
  remaining: number | null;
9
9
  };
@@ -92,7 +92,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
92
92
  if (remaining === null)
93
93
  return result();
94
94
  const windowId = currentWindowId(ctx);
95
- const { reminder, warning } = thresholdsFor(ctx);
95
+ const { reminder, warning, reserve } = thresholdsFor(ctx);
96
96
  if (remaining <= warning) {
97
97
  if (hasWindowMessage(ctx, WARNING_TYPE))
98
98
  return result();
@@ -116,28 +116,27 @@ export function registerBudget(pi, isEnabled, settingsManager) {
116
116
  if (pendingGuidance?.windowId !== windowId) {
117
117
  if (remaining > reminder)
118
118
  return result();
119
- pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
119
+ pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, reserve) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
120
120
  }
121
121
  return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
122
122
  });
123
123
  pi.registerTool(defineTool({
124
124
  name: "get_context_remaining",
125
125
  label: "Get context remaining",
126
- description: "Return estimated context tokens left before your memory is wiped; null when Pi cannot estimate usage.",
126
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
127
127
  parameters: Type.Object({}, { additionalProperties: false }),
128
128
  async execute(_id, _params, _signal, _update, ctx) {
129
- // The countdown the model sees ends at the warning line (reserve + runway);
130
- // the runway below it is overdraft the model never sees. See budget/constants.ts.
129
+ // Report room to the hard-reserve wipe, including the warning runway.
131
130
  const remaining = remainingTokens(ctx);
132
- return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).warning) });
131
+ return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) });
133
132
  },
134
133
  }));
135
134
  return {
136
135
  automaticResetEnabled,
137
136
  hardReserveDue,
138
137
  consumeTurnEnd,
139
- /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
140
- statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
138
+ /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
139
+ statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).reserve) }),
141
140
  clear: () => { clearStaged(); notifiedWindows.clear(); },
142
141
  };
143
142
  }
@@ -4,7 +4,7 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } 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 } from "./window.js";
7
+ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } 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, settingsManager) {
75
75
  const tail = branch.slice(branch.indexOf(marker) + 1);
76
76
  const lastWordEntry = tail.find((entry) => entry.customType === RESET_LAST_WORD_TYPE);
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));
@@ -208,7 +209,7 @@ export function registerContext(pi, settingsManager) {
208
209
  name: "empty_brain",
209
210
  label: "Empty Brain",
210
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.",
211
- 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 }),
212
213
  async execute(_id, params, _signal, _update, ctx) {
213
214
  if (!enabled)
214
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);
@@ -1354,7 +1354,7 @@ test("real AgentSession: injected settings managers own live policy and ignore c
1354
1354
  });
1355
1355
  await Promise.all([first.session.prompt("INJECTED_FIRST"), second.session.prompt("INJECTED_SECOND")]);
1356
1356
  await Promise.all([first.session.waitForIdle(), second.session.waitForIdle()]);
1357
- assert.deepEqual(contextRemainingResults(first), [0], "the injected high reserve reaches the warning line in the real tool result");
1357
+ assert.deepEqual(contextRemainingResults(first), [0], "the injected high reserve reaches the hard-reserve line in the real tool result");
1358
1358
  assert.ok((contextRemainingResults(second)[0] ?? 0) > 0, "the second injected reserve produces a distinct real tool result");
1359
1359
  assert.equal(resetMarkers(first).length, 1, "enabled injected policy resets at the first session's reserve");
1360
1360
  assert.equal(resetMarkers(second).length, 0, "disabled injected policy does not inherit the first session's reset decision");
@@ -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));
@@ -85,7 +85,7 @@ test("the root boot and reset boot carry durable window identity", async () => {
85
85
  assert.equal(boundary.continue, true);
86
86
  await runHandlers(captured, "turn_start", {}, ctx);
87
87
  await runHandlers(captured, "agent_settled", {}, ctx);
88
- assert.equal(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")).length, 1, "the committed reset is announced once");
88
+ assert.deepEqual(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")), [{ message: "🥣 Brain emptied", type: "info" }], "the committed reset is announced once");
89
89
  const entries = sessionManager.getBranch();
90
90
  const marker = entries.find((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
91
91
  assert.ok(marker && marker.type === "custom");
@@ -371,6 +371,14 @@ test("notesoup command toggles future work, /empty-brain schedules a turn-end re
371
371
  notices = await runCommand(captured, "notesoup", "", low);
372
372
  assert.match(notices[0]?.message ?? "", /on/);
373
373
  });
374
+ test("forced reset confirmation warns about overflow", async () => {
375
+ const sessionManager = manager();
376
+ const captured = makeExtension(sessionManager);
377
+ const ctx = context(sessionManager, undefined, { tokens: 199_000, contextWindow: 200_000, percent: 99.5 });
378
+ await commitTurnEndBoundary(captured, sessionManager, ctx);
379
+ await runHandlers(captured, "agent_settled", {}, ctx);
380
+ assert.deepEqual(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")), [{ message: "🥣 Brain emptied forcibly: overflow", type: "warning" }]);
381
+ });
374
382
  test("committed reset confirmation survives later work while repair refuses that suffix", async () => {
375
383
  const sessionManager = manager();
376
384
  const captured = makeExtension(sessionManager);
@@ -12,6 +12,7 @@ test("low-budget guidance and warning persist at turn_end, once per active windo
12
12
  const low = context(sessionManager, undefined, { tokens: 165_000, percent: 82.5, contextWindow: 200_000 });
13
13
  const guidance = await runContextHook(captured, low);
14
14
  assert.deepEqual(guidance?.messages.map((message) => message.customType), [GUIDANCE_TYPE], "guidance reaches the crossing request");
15
+ assert.match(String((guidance?.messages[0]).content), /About 18616 tokens of room left in your brain\./, "the reminder reports room to the reserve, not to the warning");
15
16
  assert.equal(captured.sent.length, 0, "guidance does not trigger a detached turn");
16
17
  const guidanceBoundary = await commitTurnEndBoundary(captured, sessionManager, low);
17
18
  assert.equal(guidanceBoundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE).length, 1);
@@ -44,7 +45,7 @@ test("early guidance stays silent and the final warning notifies immediately onc
44
45
  await runHandlers(captured, "agent_settled", {}, final);
45
46
  assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "repeated injection and commit do not notify again");
46
47
  });
47
- test("the visible countdown ends at the warning line, clamps at zero, and preserves unknown usage", async () => {
48
+ test("the reported room ends at the hard reserve, clamps at zero, and preserves unknown usage", async () => {
48
49
  const fixture = settingsFixture({
49
50
  reserveTokens: 16_384,
50
51
  project: { compaction: { reserveTokens: 32_768 } },
@@ -56,8 +57,9 @@ test("the visible countdown ends at the warning line, clamps at zero, and preser
56
57
  const ctx = context(sm, undefined, { tokens, contextWindow: 200_000, percent: tokens === null ? null : tokens / 2000 }, true, fixture.cwd, trusted);
57
58
  return resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
58
59
  };
59
- assert.equal(await readBudget(72_563), 78_285, "the reported 127437 physical tokens exclude reserve plus runway (49152)");
60
- assert.equal(await readBudget(167_232), 0, "inside the runway the countdown reads zero");
60
+ assert.equal(await readBudget(72_563), 94_669, "the reported room excludes only the project reserve (32768)");
61
+ assert.equal(await readBudget(150_848), 16_384, "the warning line still has the entire runway left");
62
+ assert.equal(await readBudget(167_232), 0, "the hard reserve reads zero");
61
63
  assert.equal(await readBudget(190_000), 0, "below the reserve, still zero");
62
64
  assert.equal(await readBudget(210_000), 0, "over the physical window");
63
65
  assert.equal(await readBudget(null), null, "unknown usage remains unknown");
@@ -65,7 +67,7 @@ test("the visible countdown ends at the warning line, clamps at zero, and preser
65
67
  assert.equal(resultJson(await call(captured, "get_context_remaining", {}, absent)).remaining_tokens, null);
66
68
  const untrusted = context(sm, undefined, { tokens: 72_563, contextWindow: 200_000, percent: 36.2815 }, true, fixture.cwd, false);
67
69
  await runHandlers(captured, "session_start", {}, untrusted);
68
- assert.equal(await readBudget(72_563, false), 94_669, "session start reloads the global reserve when the project is untrusted");
70
+ assert.equal(await readBudget(72_563, false), 111_053, "session start reloads the global reserve when the project is untrusted");
69
71
  });
70
72
  test("absent notesoup key or margins reproduce the default reminder threshold at Pi's default reserve", async () => {
71
73
  assert.equal(DEFAULT_RESERVE_TOKENS, 16_384);
@@ -233,7 +233,7 @@ test("dsh budget follows configured host reserve, close-out tool runs across ste
233
233
  assert.equal(budget?.reserve, 60000);
234
234
  assert.equal(budget?.warning, 76384);
235
235
  assert.equal(budget?.reminder, 84576);
236
- assert.equal(budget?.countdown, Math.max(0, 123616 - budget.used));
236
+ assert.equal(budget?.countdown, Math.max(0, 140000 - budget.used));
237
237
  mock.script.push({ tool: "notes_write", input: { address: "handoff", content: "checkpoint", }, inputTokens: 125000 }, { tool: "empty_brain", input: {} }, { text: "fresh" });
238
238
  await run(agent, "continue");
239
239
  assert.equal(engine.windows.get(agent.session).snapshot.window, 1);
@@ -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, "");