notesoup 0.41.0 → 0.43.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 (127) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/claude/helper.ts
8
- import { realpathSync } from "node:fs";
8
+ import { realpathSync as realpathSync2 } from "node:fs";
9
9
  import { pathToFileURL } from "node:url";
10
10
 
11
11
  // node_modules/typebox/build/system/arguments/arguments.mjs
@@ -7933,10 +7933,17 @@ function parseNote(raw, now = Date.now()) {
7933
7933
  function yamlScalar(value) {
7934
7934
  if (typeof value === "string") {
7935
7935
  const reserved = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
7936
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase())) return value;
7936
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
7937
7937
  }
7938
7938
  return JSON.stringify(value);
7939
7939
  }
7940
+ function parsesAsNonString(text) {
7941
+ try {
7942
+ return typeof JSON.parse(text) !== "string";
7943
+ } catch {
7944
+ return false;
7945
+ }
7946
+ }
7940
7947
  function serializeNote(meta, body) {
7941
7948
  const lines = [];
7942
7949
  for (const key of KNOWN_KEYS) {
@@ -7996,16 +8003,32 @@ var NoteError = class extends Error {
7996
8003
  this.editIndex = extra.editIndex;
7997
8004
  }
7998
8005
  };
8006
+ function shown(value) {
8007
+ const json = JSON.stringify(value);
8008
+ return json === void 0 ? String(value) : json;
8009
+ }
7999
8010
 
8000
8011
  // src/notes/paths.ts
8001
8012
  import { createHash } from "node:crypto";
8002
- import { existsSync, readFileSync, statSync } from "node:fs";
8013
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
8003
8014
  import { readdir } from "node:fs/promises";
8004
8015
  import { basename, dirname, join, resolve, sep } from "node:path";
8005
8016
  var SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
8017
+ function assertVirtualPath(value) {
8018
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
8019
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
8020
+ const parts = value.split("/");
8021
+ if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
8022
+ return value;
8023
+ }
8006
8024
  function projectKey(cwd) {
8007
8025
  const absolute = resolve(cwd);
8008
- const root = gitRoot(absolute) ?? absolute;
8026
+ const spelled = gitRoot(absolute) ?? absolute;
8027
+ let root = spelled;
8028
+ try {
8029
+ root = realpathSync(spelled);
8030
+ } catch {
8031
+ }
8009
8032
  const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
8010
8033
  return `${basename(root)}-${digest}`;
8011
8034
  }
@@ -8064,24 +8087,11 @@ function noteFileName(vpath) {
8064
8087
  return vpath.endsWith(".md") ? vpath : `${vpath}.md`;
8065
8088
  }
8066
8089
  function physicalPath(scope, vpath, identity2, who) {
8067
- if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/")) throw new TypeError("path must be a safe virtual relative path");
8068
- if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === "..")) throw new TypeError("path contains an unsupported component");
8069
8090
  return join(scopeDir(scope, identity2, who), ...noteFileName(vpath).split("/"));
8070
8091
  }
8071
8092
 
8072
8093
  // src/notes/address.ts
