notesoup 0.57.4 → 0.58.1

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 (129) hide show
  1. package/README.md +15 -1
  2. package/dist/plugins/claude/src/helper.js +2 -11
  3. package/dist/plugins/claude/src/thresholds.js +23 -43
  4. package/dist/plugins/codex/src/mcp.js +3 -11
  5. package/dist/plugins/codex/src/state.d.ts +1 -1
  6. package/dist/plugins/codex/src/state.js +1 -1
  7. package/dist/plugins/dsh/tools.js +1 -1
  8. package/dist/plugins/pi/boot.d.ts +1 -1
  9. package/dist/plugins/pi/boot.js +2 -3
  10. package/dist/plugins/pi/budget.d.ts +1 -1
  11. package/dist/plugins/pi/budget.js +1 -1
  12. package/dist/plugins/pi/render.d.ts +1 -1
  13. package/dist/plugins/pi/render.js +20 -11
  14. package/dist/plugins/pi/runtime.js +6 -2
  15. package/dist/plugins/pi/tool-result.d.ts +2 -1
  16. package/dist/plugins/pi/window.js +24 -1
  17. package/dist/src/boot/render.d.ts +3 -4
  18. package/dist/src/boot/render.js +23 -21
  19. package/dist/src/boot/text.d.ts +2 -5
  20. package/dist/src/boot/text.js +12 -9
  21. package/dist/src/budget/text.d.ts +1 -1
  22. package/dist/src/budget/text.js +1 -1
  23. package/dist/src/history/corpus.d.ts +1 -1
  24. package/dist/src/history/corpus.js +1 -1
  25. package/dist/src/history/history.d.ts +2 -2
  26. package/dist/src/history/history.js +5 -8
  27. package/dist/src/history/query.d.ts +11 -3
  28. package/dist/src/history/query.js +7 -11
  29. package/dist/src/index.d.ts +4 -3
  30. package/dist/src/index.js +1 -1
  31. package/dist/src/notes/constants.d.ts +1 -1
  32. package/dist/src/notes/constants.js +1 -1
  33. package/dist/src/notes/errors.d.ts +1 -1
  34. package/dist/src/notes/frontmatter.d.ts +2 -1
  35. package/dist/src/notes/frontmatter.js +3 -1
  36. package/dist/src/notes/index.d.ts +1 -0
  37. package/dist/src/notes/index.js +1 -0
  38. package/dist/src/notes/policy.d.ts +16 -0
  39. package/dist/src/notes/policy.js +43 -0
  40. package/dist/src/notes/store.d.ts +7 -2
  41. package/dist/src/notes/store.js +61 -19
  42. package/dist/src/result.d.ts +21 -0
  43. package/dist/src/result.js +18 -0
  44. package/dist/src/text-match.d.ts +8 -0
  45. package/dist/src/text-match.js +34 -0
  46. package/dist/src/tools/dream.d.ts +9 -1
  47. package/dist/src/tools/dream.js +2 -1
  48. package/dist/src/tools/history.js +14 -5
  49. package/dist/src/tools/notes.d.ts +75 -13
  50. package/dist/src/tools/notes.js +58 -19
  51. package/dist/src/tools/output.d.ts +1 -3
  52. package/dist/src/tools/output.js +1 -19
  53. package/dist/src/tools/result.d.ts +2 -20
  54. package/dist/src/tools/result.js +4 -18
  55. package/dist/src/tools/schema.d.ts +3 -7
  56. package/dist/src/tools/schema.js +10 -16
  57. package/dist/test/agent-loop.test.js +78 -6
  58. package/dist/test/boot.integration.test.js +30 -3
  59. package/dist/test/claude-mod.test.js +101 -16
  60. package/dist/test/codex-history.test.js +2 -2
  61. package/dist/test/codex-plugin.test.js +2 -0
  62. package/dist/test/dependencies.test.js +38 -3
  63. package/dist/test/dsh.test.js +1 -1
  64. package/dist/test/helpers/dependency-graph.js +12 -6
  65. package/dist/test/helpers/extension.d.ts +2 -1
  66. package/dist/test/history.integration.test.js +47 -1
  67. package/dist/test/host-neutral.test.js +4 -3
  68. package/dist/test/model-facing-text.test.js +20 -16
  69. package/dist/test/note-policy.test.d.ts +1 -0
  70. package/dist/test/note-policy.test.js +227 -0
  71. package/dist/test/notes.integration.test.js +9 -9
  72. package/dist/test/notes.test.js +4 -4
  73. package/dist/test/pi-render.test.js +28 -1
  74. package/dist/test/project-namespace.test.js +1 -1
  75. package/docs/architecture.md +10 -7
  76. package/docs/claude-code-mod.md +3 -3
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +19 -6
  79. package/docs/reset-lifecycle.md +2 -2
  80. package/docs/tool-results.md +3 -1
  81. package/package.json +12 -12
  82. package/playbook.md +1 -1
  83. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/claude/dist/claude/helper.js +535 -439
  85. package/plugins/claude/hooks/register.ts +26 -36
  86. package/plugins/claude/playbook.md +1 -1
  87. package/plugins/claude/skills/dream/SKILL.md +1 -1
  88. package/plugins/claude/skills/memory/SKILL.md +1 -1
  89. package/plugins/claude/src/helper.ts +2 -11
  90. package/plugins/claude/src/thresholds.ts +22 -42
  91. package/plugins/codex/dist/codex/notesoup.js +519 -403
  92. package/plugins/codex/src/mcp.ts +5 -12
  93. package/plugins/codex/src/state.ts +1 -1
  94. package/plugins/dsh/tools.ts +2 -1
  95. package/plugins/pi/boot.ts +3 -4
  96. package/plugins/pi/budget.ts +1 -1
  97. package/plugins/pi/render.ts +20 -8
  98. package/plugins/pi/runtime.ts +6 -2
  99. package/plugins/pi/tool-result.ts +2 -1
  100. package/plugins/pi/window.ts +20 -1
  101. package/skills/dream/SKILL.md +1 -1
  102. package/skills/memory/SKILL.md +1 -1
  103. package/src/boot/render.ts +24 -21
  104. package/src/boot/text.ts +12 -9
  105. package/src/budget/text.ts +1 -1
  106. package/src/history/corpus.ts +1 -1
  107. package/src/history/history.ts +5 -6
  108. package/src/history/query.ts +11 -14
  109. package/src/index.ts +5 -2
  110. package/src/notes/constants.ts +1 -1
  111. package/src/notes/errors.ts +1 -1
  112. package/src/notes/frontmatter.ts +4 -2
  113. package/src/notes/index.ts +1 -0
  114. package/src/notes/policy.ts +49 -0
  115. package/src/notes/store.ts +63 -24
  116. package/src/result.ts +26 -0
  117. package/src/text-match.ts +32 -0
  118. package/src/tools/dream.ts +2 -1
  119. package/src/tools/history.ts +15 -6
  120. package/src/tools/notes.ts +60 -20
  121. package/src/tools/output.ts +1 -17
  122. package/src/tools/result.ts +4 -26
  123. package/src/tools/schema.ts +11 -17
  124. package/dist/plugins/codex/src/history.d.ts +0 -3
  125. package/dist/plugins/codex/src/history.js +0 -2
  126. package/dist/plugins/codex/src/transcript.d.ts +0 -3
  127. package/dist/plugins/codex/src/transcript.js +0 -2
  128. package/plugins/codex/src/history.ts +0 -3
  129. package/plugins/codex/src/transcript.ts +0 -3
@@ -7849,146 +7849,181 @@ __export(typebox_exports, {
7849
7849
  With: () => With2
7850
7850
  });
7851
7851
 
