notesoup 0.57.4 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) 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 +5 -18
  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 +7 -6
  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/dsh.md +1 -1
  77. package/docs/notes-library.md +19 -6
  78. package/docs/reset-lifecycle.md +2 -2
  79. package/docs/tool-results.md +3 -1
  80. package/package.json +12 -12
  81. package/playbook.md +1 -1
  82. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  83. package/plugins/claude/dist/claude/helper.js +527 -422
  84. package/plugins/claude/hooks/register.ts +1 -10
  85. package/plugins/claude/playbook.md +1 -1
  86. package/plugins/claude/skills/dream/SKILL.md +1 -1
  87. package/plugins/claude/skills/memory/SKILL.md +1 -1
  88. package/plugins/claude/src/helper.ts +2 -11
  89. package/plugins/claude/src/thresholds.ts +5 -15
  90. package/plugins/codex/dist/codex/notesoup.js +519 -403
  91. package/plugins/codex/src/mcp.ts +5 -12
  92. package/plugins/codex/src/state.ts +1 -1
  93. package/plugins/dsh/tools.ts +2 -1
  94. package/plugins/pi/boot.ts +3 -4
  95. package/plugins/pi/budget.ts +1 -1
  96. package/plugins/pi/render.ts +20 -8
  97. package/plugins/pi/runtime.ts +6 -2
  98. package/plugins/pi/tool-result.ts +2 -1
  99. package/plugins/pi/window.ts +20 -1
  100. package/skills/dream/SKILL.md +1 -1
  101. package/skills/memory/SKILL.md +1 -1
  102. package/src/boot/render.ts +24 -21
  103. package/src/boot/text.ts +12 -9
  104. package/src/budget/text.ts +1 -1
  105. package/src/history/corpus.ts +1 -1
  106. package/src/history/history.ts +5 -6
  107. package/src/history/query.ts +11 -14
  108. package/src/index.ts +5 -2
  109. package/src/notes/constants.ts +1 -1
  110. package/src/notes/errors.ts +1 -1
  111. package/src/notes/frontmatter.ts +4 -2
  112. package/src/notes/index.ts +1 -0
  113. package/src/notes/policy.ts +49 -0
  114. package/src/notes/store.ts +63 -24
  115. package/src/result.ts +26 -0
  116. package/src/text-match.ts +32 -0
  117. package/src/tools/dream.ts +2 -1
  118. package/src/tools/history.ts +15 -6
  119. package/src/tools/notes.ts +60 -20
  120. package/src/tools/output.ts +1 -17
  121. package/src/tools/result.ts +4 -26
  122. package/src/tools/schema.ts +11 -17
  123. package/dist/plugins/codex/src/history.d.ts +0 -3
  124. package/dist/plugins/codex/src/history.js +0 -2
  125. package/dist/plugins/codex/src/transcript.d.ts +0 -3
  126. package/dist/plugins/codex/src/transcript.js +0 -2
  127. package/plugins/codex/src/history.ts +0 -3
  128. package/plugins/codex/src/transcript.ts +0 -3
@@ -24824,146 +24824,181 @@ __export(typebox_exports, {
24824
24824
  With: () => With2
24825
24825
  });
24826
24826
 