8073
- var ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
8074
- function shown(value) {
8075
- const json = JSON.stringify(value);
8076
- return json === void 0 ? String(value) : json;
8077
- }
8078
- function assertVirtualPath(value) {
8079
- if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
8080
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
8081
- const parts = value.split("/");
8082
- if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
8083
- return value;
8084
- }
8094
+ var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8085
8095
  function globToRegExp(pattern) {
8086
8096
  let source = "^";
8087
8097
  for (let index = 0; index < pattern.length; index++) {
@@ -8094,6 +8104,8 @@ function globToRegExp(pattern) {
8094
8104
  } else {
8095
8105
  source += "[^/]*";
8096
8106
  }
8107
+ } else if (char === "?") {
8108
+ source += "[^/]";
8097
8109
  } else {
8098
8110
  source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
8099
8111
  }
@@ -8102,12 +8114,12 @@ function globToRegExp(pattern) {
8102
8114
  }
8103
8115
  function assertGlobPattern(value) {
8104
8116
  if (value === void 0 || value === null || value === "") return void 0;
8105
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
8106
- if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
8117
+ if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
8118
+ if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
8107
8119
  return value;
8108
8120
  }
8109
8121
  function assertAddress(value) {
8110
- if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8122
+ if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8111
8123
  let scope = "session";
8112
8124
  let path = value;
8113
8125
  let who;
@@ -8124,16 +8136,16 @@ function assertAddress(value) {
8124
8136
  else if (head === "agents" || head === "models") {
8125
8137
  const nameEnd = tail.indexOf("/");
8126
8138
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
8127
- if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8139
+ if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8128
8140
  scope = head === "agents" ? "agent" : "model";
8129
8141
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
8130
8142
  } else {
8131
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8143
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8132
8144
  }
8133
- if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8134
- if (path === "" && who === void 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8145
+ if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8146
+ if (path === "" && who === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8135
8147
  }
8136
- if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8148
+ if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8137
8149
  assertVirtualPath(path);
8138
8150
  return { scope, path, who };
8139
8151
  }
@@ -8163,8 +8175,6 @@ function assertDirectoryComponent(field, value) {
8163
8175
  }
8164
8176
  function snapshotNotesIdentity(value) {
8165
8177
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("notes context must be a plain object");
8166
- const prototype = Object.getPrototypeOf(value);
8167
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("notes context must be a plain object");
8168
8178
  const homeValue = requireString("home", value.home);
8169
8179
  const sessionId = requireString("sessionId", value.sessionId);
8170
8180
  const projectKey2 = requireString("projectKey", value.projectKey);
@@ -8236,10 +8246,6 @@ async function walkMarkdown(dir, base = dir) {
8236
8246
  }
8237
8247
  return paths;
8238
8248
  }
8239
- function matcherFor(pattern) {
8240
- const normalized = assertGlobPattern(pattern);
8241
- return normalized === void 0 ? void 0 : globToRegExp(normalized);
8242
- }
8243
8249
  async function homesForPattern(pattern, identity2) {
8244
8250
  if (!pattern || !pattern.startsWith("@")) return void 0;
8245
8251
  const head = /^@([^/]+)\//.exec(pattern)?.[1];
@@ -8261,10 +8267,6 @@ function normalizePattern(pattern, identity2) {
8261
8267
  if (pattern.startsWith("@model/")) return `@models/${identity2.model}/${pattern.slice("@model/".length)}`;
8262
8268
  return pattern;
8263
8269
  }
8264
- function assertScope(value) {
8265
- if (!isScope(value)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(value)})`);
8266
- return value;
8267
- }
8268
8270
  function assertOrigin(value) {
8269
8271
  if (!isOrigin(value)) throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
8270
8272
  return value;
@@ -8277,7 +8279,8 @@ function assertWho(value) {
8277
8279
  }
8278
8280
  async function homesFor(identity2, opts) {
8279
8281
  if (opts.scope !== void 0) {
8280
- const scope = assertScope(opts.scope);
8282
+ if (!isScope(opts.scope)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
8283
+ const scope = opts.scope;
8281
8284
  if (opts.who !== void 0) {
8282
8285
  const who = assertWho(opts.who);
8283
8286
  if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
@@ -8326,11 +8329,14 @@ async function atomicWrite(path, content) {
8326
8329
  }
8327
8330
  function assertWritablePath(vpath) {
8328
8331
  const bytes = Buffer.byteLength(vpath, "utf8");
8329
- if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
8332
+ if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
8333
+ }
8334
+ function megabytes(bytes) {
8335
+ return `${Math.ceil(bytes / 1e4) / 100} MB`;
8330
8336
  }
8331
8337
  function assertSerializedSize(content) {
8332
8338
  const bytes = Buffer.byteLength(content, "utf8");
8333
- if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
8339
+ if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `This note would be ${megabytes(bytes)}, over the ${megabytes(MAX_NOTE_BYTES)} limit per note; split it into several notes.`);
8334
8340
  }
8335
8341
  function frontmatterOf(meta) {
8336
8342
  return serializeNote(meta, "").slice(0, -2);
@@ -8340,13 +8346,7 @@ function assertWritableHome(scope, who, identity2) {
8340
8346
  const current = scope === "agent" ? identity2.agent : identity2.model;
8341
8347
  if (who === current) return;
8342
8348
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
8343
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
8344
- }
8345
- function accessedMeta(meta, scope, now) {
8346
- const next = { ...meta, scope };
8347
- next.lastAccessed = now;
8348
- next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
8349
- return next;
8349
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
8350
8350
  }
8351
8351
  function createNotesStore(input) {
8352
8352
  const identity2 = snapshotNotesIdentity(input);
@@ -8356,7 +8356,7 @@ function createNotesStore(input) {
8356
8356
  assertWritablePath(destination.path);
8357
8357
  const scope = destination.scope;
8358
8358
  assertWritableHome(scope, destination.who, identity2);
8359
- const origin = assertOrigin(stableOptions.origin ?? "self");
8359
+ const origin = stableOptions.origin === void 0 ? void 0 : assertOrigin(stableOptions.origin);
8360
8360
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8361
8361
  return withPathQueue(path, async () => {
8362
8362
  const now = writeStamp();
@@ -8366,7 +8366,7 @@ function createNotesStore(input) {
8366
8366
  const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
8367
8367
  const meta = existing ?? {
8368
8368
  scope,
8369
- origin,
8369
+ origin: origin ?? "self",
8370
8370
  createdAt: now,
8371
8371
  updatedAt: now,
8372
8372
  lastAccessed: now,
@@ -8374,7 +8374,7 @@ function createNotesStore(input) {
8374
8374
  ...scope === "session" ? { project: identity2.projectKey } : {}
8375
8375
  };
8376
8376
  meta.scope = scope;
8377
- meta.origin = origin;
8377
+ if (origin !== void 0) meta.origin = origin;
8378
8378
  delete meta.crumpledAt;
8379
8379
  meta.updatedAt = now;
8380
8380
  const serialized = serializeNote(meta, cleanBody);
@@ -8392,7 +8392,7 @@ function createNotesStore(input) {
8392
8392
  if (raw === void 0) return void 0;
8393
8393
  const now = Date.now();
8394
8394
  const parsed = parseNote(raw, now);
8395
- const meta = accessedMeta(parsed.meta, scope, now);
8395
+ const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
8396
8396
  await atomicWrite(path, serializeNote(meta, parsed.body));
8397
8397
  return { meta, body: parsed.body, resolvedScope: scope };
8398
8398
  });
@@ -8405,12 +8405,12 @@ function createNotesStore(input) {
8405
8405
  const scope = destination.scope;
8406
8406
  assertWritableHome(scope, destination.who, identity2);
8407
8407
  if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0) {
8408
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
8408
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
8409
8409
  }
8410
8410
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8411
8411
  return withPathQueue(path, async () => {
8412
8412
  const raw = await readFileIfExists(path);
8413
- if (raw === void 0) throw new NoteError("not_found", "note not found");
8413
+ if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8414
8414
  const { meta, body } = parseNote(raw);
8415
8415
  meta.scope = scope;
8416
8416
  const beforeMeta = { ...meta };
@@ -8419,12 +8419,12 @@ function createNotesStore(input) {
8419
8419
  operations.forEach((operation, index) => {
8420
8420
  const oldText = operation?.oldText;
8421
8421
  const newText = operation?.newText;
8422
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
8423
- if (typeof newText !== "string") throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
8422
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
8423
+ if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
8424
8424
  const lines = matchLineNumbers(next, oldText);
8425
- if (lines.length === 0) throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
8425
+ 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 });
8426
8426
  if (lines.length > 1 && !stableOptions.replaceAll) {
8427
- throw new NoteError("ambiguous_edit", `edit ${index}: oldText occurs ${lines.length} times (${anchorLines(lines)}); pass replace_all to replace every occurrence`, { lineNumbers: lines, editIndex: index });
8427
+ throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
8428
8428
  }
8429
8429
  if (oldText !== newText) applied++;
8430
8430
  if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
@@ -8461,14 +8461,14 @@ function createNotesStore(input) {
8461
8461
  assertWritableHome(toScope, to.who, identity2);
8462
8462
  const fromPath = physicalPath(fromScope, from.path, identity2, from.who);
8463
8463
  const toPath = physicalPath(toScope, to.path, identity2, to.who);
8464
- if (resolve3(fromPath) === resolve3(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
8464
+ if (resolve3(fromPath) === resolve3(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
8465
8465
  const [first, second] = [fromPath, toPath].sort();
8466
8466
  return withPathQueue(first, () => withPathQueue(second, async () => {
8467
8467
  const raw = await readFileIfExists(fromPath);
8468
- if (raw === void 0) throw new NoteError("not_found", "note not found");
8468
+ if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, fromAddress).address}.`);
8469
8469
  const targetRaw = await readFileIfExists(toPath);
8470
8470
  if (targetRaw !== void 0 && parseNote(targetRaw).meta.crumpledAt === void 0) {
8471
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
8471
+ throw new NoteError("already_exists", `${noteIdentity(identity2, toAddress).address} already holds a note; crumple it first or pick another address.`);
8472
8472
  }
8473
8473
  const { meta, body } = parseNote(raw);
8474
8474
  meta.scope = toScope;
@@ -8483,7 +8483,9 @@ function createNotesStore(input) {
8483
8483
  }));
8484
8484
  }