7852
- // src/notes/frontmatter.ts
7853
- var SCOPES = ["session", "project", "human", "agent", "model"];
7854
- var ORIGINS = ["user", "self", "external"];
7855
- var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
7856
- var KNOWN_KEYS = ["origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
7857
- var pad2 = (value) => String(value).padStart(2, "0");
7858
- function localIso(epochMs) {
7859
- const date = new Date(epochMs);
7860
- const offsetMinutes = -date.getTimezoneOffset();
7861
- const absOffset = Math.abs(offsetMinutes);
7862
- const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
7863
- const wallClock = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
7864
- return `${wallClock}${offset}`;
7852
+ // src/history/history.ts
7853
+ var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
7854
+ var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
7855
+ function isTextContent(part) {
7856
+ return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
7865
7857
  }
7866
- function isScope(value) {
7867
- return typeof value === "string" && SCOPES.includes(value);
7858
+ function contentText(content) {
7859
+ if (typeof content === "string") return content;
7860
+ return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
7868
7861
  }
7869
- function isOrigin(value) {
7870
- return typeof value === "string" && ORIGINS.includes(value);
7862
+ function argumentText(execution) {
7863
+ return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
7871
7864
  }
7872
- function toEpoch(value, fallback) {
7873
- if (typeof value === "number" && Number.isFinite(value)) return value;
7874
- if (typeof value === "string") {
7875
- const parsed = Date.parse(value);
7876
- if (Number.isFinite(parsed)) return parsed;
7877
- }
7878
- return fallback;
7865
+ function nestedCallLine(call) {
7866
+ const parts = [`${call.id} ${call.name} [${call.status}]`];
7867
+ if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
7868
+ if (call.error !== void 0) parts.push(`error: ${call.error}`);
7869
+ parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
7870
+ return `- ${parts.join(" ")}`;
7879
7871
  }
7880
- function parseScalar(text) {
7881
- const trimmed = text.trim();
7882
- if (trimmed === "") return "";
7883
- try {
7884
- return JSON.parse(trimmed);
7885
- } catch {
7886
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
7887
- return trimmed;
7872
+ function historyDocument(event) {
7873
+ if (event.execution === void 0) return event.text;
7874
+ const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
7875
+ if (event.text !== "") sections.push(`--- output ---
7876
+ ${event.text}`);
7877
+ const nested = event.execution.nestedCalls;
7878
+ if (nested !== void 0) {
7879
+ const header2 = nested.complete ? "complete" : "incomplete";
7880
+ sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
7881
+ ${nested.calls.map(nestedCallLine).join("\n")}`);
7888
7882
  }
7883
+ return sections.join("\n");
7889
7884
  }
7890
- function parseFrontmatter(raw) {
7891
- const stripped = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
7892
- const lines = stripped.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
7893
- if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
7894
- let close = -1;
7895
- for (let index = 1; index < lines.length; index++) {
7896
- if (lines[index]?.trim() === "---") {
7897
- close = index;
7898
- break;
7885
+ var documents = /* @__PURE__ */ new WeakMap();
7886
+ function eventDocument(event) {
7887
+ const cached = documents.get(event);
7888
+ if (cached !== void 0) return cached;
7889
+ const text = historyDocument(event);
7890
+ documents.set(event, text);
7891
+ return text;
7892
+ }
7893
+ function toolEvent(item, result) {
7894
+ const run = result ?? item;
7895
+ const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
7896
+ const truncated = run.outputTruncated === true;
7897
+ return {
7898
+ seq: item.seq,
7899
+ windowId: item.windowId,
7900
+ role: "tool",
7901
+ text: result?.text ?? (item.role === "tool" ? item.text : ""),
7902
+ createdAt: item.createdAt,
7903
+ execution: {
7904
+ name: item.toolName ?? "unknown",
7905
+ status,
7906
+ // A call records its arguments; a bare result records none, and gets none invented.
7907
+ ...item.arguments === void 0 ? {} : { arguments: item.arguments },
7908
+ ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
7909
+ ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
7899
7910
  }
7911
+ };
7912
+ }
7913
+ function projectHistory(rawWindows, highestSeq, branchSeqs) {
7914
+ const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
7915
+ const resultsById = /* @__PURE__ */ new Map();
7916
+ for (const item of raw) {
7917
+ if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
7900
7918
  }
7901
- if (close === -1) return { fields: {}, body: raw };
7902
- const fields = /* @__PURE__ */ Object.create(null);
7903
- for (let index = 1; index < close; index++) {
7904
- const line = lines[index];
7905
- const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
7906
- if (!match) continue;
7907
- const key = match[1];
7908
- const rest2 = match[2];
7909
- if (rest2.trim() === "") {
7910
- const items = [];
7911
- while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
7912
- index++;
7913
- items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
7914
- }
7915
- fields[key] = items;
7916
- } else {
7917
- fields[key] = parseScalar(rest2);
7919
+ const pairedResults = /* @__PURE__ */ new Map();
7920
+ for (const item of raw) {
7921
+ const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
7922
+ if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
7923
+ pairedResults.set(result.seq, item.seq);
7918
7924
  }
7919
7925
  }
7920
- const rest = lines.slice(close + 1);
7921
- if (rest[0] === "") rest.shift();
7922
- return { fields, body: rest.join("\n") };
7926
+ const windows = rawWindows.map((current) => ({
7927
+ windowId: current.windowId,
7928
+ ...current.createdAt ? { createdAt: current.createdAt } : {},
7929
+ items: current.items.flatMap((item) => {
7930
+ if (pairedResults.has(item.seq)) return [];
7931
+ if (item.role === "tool_call" || item.role === "tool") {
7932
+ const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
7933
+ const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
7934
+ return [toolEvent(item, paired)];
7935
+ }
7936
+ return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
7937
+ })
7938
+ }));
7939
+ return { windows, highestSeq, branchSeqs, pairedResults };
7923
7940
  }
7924
- function parseNote(raw, now = Date.now()) {
7925
- const { fields, body } = parseFrontmatter(raw);
7926
- const meta = { ...fields };
7927
- meta.scope = isScope(meta.scope) ? meta.scope : "session";
7928
- meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
7929
- for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
7930
- meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
7931
- return { meta, body };
7941
+ var NestedCallSummarySchema = typebox_exports.Object({
7942
+ call_count: typebox_exports.Integer({ minimum: 0 }),
7943
+ complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
7944
+ }, { additionalProperties: false });
7945
+ var ToolSummarySchema = typebox_exports.Object({
7946
+ tool: typebox_exports.Optional(typebox_exports.String()),
7947
+ tool_status: typebox_exports.Optional(ToolCallStatusSchema),
7948
+ output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
7949
+ full_output_path: typebox_exports.Optional(typebox_exports.String())
7950
+ }, { additionalProperties: false });
7951
+ function toolSummary(event) {
7952
+ const execution = event.execution;
7953
+ if (!execution) return {};
7954
+ return {
7955
+ tool: execution.name,
7956
+ tool_status: execution.status,
7957
+ ...execution.outputTruncated ? { output_truncated: true } : {},
7958
+ ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
7959
+ };
7932
7960
  }
7933
- function yamlScalar(value) {
7934
- if (typeof value === "string") {
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()) && !parsesAsNonString(value)) return value;
7937
- }
7938
- return JSON.stringify(value);
7961
+ function nestedCallSummary(event) {
7962
+ const nested = event.execution?.nestedCalls;
7963
+ return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
7939
7964
  }
7940
- function parsesAsNonString(text) {
7941
- try {
7942
- return typeof JSON.parse(text) !== "string";
7943
- } catch {
7944
- return false;
7945
- }
7965
+ var HistoryFoldedRowSchema = typebox_exports.Object({
7966
+ session: typebox_exports.Optional(typebox_exports.String()),
7967
+ first_seq: typebox_exports.Integer({ minimum: 1 }),
7968
+ last_seq: typebox_exports.Integer({ minimum: 1 }),
7969
+ count: typebox_exports.Integer({ minimum: 1 }),
7970
+ tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
7971
+ }, { additionalProperties: false });
7972
+ var HistoryPageItemSchema = typebox_exports.Object({
7973
+ session: typebox_exports.Optional(typebox_exports.String()),
7974
+ folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
7975
+ seq: typebox_exports.Integer({ minimum: 1 }),
7976
+ role: HistoryRoleSchema,
7977
+ created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
7978
+ ...ToolSummarySchema.properties,
7979
+ content: typebox_exports.String(),
7980
+ truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
7981
+ offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
7982
+ }, { additionalProperties: false });
7983
+ var MAX_FOLD_TOOL_NAMES = 20;
7984
+ var MAX_FOLD_TOOL_NAME_CHARS = 120;
7985
+ function visibleItem(event, maxChars, matchOffset) {
7986
+ const document = eventDocument(event);
7987
+ const chars = Array.from(document);
7988
+ const start = matchOffset ?? 0;
7989
+ const limit = Math.max(0, maxChars);
7990
+ const truncated = start > 0 || start + limit < chars.length;
7991
+ return {
7992
+ seq: event.seq,
7993
+ role: event.role,
7994
+ created_at: event.createdAt ?? null,
7995
+ ...toolSummary(event),
7996
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
7997
+ truncated,
7998
+ ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
7999
+ };
7946
8000
  }
7947
- function serializeNote(meta, body) {
7948
- const lines = [];
7949
- for (const key of KNOWN_KEYS) {
7950
- const value = meta[key];
7951
- if (value === void 0) continue;
7952
- if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
7953
- else lines.push(`${key}: ${yamlScalar(value)}`);
7954
- }
7955
- for (const key of Object.keys(meta)) {
7956
- if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
7957
- if (meta[key] === void 0) continue;
7958
- lines.push(`${key}: ${yamlScalar(meta[key])}`);
7959
- }
7960
- return `---
7961
- ${lines.join("\n")}
7962
- ---
7963
-
7964
- ${body}`;
8001
+ function allItems(projection) {
8002
+ return projection.windows.flatMap((current) => current.items);
7965
8003
  }
7966
- function stripLeadingFrontmatter(content) {
7967
- return parseFrontmatter(content).body;
8004
+ function inSelection(event, params) {
8005
+ if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
8006
+ if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
8007
+ if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
8008
+ if (event.createdAt === void 0) return false;
8009
+ const at = Date.parse(event.createdAt);
8010
+ return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
7968
8011
  }
7969
-
7970
- // src/notes/fs-error.ts
7971
- function isFilesystemError(error) {
7972
- const code = typeof error === "object" && error !== null ? error.code : void 0;
7973
- return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
8012
+ function filteredItems(projection, params) {
8013
+ return allItems(projection).filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role))).sort((a, b) => a.seq - b.seq);
7974
8014
  }
7975
8015
 
7976
- // src/notes/store.ts
7977
- import { randomUUID as randomUUID2 } from "node:crypto";
7978
- import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
7979
- import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
7980
-
7981
- // src/text-match.ts
7982
- function earliestMatchOffsetChars(text, queries) {
7983
- let earliest = -1;
7984
- for (const query of queries) {
7985
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7986
- const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
7987
- if (index < 0) continue;
7988
- if (earliest < 0 || index < earliest) earliest = index;
7989
- }
7990
- return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
8016
+ // src/tools/schema.ts
8017
+ var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
8018
+ var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
8019
+ function paramProblem(schema, params) {
8020
+ const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
8021
+ if (!first) return "unrecognized shape";
8022
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
8023
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
8024
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
7991
8025
  }
8026
+ var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
7992
8027
 
7993
8028
  // src/notes/errors.ts
7994
8029
  var NoteError = class extends Error {
@@ -8121,12 +8156,216 @@ function canonicalAddressFor(identity2, scope, path, who) {
8121
8156
  if (scope === "agent") return `@agents/${who ?? identity2.agent}/${path}`;
8122
8157
  return `@models/${who ?? identity2.model}/${path}`;
8123
8158
  }
8124
- function addressFor(identity2, scope, path, who) {
8125
- if (scope === "session" && who === void 0) return path;
8126
- if (scope === "project" && who === void 0) return `@project/${path}`;
8127
- if (scope === "agent" && (who === void 0 || who === identity2.agent)) return `@self/${path}`;
8128
- if (scope === "model" && (who === void 0 || who === identity2.model)) return `@model/${path}`;
8129
- return canonicalAddressFor(identity2, scope, path, who);
8159
+ function addressFor(identity2, scope, path, who) {
8160
+ if (scope === "session" && who === void 0) return path;
8161
+ if (scope === "project" && who === void 0) return `@project/${path}`;
8162
+ if (scope === "agent" && (who === void 0 || who === identity2.agent)) return `@self/${path}`;
8163
+ if (scope === "model" && (who === void 0 || who === identity2.model)) return `@model/${path}`;
8164
+ return canonicalAddressFor(identity2, scope, path, who);
8165
+ }
8166
+
8167
+ // src/notes/policy.ts
8168
+ var DEFAULT_NOTE_BUDGET = 2048;
8169
+ var MAX_PINNED_NOTES = 5;
8170
+ var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
8171
+ function validateNotePolicy(fields) {
8172
+ for (const key of ["pinned", "readonly"]) {
8173
+ if (fields[key] !== void 0 && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
8174
+ }
8175
+ if (fields.budget !== void 0 && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
8176
+ throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
8177
+ }
8178
+ }
8179
+ function effectiveNotePolicy(fields, path) {
8180
+ validateNotePolicy(fields);
8181
+ return {
8182
+ pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some((page) => page === path),
8183
+ budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
8184
+ readonly: fields.readonly ?? false
8185
+ };
8186
+ }
8187
+ function pinnedPageOrder(path) {
8188
+ const index = DEFAULT_PINNED_PAGES.findIndex((page) => page === path);
8189
+ return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
8190
+ }
8191
+ function noteBudgetWarnings(body, policy) {
8192
+ const count = Array.from(body).length;
8193
+ return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
8194
+ }
8195
+ function assertNoteUnlocked(fields, unlock) {
8196
+ if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
8197
+ }
8198
+ function applyNotePolicy(target, fields) {
8199
+ validateNotePolicy(fields);
8200
+ for (const key of ["pinned", "budget", "readonly"]) {
8201
+ if (fields[key] !== void 0) Object.assign(target, { [key]: fields[key] });
8202
+ }
8203
+ }
8204
+
8205
+ // src/notes/frontmatter.ts
8206
+ var SCOPES = ["session", "project", "human", "agent", "model"];
8207
+ var ORIGINS = ["user", "self", "external"];
8208
+ var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
8209
+ var KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
8210
+ var pad2 = (value) => String(value).padStart(2, "0");
8211
+ function localIso(epochMs) {
8212
+ const date = new Date(epochMs);
8213
+ const offsetMinutes = -date.getTimezoneOffset();
8214
+ const absOffset = Math.abs(offsetMinutes);
8215
+ const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
8216
+ const wallClock = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
8217
+ return `${wallClock}${offset}`;
8218
+ }
8219
+ function isScope(value) {
8220
+ return typeof value === "string" && SCOPES.includes(value);
8221
+ }
8222
+ function isOrigin(value) {
8223
+ return typeof value === "string" && ORIGINS.includes(value);
8224
+ }
8225
+ function toEpoch(value, fallback) {
8226
+ if (typeof value === "number" && Number.isFinite(value)) return value;
8227
+ if (typeof value === "string") {
8228
+ const parsed = Date.parse(value);
8229
+ if (Number.isFinite(parsed)) return parsed;
8230
+ }
8231
+ return fallback;
8232
+ }
8233
+ function parseScalar(text) {
8234
+ const trimmed = text.trim();
8235
+ if (trimmed === "") return "";
8236
+ try {
8237
+ return JSON.parse(trimmed);
8238
+ } catch {
8239
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
8240
+ return trimmed;
8241
+ }
8242
+ }
8243
+ function parseFrontmatter(raw) {
8244
+ const stripped = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
8245
+ const lines = stripped.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
8246
+ if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
8247
+ let close = -1;
8248
+ for (let index = 1; index < lines.length; index++) {
8249
+ if (lines[index]?.trim() === "---") {
8250
+ close = index;
8251
+ break;
8252
+ }
8253
+ }
8254
+ if (close === -1) return { fields: {}, body: raw };
8255
+ const fields = /* @__PURE__ */ Object.create(null);
8256
+ for (let index = 1; index < close; index++) {
8257
+ const line = lines[index];
8258
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
8259
+ if (!match) continue;
8260
+ const key = match[1];
8261
+ const rest2 = match[2];
8262
+ if (rest2.trim() === "") {
8263
+ const items = [];
8264
+ while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
8265
+ index++;
8266
+ items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
8267
+ }
8268
+ fields[key] = items;
8269
+ } else {
8270
+ fields[key] = parseScalar(rest2);
8271
+ }
8272
+ }
8273
+ const rest = lines.slice(close + 1);
8274
+ if (rest[0] === "") rest.shift();
8275
+ return { fields, body: rest.join("\n") };
8276
+ }
8277
+ function parseNote(raw, now = Date.now()) {
8278
+ const { fields, body } = parseFrontmatter(raw);
8279
+ validateNotePolicy(fields);
8280
+ const meta = { ...fields };
8281
+ meta.scope = isScope(meta.scope) ? meta.scope : "session";
8282
+ meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
8283
+ for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
8284
+ meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
8285
+ return { meta, body };
8286
+ }
8287
+ function yamlScalar(value) {
8288
+ if (typeof value === "string") {
8289
+ const reserved = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
8290
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
8291
+ }
8292
+ return JSON.stringify(value);
8293
+ }
8294
+ function parsesAsNonString(text) {
8295
+ try {
8296
+ return typeof JSON.parse(text) !== "string";
8297
+ } catch {
8298
+ return false;
8299
+ }
8300
+ }
8301
+ function serializeNote(meta, body) {
8302
+ const lines = [];
8303
+ for (const key of KNOWN_KEYS) {
8304
+ const value = meta[key];
8305
+ if (value === void 0) continue;
8306
+ if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
8307
+ else lines.push(`${key}: ${yamlScalar(value)}`);
8308
+ }
8309
+ for (const key of Object.keys(meta)) {
8310
+ if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
8311
+ if (meta[key] === void 0) continue;
8312
+ lines.push(`${key}: ${yamlScalar(meta[key])}`);
8313
+ }
8314
+ return `---
8315
+ ${lines.join("\n")}
8316
+ ---
8317
+
8318
+ ${body}`;
8319
+ }
8320
+ function stripLeadingFrontmatter(content) {
8321
+ return parseFrontmatter(content).body;
8322
+ }
8323
+
8324
+ // src/notes/fs-error.ts
8325
+ function isFilesystemError(error) {
8326
+ const code = typeof error === "object" && error !== null ? error.code : void 0;
8327
+ return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
8328
+ }
8329
+
8330
+ // src/notes/store.ts
8331
+ import { randomUUID as randomUUID2 } from "node:crypto";
8332
+ import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
8333
+ import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
8334
+
8335
+ // src/text-match.ts
8336
+ var InvalidQueryError = class extends Error {
8337
+ constructor(message) {
8338
+ super(message);
8339
+ this.name = "InvalidQueryError";
8340
+ }
8341
+ };
8342
+ function searchQueries(query) {
8343
+ const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
8344
+ if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
8345
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8346
+ return candidates.filter((candidate) => candidate !== "");
8347
+ }
8348
+ function prefixFit(text, fits) {
8349
+ if (fits(text)) return text;
8350
+ const chars = Array.from(text);
8351
+ let low = 0;
8352
+ let high = chars.length;
8353
+ while (low < high) {
8354
+ const mid = Math.ceil((low + high) / 2);
8355
+ if (fits(chars.slice(0, mid).join(""))) low = mid;
8356
+ else high = mid - 1;
8357
+ }
8358
+ return chars.slice(0, low).join("");
8359
+ }
8360
+ function earliestMatchOffsetChars(text, queries) {
8361
+ let earliest = -1;
8362
+ for (const query of queries) {
8363
+ const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8364
+ const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
8365
+ if (index < 0) continue;
8366
+ if (earliest < 0 || index < earliest) earliest = index;
8367
+ }
8368
+ return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
8130
8369
  }
8131
8370
 
8132
8371
  // src/notes/identity.ts
@@ -8152,7 +8391,7 @@ function snapshotNotesIdentity(value) {
8152
8391
  }
8153
8392
 
8154
8393
  // src/notes/constants.ts
8155
- var MAX_NOTE_BYTES = 1e6;
8394
+ var MAX_NOTE_BYTES = 512e3;
8156
8395
  var MAX_NOTE_PATH_BYTES = 512;
8157
8396
 
8158
8397
  // src/notes/project-namespace.ts
@@ -8406,6 +8645,11 @@ function withPathQueue(path, operation) {
8406
8645
  });
8407
8646
  return result;
8408
8647
  }
8648
+ function withPathQueues(paths, operation) {
8649
+ const keys = [...new Set(paths.map((path) => resolve3(path)))].sort();
8650
+ const lock = (index) => index === keys.length ? operation() : withPathQueue(keys[index], () => lock(index + 1));
8651
+ return lock(0);
8652
+ }
8409
8653
  function errno2(error) {
8410
8654
  return typeof error === "object" && error !== null ? error.code : void 0;
8411
8655
  }
@@ -8532,6 +8776,7 @@ function assertWritablePath(vpath) {
8532
8776
  if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
8533
8777
  }
8534
8778
  function megabytes(bytes) {
8779
+ if (bytes < 1e6) return `${Math.ceil(bytes / 1e3)} KB`;
8535
8780
  return `${Math.ceil(bytes / 1e4) / 100} MB`;
8536
8781
  }
8537
8782
  function assertSerializedSize(content) {
@@ -8559,20 +8804,35 @@ function assertDreamNote(scope, who, identity2, raw, address) {
8559
8804
  }
8560
8805
  function createNotesStore(input) {
8561
8806
  const identity2 = snapshotNotesIdentity(input);
8807
+ async function assertPinAdmission(root, path, meta, previous, source) {
8808
+ const livePin = (value, name) => value !== void 0 && value.crumpledAt === void 0 && effectiveNotePolicy(value, name).pinned;
8809
+ if (!livePin(meta, path) || livePin(previous, path)) return;
8810
+ if (source?.root === root && livePin(source.meta, source.path)) return;
8811
+ let count = 0;
8812
+ for (const name of await walkMarkdown(root)) {
8813
+ const raw = await readFileIfExists(join3(root, name));
8814
+ if (raw !== void 0 && livePin(parseNote(raw).meta, name)) count++;
8815
+ }
8816
+ if (count >= MAX_PINNED_NOTES) throw new NoteError("pin_limit", `This notebook already has ${count} live pinned notes; the limit is ${MAX_PINNED_NOTES}. Unpin or crumple one first. Nothing was saved.`);
8817
+ }
8562
8818
  async function write(address, content, options = {}) {
8563
8819
  const stableOptions = { ...options };
8820
+ validateNotePolicy(stableOptions);
8564
8821
  const destination = assertAddress(address);
8565
8822
  assertWritablePath(destination.path);
8566
8823
  const scope = destination.scope;
8567
8824
  assertWritableNamespace(scope, destination.who, identity2);
8568
8825
  const origin = stableOptions.origin === void 0 ? void 0 : assertOrigin(stableOptions.origin);
8569
8826
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8570
- return withPathQueue(path, async () => {
8827
+ const root = scopeDir(scope, identity2, destination.who);
8828
+ return withPathQueues([root], () => withPathQueue(path, async () => {
8571
8829
  const now = writeStamp();
8572
8830
  const cleanBody = stripLeadingFrontmatter(content);
8573
8831
  const existingRaw = await readFileIfExists(path);
8574
8832
  assertDreamNote(scope, destination.who, identity2, existingRaw, address);
8575
8833
  const existing = existingRaw === void 0 ? void 0 : parseNote(existingRaw, now).meta;
8834
+ if (existing) assertNoteUnlocked(existing, stableOptions.readonly);
8835
+ const previous = existing === void 0 ? void 0 : { ...existing };
8576
8836
  const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
8577
8837
  const meta = existing ?? {
8578
8838
  scope,
@@ -8584,14 +8844,16 @@ function createNotesStore(input) {
8584
8844
  ...scope === "session" ? { project: identity2.projectKey } : {}
8585
8845
  };
8586
8846
  meta.scope = scope;
8847
+ applyNotePolicy(meta, stableOptions);
8587
8848
  if (origin !== void 0) meta.origin = origin;
8588
8849
  delete meta.crumpledAt;
8589
8850
  meta.updatedAt = now;
8590
8851
  const serialized = serializeNote(meta, cleanBody);
8591
8852
  assertSerializedSize(serialized);
8853
+ await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
8592
8854
  await atomicWrite(path, serialized);
8593
- return { meta, outcome };
8594
- });
8855
+ return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
8856
+ }));
8595
8857
  }
8596
8858
  async function read(address) {
8597
8859
  const destination = assertAddress(address);
@@ -8611,18 +8873,21 @@ function createNotesStore(input) {
8611
8873
  async function update(address, edits, options = {}) {
8612
8874
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
8613
8875
  const stableOptions = { ...options };
8876
+ validateNotePolicy(stableOptions);
8614
8877
  const from = assertAddress(address);
8615
8878
  const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
8616
8879
  assertWritablePath(destination.path);
8617
8880
  const scope = destination.scope;
8618
8881
  assertWritableNamespace(from.scope, from.who, identity2);
8619
8882
  assertWritableNamespace(scope, destination.who, identity2);
8620
- if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0) {
8621
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
8883
+ if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0 && stableOptions.pinned === void 0 && stableOptions.budget === void 0 && stableOptions.readonly === void 0) {
8884
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
8622
8885
  }
8623
8886
  const fromPath = physicalPath(from.scope, from.path, identity2, from.who);
8624
8887
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8625
8888
  const differentPaths = resolve3(fromPath) !== resolve3(path);
8889
+ const fromRoot = scopeDir(from.scope, identity2, from.who);
8890
+ const root = scopeDir(scope, identity2, destination.who);
8626
8891
  const mutate = async () => {
8627
8892
  const raw = await readFileIfExists(fromPath);
8628
8893
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
@@ -8636,7 +8901,10 @@ function createNotesStore(input) {
8636
8901
  throw new NoteError("already_exists", `${noteIdentity(identity2, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
8637
8902
  }
8638
8903
  const { meta, body } = parseNote(raw);
8904
+ assertNoteUnlocked(meta, stableOptions.readonly);
8905
+ if (moved && targetRaw !== void 0) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
8639
8906
  const beforeMeta = { ...meta };
8907
+ applyNotePolicy(meta, stableOptions);
8640
8908
  meta.scope = scope;
8641
8909
  if (from.scope !== "session" && scope === "session") meta.project = identity2.projectKey;
8642
8910
  if (from.scope === "session" && scope !== "session") delete meta.project;
@@ -8664,41 +8932,48 @@ function createNotesStore(input) {
8664
8932
  if (stableOptions.crumpled === false) delete meta.crumpledAt;
8665
8933
  const bodyChanged = body !== next;
8666
8934
  const originChanged = beforeMeta.origin !== meta.origin;
8667
- if (bodyChanged || originChanged || moved) meta.updatedAt = writeStamp();
8935
+ const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
8936
+ if (bodyChanged || originChanged || policyChanged || moved) meta.updatedAt = writeStamp();
8668
8937
  const serialized = serializeNote(meta, next);
8669
8938
  assertSerializedSize(serialized);
8670
- const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
8939
+ const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
8671
8940
  let change;
8672
8941
  if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
8673
8942
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
8674
8943
  else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
8675
8944
  else change = { kind: "none", before: "", after: "" };
8945
+ await assertPinAdmission(
8946
+ root,
8947
+ noteFileName(destination.path),
8948
+ meta,
8949
+ moved ? targetRaw === void 0 ? void 0 : parseNote(targetRaw).meta : beforeMeta,
8950
+ moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : void 0
8951
+ );
8676
8952
  await atomicWrite(sameFile ? sourceReal : path, serialized);
8677
8953
  if (moved) await rm(fromPath, { force: true });
8678
- return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
8954
+ return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
8679
8955
  };
8680
- if (!differentPaths) return withPathQueue(path, mutate);
8681
- const [first, second] = [fromPath, path].sort();
8682
- return withPathQueue(first, () => withPathQueue(second, mutate));
8956
+ return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
8683
8957
  }
8684
8958
  async function rename3(fromAddress, toAddress) {
8685
- const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
8686
- return { meta, replacedCrumpledTarget };
8959
+ const { meta, warnings, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
8960
+ return { meta, warnings, replacedCrumpledTarget };
8687
8961
  }
8688
8962
  async function forget(address) {
8689
8963
  if (identity2.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
8690
8964
  const target = assertAddress(address);
8691
8965
  assertWritableNamespace(target.scope, target.who, identity2);
8692
8966
  const path = physicalPath(target.scope, target.path, identity2, target.who);
8693
- return withPathQueue(path, async () => {
8967
+ return withPathQueues([scopeDir(target.scope, identity2, target.who)], () => withPathQueue(path, async () => {
8694
8968
  const raw = await readFileIfExists(path);
8695
8969
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8696
8970
  assertDreamNote(target.scope, target.who, identity2, raw, address);
8697
8971
  const { meta } = parseNote(raw);
8972
+ assertNoteUnlocked(meta);
8698
8973
  if (meta.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity2, address).address} isn't crumpled; crumple it before deleting.`);
8699
8974
  await unlink(path);
8700
8975
  return { ...meta, scope: target.scope };
8701
- });
8976
+ }));
8702
8977
  }
8703
8978
  async function* scan(options, status) {
8704
8979
  const glob = assertGlobPattern(options.glob);
@@ -8760,8 +9035,9 @@ function createNotesStore(input) {
8760
9035
  const rows = [];
8761
9036
  for await (const note of scan(stableOptions, status)) {
8762
9037
  const { address, path, scope, meta, body } = note;
9038
+ const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
8763
9039
  if (stableQueries.length === 0) {
8764
- rows.push({ address, path, scope, meta, matches: [] });
9040
+ rows.push({ address, path, scope, meta, warnings, matches: [] });
8765
9041
  continue;
8766
9042
  }
8767
9043
  let baseChars = 0;
@@ -8773,7 +9049,7 @@ function createNotesStore(input) {
8773
9049
  }
8774
9050
  baseChars += Array.from(line).length + 1;
8775
9051
  }
8776
- if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
9052
+ if (matches.length > 0) rows.push({ address, path, scope, meta, warnings, matches });
8777
9053
  }
8778
9054
  rows.sort((a, b) => a.address.localeCompare(b.address));
8779
9055
  return { rows, status: status ?? { namespacesUnavailable: [] } };
@@ -8790,20 +9066,8 @@ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
8790
9066
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
8791
9067
  var MAX_READ_WINDOW_CHARS = 5e4;
8792
9068
  var HISTORY_PREVIEW_CHARS = 1200;
8793
- function prefixFit(text, fits) {
8794
- if (fits(text)) return text;
8795
- const chars = Array.from(text);
8796
- let low = 0;
8797
- let high = chars.length;
8798
- while (low < high) {
8799
- const mid = Math.ceil((low + high) / 2);
8800
- if (fits(chars.slice(0, mid).join(""))) low = mid;
8801
- else high = mid - 1;
8802
- }
8803
- return chars.slice(0, low).join("");
8804
- }
8805
9069
 
8806
- // src/tools/result.ts
9070
+ // src/result.ts
8807
9071
  var OperationErrorSchema = typebox_exports.Object({
8808
9072
  code: typebox_exports.String(),
8809
9073
  message: typebox_exports.String()
@@ -8817,6 +9081,8 @@ function failure(code, message) {
8817
9081
  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]`;
8818
9082
  return { ok: false, error: { code, message: bounded } };
8819
9083
  }
9084
+
9085
+ // src/tools/result.ts
8820
9086
  var WireErrorSchema = typebox_exports.Object({ error: typebox_exports.String(), code: typebox_exports.String() }, { additionalProperties: false });
8821
9087
  function wireResult(result) {
8822
9088
  if (result.ok) return result.data;
@@ -8871,190 +9137,6 @@ function renderTextWindow(window) {
8871
9137
  [truncated; continue at offset_chars=${next}]`;
8872
9138
  }
8873
9139
 
8874
- // src/history/history.ts
8875
- var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
8876
- var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
8877
- function isTextContent(part) {
8878
- return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
8879
- }
8880
- function contentText(content) {
8881
- if (typeof content === "string") return content;
8882
- return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
8883
- }
8884
- function argumentText(execution) {
8885
- return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
8886
- }
8887
- function nestedCallLine(call) {
8888
- const parts = [`${call.id} ${call.name} [${call.status}]`];
8889
- if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
8890
- if (call.error !== void 0) parts.push(`error: ${call.error}`);
8891
- parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
8892
- return `- ${parts.join(" ")}`;
8893
- }
8894
- function historyDocument(event) {
8895
- if (event.execution === void 0) return event.text;
8896
- const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
8897
- if (event.text !== "") sections.push(`--- output ---
8898
- ${event.text}`);
8899
- const nested = event.execution.nestedCalls;
8900
- if (nested !== void 0) {
8901
- const header2 = nested.complete ? "complete" : "incomplete";
8902
- sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
8903
- ${nested.calls.map(nestedCallLine).join("\n")}`);
8904
- }
8905
- return sections.join("\n");
8906
- }
8907
- var documents = /* @__PURE__ */ new WeakMap();
8908
- function eventDocument(event) {
8909
- const cached = documents.get(event);
8910
- if (cached !== void 0) return cached;
8911
- const text = historyDocument(event);
8912
- documents.set(event, text);
8913
- return text;
8914
- }
8915
- function toolEvent(item, result) {
8916
- const run = result ?? item;
8917
- const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
8918
- const truncated = run.outputTruncated === true;
8919
- return {
8920
- seq: item.seq,
8921
- windowId: item.windowId,
8922
- role: "tool",
8923
- text: result?.text ?? (item.role === "tool" ? item.text : ""),
8924
- createdAt: item.createdAt,
8925
- execution: {
8926
- name: item.toolName ?? "unknown",
8927
- status,
8928
- // A call records its arguments; a bare result records none, and gets none invented.
8929
- ...item.arguments === void 0 ? {} : { arguments: item.arguments },
8930
- ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
8931
- ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
8932
- }
8933
- };
8934
- }
8935
- function projectHistory(rawWindows, highestSeq, branchSeqs) {
8936
- const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
8937
- const resultsById = /* @__PURE__ */ new Map();
8938
- for (const item of raw) {
8939
- if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
8940
- }
8941
- const pairedResults = /* @__PURE__ */ new Map();
8942
- for (const item of raw) {
8943
- const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
8944
- if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
8945
- pairedResults.set(result.seq, item.seq);
8946
- }
8947
- }
8948
- const windows = rawWindows.map((current) => ({
8949
- windowId: current.windowId,
8950
- ...current.createdAt ? { createdAt: current.createdAt } : {},
8951
- items: current.items.flatMap((item) => {
8952
- if (pairedResults.has(item.seq)) return [];
8953
- if (item.role === "tool_call" || item.role === "tool") {
8954
- const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
8955
- const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
8956
- return [toolEvent(item, paired)];
8957
- }
8958
- return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
8959
- })
8960
- }));
8961
- return { windows, highestSeq, branchSeqs, pairedResults };
8962
- }
8963
- var NestedCallSummarySchema = typebox_exports.Object({
8964
- call_count: typebox_exports.Integer({ minimum: 0 }),
8965
- complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
8966
- }, { additionalProperties: false });
8967
- var ToolSummarySchema = typebox_exports.Object({
8968
- tool: typebox_exports.Optional(typebox_exports.String()),
8969
- tool_status: typebox_exports.Optional(ToolCallStatusSchema),
8970
- output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
8971
- full_output_path: typebox_exports.Optional(typebox_exports.String())
8972
- }, { additionalProperties: false });
8973
- function toolSummary(event) {
8974
- const execution = event.execution;
8975
- if (!execution) return {};
8976
- return {
8977
- tool: execution.name,
8978
- tool_status: execution.status,
8979
- ...execution.outputTruncated ? { output_truncated: true } : {},
8980
- ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
8981
- };
8982
- }
8983
- function nestedCallSummary(event) {
8984
- const nested = event.execution?.nestedCalls;
8985
- return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
8986
- }
8987
- var HistoryFoldedRowSchema = typebox_exports.Object({
8988
- session: typebox_exports.Optional(typebox_exports.String()),
8989
- first_seq: typebox_exports.Integer({ minimum: 1 }),
8990
- last_seq: typebox_exports.Integer({ minimum: 1 }),
8991
- count: typebox_exports.Integer({ minimum: 1 }),
8992
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
8993
- }, { additionalProperties: false });
8994
- var HistoryPageItemSchema = typebox_exports.Object({
8995
- session: typebox_exports.Optional(typebox_exports.String()),
8996
- folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
8997
- seq: typebox_exports.Integer({ minimum: 1 }),
8998
- role: HistoryRoleSchema,
8999
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
9000
- ...ToolSummarySchema.properties,
9001
- content: typebox_exports.String(),
9002
- truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
9003
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
9004
- }, { additionalProperties: false });
9005
- var MAX_FOLD_TOOL_NAMES = 20;
9006
- var MAX_FOLD_TOOL_NAME_CHARS = 120;
9007
- function visibleItem(event, maxChars, matchOffset) {
9008
- const document = eventDocument(event);
9009
- const chars = Array.from(document);
9010
- const start = matchOffset ?? 0;
9011
- const limit = Math.max(0, maxChars);
9012
- const truncated = start > 0 || start + limit < chars.length;
9013
- return {
9014
- seq: event.seq,
9015
- role: event.role,
9016
- created_at: event.createdAt ?? null,
9017
- ...toolSummary(event),
9018
- content: truncated ? chars.slice(start, start + limit).join("") : document,
9019
- truncated,
9020
- ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
9021
- };
9022
- }
9023
- function allItems(projection) {
9024
- return projection.windows.flatMap((current) => current.items);
9025
- }
9026
- function inSelection(event, params) {
9027
- if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
9028
- if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
9029
- if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
9030
- if (event.createdAt === void 0) return false;
9031
- const at = Date.parse(event.createdAt);
9032
- return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
9033
- }
9034
- function filteredItems(projection, params, conversation) {
9035
- let items = allItems(projection).filter((item) => inSelection(item, params));
9036
- if (params.roles) items = items.filter((item) => params.roles.includes(item.role));
9037
- if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
9038
- return items.sort((a, b) => a.seq - b.seq);
9039
- }
9040
-
9041
- // src/tools/schema.ts
9042
- var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
9043
- var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
9044
- var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
9045
- var InvalidQueryError = class extends Error {
9046
- constructor(message) {
9047
- super(message);
9048
- this.name = "InvalidQueryError";
9049
- }
9050
- };
9051
- function searchQueries(query) {
9052
- const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
9053
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
9054
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
9055
- return candidates.filter((candidate) => candidate !== "");
9056
- }
9057
-
9058
9140
  // src/tools/notes-context.ts
9059
9141
  import { statSync as statSync2 } from "node:fs";
9060
9142
  import { resolve as resolve4 } from "node:path";
@@ -9082,6 +9164,26 @@ var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("s
9082
9164
  var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
9083
9165
  description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
9084
9166
  }));
9167
+ var POLICY_PARAMETERS = {
9168
+ pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
9169
+ budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 2048 for every note). Over budget warns but saves; boot does not truncate." })),
9170
+ readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
9171
+ };
9172
+ var PolicySchema = {
9173
+ pinned: typebox_exports.Boolean(),
9174
+ budget: typebox_exports.Integer(),
9175
+ readonly: typebox_exports.Boolean()
9176
+ };
9177
+ var WarningsSchema = { warnings: typebox_exports.Array(typebox_exports.String()) };
9178
+ function policyAt(meta, address) {
9179
+ return effectiveNotePolicy(meta, noteFileName(assertAddress(address).path));
9180
+ }
9181
+ function renderPolicy(policy) {
9182
+ return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
9183
+ }
9184
+ function withWarnings(text, data) {
9185
+ return [text, ...data.warnings].join("\n");
9186
+ }
9085
9187
  var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
9086
9188
  var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
9087
9189
  var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
@@ -9095,11 +9197,12 @@ function failureOf(error) {
9095
9197
  if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
9096
9198
  throw error;
9097
9199
  }
9098
- var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
9200
+ var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly"]);
9099
9201
  var MAX_METADATA_ENTRY_BYTES = 1024;
9100
9202
  var MAX_METADATA_VERBATIM_BYTES = 2048;
9101
9203
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9102
9204
  var NoteMetadataSchema = typebox_exports.Object({
9205
+ ...PolicySchema,
9103
9206
  origin: typebox_exports.Union([...ORIGIN_VALUES]),
9104
9207
  created_at: typebox_exports.String(),
9105
9208
  updated_at: typebox_exports.String(),
@@ -9107,7 +9210,7 @@ var NoteMetadataSchema = typebox_exports.Object({
9107
9210
  project: typebox_exports.Optional(typebox_exports.String()),
9108
9211
  extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
9109
9212
  }, { additionalProperties: false });
9110
- function noteMetadata(meta) {
9213
+ function noteMetadata(meta, address) {
9111
9214
  const extra = {};
9112
9215
  let verbatimBytes = 0;
9113
9216
  const put = (key, value) => {
@@ -9125,6 +9228,7 @@ function noteMetadata(meta) {
9125
9228
  put(key, value);
9126
9229
  }
9127
9230
  return {
9231
+ ...policyAt(meta, address),
9128
9232
  origin: meta.origin,
9129
9233
  created_at: localIso(meta.createdAt),
9130
9234
  updated_at: localIso(meta.updatedAt),
@@ -9135,6 +9239,7 @@ function noteMetadata(meta) {
9135
9239
  }
9136
9240
  function renderMetadata(metadata) {
9137
9241
  const fields = [
9242
+ renderPolicy(metadata),
9138
9243
  `origin ${metadata.origin}`,
9139
9244
  `created ${metadata.created_at}`,
9140
9245
  `updated ${metadata.updated_at}`,
@@ -9163,6 +9268,8 @@ var NoteIdentitySchema = {
9163
9268
  };
9164
9269
  var ListedFileSchema = typebox_exports.Object({
9165
9270
  ...NoteIdentitySchema,
9271
+ ...PolicySchema,
9272
+ ...WarningsSchema,
9166
9273
  updated_at: typebox_exports.String(),
9167
9274
  crumpled_at: typebox_exports.Optional(typebox_exports.String())
9168
9275
  }, { additionalProperties: false });
@@ -9181,16 +9288,21 @@ var SnapshotSchema = {
9181
9288
  };
9182
9289
  var NotesWriteDataSchema = typebox_exports.Object({
9183
9290
  ...NoteIdentitySchema,
9291
+ ...PolicySchema,
9292
+ ...WarningsSchema,
9184
9293
  outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
9185
9294
  }, { additionalProperties: false });
9186
9295
  var NotesUpdateDataSchema = typebox_exports.Object({
9187
9296
  ...NoteIdentitySchema,
9297
+ ...PolicySchema,
9298
+ ...WarningsSchema,
9188
9299
  change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
9189
9300
  rename_from: typebox_exports.Optional(typebox_exports.String())
9190
9301
  }, { additionalProperties: false });
9191
9302
  var NotesReadDataSchema = typebox_exports.Object({
9192
9303
  ...NoteIdentitySchema,
9193
9304
  metadata: NoteMetadataSchema,
9305
+ ...WarningsSchema,
9194
9306
  ...TextWindowSchema.properties
9195
9307
  }, { additionalProperties: false });
9196
9308
  var NotesListDataSchema = typebox_exports.Object({
@@ -9222,11 +9334,12 @@ function snapshot(rows, limit, status, renderData, shrink) {
9222
9334
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
9223
9335
  }
9224
9336
  function listedFile(row, identity2) {
9225
- return { ...noteIdentity(identity2, row.address), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9337
+ const policy = policyAt(row.meta, row.address);
9338
+ return { ...noteIdentity(identity2, row.address), ...policy, warnings: row.warnings ?? (row.body === void 0 ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9226
9339
  }
9227
- var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, cwd: CWD_PARAMETER }, { additionalProperties: false });
9340
+ var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9228
9341
  function renderWriteData(data) {
9229
- return `${data.outcome} ${renderIdentity(data)}`;
9342
+ return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
9230
9343
  }
9231
9344
  var notesWrite = {
9232
9345
  name: "notes_write",
@@ -9238,8 +9351,8 @@ var notesWrite = {
9238
9351
  async execute(params, context2) {
9239
9352
  try {
9240
9353
  const identity2 = notesIdentityForCall(context2, params.cwd);
9241
- const { outcome } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin });
9242
- return success({ ...noteIdentity(identity2, params.address), outcome });
9354
+ const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
9355
+ return success({ ...noteIdentity(identity2, params.address), outcome, ...policyAt(meta, params.address), warnings });
9243
9356
  } catch (error) {
9244
9357
  return failureOf(error);
9245
9358
  }
@@ -9250,18 +9363,20 @@ var notesUpdateParameters = typebox_exports.Object({
9250
9363
  address: typebox_exports.String(),
9251
9364
  edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
9252
9365
  origin: ORIGIN,
9366
+ ...POLICY_PARAMETERS,
9253
9367
  crumpled: CRUMPLED_PARAMETER,
9254
9368
  replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
9255
9369
  rename_to: typebox_exports.Optional(typebox_exports.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." })),
9256
9370
  cwd: CWD_PARAMETER
9257
9371
  }, { additionalProperties: false });
9258
9372
  function renderUpdateData(data) {
9259
- return data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
9373
+ const receipt = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
9374
+ return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
9260
9375
  }
9261
9376
  var notesUpdate = {
9262
9377
  name: "notes_update",
9263
9378
  label: "Notes update",
9264
- description: `Change part of a note's body, its origin or crumpled state, or its address. When things change, replace the stale part in place; don't just tack an update onto the bottom. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
9379
+ description: `Change part of a note's body, policy (pinned/budget/readonly), origin, crumpled state, or address. A readonly note requires explicit readonly:false before any change, or in the same call. When things change, replace the stale part in place; don't just tack an update onto the bottom. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
9265
9380
  parameters: notesUpdateParameters,
9266
9381
  outputSchema: resultSchema(NotesUpdateDataSchema),
9267
9382
  executionMode: "sequential",
@@ -9270,11 +9385,11 @@ var notesUpdate = {
9270
9385
  const identity2 = notesIdentityForCall(context2, params.cwd);
9271
9386
  const store = createNotesStore(identity2);
9272
9387
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
9273
- const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9388
+ const { change, moved, meta, warnings } = await store.update(params.address, params.edits, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9274
9389
  onChange?.(change);
9275
9390
  const from = noteIdentity(identity2, params.address).address;
9276
9391
  const to = noteIdentity(identity2, renameTo ?? params.address);
9277
- return success({ ...to, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
9392
+ return success({ ...to, ...policyAt(meta, to.address), warnings, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
9278
9393
  } catch (error) {
9279
9394
  return failureOf(error);
9280
9395
  }
@@ -9283,8 +9398,8 @@ var notesUpdate = {
9283
9398
  };
9284
9399
  var notesReadParameters = typebox_exports.Object({ address: typebox_exports.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
9285
9400
  function renderReadData(data) {
9286
- return `${renderIdentity(data)}
9287
- ${renderMetadata(data.metadata)}
9401
+ return withWarnings(`${renderIdentity(data)}
9402
+ ${renderMetadata(data.metadata)}`, data) + `
9288
9403
 
9289
9404
  ${renderTextWindow(data)}`;
9290
9405
  }
@@ -9302,8 +9417,9 @@ var notesRead = {
9302
9417
  if (!note) return failure("not_found", `No note at ${resolved.address}.`);
9303
9418
  const totalChars = Array.from(note.body).length;
9304
9419
  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.`);
9305
- const metadata = noteMetadata(note.meta);
9306
- return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
9420
+ const metadata = noteMetadata(note.meta, resolved.address);
9421
+ const warnings = noteBudgetWarnings(note.body, metadata);
9422
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
9307
9423
  } catch (error) {
9308
9424
  return failureOf(error);
9309
9425
  }
@@ -9314,7 +9430,8 @@ var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit:
9314
9430
  function renderListData(data) {
9315
9431
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9316
9432
  for (const file of data.files) {
9317
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.last_accessed === void 0 ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
9433
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at}${file.last_accessed === void 0 ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
9434
+ lines.push(...file.warnings.map((warning) => ` ${warning}`));
9318
9435
  }
9319
9436
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9320
9437
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
@@ -9341,7 +9458,8 @@ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Opti
9341
9458
  function renderSearchData(data) {
9342
9459
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9343
9460
  for (const file of data.files) {
9344
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
9461
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
9462
+ lines.push(...file.warnings.map((warning) => ` ${warning}`));
9345
9463
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9346
9464
  }
9347
9465
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -9447,7 +9565,7 @@ function prepareSelection(projection, params) {
9447
9565
  const folds = !params.roles && params.query === void 0;
9448
9566
  const candidates = [];
9449
9567
  let run = [];
9450
- for (const event of filteredItems(projection, params, false)) {
9568
+ for (const event of filteredItems(projection, params)) {
9451
9569
  if (folds && (event.role === "tool" || event.role === "context")) {
9452
9570
  run.push(event);
9453
9571
  continue;
@@ -9497,7 +9615,7 @@ function corpusSelection(params) {
9497
9615
  return resolveSelection(params);
9498
9616
  }
9499
9617
  function sessionRepresentative(projection, scoped) {
9500
- const events = filteredItems(projection, scoped, false).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
9618
+ const events = filteredItems(projection, scoped).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
9501
9619
  if (scoped.roles) return events.at(-1);
9502
9620
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9503
9621
  }
@@ -9541,7 +9659,7 @@ var CorpusCollector = class {
9541
9659
  /** Returns whether this session contributes an overview representative. */
9542
9660
  add(session, projection) {
9543
9661
  if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
9544
- for (const event of filteredItems(projection, this.scoped, false)) {
9662
+ for (const event of filteredItems(projection, this.scoped)) {
9545
9663
  const document = eventDocument(event);
9546
9664
  if ((event.role === "user" || event.role === "assistant") && document === "") continue;
9547
9665
  const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
@@ -9577,10 +9695,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
9577
9695
  break;
9578
9696
  }
9579
9697
  const page = pageData(prepared, start, end, maxChars);
9580
- if (!fits(page)) {
9581
- const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
9582
- return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
9583
- }
9698
+ if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
9584
9699
  return success(page);
9585
9700
  }
9586
9701
 
@@ -9708,6 +9823,12 @@ function renderRead(data) {
9708
9823
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9709
9824
  }
9710
9825
  var plainText = (text) => text;
9826
+ function pageOutcome(result) {
9827
+ if (!("pageTooLarge" in result)) return result;
9828
+ const { count, multi } = result.pageTooLarge;
9829
+ const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
9830
+ return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
9831
+ }
9711
9832
  var sessionParameter = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
9712
9833
  var historyListParameters = typebox_exports.Object({
9713
9834
  session: sessionParameter,
@@ -9730,7 +9851,7 @@ var historyList = {
9730
9851
  async execute(params, context2, wrapText = plainText) {
9731
9852
  const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
9732
9853
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
9733
- if (params.session === void 0) return selectPage(await currentHistory(context2), params, fits, maxChars);
9854
+ if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), params, fits, maxChars));
9734
9855
  const selector = parseSessionSelector(params.session);
9735
9856
  if (!selector.ok) return selector;
9736
9857
  const corpus = "corpus" in context2 ? context2.corpus : void 0;
@@ -9759,7 +9880,7 @@ var historyList = {
9759
9880
  }
9760
9881
  }
9761
9882
  const notice2 = notices.length ? { notice: notices.join("") } : {};
9762
- const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
9883
+ const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
9763
9884
  return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
9764
9885
  }
9765
9886
  const target = await resolveSession(corpus, selector.data);
@@ -9767,7 +9888,7 @@ var historyList = {
9767
9888
  const loaded = await loadHistorySession(target.data);
9768
9889
  if (!loaded.ok) return loaded;
9769
9890
  const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
9770
- const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
9891
+ const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
9771
9892
  return result.ok ? success({ ...result.data, ...notice }) : result;
9772
9893
  },
9773
9894
  render: (result) => renderOutcome(result, renderPage)
@@ -11061,8 +11182,6 @@ async function loadNotesSnapshot(identity2, openedAt, loadNamespace) {
11061
11182
 
11062
11183
  // src/boot/text.ts
11063
11184
  var SHELF_FRESH_LIMIT = 3;
11064
- var CHEATSHEET_BOOT_MAX_CHARS = 1536;
11065
- var MAP_BOOT_MAX_CHARS = 4096;
11066
11185
  var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
11067
11186
  var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
11068
11187
  var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -11105,9 +11224,15 @@ Still a tie? *shrugs* You've got a brain. Use it.
11105
11224
  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\`.
11106
11225
  ${NOTES_PROTOCOL_CLOSE_TAG}`;
11107
11226
  var MAPS_BLOCK = `<notesoup:maps>
11108
- Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
11109
- Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
11110
- wakes up next reads them, and next is you. So keep them short, and keep them true.
11227
+ Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
11228
+ Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
11229
+ reads them, and next is you. So keep them short, and keep them true.
11230
+
11231
+ Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
11232
+ live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
11233
+ starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
11234
+ and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
11235
+ explicitly set \`readonly:false\` to unlock, on its own or with your changes.
11111
11236
 
11112
11237
  - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
11113
11238
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -11179,20 +11304,22 @@ function notesIndex(snapshot2, tools, agentName, modelName) {
11179
11304
  continue;
11180
11305
  }
11181
11306
  const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
11182
- const pinned = ["CHEATSHEET.md", "MAP.md"].flatMap((path) => {
11183
- const row = rows.find((row2) => row2.path === path);
11184
- return row?.body ? [row] : [];
11185
- });
11186
- const fresh = rows.filter((row) => row.path !== "MAP.md" && row.path !== "CHEATSHEET.md").slice(0, SHELF_FRESH_LIMIT).map((row) => {
11307
+ const pins = rows.filter((row) => effectiveNotePolicy(row.meta, row.path).pinned).sort((a, b) => pinnedPageOrder(a.path) - pinnedPageOrder(b.path) || a.path.localeCompare(b.path));
11308
+ const pinned = pins.slice(0, MAX_PINNED_NOTES);
11309
+ const fresh = rows.filter((row) => !effectiveNotePolicy(row.meta, row.path).pinned).slice(0, SHELF_FRESH_LIMIT).map((row) => {
11187
11310
  const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
11188
11311
  const title = feedTitle(row.body);
11189
11312
  return title === void 0 ? ` ${locator}` : ` ${title}
11190
11313
  ${locator}`;
11191
11314
  });
11192
11315
  if (pinned.length === 0 && fresh.length === 0) continue;
11193
- const parts = pinned.map((row) => `${row.address}
11316
+ const parts = pinned.map((row) => {
11317
+ const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
11318
+ return `${row.address}
11194
11319
 
11195
- ${indent(pinnedBodyForBoot(row.address, row.body, row.path === "MAP.md" ? MAP_BOOT_MAX_CHARS : CHEATSHEET_BOOT_MAX_CHARS))}`);
11320
+ ${indent([...warnings, row.body].join("\n"))}`;
11321
+ });
11322
+ if (pins.length > MAX_PINNED_NOTES) parts.push(indent(`Warning: only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`));
11196
11323
  if (fresh.length > 0) parts.push(`recent
11197
11324
 
11198
11325
  ${fresh.join("\n\n")}`);
@@ -11200,13 +11327,7 @@ ${fresh.join("\n\n")}`);
11200
11327
  }
11201
11328
  return shelves.length > 0 ? ["YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500", ...shelves].join("\n\n\n") : "YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nNone yet. A blank slate is a fine place to start \u2014 just don't finish there.";
11202
11329
  }
11203
- function pinnedBodyForBoot(address, body, maxChars) {
11204
- const chars = Array.from(body);
11205
- if (chars.length <= maxChars) return body;
11206
- return `${chars.slice(0, maxChars).join("")}
11207
- [truncated at ${maxChars} chars; slim this page down, full body at \`${address}\`]`;
11208
- }
11209
- function renderBootBlock(data) {
11330
+ function renderIdentity2(data) {
11210
11331
  const shown2 = /* @__PURE__ */ new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
11211
11332
  const windows = data.tree.windows.filter((_window, index) => shown2.has(index));
11212
11333
  const width = Math.max(8, ...windows.map((window) => window.shortName.length));
@@ -11220,10 +11341,12 @@ function renderBootBlock(data) {
11220
11341
  return `${window.isCurrent ? "\u2514\u2500" : "\u251C\u2500"} ${name}${range}${window.isCurrent ? " \u2190 you are here" : ""}`;
11221
11342
  })
11222
11343
  ];
11223
- const identity2 = `${WINDOW_IDENTITY_OPEN_TAG}
11344
+ return `${WINDOW_IDENTITY_OPEN_TAG}
11224
11345
  ${lines.join("\n")}
11225
11346
  ${WINDOW_IDENTITY_CLOSE_TAG}`;
11226
- return [identity2, renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
11347
+ }
11348
+ function renderBootBlock(data) {
11349
+ return [renderIdentity2(data), renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
11227
11350
  }
11228
11351
 
11229
11352
  // src/budget/text.ts
@@ -11248,7 +11371,7 @@ function selectContinuation(origin) {
11248
11371
  return pool[Math.floor(Math.random() * pool.length)];
11249
11372
  }
11250
11373
  var WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
11251
- var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim CHEATSHEET.md and MAP.md; every new window loads them. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
11374
+ var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md and MAP.md by default); every new window loads the pins. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
11252
11375
  var WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
11253
11376
  function warningPrompt() {
11254
11377
  return `${WARNING_TIMING}
@@ -11333,21 +11456,10 @@ function settingFlag(settings2) {
11333
11456
  return isPlainObject(settings2) && typeof settings2.autoCompactEnabled === "boolean" ? settings2.autoCompactEnabled : void 0;
11334
11457
  }
11335
11458
  function configuredWindow(settings2, env, model) {
11336
- const windows = [];
11337
- const fromEnv = positiveNumber(env.autoCompactWindow);
11338
- if (fromEnv !== void 0) windows.push(fromEnv);
11339
- if (typeof model === "string" && model.length > 0 && isPlainObject(settings2)) {
11340
- const modelSettings = isPlainObject(settings2.modelSettings) ? settings2.modelSettings : {};
11341
- const perModel = modelSettings[model];
11342
- if (isPlainObject(perModel)) {
11343
- const value = positiveNumber(perModel.autoCompactWindow);
11344
- if (value !== void 0) windows.push(value);
11345
- }
11346
- }
11347
- if (isPlainObject(settings2)) {
11348
- const value = positiveNumber(settings2.autoCompactWindow);
11349
- if (value !== void 0) windows.push(value);
11350
- }
11459
+ const root = isPlainObject(settings2) ? settings2 : {};
11460
+ const models = isPlainObject(root.modelSettings) ? root.modelSettings : {};
11461
+ const perModel = typeof model === "string" && model.length > 0 ? models[model] : void 0;
11462
+ const windows = [env.autoCompactWindow, isPlainObject(perModel) ? perModel.autoCompactWindow : void 0, root.autoCompactWindow].map(positiveNumber).filter((value) => value !== void 0);
11351
11463
  return windows.length === 0 ? void 0 : Math.min(...windows);
11352
11464
  }
11353
11465
  function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
@@ -11364,21 +11476,6 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
11364
11476
  warningRunway
11365
11477
  };
11366
11478
  }
11367
- function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
11368
- const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
11369
- const native = pct === void 0 ? base : Math.min(pct, base);
11370
- const reset = Math.max(MIN_POINT_PERCENT, native - resetMargin / ASSUMED_WINDOW_TOKENS * 100);
11371
- return {
11372
- source: "percent",
11373
- autoCompact,
11374
- unit: "percent",
11375
- native,
11376
- reset,
11377
- warn: Math.max(MIN_POINT_PERCENT, reset - warningRunway / ASSUMED_WINDOW_TOKENS * 100),
11378
- resetMargin,
11379
- warningRunway
11380
- };
11381
- }
11382
11479
  function resolveClaudeLimits(facts) {
11383
11480
  const root = isPlainObject(facts) ? facts : {};
11384
11481
  const usage = isPlainObject(root.usage) ? root.usage : {};
@@ -11392,19 +11489,25 @@ function resolveClaudeLimits(facts) {
11392
11489
  const pct = percent(env.pctOverride);
11393
11490
  const threshold = positiveNumber(breakdown.autoCompactThreshold);
11394
11491
  if (autoCompact && threshold !== void 0) {
11395
- const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
11396
- if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
11492
+ const native2 = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
11493
+ if (native2 > 0) return tokenLimits("auto-compact", true, native2, resetMargin, warningRunway);
11397
11494
  }
11398
11495
  const window = positiveNumber(usage.window);
11399
- if (window !== void 0) {
11400
- const configured = configuredWindow(settings2, env, breakdown.model);
11401
- const effective = Math.min(configured ?? window, window);
11402
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
11403
- const threshold2 = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
11404
- const native = autoCompact ? pct === void 0 ? threshold2 : Math.min(Math.floor(available * (pct / 100)), threshold2) : available;
11405
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
11406
- }
11407
- return percentLimits(autoCompact, pct, resetMargin, warningRunway);
11496
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
11497
+ const configured = configuredWindow(settings2, env, breakdown.model);
11498
+ const effective = Math.min(configured ?? capacity, capacity);
11499
+ const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
11500
+ const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
11501
+ const native = autoCompact ? pct === void 0 ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow) : available;
11502
+ const limits = tokenLimits(window === void 0 ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
11503
+ if (window !== void 0) return limits;
11504
+ return {
11505
+ ...limits,
11506
+ unit: "percent",
11507
+ native: limits.native / capacity * 100,
11508
+ reset: Math.max(MIN_POINT_PERCENT, limits.reset / capacity * 100),
11509
+ warn: Math.max(MIN_POINT_PERCENT, limits.warn / capacity * 100)
11510
+ };
11408
11511
  }
11409
11512
 
11410
11513
  // plugins/claude/src/helper.ts
@@ -11414,13 +11517,6 @@ function identity(input) {
11414
11517
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
11415
11518
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd, input.home), agent: input.agent, model: input.model });
11416
11519
  }
11417
- function paramProblem(schema, params) {
11418
- const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
11419
- if (!first) return "unrecognized shape";
11420
- const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
11421
- const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
11422
- return `${field ? `${field} ` : ""}${first.message}${extra}`;
11423
- }
11424
11520
  function boundOperation(operation) {
11425
11521
  return {
11426
11522
  description: operation.description,