24827
- // src/notes/frontmatter.ts
24828
- var SCOPES = ["session", "project", "human", "agent", "model"];
24829
- var ORIGINS = ["user", "self", "external"];
24830
- var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
24831
- var KNOWN_KEYS = ["origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
24832
- var pad2 = (value) => String(value).padStart(2, "0");
24833
- function localIso(epochMs) {
24834
- const date3 = new Date(epochMs);
24835
- const offsetMinutes = -date3.getTimezoneOffset();
24836
- const absOffset = Math.abs(offsetMinutes);
24837
- const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
24838
- const wallClock = `${date3.getFullYear()}-${pad2(date3.getMonth() + 1)}-${pad2(date3.getDate())}T${pad2(date3.getHours())}:${pad2(date3.getMinutes())}:${pad2(date3.getSeconds())}.${String(date3.getMilliseconds()).padStart(3, "0")}`;
24839
- return `${wallClock}${offset}`;
24827
+ // src/history/history.ts
24828
+ var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
24829
+ var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
24830
+ function isTextContent(part) {
24831
+ return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
24840
24832
  }
24841
- function isScope(value) {
24842
- return typeof value === "string" && SCOPES.includes(value);
24833
+ function contentText(content) {
24834
+ if (typeof content === "string") return content;
24835
+ return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
24843
24836
  }
24844
- function isOrigin(value) {
24845
- return typeof value === "string" && ORIGINS.includes(value);
24837
+ function argumentText(execution) {
24838
+ return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
24846
24839
  }
24847
- function toEpoch(value, fallback) {
24848
- if (typeof value === "number" && Number.isFinite(value)) return value;
24849
- if (typeof value === "string") {
24850
- const parsed = Date.parse(value);
24851
- if (Number.isFinite(parsed)) return parsed;
24852
- }
24853
- return fallback;
24840
+ function nestedCallLine(call) {
24841
+ const parts = [`${call.id} ${call.name} [${call.status}]`];
24842
+ if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
24843
+ if (call.error !== void 0) parts.push(`error: ${call.error}`);
24844
+ parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
24845
+ return `- ${parts.join(" ")}`;
24854
24846
  }
24855
- function parseScalar(text2) {
24856
- const trimmed = text2.trim();
24857
- if (trimmed === "") return "";
24858
- try {
24859
- return JSON.parse(trimmed);
24860
- } catch {
24861
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
24862
- return trimmed;
24847
+ function historyDocument(event) {
24848
+ if (event.execution === void 0) return event.text;
24849
+ const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
24850
+ if (event.text !== "") sections.push(`--- output ---
24851
+ ${event.text}`);
24852
+ const nested = event.execution.nestedCalls;
24853
+ if (nested !== void 0) {
24854
+ const header2 = nested.complete ? "complete" : "incomplete";
24855
+ sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
24856
+ ${nested.calls.map(nestedCallLine).join("\n")}`);
24863
24857
  }
24858
+ return sections.join("\n");
24864
24859
  }
24865
- function parseFrontmatter(raw) {
24866
- const stripped = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
24867
- const lines = stripped.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
24868
- if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
24869
- let close = -1;
24870
- for (let index = 1; index < lines.length; index++) {
24871
- if (lines[index]?.trim() === "---") {
24872
- close = index;
24873
- break;
24860
+ var documents = /* @__PURE__ */ new WeakMap();
24861
+ function eventDocument(event) {
24862
+ const cached2 = documents.get(event);
24863
+ if (cached2 !== void 0) return cached2;
24864
+ const text2 = historyDocument(event);
24865
+ documents.set(event, text2);
24866
+ return text2;
24867
+ }
24868
+ function toolEvent(item, result) {
24869
+ const run = result ?? item;
24870
+ const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
24871
+ const truncated = run.outputTruncated === true;
24872
+ return {
24873
+ seq: item.seq,
24874
+ windowId: item.windowId,
24875
+ role: "tool",
24876
+ text: result?.text ?? (item.role === "tool" ? item.text : ""),
24877
+ createdAt: item.createdAt,
24878
+ execution: {
24879
+ name: item.toolName ?? "unknown",
24880
+ status,
24881
+ // A call records its arguments; a bare result records none, and gets none invented.
24882
+ ...item.arguments === void 0 ? {} : { arguments: item.arguments },
24883
+ ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
24884
+ ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
24874
24885
  }
24886
+ };
24887
+ }
24888
+ function projectHistory(rawWindows, highestSeq, branchSeqs) {
24889
+ const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
24890
+ const resultsById = /* @__PURE__ */ new Map();
24891
+ for (const item of raw) {
24892
+ if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
24875
24893
  }
24876
- if (close === -1) return { fields: {}, body: raw };
24877
- const fields = /* @__PURE__ */ Object.create(null);
24878
- for (let index = 1; index < close; index++) {
24879
- const line = lines[index];
24880
- const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
24881
- if (!match) continue;
24882
- const key = match[1];
24883
- const rest2 = match[2];
24884
- if (rest2.trim() === "") {
24885
- const items = [];
24886
- while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
24887
- index++;
24888
- items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
24889
- }
24890
- fields[key] = items;
24891
- } else {
24892
- fields[key] = parseScalar(rest2);
24894
+ const pairedResults = /* @__PURE__ */ new Map();
24895
+ for (const item of raw) {
24896
+ const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
24897
+ if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
24898
+ pairedResults.set(result.seq, item.seq);
24893
24899
  }
24894
24900
  }
24895
- const rest = lines.slice(close + 1);
24896
- if (rest[0] === "") rest.shift();
24897
- return { fields, body: rest.join("\n") };
24901
+ const windows = rawWindows.map((current) => ({
24902
+ windowId: current.windowId,
24903
+ ...current.createdAt ? { createdAt: current.createdAt } : {},
24904
+ items: current.items.flatMap((item) => {
24905
+ if (pairedResults.has(item.seq)) return [];
24906
+ if (item.role === "tool_call" || item.role === "tool") {
24907
+ const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
24908
+ const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
24909
+ return [toolEvent(item, paired)];
24910
+ }
24911
+ return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
24912
+ })
24913
+ }));
24914
+ return { windows, highestSeq, branchSeqs, pairedResults };
24898
24915
  }
24899
- function parseNote(raw, now = Date.now()) {
24900
- const { fields, body } = parseFrontmatter(raw);
24901
- const meta2 = { ...fields };
24902
- meta2.scope = isScope(meta2.scope) ? meta2.scope : "session";
24903
- meta2.origin = isOrigin(meta2.origin) ? meta2.origin : "self";
24904
- for (const key of TIMESTAMP_KEYS) meta2[key] = toEpoch(meta2[key], now);
24905
- meta2.accessCount = typeof meta2.accessCount === "number" && Number.isFinite(meta2.accessCount) ? meta2.accessCount : 0;
24906
- return { meta: meta2, body };
24916
+ var NestedCallSummarySchema = typebox_exports.Object({
24917
+ call_count: typebox_exports.Integer({ minimum: 0 }),
24918
+ complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
24919
+ }, { additionalProperties: false });
24920
+ var ToolSummarySchema = typebox_exports.Object({
24921
+ tool: typebox_exports.Optional(typebox_exports.String()),
24922
+ tool_status: typebox_exports.Optional(ToolCallStatusSchema),
24923
+ output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
24924
+ full_output_path: typebox_exports.Optional(typebox_exports.String())
24925
+ }, { additionalProperties: false });
24926
+ function toolSummary(event) {
24927
+ const execution = event.execution;
24928
+ if (!execution) return {};
24929
+ return {
24930
+ tool: execution.name,
24931
+ tool_status: execution.status,
24932
+ ...execution.outputTruncated ? { output_truncated: true } : {},
24933
+ ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
24934
+ };
24907
24935
  }
24908
- function yamlScalar(value) {
24909
- if (typeof value === "string") {
24910
- const reserved = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
24911
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
24912
- }
24913
- return JSON.stringify(value);
24936
+ function nestedCallSummary(event) {
24937
+ const nested = event.execution?.nestedCalls;
24938
+ return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
24914
24939
  }
24915
- function parsesAsNonString(text2) {
24916
- try {
24917
- return typeof JSON.parse(text2) !== "string";
24918
- } catch {
24919
- return false;
24920
- }
24940
+ var HistoryFoldedRowSchema = typebox_exports.Object({
24941
+ session: typebox_exports.Optional(typebox_exports.String()),
24942
+ first_seq: typebox_exports.Integer({ minimum: 1 }),
24943
+ last_seq: typebox_exports.Integer({ minimum: 1 }),
24944
+ count: typebox_exports.Integer({ minimum: 1 }),
24945
+ tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
24946
+ }, { additionalProperties: false });
24947
+ var HistoryPageItemSchema = typebox_exports.Object({
24948
+ session: typebox_exports.Optional(typebox_exports.String()),
24949
+ folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
24950
+ seq: typebox_exports.Integer({ minimum: 1 }),
24951
+ role: HistoryRoleSchema,
24952
+ created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
24953
+ ...ToolSummarySchema.properties,
24954
+ content: typebox_exports.String(),
24955
+ truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
24956
+ offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
24957
+ }, { additionalProperties: false });
24958
+ var MAX_FOLD_TOOL_NAMES = 20;
24959
+ var MAX_FOLD_TOOL_NAME_CHARS = 120;
24960
+ function visibleItem(event, maxChars, matchOffset) {
24961
+ const document = eventDocument(event);
24962
+ const chars = Array.from(document);
24963
+ const start = matchOffset ?? 0;
24964
+ const limit = Math.max(0, maxChars);
24965
+ const truncated = start > 0 || start + limit < chars.length;
24966
+ return {
24967
+ seq: event.seq,
24968
+ role: event.role,
24969
+ created_at: event.createdAt ?? null,
24970
+ ...toolSummary(event),
24971
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
24972
+ truncated,
24973
+ ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
24974
+ };
24921
24975
  }
24922
- function serializeNote(meta2, body) {
24923
- const lines = [];
24924
- for (const key of KNOWN_KEYS) {
24925
- const value = meta2[key];
24926
- if (value === void 0) continue;
24927
- if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
24928
- else lines.push(`${key}: ${yamlScalar(value)}`);
24929
- }
24930
- for (const key of Object.keys(meta2)) {
24931
- if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
24932
- if (meta2[key] === void 0) continue;
24933
- lines.push(`${key}: ${yamlScalar(meta2[key])}`);
24934
- }
24935
- return `---
24936
- ${lines.join("\n")}
24937
- ---
24938
-
24939
- ${body}`;
24976
+ function allItems(projection) {
24977
+ return projection.windows.flatMap((current) => current.items);
24940
24978
  }
24941
- function stripLeadingFrontmatter(content) {
24942
- return parseFrontmatter(content).body;
24979
+ function inSelection(event, params) {
24980
+ if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
24981
+ if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
24982
+ if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
24983
+ if (event.createdAt === void 0) return false;
24984
+ const at = Date.parse(event.createdAt);
24985
+ return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
24943
24986
  }
24944
-
24945
- // src/notes/fs-error.ts
24946
- function isFilesystemError(error2) {
24947
- const code = typeof error2 === "object" && error2 !== null ? error2.code : void 0;
24948
- return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
24987
+ function filteredItems(projection, params) {
24988
+ return allItems(projection).filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role))).sort((a, b) => a.seq - b.seq);
24949
24989
  }
24950
24990
 
24951
- // src/notes/store.ts
24952
- import { randomUUID as randomUUID2 } from "node:crypto";
24953
- import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
24954
- import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
24955
-
24956
- // src/text-match.ts
24957
- function earliestMatchOffsetChars(text2, queries) {
24958
- let earliest = -1;
24959
- for (const query of queries) {
24960
- const literal2 = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24961
- const index = new RegExp(literal2, "iu").exec(text2)?.index ?? -1;
24962
- if (index < 0) continue;
24963
- if (earliest < 0 || index < earliest) earliest = index;
24964
- }
24965
- return earliest < 0 ? -1 : Array.from(text2.slice(0, earliest)).length;
24991
+ // src/tools/schema.ts
24992
+ var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
24993
+ 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." }));
24994
+ function paramProblem(schema, params) {
24995
+ const first = Errors2(schema, params).find((error2) => error2.keyword !== "boolean");
24996
+ if (!first) return "unrecognized shape";
24997
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
24998
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
24999
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
24966
25000
  }
25001
+ 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 });
24967
25002
 
24968
25003
  // src/notes/errors.ts
24969
25004
  var NoteError = class extends Error {
@@ -25089,19 +25124,223 @@ function assertAddress(value) {
25089
25124
  assertVirtualPath(path);
25090
25125
  return { scope, path, who };
25091
25126
  }
25092
- function canonicalAddressFor(identity, scope, path, who) {
25093
- if (scope === "session") return `@sessions/${who ?? identity.sessionId}/${path}`;
25094
- if (scope === "project") return `@projects/${who ?? identity.projectKey}/${path}`;
25095
- if (scope === "human") return `@human/${path}`;
25096
- if (scope === "agent") return `@agents/${who ?? identity.agent}/${path}`;
25097
- return `@models/${who ?? identity.model}/${path}`;
25127
+ function canonicalAddressFor(identity, scope, path, who) {
25128
+ if (scope === "session") return `@sessions/${who ?? identity.sessionId}/${path}`;
25129
+ if (scope === "project") return `@projects/${who ?? identity.projectKey}/${path}`;
25130
+ if (scope === "human") return `@human/${path}`;
25131
+ if (scope === "agent") return `@agents/${who ?? identity.agent}/${path}`;
25132
+ return `@models/${who ?? identity.model}/${path}`;
25133
+ }
25134
+ function addressFor(identity, scope, path, who) {
25135
+ if (scope === "session" && who === void 0) return path;
25136
+ if (scope === "project" && who === void 0) return `@project/${path}`;
25137
+ if (scope === "agent" && (who === void 0 || who === identity.agent)) return `@self/${path}`;
25138
+ if (scope === "model" && (who === void 0 || who === identity.model)) return `@model/${path}`;
25139
+ return canonicalAddressFor(identity, scope, path, who);
25140
+ }
25141
+
25142
+ // src/notes/policy.ts
25143
+ var DEFAULT_NOTE_BUDGET = 2048;
25144
+ var MAX_PINNED_NOTES = 5;
25145
+ var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
25146
+ function validateNotePolicy(fields) {
25147
+ for (const key of ["pinned", "readonly"]) {
25148
+ if (fields[key] !== void 0 && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
25149
+ }
25150
+ if (fields.budget !== void 0 && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
25151
+ throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
25152
+ }
25153
+ }
25154
+ function effectiveNotePolicy(fields, path) {
25155
+ validateNotePolicy(fields);
25156
+ return {
25157
+ pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some((page) => page === path),
25158
+ budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
25159
+ readonly: fields.readonly ?? false
25160
+ };
25161
+ }
25162
+ function pinnedPageOrder(path) {
25163
+ const index = DEFAULT_PINNED_PAGES.findIndex((page) => page === path);
25164
+ return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
25165
+ }
25166
+ function noteBudgetWarnings(body, policy) {
25167
+ const count = Array.from(body).length;
25168
+ return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
25169
+ }
25170
+ function assertNoteUnlocked(fields, unlock) {
25171
+ 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).");
25172
+ }
25173
+ function applyNotePolicy(target, fields) {
25174
+ validateNotePolicy(fields);
25175
+ for (const key of ["pinned", "budget", "readonly"]) {
25176
+ if (fields[key] !== void 0) Object.assign(target, { [key]: fields[key] });
25177
+ }
25178
+ }
25179
+
25180
+ // src/notes/frontmatter.ts
25181
+ var SCOPES = ["session", "project", "human", "agent", "model"];
25182
+ var ORIGINS = ["user", "self", "external"];
25183
+ var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
25184
+ var KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
25185
+ var pad2 = (value) => String(value).padStart(2, "0");
25186
+ function localIso(epochMs) {
25187
+ const date3 = new Date(epochMs);
25188
+ const offsetMinutes = -date3.getTimezoneOffset();
25189
+ const absOffset = Math.abs(offsetMinutes);
25190
+ const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
25191
+ const wallClock = `${date3.getFullYear()}-${pad2(date3.getMonth() + 1)}-${pad2(date3.getDate())}T${pad2(date3.getHours())}:${pad2(date3.getMinutes())}:${pad2(date3.getSeconds())}.${String(date3.getMilliseconds()).padStart(3, "0")}`;
25192
+ return `${wallClock}${offset}`;
25193
+ }
25194
+ function isScope(value) {
25195
+ return typeof value === "string" && SCOPES.includes(value);
25196
+ }
25197
+ function isOrigin(value) {
25198
+ return typeof value === "string" && ORIGINS.includes(value);
25199
+ }
25200
+ function toEpoch(value, fallback) {
25201
+ if (typeof value === "number" && Number.isFinite(value)) return value;
25202
+ if (typeof value === "string") {
25203
+ const parsed = Date.parse(value);
25204
+ if (Number.isFinite(parsed)) return parsed;
25205
+ }
25206
+ return fallback;
25207
+ }
25208
+ function parseScalar(text2) {
25209
+ const trimmed = text2.trim();
25210
+ if (trimmed === "") return "";
25211
+ try {
25212
+ return JSON.parse(trimmed);
25213
+ } catch {
25214
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
25215
+ return trimmed;
25216
+ }
25217
+ }
25218
+ function parseFrontmatter(raw) {
25219
+ const stripped = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
25220
+ const lines = stripped.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
25221
+ if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
25222
+ let close = -1;
25223
+ for (let index = 1; index < lines.length; index++) {
25224
+ if (lines[index]?.trim() === "---") {
25225
+ close = index;
25226
+ break;
25227
+ }
25228
+ }
25229
+ if (close === -1) return { fields: {}, body: raw };
25230
+ const fields = /* @__PURE__ */ Object.create(null);
25231
+ for (let index = 1; index < close; index++) {
25232
+ const line = lines[index];
25233
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
25234
+ if (!match) continue;
25235
+ const key = match[1];
25236
+ const rest2 = match[2];
25237
+ if (rest2.trim() === "") {
25238
+ const items = [];
25239
+ while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
25240
+ index++;
25241
+ items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
25242
+ }
25243
+ fields[key] = items;
25244
+ } else {
25245
+ fields[key] = parseScalar(rest2);
25246
+ }
25247
+ }
25248
+ const rest = lines.slice(close + 1);
25249
+ if (rest[0] === "") rest.shift();
25250
+ return { fields, body: rest.join("\n") };
25251
+ }
25252
+ function parseNote(raw, now = Date.now()) {
25253
+ const { fields, body } = parseFrontmatter(raw);
25254
+ validateNotePolicy(fields);
25255
+ const meta2 = { ...fields };
25256
+ meta2.scope = isScope(meta2.scope) ? meta2.scope : "session";
25257
+ meta2.origin = isOrigin(meta2.origin) ? meta2.origin : "self";
25258
+ for (const key of TIMESTAMP_KEYS) meta2[key] = toEpoch(meta2[key], now);
25259
+ meta2.accessCount = typeof meta2.accessCount === "number" && Number.isFinite(meta2.accessCount) ? meta2.accessCount : 0;
25260
+ return { meta: meta2, body };
25261
+ }
25262
+ function yamlScalar(value) {
25263
+ if (typeof value === "string") {
25264
+ const reserved = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
25265
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
25266
+ }
25267
+ return JSON.stringify(value);
25268
+ }
25269
+ function parsesAsNonString(text2) {
25270
+ try {
25271
+ return typeof JSON.parse(text2) !== "string";
25272
+ } catch {
25273
+ return false;
25274
+ }
25275
+ }
25276
+ function serializeNote(meta2, body) {
25277
+ const lines = [];
25278
+ for (const key of KNOWN_KEYS) {
25279
+ const value = meta2[key];
25280
+ if (value === void 0) continue;
25281
+ if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
25282
+ else lines.push(`${key}: ${yamlScalar(value)}`);
25283
+ }
25284
+ for (const key of Object.keys(meta2)) {
25285
+ if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
25286
+ if (meta2[key] === void 0) continue;
25287
+ lines.push(`${key}: ${yamlScalar(meta2[key])}`);
25288
+ }
25289
+ return `---
25290
+ ${lines.join("\n")}
25291
+ ---
25292
+
25293
+ ${body}`;
25294
+ }
25295
+ function stripLeadingFrontmatter(content) {
25296
+ return parseFrontmatter(content).body;
25297
+ }
25298
+
25299
+ // src/notes/fs-error.ts
25300
+ function isFilesystemError(error2) {
25301
+ const code = typeof error2 === "object" && error2 !== null ? error2.code : void 0;
25302
+ return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
25303
+ }
25304
+
25305
+ // src/notes/store.ts
25306
+ import { randomUUID as randomUUID2 } from "node:crypto";
25307
+ import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
25308
+ import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
25309
+
25310
+ // src/text-match.ts
25311
+ var InvalidQueryError = class extends Error {
25312
+ constructor(message) {
25313
+ super(message);
25314
+ this.name = "InvalidQueryError";
25315
+ }
25316
+ };
25317
+ function searchQueries(query) {
25318
+ const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
25319
+ if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
25320
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
25321
+ return candidates.filter((candidate) => candidate !== "");
25322
+ }
25323
+ function prefixFit(text2, fits) {
25324
+ if (fits(text2)) return text2;
25325
+ const chars = Array.from(text2);
25326
+ let low = 0;
25327
+ let high = chars.length;
25328
+ while (low < high) {
25329
+ const mid = Math.ceil((low + high) / 2);
25330
+ if (fits(chars.slice(0, mid).join(""))) low = mid;
25331
+ else high = mid - 1;
25332
+ }
25333
+ return chars.slice(0, low).join("");
25098
25334
  }
25099
- function addressFor(identity, scope, path, who) {
25100
- if (scope === "session" && who === void 0) return path;
25101
- if (scope === "project" && who === void 0) return `@project/${path}`;
25102
- if (scope === "agent" && (who === void 0 || who === identity.agent)) return `@self/${path}`;
25103
- if (scope === "model" && (who === void 0 || who === identity.model)) return `@model/${path}`;
25104
- return canonicalAddressFor(identity, scope, path, who);
25335
+ function earliestMatchOffsetChars(text2, queries) {
25336
+ let earliest = -1;
25337
+ for (const query of queries) {
25338
+ const literal2 = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25339
+ const index = new RegExp(literal2, "iu").exec(text2)?.index ?? -1;
25340
+ if (index < 0) continue;
25341
+ if (earliest < 0 || index < earliest) earliest = index;
25342
+ }
25343
+ return earliest < 0 ? -1 : Array.from(text2.slice(0, earliest)).length;
25105
25344
  }
25106
25345
 
25107
25346
  // src/notes/identity.ts
@@ -25127,7 +25366,7 @@ function snapshotNotesIdentity(value) {
25127
25366
  }
25128
25367
 
25129
25368
  // src/notes/constants.ts
25130
- var MAX_NOTE_BYTES = 1e6;
25369
+ var MAX_NOTE_BYTES = 512e3;
25131
25370
  var MAX_NOTE_PATH_BYTES = 512;
25132
25371
 
25133
25372
  // src/notes/project-namespace.ts
@@ -25381,6 +25620,11 @@ function withPathQueue(path, operation) {
25381
25620
  });
25382
25621
  return result;
25383
25622
  }
25623
+ function withPathQueues(paths, operation) {
25624
+ const keys = [...new Set(paths.map((path) => resolve3(path)))].sort();
25625
+ const lock = (index) => index === keys.length ? operation() : withPathQueue(keys[index], () => lock(index + 1));
25626
+ return lock(0);
25627
+ }
25384
25628
  function errno2(error2) {
25385
25629
  return typeof error2 === "object" && error2 !== null ? error2.code : void 0;
25386
25630
  }
@@ -25507,6 +25751,7 @@ function assertWritablePath(vpath) {
25507
25751
  if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
25508
25752
  }
25509
25753
  function megabytes(bytes) {
25754
+ if (bytes < 1e6) return `${Math.ceil(bytes / 1e3)} KB`;
25510
25755
  return `${Math.ceil(bytes / 1e4) / 100} MB`;
25511
25756
  }
25512
25757
  function assertSerializedSize(content) {
@@ -25534,20 +25779,35 @@ function assertDreamNote(scope, who, identity, raw, address) {
25534
25779
  }
25535
25780
  function createNotesStore(input) {
25536
25781
  const identity = snapshotNotesIdentity(input);
25782
+ async function assertPinAdmission(root, path, meta2, previous, source) {
25783
+ const livePin = (value, name) => value !== void 0 && value.crumpledAt === void 0 && effectiveNotePolicy(value, name).pinned;
25784
+ if (!livePin(meta2, path) || livePin(previous, path)) return;
25785
+ if (source?.root === root && livePin(source.meta, source.path)) return;
25786
+ let count = 0;
25787
+ for (const name of await walkMarkdown(root)) {
25788
+ const raw = await readFileIfExists(join3(root, name));
25789
+ if (raw !== void 0 && livePin(parseNote(raw).meta, name)) count++;
25790
+ }
25791
+ 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.`);
25792
+ }
25537
25793
  async function write(address, content, options = {}) {
25538
25794
  const stableOptions = { ...options };
25795
+ validateNotePolicy(stableOptions);
25539
25796
  const destination = assertAddress(address);
25540
25797
  assertWritablePath(destination.path);
25541
25798
  const scope = destination.scope;
25542
25799
  assertWritableNamespace(scope, destination.who, identity);
25543
25800
  const origin = stableOptions.origin === void 0 ? void 0 : assertOrigin(stableOptions.origin);
25544
25801
  const path = physicalPath(scope, destination.path, identity, destination.who);
25545
- return withPathQueue(path, async () => {
25802
+ const root = scopeDir(scope, identity, destination.who);
25803
+ return withPathQueues([root], () => withPathQueue(path, async () => {
25546
25804
  const now = writeStamp();
25547
25805
  const cleanBody = stripLeadingFrontmatter(content);
25548
25806
  const existingRaw = await readFileIfExists(path);
25549
25807
  assertDreamNote(scope, destination.who, identity, existingRaw, address);
25550
25808
  const existing = existingRaw === void 0 ? void 0 : parseNote(existingRaw, now).meta;
25809
+ if (existing) assertNoteUnlocked(existing, stableOptions.readonly);
25810
+ const previous = existing === void 0 ? void 0 : { ...existing };
25551
25811
  const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
25552
25812
  const meta2 = existing ?? {
25553
25813
  scope,
@@ -25559,14 +25819,16 @@ function createNotesStore(input) {
25559
25819
  ...scope === "session" ? { project: identity.projectKey } : {}
25560
25820
  };
25561
25821
  meta2.scope = scope;
25822
+ applyNotePolicy(meta2, stableOptions);
25562
25823
  if (origin !== void 0) meta2.origin = origin;
25563
25824
  delete meta2.crumpledAt;
25564
25825
  meta2.updatedAt = now;
25565
25826
  const serialized = serializeNote(meta2, cleanBody);
25566
25827
  assertSerializedSize(serialized);
25828
+ await assertPinAdmission(root, noteFileName(destination.path), meta2, previous);
25567
25829
  await atomicWrite(path, serialized);
25568
- return { meta: meta2, outcome };
25569
- });
25830
+ return { meta: meta2, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta2, noteFileName(destination.path))) };
25831
+ }));
25570
25832
  }
25571
25833
  async function read(address) {
25572
25834
  const destination = assertAddress(address);
@@ -25586,18 +25848,21 @@ function createNotesStore(input) {
25586
25848
  async function update(address, edits, options = {}) {
25587
25849
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
25588
25850
  const stableOptions = { ...options };
25851
+ validateNotePolicy(stableOptions);
25589
25852
  const from = assertAddress(address);
25590
25853
  const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
25591
25854
  assertWritablePath(destination.path);
25592
25855
  const scope = destination.scope;
25593
25856
  assertWritableNamespace(from.scope, from.who, identity);
25594
25857
  assertWritableNamespace(scope, destination.who, identity);
25595
- if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0) {
25596
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
25858
+ 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) {
25859
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
25597
25860
  }
25598
25861
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
25599
25862
  const path = physicalPath(scope, destination.path, identity, destination.who);
25600
25863
  const differentPaths = resolve3(fromPath) !== resolve3(path);
25864
+ const fromRoot = scopeDir(from.scope, identity, from.who);
25865
+ const root = scopeDir(scope, identity, destination.who);
25601
25866
  const mutate = async () => {
25602
25867
  const raw = await readFileIfExists(fromPath);
25603
25868
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
@@ -25611,7 +25876,10 @@ function createNotesStore(input) {
25611
25876
  throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
25612
25877
  }
25613
25878
  const { meta: meta2, body } = parseNote(raw);
25879
+ assertNoteUnlocked(meta2, stableOptions.readonly);
25880
+ if (moved && targetRaw !== void 0) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
25614
25881
  const beforeMeta = { ...meta2 };
25882
+ applyNotePolicy(meta2, stableOptions);
25615
25883
  meta2.scope = scope;
25616
25884
  if (from.scope !== "session" && scope === "session") meta2.project = identity.projectKey;
25617
25885
  if (from.scope === "session" && scope !== "session") delete meta2.project;
@@ -25639,41 +25907,48 @@ function createNotesStore(input) {
25639
25907
  if (stableOptions.crumpled === false) delete meta2.crumpledAt;
25640
25908
  const bodyChanged = body !== next;
25641
25909
  const originChanged = beforeMeta.origin !== meta2.origin;
25642
- if (bodyChanged || originChanged || moved) meta2.updatedAt = writeStamp();
25910
+ const policyChanged = beforeMeta.pinned !== meta2.pinned || beforeMeta.budget !== meta2.budget || beforeMeta.readonly !== meta2.readonly;
25911
+ if (bodyChanged || originChanged || policyChanged || moved) meta2.updatedAt = writeStamp();
25643
25912
  const serialized = serializeNote(meta2, next);
25644
25913
  assertSerializedSize(serialized);
25645
- const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta2.crumpledAt;
25914
+ const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta2.crumpledAt;
25646
25915
  let change;
25647
25916
  if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
25648
25917
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
25649
25918
  else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta2) };
25650
25919
  else change = { kind: "none", before: "", after: "" };
25920
+ await assertPinAdmission(
25921
+ root,
25922
+ noteFileName(destination.path),
25923
+ meta2,
25924
+ moved ? targetRaw === void 0 ? void 0 : parseNote(targetRaw).meta : beforeMeta,
25925
+ moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : void 0
25926
+ );
25651
25927
  await atomicWrite(sameFile ? sourceReal : path, serialized);
25652
25928
  if (moved) await rm(fromPath, { force: true });
25653
- return { meta: meta2, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
25929
+ return { meta: meta2, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta2, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
25654
25930
  };
25655
- if (!differentPaths) return withPathQueue(path, mutate);
25656
- const [first, second] = [fromPath, path].sort();
25657
- return withPathQueue(first, () => withPathQueue(second, mutate));
25931
+ return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
25658
25932
  }
25659
25933
  async function rename4(fromAddress, toAddress) {
25660
- const { meta: meta2, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
25661
- return { meta: meta2, replacedCrumpledTarget };
25934
+ const { meta: meta2, warnings, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
25935
+ return { meta: meta2, warnings, replacedCrumpledTarget };
25662
25936
  }
25663
25937
  async function forget(address) {
25664
25938
  if (identity.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
25665
25939
  const target = assertAddress(address);
25666
25940
  assertWritableNamespace(target.scope, target.who, identity);
25667
25941
  const path = physicalPath(target.scope, target.path, identity, target.who);
25668
- return withPathQueue(path, async () => {
25942
+ return withPathQueues([scopeDir(target.scope, identity, target.who)], () => withPathQueue(path, async () => {
25669
25943
  const raw = await readFileIfExists(path);
25670
25944
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
25671
25945
  assertDreamNote(target.scope, target.who, identity, raw, address);
25672
25946
  const { meta: meta2 } = parseNote(raw);
25947
+ assertNoteUnlocked(meta2);
25673
25948
  if (meta2.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
25674
25949
  await unlink(path);
25675
25950
  return { ...meta2, scope: target.scope };
25676
- });
25951
+ }));
25677
25952
  }
25678
25953
  async function* scan(options, status) {
25679
25954
  const glob = assertGlobPattern(options.glob);
@@ -25735,8 +26010,9 @@ function createNotesStore(input) {
25735
26010
  const rows = [];
25736
26011
  for await (const note of scan(stableOptions, status)) {
25737
26012
  const { address, path, scope, meta: meta2, body } = note;
26013
+ const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta2, path));
25738
26014
  if (stableQueries.length === 0) {
25739
- rows.push({ address, path, scope, meta: meta2, matches: [] });
26015
+ rows.push({ address, path, scope, meta: meta2, warnings, matches: [] });
25740
26016
  continue;
25741
26017
  }
25742
26018
  let baseChars = 0;
@@ -25748,7 +26024,7 @@ function createNotesStore(input) {
25748
26024
  }
25749
26025
  baseChars += Array.from(line).length + 1;
25750
26026
  }
25751
- if (matches.length > 0) rows.push({ address, path, scope, meta: meta2, matches });
26027
+ if (matches.length > 0) rows.push({ address, path, scope, meta: meta2, warnings, matches });
25752
26028
  }
25753
26029
  rows.sort((a, b) => a.address.localeCompare(b.address));
25754
26030
  return { rows, status: status ?? { namespacesUnavailable: [] } };
@@ -25765,20 +26041,8 @@ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
25765
26041
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
25766
26042
  var MAX_READ_WINDOW_CHARS = 5e4;
25767
26043
  var HISTORY_PREVIEW_CHARS = 1200;
25768
- function prefixFit(text2, fits) {
25769
- if (fits(text2)) return text2;
25770
- const chars = Array.from(text2);
25771
- let low = 0;
25772
- let high = chars.length;
25773
- while (low < high) {
25774
- const mid = Math.ceil((low + high) / 2);
25775
- if (fits(chars.slice(0, mid).join(""))) low = mid;
25776
- else high = mid - 1;
25777
- }
25778
- return chars.slice(0, low).join("");
25779
- }
25780
26044
 
25781
- // src/tools/result.ts
26045
+ // src/result.ts
25782
26046
  var OperationErrorSchema = typebox_exports.Object({
25783
26047
  code: typebox_exports.String(),
25784
26048
  message: typebox_exports.String()
@@ -25792,6 +26056,8 @@ function failure2(code, message) {
25792
26056
  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]`;
25793
26057
  return { ok: false, error: { code, message: bounded } };
25794
26058
  }
26059
+
26060
+ // src/tools/result.ts
25795
26061
  var WireErrorSchema = typebox_exports.Object({ error: typebox_exports.String(), code: typebox_exports.String() }, { additionalProperties: false });
25796
26062
  function wireResult(result) {
25797
26063
  if (result.ok) return result.data;
@@ -25846,190 +26112,6 @@ function renderTextWindow(window) {
25846
26112
  [truncated; continue at offset_chars=${next}]`;
25847
26113
  }
25848
26114
 
25849
- // src/history/history.ts
25850
- var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
25851
- var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
25852
- function isTextContent(part) {
25853
- return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
25854
- }
25855
- function contentText(content) {
25856
- if (typeof content === "string") return content;
25857
- return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
25858
- }
25859
- function argumentText(execution) {
25860
- return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
25861
- }
25862
- function nestedCallLine(call) {
25863
- const parts = [`${call.id} ${call.name} [${call.status}]`];
25864
- if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
25865
- if (call.error !== void 0) parts.push(`error: ${call.error}`);
25866
- parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
25867
- return `- ${parts.join(" ")}`;
25868
- }
25869
- function historyDocument(event) {
25870
- if (event.execution === void 0) return event.text;
25871
- const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
25872
- if (event.text !== "") sections.push(`--- output ---
25873
- ${event.text}`);
25874
- const nested = event.execution.nestedCalls;
25875
- if (nested !== void 0) {
25876
- const header2 = nested.complete ? "complete" : "incomplete";
25877
- sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
25878
- ${nested.calls.map(nestedCallLine).join("\n")}`);
25879
- }
25880
- return sections.join("\n");
25881
- }
25882
- var documents = /* @__PURE__ */ new WeakMap();
25883
- function eventDocument(event) {
25884
- const cached2 = documents.get(event);
25885
- if (cached2 !== void 0) return cached2;
25886
- const text2 = historyDocument(event);
25887
- documents.set(event, text2);
25888
- return text2;
25889
- }
25890
- function toolEvent(item, result) {
25891
- const run = result ?? item;
25892
- const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
25893
- const truncated = run.outputTruncated === true;
25894
- return {
25895
- seq: item.seq,
25896
- windowId: item.windowId,
25897
- role: "tool",
25898
- text: result?.text ?? (item.role === "tool" ? item.text : ""),
25899
- createdAt: item.createdAt,
25900
- execution: {
25901
- name: item.toolName ?? "unknown",
25902
- status,
25903
- // A call records its arguments; a bare result records none, and gets none invented.
25904
- ...item.arguments === void 0 ? {} : { arguments: item.arguments },
25905
- ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
25906
- ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
25907
- }
25908
- };
25909
- }
25910
- function projectHistory(rawWindows, highestSeq, branchSeqs) {
25911
- const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
25912
- const resultsById = /* @__PURE__ */ new Map();
25913
- for (const item of raw) {
25914
- if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
25915
- }
25916
- const pairedResults = /* @__PURE__ */ new Map();
25917
- for (const item of raw) {
25918
- const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
25919
- if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
25920
- pairedResults.set(result.seq, item.seq);
25921
- }
25922
- }
25923
- const windows = rawWindows.map((current) => ({
25924
- windowId: current.windowId,
25925
- ...current.createdAt ? { createdAt: current.createdAt } : {},
25926
- items: current.items.flatMap((item) => {
25927
- if (pairedResults.has(item.seq)) return [];
25928
- if (item.role === "tool_call" || item.role === "tool") {
25929
- const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
25930
- const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
25931
- return [toolEvent(item, paired)];
25932
- }
25933
- return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
25934
- })
25935
- }));
25936
- return { windows, highestSeq, branchSeqs, pairedResults };
25937
- }
25938
- var NestedCallSummarySchema = typebox_exports.Object({
25939
- call_count: typebox_exports.Integer({ minimum: 0 }),
25940
- complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
25941
- }, { additionalProperties: false });
25942
- var ToolSummarySchema = typebox_exports.Object({
25943
- tool: typebox_exports.Optional(typebox_exports.String()),
25944
- tool_status: typebox_exports.Optional(ToolCallStatusSchema),
25945
- output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
25946
- full_output_path: typebox_exports.Optional(typebox_exports.String())
25947
- }, { additionalProperties: false });
25948
- function toolSummary(event) {
25949
- const execution = event.execution;
25950
- if (!execution) return {};
25951
- return {
25952
- tool: execution.name,
25953
- tool_status: execution.status,
25954
- ...execution.outputTruncated ? { output_truncated: true } : {},
25955
- ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
25956
- };
25957
- }
25958
- function nestedCallSummary(event) {
25959
- const nested = event.execution?.nestedCalls;
25960
- return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
25961
- }
25962
- var HistoryFoldedRowSchema = typebox_exports.Object({
25963
- session: typebox_exports.Optional(typebox_exports.String()),
25964
- first_seq: typebox_exports.Integer({ minimum: 1 }),
25965
- last_seq: typebox_exports.Integer({ minimum: 1 }),
25966
- count: typebox_exports.Integer({ minimum: 1 }),
25967
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
25968
- }, { additionalProperties: false });
25969
- var HistoryPageItemSchema = typebox_exports.Object({
25970
- session: typebox_exports.Optional(typebox_exports.String()),
25971
- folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
25972
- seq: typebox_exports.Integer({ minimum: 1 }),
25973
- role: HistoryRoleSchema,
25974
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
25975
- ...ToolSummarySchema.properties,
25976
- content: typebox_exports.String(),
25977
- truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
25978
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
25979
- }, { additionalProperties: false });
25980
- var MAX_FOLD_TOOL_NAMES = 20;
25981
- var MAX_FOLD_TOOL_NAME_CHARS = 120;
25982
- function visibleItem(event, maxChars, matchOffset) {
25983
- const document = eventDocument(event);
25984
- const chars = Array.from(document);
25985
- const start = matchOffset ?? 0;
25986
- const limit = Math.max(0, maxChars);
25987
- const truncated = start > 0 || start + limit < chars.length;
25988
- return {
25989
- seq: event.seq,
25990
- role: event.role,
25991
- created_at: event.createdAt ?? null,
25992
- ...toolSummary(event),
25993
- content: truncated ? chars.slice(start, start + limit).join("") : document,
25994
- truncated,
25995
- ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
25996
- };
25997
- }
25998
- function allItems(projection) {
25999
- return projection.windows.flatMap((current) => current.items);
26000
- }
26001
- function inSelection(event, params) {
26002
- if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
26003
- if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
26004
- if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
26005
- if (event.createdAt === void 0) return false;
26006
- const at = Date.parse(event.createdAt);
26007
- return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
26008
- }
26009
- function filteredItems(projection, params, conversation) {
26010
- let items = allItems(projection).filter((item) => inSelection(item, params));
26011
- if (params.roles) items = items.filter((item) => params.roles.includes(item.role));
26012
- if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
26013
- return items.sort((a, b) => a.seq - b.seq);
26014
- }
26015
-
26016
- // src/tools/schema.ts
26017
- var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
26018
- 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." }));
26019
- 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 });
26020
- var InvalidQueryError = class extends Error {
26021
- constructor(message) {
26022
- super(message);
26023
- this.name = "InvalidQueryError";
26024
- }
26025
- };
26026
- function searchQueries(query) {
26027
- const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
26028
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
26029
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
26030
- return candidates.filter((candidate) => candidate !== "");
26031
- }
26032
-
26033
26115
  // src/tools/notes-context.ts
26034
26116
  import { statSync as statSync2 } from "node:fs";
26035
26117
  import { resolve as resolve4 } from "node:path";
@@ -26057,6 +26139,26 @@ var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("s
26057
26139
  var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
26058
26140
  description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
26059
26141
  }));
26142
+ var POLICY_PARAMETERS = {
26143
+ 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." })),
26144
+ 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." })),
26145
+ 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." }))
26146
+ };
26147
+ var PolicySchema = {
26148
+ pinned: typebox_exports.Boolean(),
26149
+ budget: typebox_exports.Integer(),
26150
+ readonly: typebox_exports.Boolean()
26151
+ };
26152
+ var WarningsSchema = { warnings: typebox_exports.Array(typebox_exports.String()) };
26153
+ function policyAt(meta2, address) {
26154
+ return effectiveNotePolicy(meta2, noteFileName(assertAddress(address).path));
26155
+ }
26156
+ function renderPolicy(policy) {
26157
+ return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
26158
+ }
26159
+ function withWarnings(text2, data) {
26160
+ return [text2, ...data.warnings].join("\n");
26161
+ }
26060
26162
  var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
26061
26163
  var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
26062
26164
  var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
@@ -26070,11 +26172,12 @@ function failureOf(error2) {
26070
26172
  if (isFilesystemError(error2)) return failure2("io_error", "notes operation failed");
26071
26173
  throw error2;
26072
26174
  }
26073
- var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
26175
+ var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly"]);
26074
26176
  var MAX_METADATA_ENTRY_BYTES = 1024;
26075
26177
  var MAX_METADATA_VERBATIM_BYTES = 2048;
26076
26178
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
26077
26179
  var NoteMetadataSchema = typebox_exports.Object({
26180
+ ...PolicySchema,
26078
26181
  origin: typebox_exports.Union([...ORIGIN_VALUES]),
26079
26182
  created_at: typebox_exports.String(),
26080
26183
  updated_at: typebox_exports.String(),
@@ -26082,7 +26185,7 @@ var NoteMetadataSchema = typebox_exports.Object({
26082
26185
  project: typebox_exports.Optional(typebox_exports.String()),
26083
26186
  extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
26084
26187
  }, { additionalProperties: false });
26085
- function noteMetadata(meta2) {
26188
+ function noteMetadata(meta2, address) {
26086
26189
  const extra = {};
26087
26190
  let verbatimBytes = 0;
26088
26191
  const put = (key, value) => {
@@ -26100,6 +26203,7 @@ function noteMetadata(meta2) {
26100
26203
  put(key, value);
26101
26204
  }
26102
26205
  return {
26206
+ ...policyAt(meta2, address),
26103
26207
  origin: meta2.origin,
26104
26208
  created_at: localIso(meta2.createdAt),
26105
26209
  updated_at: localIso(meta2.updatedAt),
@@ -26110,6 +26214,7 @@ function noteMetadata(meta2) {
26110
26214
  }
26111
26215
  function renderMetadata(metadata) {
26112
26216
  const fields = [
26217
+ renderPolicy(metadata),
26113
26218
  `origin ${metadata.origin}`,
26114
26219
  `created ${metadata.created_at}`,
26115
26220
  `updated ${metadata.updated_at}`,
@@ -26138,6 +26243,8 @@ var NoteIdentitySchema = {
26138
26243
  };
26139
26244
  var ListedFileSchema = typebox_exports.Object({
26140
26245
  ...NoteIdentitySchema,
26246
+ ...PolicySchema,
26247
+ ...WarningsSchema,
26141
26248
  updated_at: typebox_exports.String(),
26142
26249
  crumpled_at: typebox_exports.Optional(typebox_exports.String())
26143
26250
  }, { additionalProperties: false });
@@ -26156,16 +26263,21 @@ var SnapshotSchema = {
26156
26263
  };
26157
26264
  var NotesWriteDataSchema = typebox_exports.Object({
26158
26265
  ...NoteIdentitySchema,
26266
+ ...PolicySchema,
26267
+ ...WarningsSchema,
26159
26268
  outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
26160
26269
  }, { additionalProperties: false });
26161
26270
  var NotesUpdateDataSchema = typebox_exports.Object({
26162
26271
  ...NoteIdentitySchema,
26272
+ ...PolicySchema,
26273
+ ...WarningsSchema,
26163
26274
  change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
26164
26275
  rename_from: typebox_exports.Optional(typebox_exports.String())
26165
26276
  }, { additionalProperties: false });
26166
26277
  var NotesReadDataSchema = typebox_exports.Object({
26167
26278
  ...NoteIdentitySchema,
26168
26279
  metadata: NoteMetadataSchema,
26280
+ ...WarningsSchema,
26169
26281
  ...TextWindowSchema.properties
26170
26282
  }, { additionalProperties: false });
26171
26283
  var NotesListDataSchema = typebox_exports.Object({
@@ -26197,11 +26309,12 @@ function snapshot(rows, limit, status, renderData, shrink) {
26197
26309
  return fitsResult(outcome, render) ? outcome : failure2("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
26198
26310
  }
26199
26311
  function listedFile(row, identity) {
26200
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
26312
+ const policy = policyAt(row.meta, row.address);
26313
+ return { ...noteIdentity(identity, 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 } };
26201
26314
  }
26202
- var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, cwd: CWD_PARAMETER }, { additionalProperties: false });
26315
+ var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
26203
26316
  function renderWriteData(data) {
26204
- return `${data.outcome} ${renderIdentity(data)}`;
26317
+ return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
26205
26318
  }
26206
26319
  var notesWrite = {
26207
26320
  name: "notes_write",
@@ -26213,8 +26326,8 @@ var notesWrite = {
26213
26326
  async execute(params, context2) {
26214
26327
  try {
26215
26328
  const identity = notesIdentityForCall(context2, params.cwd);
26216
- const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin });
26217
- return success({ ...noteIdentity(identity, params.address), outcome });
26329
+ const { outcome, meta: meta2, warnings } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
26330
+ return success({ ...noteIdentity(identity, params.address), outcome, ...policyAt(meta2, params.address), warnings });
26218
26331
  } catch (error2) {
26219
26332
  return failureOf(error2);
26220
26333
  }
@@ -26225,18 +26338,20 @@ var notesUpdateParameters = typebox_exports.Object({
26225
26338
  address: typebox_exports.String(),
26226
26339
  edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
26227
26340
  origin: ORIGIN,
26341
+ ...POLICY_PARAMETERS,
26228
26342
  crumpled: CRUMPLED_PARAMETER,
26229
26343
  replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
26230
26344
  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." })),
26231
26345
  cwd: CWD_PARAMETER
26232
26346
  }, { additionalProperties: false });
26233
26347
  function renderUpdateData(data) {
26234
- return data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
26348
+ const receipt = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
26349
+ return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
26235
26350
  }
26236
26351
  var notesUpdate = {
26237
26352
  name: "notes_update",
26238
26353
  label: "Notes update",
26239
- 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}`,
26354
+ 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}`,
26240
26355
  parameters: notesUpdateParameters,
26241
26356
  outputSchema: resultSchema(NotesUpdateDataSchema),
26242
26357
  executionMode: "sequential",
@@ -26245,11 +26360,11 @@ var notesUpdate = {
26245
26360
  const identity = notesIdentityForCall(context2, params.cwd);
26246
26361
  const store = createNotesStore(identity);
26247
26362
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
26248
- const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
26363
+ const { change, moved, meta: meta2, 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 });
26249
26364
  onChange?.(change);
26250
26365
  const from = noteIdentity(identity, params.address).address;
26251
26366
  const to = noteIdentity(identity, renameTo ?? params.address);
26252
- return success({ ...to, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
26367
+ return success({ ...to, ...policyAt(meta2, to.address), warnings, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
26253
26368
  } catch (error2) {
26254
26369
  return failureOf(error2);
26255
26370
  }
@@ -26258,8 +26373,8 @@ var notesUpdate = {
26258
26373
  };
26259
26374
  var notesReadParameters = typebox_exports.Object({ address: typebox_exports.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
26260
26375
  function renderReadData(data) {
26261
- return `${renderIdentity(data)}
26262
- ${renderMetadata(data.metadata)}
26376
+ return withWarnings(`${renderIdentity(data)}
26377
+ ${renderMetadata(data.metadata)}`, data) + `
26263
26378
 
26264
26379
  ${renderTextWindow(data)}`;
26265
26380
  }
@@ -26277,8 +26392,9 @@ var notesRead = {
26277
26392
  if (!note) return failure2("not_found", `No note at ${resolved.address}.`);
26278
26393
  const totalChars = Array.from(note.body).length;
26279
26394
  if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure2("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
26280
- const metadata = noteMetadata(note.meta);
26281
- return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
26395
+ const metadata = noteMetadata(note.meta, resolved.address);
26396
+ const warnings = noteBudgetWarnings(note.body, metadata);
26397
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
26282
26398
  } catch (error2) {
26283
26399
  return failureOf(error2);
26284
26400
  }
@@ -26289,7 +26405,8 @@ var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit:
26289
26405
  function renderListData(data) {
26290
26406
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
26291
26407
  for (const file of data.files) {
26292
- 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}`}`);
26408
+ 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}`}`);
26409
+ lines.push(...file.warnings.map((warning) => ` ${warning}`));
26293
26410
  }
26294
26411
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
26295
26412
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
@@ -26316,7 +26433,8 @@ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Opti
26316
26433
  function renderSearchData(data) {
26317
26434
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
26318
26435
  for (const file of data.files) {
26319
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
26436
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
26437
+ lines.push(...file.warnings.map((warning) => ` ${warning}`));
26320
26438
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
26321
26439
  }
26322
26440
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -26422,7 +26540,7 @@ function prepareSelection(projection, params) {
26422
26540
  const folds = !params.roles && params.query === void 0;
26423
26541
  const candidates = [];
26424
26542
  let run = [];
26425
- for (const event of filteredItems(projection, params, false)) {
26543
+ for (const event of filteredItems(projection, params)) {
26426
26544
  if (folds && (event.role === "tool" || event.role === "context")) {
26427
26545
  run.push(event);
26428
26546
  continue;
@@ -26472,7 +26590,7 @@ function corpusSelection(params) {
26472
26590
  return resolveSelection(params);
26473
26591
  }
26474
26592
  function sessionRepresentative(projection, scoped) {
26475
- const events = filteredItems(projection, scoped, false).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
26593
+ const events = filteredItems(projection, scoped).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
26476
26594
  if (scoped.roles) return events.at(-1);
26477
26595
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
26478
26596
  }
@@ -26516,7 +26634,7 @@ var CorpusCollector = class {
26516
26634
  /** Returns whether this session contributes an overview representative. */
26517
26635
  add(session, projection) {
26518
26636
  if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
26519
- for (const event of filteredItems(projection, this.scoped, false)) {
26637
+ for (const event of filteredItems(projection, this.scoped)) {
26520
26638
  const document = eventDocument(event);
26521
26639
  if ((event.role === "user" || event.role === "assistant") && document === "") continue;
26522
26640
  const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
@@ -26552,10 +26670,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
26552
26670
  break;
26553
26671
  }
26554
26672
  const page = pageData(prepared, start, end, maxChars);
26555
- if (!fits(page)) {
26556
- 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";
26557
- return failure2("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}.`);
26558
- }
26673
+ if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
26559
26674
  return success(page);
26560
26675
  }
26561
26676
 
@@ -26683,6 +26798,12 @@ function renderRead(data) {
26683
26798
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
26684
26799
  }
26685
26800
  var plainText = (text2) => text2;
26801
+ function pageOutcome(result) {
26802
+ if (!("pageTooLarge" in result)) return result;
26803
+ const { count, multi } = result.pageTooLarge;
26804
+ 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";
26805
+ return failure2("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}.`);
26806
+ }
26686
26807
  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." }));
26687
26808
  var historyListParameters = typebox_exports.Object({
26688
26809
  session: sessionParameter,
@@ -26705,7 +26826,7 @@ var historyList = {
26705
26826
  async execute(params, context2, wrapText = plainText) {
26706
26827
  const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
26707
26828
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
26708
- if (params.session === void 0) return selectPage(await currentHistory(context2), params, fits, maxChars);
26829
+ if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), params, fits, maxChars));
26709
26830
  const selector = parseSessionSelector(params.session);
26710
26831
  if (!selector.ok) return selector;
26711
26832
  const corpus = "corpus" in context2 ? context2.corpus : void 0;
@@ -26734,7 +26855,7 @@ var historyList = {
26734
26855
  }
26735
26856
  }
26736
26857
  const notice2 = notices.length ? { notice: notices.join("") } : {};
26737
- const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
26858
+ const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
26738
26859
  return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
26739
26860
  }
26740
26861
  const target = await resolveSession(corpus, selector.data);
@@ -26742,7 +26863,7 @@ var historyList = {
26742
26863
  const loaded = await loadHistorySession(target.data);
26743
26864
  if (!loaded.ok) return loaded;
26744
26865
  const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
26745
- const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
26866
+ const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
26746
26867
  return result.ok ? success({ ...result.data, ...notice }) : result;
26747
26868
  },
26748
26869
  render: (result) => renderOutcome(result, renderPage)
@@ -28116,8 +28237,6 @@ function localHistoryCorpus(options) {
28116
28237
 
28117
28238
  // src/boot/text.ts
28118
28239
  var SHELF_FRESH_LIMIT = 3;
28119
- var CHEATSHEET_BOOT_MAX_CHARS = 1536;
28120
- var MAP_BOOT_MAX_CHARS = 4096;
28121
28240
  var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
28122
28241
  var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
28123
28242
  var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -28160,9 +28279,15 @@ Still a tie? *shrugs* You've got a brain. Use it.
28160
28279
  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\`.
28161
28280
  ${NOTES_PROTOCOL_CLOSE_TAG}`;
28162
28281
  var MAPS_BLOCK = `<notesoup:maps>
28163
- Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
28164
- Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
28165
- wakes up next reads them, and next is you. So keep them short, and keep them true.
28282
+ Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
28283
+ Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
28284
+ reads them, and next is you. So keep them short, and keep them true.
28285
+
28286
+ Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
28287
+ live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
28288
+ starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
28289
+ and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
28290
+ explicitly set \`readonly:false\` to unlock, on its own or with your changes.
28166
28291
 
28167
28292
  - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
28168
28293
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -28241,20 +28366,22 @@ function notesIndex(snapshot2, tools2, agentName, modelName) {
28241
28366
  continue;
28242
28367
  }
28243
28368
  const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
28244
- const pinned = ["CHEATSHEET.md", "MAP.md"].flatMap((path) => {
28245
- const row = rows.find((row2) => row2.path === path);
28246
- return row?.body ? [row] : [];
28247
- });
28248
- const fresh = rows.filter((row) => row.path !== "MAP.md" && row.path !== "CHEATSHEET.md").slice(0, SHELF_FRESH_LIMIT).map((row) => {
28369
+ 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));
28370
+ const pinned = pins.slice(0, MAX_PINNED_NOTES);
28371
+ const fresh = rows.filter((row) => !effectiveNotePolicy(row.meta, row.path).pinned).slice(0, SHELF_FRESH_LIMIT).map((row) => {
28249
28372
  const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
28250
28373
  const title = feedTitle(row.body);
28251
28374
  return title === void 0 ? ` ${locator}` : ` ${title}
28252
28375
  ${locator}`;
28253
28376
  });
28254
28377
  if (pinned.length === 0 && fresh.length === 0) continue;
28255
- const parts = pinned.map((row) => `${row.address}
28378
+ const parts = pinned.map((row) => {
28379
+ const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
28380
+ return `${row.address}
28256
28381
 
28257
- ${indent(pinnedBodyForBoot(row.address, row.body, row.path === "MAP.md" ? MAP_BOOT_MAX_CHARS : CHEATSHEET_BOOT_MAX_CHARS))}`);
28382
+ ${indent([...warnings, row.body].join("\n"))}`;
28383
+ });
28384
+ 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 ${tools2.notes}.`));
28258
28385
  if (fresh.length > 0) parts.push(`recent
28259
28386
 
28260
28387
  ${fresh.join("\n\n")}`);
@@ -28262,13 +28389,7 @@ ${fresh.join("\n\n")}`);
28262
28389
  }
28263
28390
  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.";
28264
28391
  }
28265
- function pinnedBodyForBoot(address, body, maxChars) {
28266
- const chars = Array.from(body);
28267
- if (chars.length <= maxChars) return body;
28268
- return `${chars.slice(0, maxChars).join("")}
28269
- [truncated at ${maxChars} chars; slim this page down, full body at \`${address}\`]`;
28270
- }
28271
- function renderBootBlock(data) {
28392
+ function renderIdentity2(data) {
28272
28393
  const shown2 = /* @__PURE__ */ new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
28273
28394
  const windows = data.tree.windows.filter((_window, index) => shown2.has(index));
28274
28395
  const width = Math.max(8, ...windows.map((window) => window.shortName.length));
@@ -28282,10 +28403,12 @@ function renderBootBlock(data) {
28282
28403
  return `${window.isCurrent ? "\u2514\u2500" : "\u251C\u2500"} ${name}${range}${window.isCurrent ? " \u2190 you are here" : ""}`;
28283
28404
  })
28284
28405
  ];
28285
- const identity = `${WINDOW_IDENTITY_OPEN_TAG}
28406
+ return `${WINDOW_IDENTITY_OPEN_TAG}
28286
28407
  ${lines.join("\n")}
28287
28408
  ${WINDOW_IDENTITY_CLOSE_TAG}`;
28288
- return [identity, renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
28409
+ }
28410
+ function renderBootBlock(data) {
28411
+ return [renderIdentity2(data), renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
28289
28412
  }
28290
28413
 
28291
28414
  // plugins/codex/src/text.ts
@@ -28411,13 +28534,6 @@ function successFor(bound, outcome) {
28411
28534
  ...outcome.ok ? {} : { isError: true }
28412
28535
  };
28413
28536
  }
28414
- function paramProblem(schema, params) {
28415
- const first = Errors2(schema, params).find((error2) => error2.keyword !== "boolean");
28416
- if (!first) return "unrecognized shape";
28417
- const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
28418
- const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28419
- return `${field ? `${field} ` : ""}${first.message}${extra}`;
28420
- }
28421
28537
  function metaFacts(meta2, binding) {
28422
28538
  const rootSessionId = rootSessionIdOf(meta2);
28423
28539
  if (binding.rootSessionId !== rootSessionId) {