8485
8485
  async function* scan(options, status) {
8486
- const matcher = matcherFor(normalizePattern(options.glob, identity2));
8486
+ const pattern = normalizePattern(options.glob, identity2);
8487
+ const normalized = assertGlobPattern(pattern);
8488
+ const matcher = normalized === void 0 ? void 0 : globToRegExp(normalized);
8487
8489
  let homes;
8488
8490
  try {
8489
8491
  homes = await homesFor(identity2, options);
@@ -8495,24 +8497,31 @@ function createNotesStore(input) {
8495
8497
  for (const home of homes) {
8496
8498
  const scope = home.scope;
8497
8499
  const root = scopeDir(scope, identity2, home.who);
8498
- const homeRows = [];
8500
+ let paths;
8499
8501
  try {
8500
- for (const path of await walkMarkdown(root)) {
8501
- if (matcher && !matcher.test(canonicalAddressFor(identity2, scope, path, home.who))) continue;
8502
- const address = addressFor(identity2, scope, path, home.who);
8503
- const fullPath = join2(root, path);
8504
- const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
8505
- const { meta, body } = parseNote(raw);
8506
- meta.scope = scope;
8507
- if (meta.crumpledAt !== void 0 !== (options.crumpled === true)) continue;
8508
- homeRows.push({ address, scope, path, meta, body });
8509
- }
8502
+ paths = await walkMarkdown(root);
8510
8503
  } catch (error) {
8511
8504
  if (!status || !isFilesystemError(error)) throw error;
8512
8505
  status.homesUnavailable.push(addressFor(identity2, scope, "", home.who).replace(/\/$/, "") || "session");
8513
8506
  continue;
8514
8507
  }
8515
- for (const row of homeRows) yield row;
8508
+ for (const path of paths) {
8509
+ if (matcher && !matcher.test(canonicalAddressFor(identity2, scope, path, home.who))) continue;
8510
+ const address = addressFor(identity2, scope, path, home.who);
8511
+ const fullPath = join2(root, path);
8512
+ let raw;
8513
+ try {
8514
+ raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
8515
+ } catch (error) {
8516
+ if (!status || !isFilesystemError(error)) throw error;
8517
+ status.homesUnavailable.push(address);
8518
+ continue;
8519
+ }
8520
+ const { meta, body } = parseNote(raw);
8521
+ meta.scope = scope;
8522
+ if (meta.crumpledAt !== void 0 !== (options.crumpled === true)) continue;
8523
+ yield { address, scope, path, meta, body };
8524
+ }
8516
8525
  }
8517
8526
  }
8518
8527
  async function list(options = {}) {
@@ -8561,11 +8570,9 @@ function createNotesStore(input) {
8561
8570
 
8562
8571
  // src/tools/output.ts
8563
8572
  var TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
8573
+ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
8564
8574
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
8565
8575
  var MAX_READ_WINDOW_CHARS = 5e4;
8566
- function withinTextBudget(text, budget = TOOL_OUTPUT_MAX_BYTES) {
8567
- return Buffer.byteLength(text, "utf8") <= budget;
8568
- }
8569
8576
  function prefixFit(text, fits) {
8570
8577
  if (fits(text)) return text;
8571
8578
  const chars = Array.from(text);
@@ -8588,12 +8595,10 @@ function success(data) {
8588
8595
  return { ok: true, data };
8589
8596
  }
8590
8597
  var ERROR_MESSAGE_MAX_CHARS = 2e3;
8591
- function boundedMessage(message) {
8592
- const chars = Array.from(message);
8593
- return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}\u2026[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
8594
- }
8595
8598
  function failure(code, message) {
8596
- return { ok: false, error: { code, message: boundedMessage(message) } };
8599
+ const chars = Array.from(message);
8600
+ const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}\u2026[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
8601
+ return { ok: false, error: { code, message: bounded } };
8597
8602
  }
8598
8603
  var WireErrorSchema = typebox_exports.Object({ error: typebox_exports.String(), code: typebox_exports.String() }, { additionalProperties: false });
8599
8604
  function wireResult(result) {
@@ -8611,7 +8616,7 @@ function structuredBytes(value) {
8611
8616
  return Buffer.byteLength(JSON.stringify(value), "utf8");
8612
8617
  }
8613
8618
  function fitsResult(result, render) {
8614
- return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
8619
+ return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
8615
8620
  }
8616
8621
  var TextWindowSchema = typebox_exports.Object({
8617
8622
  text: typebox_exports.String(),
@@ -8627,26 +8632,20 @@ function readTextWindow(text, offset, limit, makeData, render) {
8627
8632
  const requested = offset ?? 0;
8628
8633
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
8629
8634
  const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
8630
- const range = Math.min(requestedChars, chars.length - start);
8631
- const window = (delivered) => {
8632
- const end = start + delivered;
8635
+ const range = Math.max(0, Math.min(requestedChars, chars.length - start));
8636
+ const window = (delivered2) => {
8637
+ const end = start + delivered2;
8633
8638
  return {
8634
8639
  text: chars.slice(start, end).join(""),
8635
8640
  total_chars: chars.length,
8636
8641
  next_offset_chars: end < chars.length ? end : null
8637
8642
  };
8638
8643
  };
8639
- const fits = (delivered) => fitsResult(success(makeData(window(delivered))), render);
8644
+ const fits = (delivered2) => fitsResult(success(makeData(window(delivered2))), render);
8640
8645
  if (fits(range)) return success(makeData(window(range)));
8641
- let low = 0;
8642
- let high = range;
8643
- while (low < high) {
8644
- const mid = Math.ceil((low + high) / 2);
8645
- if (fits(mid)) low = mid;
8646
- else high = mid - 1;
8647
- }
8648
- if (low === 0) return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
8649
- return success(makeData(window(low)));
8646
+ const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
8647
+ if (delivered === 0) return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
8648
+ return success(makeData(window(delivered)));
8650
8649
  }
8651
8650
  function renderTextWindow(window) {
8652
8651
  const next = window.next_offset_chars;
@@ -8697,9 +8696,9 @@ var InvalidQueryError = class extends Error {
8697
8696
  };
8698
8697
  function searchQueries(query) {
8699
8698
  const candidates = typeof query === "string" ? [query] : query;
8700
- if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("query must be a string or a non-empty array of strings");
8701
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("query array elements must be strings");
8702
- if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("query strings must be non-empty: an empty query matches everything");
8699
+ if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("`query` must be a string or a non-empty list of strings.");
8700
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8701
+ if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("`query` can't be an empty string; it would match everything.");
8703
8702
  return candidates;
8704
8703
  }
8705
8704
 
@@ -8713,25 +8712,16 @@ var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({
8713
8712
  var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
8714
8713
  var GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
8715
8714
  var ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
8716
- function projectKeyField(scope, projectKey2) {
8717
- return scope === "project" ? { project_key: projectKey2 } : {};
8718
- }
8719
8715
  function failureOf(error) {
8720
8716
  if (error instanceof NoteError) return failure(error.code, error.message);
8721
8717
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
8722
8718
  if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
8723
8719
  throw error;
8724
8720
  }
8725
- function byRecent(a, b) {
8726
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
8727
- }
8728
8721
  var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
8729
8722
  var MAX_METADATA_ENTRY_BYTES = 1024;
8730
8723
  var MAX_METADATA_VERBATIM_BYTES = 2048;
8731
8724
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
8732
- function extraEntryBytes(key, value) {
8733
- return structuredBytes(key) + 1 + structuredBytes(value);
8734
- }
8735
8725
  var NoteMetadataSchema = typebox_exports.Object({
8736
8726
  origin: typebox_exports.Union([...ORIGIN_VALUES]),
8737
8727
  created_at: typebox_exports.String(),
@@ -8749,7 +8739,7 @@ function noteMetadata(meta) {
8749
8739
  for (const [key, value] of Object.entries(meta)) {
8750
8740
  if (NORMALIZED_META_KEYS.has(key) || value === void 0) continue;
8751
8741
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES) continue;
8752
- const entryBytes = extraEntryBytes(key, value);
8742
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
8753
8743
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
8754
8744
  put(key, TOO_LARGE_EXTRA_VALUE);
8755
8745
  continue;
@@ -8840,14 +8830,14 @@ function snapshot(rows, limit, status, renderData, shrink) {
8840
8830
  const reduced = shrink(item, fits);
8841
8831
  if (fits(reduced)) files.push(reduced);
8842
8832
  }
8843
- if (files.length === 0) return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
8833
+ if (files.length === 0) return failure("output_too_large", `\`${item.address}\` won't fit on the list (${TOOL_OUTPUT_LIMIT} per call); narrow \`glob\` to leave it out.`);
8844
8834
  break;
8845
8835
  }
8846
8836
  const outcome = success(data(files));
8847
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
8837
+ return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
8848
8838
  }
8849
8839
  function listedFile(row, identity2) {
8850
- return { address: row.address, ...projectKeyField(row.scope, identity2.projectKey), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
8840
+ return { address: row.address, ...row.scope === "project" ? { project_key: identity2.projectKey } : {}, updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
8851
8841
  }
8852
8842
  var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN }, { additionalProperties: false });
8853
8843
  function renderWriteData(data) {
@@ -8856,7 +8846,7 @@ function renderWriteData(data) {
8856
8846
  var notesWrite = {
8857
8847
  name: "notes_write",
8858
8848
  label: "Notes write",
8859
- description: `Create or replace a note's body, keeping metadata; uncrumples a crumpled note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
8849
+ description: `Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
8860
8850
  parameters: notesWriteParameters,
8861
8851
  outputSchema: resultSchema(NotesWriteDataSchema),
8862
8852
  executionMode: "sequential",
@@ -8888,19 +8878,20 @@ function renderUpdate(result) {
8888
8878
  return renderOutcome(result, renderUpdateData);
8889
8879
  }
8890
8880
  var DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
8881
+ var RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
8891
8882
  function boundedUpdate(data) {
8892
8883
  if (fitsResult(success(data), renderUpdate)) return success(data);
8893
- if (data.diff === "") return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
8884
+ if (data.diff === "") return failure("output_too_large", RECEIPT_TOO_LONG);
8894
8885
  const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}
8895
8886
  ${DIFF_SHORTENED_MARKER}` }), renderUpdate));
8896
8887
  const result = success({ ...data, diff: `${diff}
8897
8888
  ${DIFF_SHORTENED_MARKER}` });
8898
- return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
8889
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
8899
8890
  }
8900
8891
  var notesUpdate = {
8901
8892
  name: "notes_update",
8902
8893
  label: "Notes update",
8903
- description: `Edit a note's body, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true; frontmatter can't be edited. Returns a diff. ${ADDRESS_DESCRIPTION}`,
8894
+ description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
8904
8895
  parameters: notesUpdateParameters,
8905
8896
  outputSchema: resultSchema(NotesUpdateDataSchema),
8906
8897
  executionMode: "sequential",
@@ -8935,16 +8926,16 @@ ${renderTextWindow(data)}`;
8935
8926
  var notesRead = {
8936
8927
  name: "notes_read",
8937
8928
  label: "Notes read",
8938
- description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
8929
+ description: `Read a note. ${ADDRESS_DESCRIPTION}`,
8939
8930
  parameters: notesReadParameters,
8940
8931
  outputSchema: resultSchema(NotesReadDataSchema),
8941
8932
  async execute(params, identity2) {
8942
8933
  try {
8943
8934
  const note = await createNotesStore(identity2).read(params.address);
8944
- if (!note) return failure("not_found", "note not found");
8945
- const totalChars = Array.from(note.body).length;
8946
- if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
8947
8935
  const resolved = noteIdentity(identity2, params.address);
8936
+ if (!note) return failure("not_found", `No note at ${resolved.address}.`);
8937
+ const totalChars = Array.from(note.body).length;
8938
+ if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
8948
8939
  const metadata = noteMetadata(note.meta);
8949
8940
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
8950
8941
  } catch (error) {
@@ -9014,7 +9005,7 @@ var notesSearch = {
9014
9005
  async execute(params, identity2) {
9015
9006
  try {
9016
9007
  const { rows, status } = await createNotesStore(identity2).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? void 0, crumpled: params.crumpled });
9017
- const files = rows.sort(byRecent).map((row) => ({
9008
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => ({
9018
9009
  ...listedFile(row, identity2),
9019
9010
  matches: row.matches.slice(0, params.max_matches_per_file).map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9020
9011
  }));
@@ -9034,13 +9025,9 @@ var NOTES_HOMES = [
9034
9025
  { scope: "agent", label: "@self" },
9035
9026
  { scope: "model", label: "@model" }
9036
9027
  ];
9037
- function queryForScope(scope) {
9038
- if (scope === "agent" || scope === "model") return { scope };
9039
- return { scope };
9040
- }
9041
9028
  async function loadNotesSnapshot(identity2, openedAt, loadHome) {
9042
9029
  const store = createNotesStore(identity2);
9043
- const load = loadHome ?? ((scope) => store.list(queryForScope(scope)));
9030
+ const load = loadHome ?? ((scope) => store.list({ scope }));
9044
9031
  const homes = /* @__PURE__ */ new Map();
9045
9032
  const unavailable = [];
9046
9033
  for (const home of NOTES_HOMES) {
@@ -9062,6 +9049,8 @@ var CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
9062
9049
  var CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
9063
9050
  var CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
9064
9051
  var CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9052
+ var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
9053
+ var CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9065
9054
  var PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
9066
9055
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
9067
9056
 
@@ -9075,7 +9064,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
9075
9064
  *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
9076
9065
  Something's not true anymore? Cross it out! Write the right thing!
9077
9066
 
9078
- \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. If this feels like the right moment, call \`clear_memory\` and erase yourself with dignity.
9067
+ \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
9079
9068
 
9080
9069
  An address decides who the note belongs to \u2014 and how long it is meant to last. Ask that first; the rest follows.
9081
9070
 
@@ -9091,7 +9080,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
9091
9080
 
9092
9081
  Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
9093
9082
 
9094
- \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
9083
+ \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each may carry a short Cheatsheet of rules that always apply (about 5 lines); the rest is the note index, with addresses and gists for lookup. Keep each one current.
9095
9084
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
9096
9085
  function renderProtocolBlock(tools) {
9097
9086
  const names = {
@@ -9100,21 +9089,11 @@ function renderProtocolBlock(tools) {
9100
9089
  get_context_remaining: tools.remaining,
9101
9090
  clear_memory: tools.wipe
9102
9091
  };
9103
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
9092
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : PROTOCOL_BLOCK;
9093
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
9104
9094
  }
9105
9095
 
9106
9096
  // src/boot/render.ts
9107
- function identityBlock(agentName, modelName, firstWindowId, currentWindowId, previousWindowId) {
9108
- const lines = [
9109
- `Agent name: ${agentName} (brain: ${modelName})`,
9110
- `First context window id: ${firstWindowId}`,
9111
- `Current context window id: ${currentWindowId}`
9112
- ];
9113
- if (previousWindowId) lines.push(`Previous context window id: ${previousWindowId}`);
9114
- return `${CONTEXT_WINDOW_OPEN_TAG}
9115
- ${lines.join("\n")}
9116
- ${CONTEXT_WINDOW_CLOSE_TAG}`;
9117
- }
9118
9097
  function relativeTime(timestamp, now) {
9119
9098
  const seconds = Math.trunc((timestamp - now) / 1e3);
9120
9099
  if (seconds === 0) return "just now";
@@ -9122,9 +9101,6 @@ function relativeTime(timestamp, now) {
9122
9101
  const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
9123
9102
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
9124
9103
  }
9125
- function rowsFor(snapshot2, scope) {
9126
- return snapshot2.homes.get(scope) ?? [];
9127
- }
9128
9104
  var FEED_TITLE_MAX_CHARS = 40;
9129
9105
  function feedTitle(body) {
9130
9106
  const lines = body.split("\n");
@@ -9157,7 +9133,7 @@ function notesIndex(snapshot2, tools) {
9157
9133
  shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
9158
9134
  continue;
9159
9135
  }
9160
- const rows = rowsFor(snapshot2, home.scope).filter((row) => row.meta.crumpledAt === void 0);
9136
+ const rows = (snapshot2.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
9161
9137
  const map = rows.find((row) => row.path === "MAP.md");
9162
9138
  const fresh = rows.filter((row) => row.path !== "MAP.md").slice(0, SHELF_FRESH_LIMIT).map((row) => {
9163
9139
  const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
@@ -9184,11 +9160,162 @@ function mapBodyForBoot(address, body) {
9184
9160
  [truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
9185
9161
  }
9186
9162
  function renderBootBlock(data) {
9187
- const parts = [];
9188
- parts.push(identityBlock(data.agentName, data.modelName, data.firstWindowId, data.currentWindowId, data.previousWindowId));
9189
- parts.push(renderProtocolBlock(data.tools));
9190
- parts.push(notesIndex(data.notes, data.tools));
9191
- return parts.join("\n\n");
9163
+ const lines = [
9164
+ `Agent name: ${data.agentName} (brain: ${data.modelName})`,
9165
+ `First context window id: ${data.firstWindowId}`,
9166
+ `Current context window id: ${data.currentWindowId}`,
9167
+ ...data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []
9168
+ ];
9169
+ const identity2 = `${CONTEXT_WINDOW_OPEN_TAG}
9170
+ ${lines.join("\n")}
9171
+ ${CONTEXT_WINDOW_CLOSE_TAG}`;
9172
+ return [identity2, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
9173
+ }
9174
+
9175
+ // src/budget/text.ts
9176
+ var GUIDANCE_OPEN_TAG = "<context_window_guidance>";
9177
+ var GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
9178
+ var CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
9179
+ var WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
9180
+ var WARNING_PROMPT = `${WARNING_BODY}
9181
+ When the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
9182
+ var WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}
9183
+ ${WARNING_PROMPT}
9184
+ ${GUIDANCE_CLOSE_TAG}`;
9185
+ var CLAUDE_WARNING_PROMPT = `${WARNING_BODY}
9186
+ When the notes are ready, end your turn; the reset runs after it.`;
9187
+
9188
+ // src/budget/constants.ts
9189
+ var WARNING_RUNWAY_TOKENS = 16384;
9190
+
9191
+ // src/budget/parse.ts
9192
+ function numberOf(value) {
9193
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
9194
+ if (typeof value === "string" && value.trim() !== "") {
9195
+ const parsed = Number(value);
9196
+ return Number.isFinite(parsed) ? parsed : void 0;
9197
+ }
9198
+ return void 0;
9199
+ }
9200
+ function positiveNumber(value) {
9201
+ const parsed = numberOf(value);
9202
+ return parsed !== void 0 && parsed > 0 ? parsed : void 0;
9203
+ }
9204
+ function positiveInteger(value) {
9205
+ const parsed = numberOf(value);
9206
+ return parsed !== void 0 && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : void 0;
9207
+ }
9208
+ function percent(value) {
9209
+ const parsed = numberOf(value);
9210
+ return parsed !== void 0 && parsed > 0 && parsed <= 100 ? parsed : void 0;
9211
+ }
9212
+ function presenceFlag(value) {
9213
+ if (typeof value !== "string") return false;
9214
+ const text = value.trim().toLowerCase();
9215
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
9216
+ }
9217
+
9218
+ // src/settings.ts
9219
+ var NOTESOUP_SETTINGS_KEY = "notesoup";
9220
+ function isPlainObject(value) {
9221
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9222
+ }
9223
+ function notesoupSettings(settings2) {
9224
+ if (!isPlainObject(settings2)) return {};
9225
+ const value = settings2[NOTESOUP_SETTINGS_KEY];
9226
+ return isPlainObject(value) ? value : {};
9227
+ }
9228
+ function mergeNotesoupSettings(globalSettings, projectSettings) {
9229
+ const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
9230
+ return {
9231
+ reminderMarginTokens: merged.reminderMarginTokens,
9232
+ resetMarginTokens: merged.resetMarginTokens,
9233
+ warningRunwayTokens: merged.warningRunwayTokens,
9234
+ dreamer: merged.dreamer
9235
+ };
9236
+ }
9237
+
9238
+ // src/claude/thresholds.ts
9239
+ var CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13e3;
9240
+ var CLAUDE_OUTPUT_RESERVE_TOKENS = 2e4;
9241
+ var DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8192;
9242
+ var MIN_POINT_TOKENS = 1;
9243
+ var MIN_POINT_PERCENT = 0.1;
9244
+ var ASSUMED_WINDOW_TOKENS = 2e5;
9245
+ function settingFlag(settings2) {
9246
+ return isPlainObject(settings2) && typeof settings2.autoCompactEnabled === "boolean" ? settings2.autoCompactEnabled : void 0;
9247
+ }
9248
+ function configuredWindow(settings2, env, model) {
9249
+ const windows = [];
9250
+ const fromEnv = positiveNumber(env.autoCompactWindow);
9251
+ if (fromEnv !== void 0) windows.push(fromEnv);
9252
+ if (typeof model === "string" && model.length > 0 && isPlainObject(settings2)) {
9253
+ const modelSettings = isPlainObject(settings2.modelSettings) ? settings2.modelSettings : {};
9254
+ const perModel = modelSettings[model];
9255
+ if (isPlainObject(perModel)) {
9256
+ const value = positiveNumber(perModel.autoCompactWindow);
9257
+ if (value !== void 0) windows.push(value);
9258
+ }
9259
+ }
9260
+ if (isPlainObject(settings2)) {
9261
+ const value = positiveNumber(settings2.autoCompactWindow);
9262
+ if (value !== void 0) windows.push(value);
9263
+ }
9264
+ return windows.length === 0 ? void 0 : Math.min(...windows);
9265
+ }
9266
+ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
9267
+ const tokens = Math.max(0, Math.floor(native));
9268
+ const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
9269
+ return {
9270
+ source,
9271
+ autoCompact,
9272
+ unit: "tokens",
9273
+ native: tokens,
9274
+ reset,
9275
+ warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway),
9276
+ resetMargin,
9277
+ warningRunway
9278
+ };
9279
+ }
9280
+ function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
9281
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
9282
+ const native = pct === void 0 ? base : Math.min(pct, base);
9283
+ const reset = Math.max(MIN_POINT_PERCENT, native - resetMargin / ASSUMED_WINDOW_TOKENS * 100);
9284
+ return {
9285
+ source: "percent",
9286
+ autoCompact,
9287
+ unit: "percent",
9288
+ native,
9289
+ reset,
9290
+ warn: Math.max(MIN_POINT_PERCENT, reset - warningRunway / ASSUMED_WINDOW_TOKENS * 100),
9291
+ resetMargin,
9292
+ warningRunway
9293
+ };
9294
+ }
9295
+ function resolveClaudeLimits(facts) {
9296
+ const root = isPlainObject(facts) ? facts : {};
9297
+ const usage = isPlainObject(root.usage) ? root.usage : {};
9298
+ const breakdown = isPlainObject(root.breakdown) ? root.breakdown : {};
9299
+ const env = isPlainObject(root.env) ? root.env : {};
9300
+ const settings2 = root.settings;
9301
+ const margins = mergeNotesoupSettings(settings2, void 0);
9302
+ const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
9303
+ const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
9304
+ const autoCompact = settingFlag(settings2) !== false && !presenceFlag(env.disableAutoCompact) && breakdown.isAutoCompactEnabled !== false;
9305
+ const pct = percent(env.pctOverride);
9306
+ const threshold = positiveNumber(breakdown.autoCompactThreshold);
9307
+ if (autoCompact && threshold !== void 0) {
9308
+ const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
9309
+ if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
9310
+ }
9311
+ const window = positiveNumber(usage.window);
9312
+ if (window !== void 0) {
9313
+ const configured = configuredWindow(settings2, env, breakdown.model);
9314
+ const effective = Math.min(configured ?? window, window);
9315
+ const native = autoCompact ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
9316
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
9317
+ }
9318
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
9192
9319
  }
9193
9320
 
9194
9321
  // src/claude/helper.ts
@@ -9199,15 +9326,19 @@ function identity(input) {
9199
9326
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
9200
9327
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
9201
9328
  }
9202
- function jsonValue(value) {
9203
- return JSON.parse(JSON.stringify(value));
9329
+ function paramProblem(schema, params) {
9330
+ const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
9331
+ if (!first) return "unrecognized shape";
9332
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
9333
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
9334
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
9204
9335
  }
9205
9336
  function boundOperation(operation, ...rest) {
9206
9337
  return {
9207
9338
  description: operation.description,
9208
9339
  parameters: operation.parameters,
9209
9340
  async call(params, id) {
9210
- if (!Check2(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters`);
9341
+ if (!Check2(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
9211
9342
  const outcome = await operation.execute(params, id, ...rest);
9212
9343
  return { text: operation.render(outcome), outcome };
9213
9344
  }
@@ -9226,7 +9357,9 @@ var OPERATIONS = {
9226
9357
  async function dispatch(request) {
9227
9358
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
9228
9359
  const value = request;
9229
- if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
9360
+ if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
9361
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
9362
+ if (value.op === "limits") return resolveClaudeLimits(value.facts);
9230
9363
  if (value.op === "tool") {
9231
9364
  if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool)) throw new Error("unknown tool");
9232
9365
  const id = identity(value.identity);
@@ -9256,7 +9389,7 @@ async function handleLine(line) {
9256
9389
  return JSON.stringify({ ok: false, error: safeError(error) });
9257
9390
  }
9258
9391
  }
9259
- if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) {
9392
+ if (process.argv[1] && pathToFileURL(realpathSync2(process.argv[1])).href === import.meta.url) {
9260
9393
  process.stdin.setEncoding("utf8");
9261
9394
  let input = "";
9262
9395
  process.stdin.on("data", (chunk) => {