notesoup 0.57.3 → 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 (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 +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 +8 -3
  41. package/dist/src/notes/store.js +64 -20
  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-query-namespaces.test.js +7 -3
  72. package/dist/test/notes.integration.test.js +10 -10
  73. package/dist/test/notes.test.js +4 -4
  74. package/dist/test/pi-render.test.js +28 -1
  75. package/dist/test/project-namespace.test.js +1 -1
  76. package/docs/architecture.md +10 -7
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +20 -7
  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 +528 -422
  85. package/plugins/claude/hooks/register.ts +1 -10
  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 +5 -15
  91. package/plugins/codex/dist/codex/notesoup.js +520 -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 +66 -26
  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
@@ -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
  }
@@ -25450,6 +25694,7 @@ async function namespacesForPattern(pattern, identity, status) {
25450
25694
  }
25451
25695
  function normalizePattern(pattern, identity) {
25452
25696
  if (!pattern) return pattern;
25697
+ if (!pattern.startsWith("@") && !pattern.includes("/")) return `**/${pattern}`;
25453
25698
  if (pattern.startsWith("@project/")) return `@projects/${identity.projectKey}/${pattern.slice("@project/".length)}`;
25454
25699
  if (pattern.startsWith("@self/")) return `@agents/${identity.agent}/${pattern.slice("@self/".length)}`;
25455
25700
  if (pattern.startsWith("@model/")) return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
@@ -25506,6 +25751,7 @@ function assertWritablePath(vpath) {
25506
25751
  if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
25507
25752
  }
25508
25753
  function megabytes(bytes) {
25754
+ if (bytes < 1e6) return `${Math.ceil(bytes / 1e3)} KB`;
25509
25755
  return `${Math.ceil(bytes / 1e4) / 100} MB`;
25510
25756
  }
25511
25757
  function assertSerializedSize(content) {
@@ -25533,20 +25779,35 @@ function assertDreamNote(scope, who, identity, raw, address) {
25533
25779
  }
25534
25780
  function createNotesStore(input) {
25535
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
+ }
25536
25793
  async function write(address, content, options = {}) {
25537
25794
  const stableOptions = { ...options };
25795
+ validateNotePolicy(stableOptions);
25538
25796
  const destination = assertAddress(address);
25539
25797
  assertWritablePath(destination.path);
25540
25798
  const scope = destination.scope;
25541
25799
  assertWritableNamespace(scope, destination.who, identity);
25542
25800
  const origin = stableOptions.origin === void 0 ? void 0 : assertOrigin(stableOptions.origin);
25543
25801
  const path = physicalPath(scope, destination.path, identity, destination.who);
25544
- return withPathQueue(path, async () => {
25802
+ const root = scopeDir(scope, identity, destination.who);
25803
+ return withPathQueues([root], () => withPathQueue(path, async () => {
25545
25804
  const now = writeStamp();
25546
25805
  const cleanBody = stripLeadingFrontmatter(content);
25547
25806
  const existingRaw = await readFileIfExists(path);
25548
25807
  assertDreamNote(scope, destination.who, identity, existingRaw, address);
25549
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 };
25550
25811
  const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
25551
25812
  const meta2 = existing ?? {
25552
25813
  scope,
@@ -25558,14 +25819,16 @@ function createNotesStore(input) {
25558
25819
  ...scope === "session" ? { project: identity.projectKey } : {}
25559
25820
  };
25560
25821
  meta2.scope = scope;
25822
+ applyNotePolicy(meta2, stableOptions);
25561
25823
  if (origin !== void 0) meta2.origin = origin;
25562
25824
  delete meta2.crumpledAt;
25563
25825
  meta2.updatedAt = now;
25564
25826
  const serialized = serializeNote(meta2, cleanBody);
25565
25827
  assertSerializedSize(serialized);
25828
+ await assertPinAdmission(root, noteFileName(destination.path), meta2, previous);
25566
25829
  await atomicWrite(path, serialized);
25567
- return { meta: meta2, outcome };
25568
- });
25830
+ return { meta: meta2, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta2, noteFileName(destination.path))) };
25831
+ }));
25569
25832
  }
25570
25833
  async function read(address) {
25571
25834
  const destination = assertAddress(address);
@@ -25585,18 +25848,21 @@ function createNotesStore(input) {
25585
25848
  async function update(address, edits, options = {}) {
25586
25849
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
25587
25850
  const stableOptions = { ...options };
25851
+ validateNotePolicy(stableOptions);
25588
25852
  const from = assertAddress(address);
25589
25853
  const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
25590
25854
  assertWritablePath(destination.path);
25591
25855
  const scope = destination.scope;
25592
25856
  assertWritableNamespace(from.scope, from.who, identity);
25593
25857
  assertWritableNamespace(scope, destination.who, identity);
25594
- if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0) {
25595
- 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.");
25596
25860
  }
25597
25861
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
25598
25862
  const path = physicalPath(scope, destination.path, identity, destination.who);
25599
25863
  const differentPaths = resolve3(fromPath) !== resolve3(path);
25864
+ const fromRoot = scopeDir(from.scope, identity, from.who);
25865
+ const root = scopeDir(scope, identity, destination.who);
25600
25866
  const mutate = async () => {
25601
25867
  const raw = await readFileIfExists(fromPath);
25602
25868
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
@@ -25610,7 +25876,10 @@ function createNotesStore(input) {
25610
25876
  throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
25611
25877
  }
25612
25878
  const { meta: meta2, body } = parseNote(raw);
25879
+ assertNoteUnlocked(meta2, stableOptions.readonly);
25880
+ if (moved && targetRaw !== void 0) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
25613
25881
  const beforeMeta = { ...meta2 };
25882
+ applyNotePolicy(meta2, stableOptions);
25614
25883
  meta2.scope = scope;
25615
25884
  if (from.scope !== "session" && scope === "session") meta2.project = identity.projectKey;
25616
25885
  if (from.scope === "session" && scope !== "session") delete meta2.project;
@@ -25638,41 +25907,48 @@ function createNotesStore(input) {
25638
25907
  if (stableOptions.crumpled === false) delete meta2.crumpledAt;
25639
25908
  const bodyChanged = body !== next;
25640
25909
  const originChanged = beforeMeta.origin !== meta2.origin;
25641
- 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();
25642
25912
  const serialized = serializeNote(meta2, next);
25643
25913
  assertSerializedSize(serialized);
25644
- const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta2.crumpledAt;
25914
+ const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta2.crumpledAt;
25645
25915
  let change;
25646
25916
  if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
25647
25917
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
25648
25918
  else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta2) };
25649
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
+ );
25650
25927
  await atomicWrite(sameFile ? sourceReal : path, serialized);
25651
25928
  if (moved) await rm(fromPath, { force: true });
25652
- 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 };
25653
25930
  };
25654
- if (!differentPaths) return withPathQueue(path, mutate);
25655
- const [first, second] = [fromPath, path].sort();
25656
- return withPathQueue(first, () => withPathQueue(second, mutate));
25931
+ return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
25657
25932
  }
25658
25933
  async function rename4(fromAddress, toAddress) {
25659
- const { meta: meta2, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
25660
- return { meta: meta2, replacedCrumpledTarget };
25934
+ const { meta: meta2, warnings, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
25935
+ return { meta: meta2, warnings, replacedCrumpledTarget };
25661
25936
  }
25662
25937
  async function forget(address) {
25663
25938
  if (identity.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
25664
25939
  const target = assertAddress(address);
25665
25940
  assertWritableNamespace(target.scope, target.who, identity);
25666
25941
  const path = physicalPath(target.scope, target.path, identity, target.who);
25667
- return withPathQueue(path, async () => {
25942
+ return withPathQueues([scopeDir(target.scope, identity, target.who)], () => withPathQueue(path, async () => {
25668
25943
  const raw = await readFileIfExists(path);
25669
25944
  if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
25670
25945
  assertDreamNote(target.scope, target.who, identity, raw, address);
25671
25946
  const { meta: meta2 } = parseNote(raw);
25947
+ assertNoteUnlocked(meta2);
25672
25948
  if (meta2.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
25673
25949
  await unlink(path);
25674
25950
  return { ...meta2, scope: target.scope };
25675
- });
25951
+ }));
25676
25952
  }
25677
25953
  async function* scan(options, status) {
25678
25954
  const glob = assertGlobPattern(options.glob);
@@ -25734,8 +26010,9 @@ function createNotesStore(input) {
25734
26010
  const rows = [];
25735
26011
  for await (const note of scan(stableOptions, status)) {
25736
26012
  const { address, path, scope, meta: meta2, body } = note;
26013
+ const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta2, path));
25737
26014
  if (stableQueries.length === 0) {
25738
- rows.push({ address, path, scope, meta: meta2, matches: [] });
26015
+ rows.push({ address, path, scope, meta: meta2, warnings, matches: [] });
25739
26016
  continue;
25740
26017
  }
25741
26018
  let baseChars = 0;
@@ -25747,7 +26024,7 @@ function createNotesStore(input) {
25747
26024
  }
25748
26025
  baseChars += Array.from(line).length + 1;
25749
26026
  }
25750
- 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 });
25751
26028
  }
25752
26029
  rows.sort((a, b) => a.address.localeCompare(b.address));
25753
26030
  return { rows, status: status ?? { namespacesUnavailable: [] } };
@@ -25764,20 +26041,8 @@ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
25764
26041
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
25765
26042
  var MAX_READ_WINDOW_CHARS = 5e4;
25766
26043
  var HISTORY_PREVIEW_CHARS = 1200;
25767
- function prefixFit(text2, fits) {
25768
- if (fits(text2)) return text2;
25769
- const chars = Array.from(text2);
25770
- let low = 0;
25771
- let high = chars.length;
25772
- while (low < high) {
25773
- const mid = Math.ceil((low + high) / 2);
25774
- if (fits(chars.slice(0, mid).join(""))) low = mid;
25775
- else high = mid - 1;
25776
- }
25777
- return chars.slice(0, low).join("");
25778
- }
25779
26044
 
25780
- // src/tools/result.ts
26045
+ // src/result.ts
25781
26046
  var OperationErrorSchema = typebox_exports.Object({
25782
26047
  code: typebox_exports.String(),
25783
26048
  message: typebox_exports.String()
@@ -25791,6 +26056,8 @@ function failure2(code, message) {
25791
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]`;
25792
26057
  return { ok: false, error: { code, message: bounded } };
25793
26058
  }
26059
+
26060
+ // src/tools/result.ts
25794
26061
  var WireErrorSchema = typebox_exports.Object({ error: typebox_exports.String(), code: typebox_exports.String() }, { additionalProperties: false });
25795
26062
  function wireResult(result) {
25796
26063
  if (result.ok) return result.data;
@@ -25845,190 +26112,6 @@ function renderTextWindow(window) {
25845
26112
  [truncated; continue at offset_chars=${next}]`;
25846
26113
  }
25847
26114
 
25848
- // src/history/history.ts
25849
- var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
25850
- var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
25851
- function isTextContent(part) {
25852
- return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
25853
- }
25854
- function contentText(content) {
25855
- if (typeof content === "string") return content;
25856
- return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
25857
- }
25858
- function argumentText(execution) {
25859
- return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
25860
- }
25861
- function nestedCallLine(call) {
25862
- const parts = [`${call.id} ${call.name} [${call.status}]`];
25863
- if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
25864
- if (call.error !== void 0) parts.push(`error: ${call.error}`);
25865
- parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
25866
- return `- ${parts.join(" ")}`;
25867
- }
25868
- function historyDocument(event) {
25869
- if (event.execution === void 0) return event.text;
25870
- const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
25871
- if (event.text !== "") sections.push(`--- output ---
25872
- ${event.text}`);
25873
- const nested = event.execution.nestedCalls;
25874
- if (nested !== void 0) {
25875
- const header2 = nested.complete ? "complete" : "incomplete";
25876
- sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
25877
- ${nested.calls.map(nestedCallLine).join("\n")}`);
25878
- }
25879
- return sections.join("\n");
25880
- }
25881
- var documents = /* @__PURE__ */ new WeakMap();
25882
- function eventDocument(event) {
25883
- const cached2 = documents.get(event);
25884
- if (cached2 !== void 0) return cached2;
25885
- const text2 = historyDocument(event);
25886
- documents.set(event, text2);
25887
- return text2;
25888
- }
25889
- function toolEvent(item, result) {
25890
- const run = result ?? item;
25891
- const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
25892
- const truncated = run.outputTruncated === true;
25893
- return {
25894
- seq: item.seq,
25895
- windowId: item.windowId,
25896
- role: "tool",
25897
- text: result?.text ?? (item.role === "tool" ? item.text : ""),
25898
- createdAt: item.createdAt,
25899
- execution: {
25900
- name: item.toolName ?? "unknown",
25901
- status,
25902
- // A call records its arguments; a bare result records none, and gets none invented.
25903
- ...item.arguments === void 0 ? {} : { arguments: item.arguments },
25904
- ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
25905
- ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
25906
- }
25907
- };
25908
- }
25909
- function projectHistory(rawWindows, highestSeq, branchSeqs) {
25910
- const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
25911
- const resultsById = /* @__PURE__ */ new Map();
25912
- for (const item of raw) {
25913
- if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
25914
- }
25915
- const pairedResults = /* @__PURE__ */ new Map();
25916
- for (const item of raw) {
25917
- const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
25918
- if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
25919
- pairedResults.set(result.seq, item.seq);
25920
- }
25921
- }
25922
- const windows = rawWindows.map((current) => ({
25923
- windowId: current.windowId,
25924
- ...current.createdAt ? { createdAt: current.createdAt } : {},
25925
- items: current.items.flatMap((item) => {
25926
- if (pairedResults.has(item.seq)) return [];
25927
- if (item.role === "tool_call" || item.role === "tool") {
25928
- const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
25929
- const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
25930
- return [toolEvent(item, paired)];
25931
- }
25932
- return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
25933
- })
25934
- }));
25935
- return { windows, highestSeq, branchSeqs, pairedResults };
25936
- }
25937
- var NestedCallSummarySchema = typebox_exports.Object({
25938
- call_count: typebox_exports.Integer({ minimum: 0 }),
25939
- complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
25940
- }, { additionalProperties: false });
25941
- var ToolSummarySchema = typebox_exports.Object({
25942
- tool: typebox_exports.Optional(typebox_exports.String()),
25943
- tool_status: typebox_exports.Optional(ToolCallStatusSchema),
25944
- output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
25945
- full_output_path: typebox_exports.Optional(typebox_exports.String())
25946
- }, { additionalProperties: false });
25947
- function toolSummary(event) {
25948
- const execution = event.execution;
25949
- if (!execution) return {};
25950
- return {
25951
- tool: execution.name,
25952
- tool_status: execution.status,
25953
- ...execution.outputTruncated ? { output_truncated: true } : {},
25954
- ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
25955
- };
25956
- }
25957
- function nestedCallSummary(event) {
25958
- const nested = event.execution?.nestedCalls;
25959
- return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
25960
- }
25961
- var HistoryFoldedRowSchema = typebox_exports.Object({
25962
- session: typebox_exports.Optional(typebox_exports.String()),
25963
- first_seq: typebox_exports.Integer({ minimum: 1 }),
25964
- last_seq: typebox_exports.Integer({ minimum: 1 }),
25965
- count: typebox_exports.Integer({ minimum: 1 }),
25966
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
25967
- }, { additionalProperties: false });
25968
- var HistoryPageItemSchema = typebox_exports.Object({
25969
- session: typebox_exports.Optional(typebox_exports.String()),
25970
- folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
25971
- seq: typebox_exports.Integer({ minimum: 1 }),
25972
- role: HistoryRoleSchema,
25973
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
25974
- ...ToolSummarySchema.properties,
25975
- content: typebox_exports.String(),
25976
- truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
25977
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
25978
- }, { additionalProperties: false });
25979
- var MAX_FOLD_TOOL_NAMES = 20;
25980
- var MAX_FOLD_TOOL_NAME_CHARS = 120;
25981
- function visibleItem(event, maxChars, matchOffset) {
25982
- const document = eventDocument(event);
25983
- const chars = Array.from(document);
25984
- const start = matchOffset ?? 0;
25985
- const limit = Math.max(0, maxChars);
25986
- const truncated = start > 0 || start + limit < chars.length;
25987
- return {
25988
- seq: event.seq,
25989
- role: event.role,
25990
- created_at: event.createdAt ?? null,
25991
- ...toolSummary(event),
25992
- content: truncated ? chars.slice(start, start + limit).join("") : document,
25993
- truncated,
25994
- ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
25995
- };
25996
- }
25997
- function allItems(projection) {
25998
- return projection.windows.flatMap((current) => current.items);
25999
- }
26000
- function inSelection(event, params) {
26001
- if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
26002
- if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
26003
- if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
26004
- if (event.createdAt === void 0) return false;
26005
- const at = Date.parse(event.createdAt);
26006
- return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
26007
- }
26008
- function filteredItems(projection, params, conversation) {
26009
- let items = allItems(projection).filter((item) => inSelection(item, params));
26010
- if (params.roles) items = items.filter((item) => params.roles.includes(item.role));
26011
- if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
26012
- return items.sort((a, b) => a.seq - b.seq);
26013
- }
26014
-
26015
- // src/tools/schema.ts
26016
- var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
26017
- 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." }));
26018
- 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 });
26019
- var InvalidQueryError = class extends Error {
26020
- constructor(message) {
26021
- super(message);
26022
- this.name = "InvalidQueryError";
26023
- }
26024
- };
26025
- function searchQueries(query) {
26026
- const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
26027
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
26028
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
26029
- return candidates.filter((candidate) => candidate !== "");
26030
- }
26031
-
26032
26115
  // src/tools/notes-context.ts
26033
26116
  import { statSync as statSync2 } from "node:fs";
26034
26117
  import { resolve as resolve4 } from "node:path";
@@ -26056,6 +26139,26 @@ var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("s
26056
26139
  var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
26057
26140
  description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
26058
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
+ }
26059
26162
  var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
26060
26163
  var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
26061
26164
  var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
@@ -26069,11 +26172,12 @@ function failureOf(error2) {
26069
26172
  if (isFilesystemError(error2)) return failure2("io_error", "notes operation failed");
26070
26173
  throw error2;
26071
26174
  }
26072
- 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"]);
26073
26176
  var MAX_METADATA_ENTRY_BYTES = 1024;
26074
26177
  var MAX_METADATA_VERBATIM_BYTES = 2048;
26075
26178
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
26076
26179
  var NoteMetadataSchema = typebox_exports.Object({
26180
+ ...PolicySchema,
26077
26181
  origin: typebox_exports.Union([...ORIGIN_VALUES]),
26078
26182
  created_at: typebox_exports.String(),
26079
26183
  updated_at: typebox_exports.String(),
@@ -26081,7 +26185,7 @@ var NoteMetadataSchema = typebox_exports.Object({
26081
26185
  project: typebox_exports.Optional(typebox_exports.String()),
26082
26186
  extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
26083
26187
  }, { additionalProperties: false });
26084
- function noteMetadata(meta2) {
26188
+ function noteMetadata(meta2, address) {
26085
26189
  const extra = {};
26086
26190
  let verbatimBytes = 0;
26087
26191
  const put = (key, value) => {
@@ -26099,6 +26203,7 @@ function noteMetadata(meta2) {
26099
26203
  put(key, value);
26100
26204
  }
26101
26205
  return {
26206
+ ...policyAt(meta2, address),
26102
26207
  origin: meta2.origin,
26103
26208
  created_at: localIso(meta2.createdAt),
26104
26209
  updated_at: localIso(meta2.updatedAt),
@@ -26109,6 +26214,7 @@ function noteMetadata(meta2) {
26109
26214
  }
26110
26215
  function renderMetadata(metadata) {
26111
26216
  const fields = [
26217
+ renderPolicy(metadata),
26112
26218
  `origin ${metadata.origin}`,
26113
26219
  `created ${metadata.created_at}`,
26114
26220
  `updated ${metadata.updated_at}`,
@@ -26137,6 +26243,8 @@ var NoteIdentitySchema = {
26137
26243
  };
26138
26244
  var ListedFileSchema = typebox_exports.Object({
26139
26245
  ...NoteIdentitySchema,
26246
+ ...PolicySchema,
26247
+ ...WarningsSchema,
26140
26248
  updated_at: typebox_exports.String(),
26141
26249
  crumpled_at: typebox_exports.Optional(typebox_exports.String())
26142
26250
  }, { additionalProperties: false });
@@ -26155,16 +26263,21 @@ var SnapshotSchema = {
26155
26263
  };
26156
26264
  var NotesWriteDataSchema = typebox_exports.Object({
26157
26265
  ...NoteIdentitySchema,
26266
+ ...PolicySchema,
26267
+ ...WarningsSchema,
26158
26268
  outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
26159
26269
  }, { additionalProperties: false });
26160
26270
  var NotesUpdateDataSchema = typebox_exports.Object({
26161
26271
  ...NoteIdentitySchema,
26272
+ ...PolicySchema,
26273
+ ...WarningsSchema,
26162
26274
  change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
26163
26275
  rename_from: typebox_exports.Optional(typebox_exports.String())
26164
26276
  }, { additionalProperties: false });
26165
26277
  var NotesReadDataSchema = typebox_exports.Object({
26166
26278
  ...NoteIdentitySchema,
26167
26279
  metadata: NoteMetadataSchema,
26280
+ ...WarningsSchema,
26168
26281
  ...TextWindowSchema.properties
26169
26282
  }, { additionalProperties: false });
26170
26283
  var NotesListDataSchema = typebox_exports.Object({
@@ -26196,11 +26309,12 @@ function snapshot(rows, limit, status, renderData, shrink) {
26196
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.`);
26197
26310
  }
26198
26311
  function listedFile(row, identity) {
26199
- 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 } };
26200
26314
  }
26201
- 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 });
26202
26316
  function renderWriteData(data) {
26203
- return `${data.outcome} ${renderIdentity(data)}`;
26317
+ return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
26204
26318
  }
26205
26319
  var notesWrite = {
26206
26320
  name: "notes_write",
@@ -26212,8 +26326,8 @@ var notesWrite = {
26212
26326
  async execute(params, context2) {
26213
26327
  try {
26214
26328
  const identity = notesIdentityForCall(context2, params.cwd);
26215
- const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin });
26216
- 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 });
26217
26331
  } catch (error2) {
26218
26332
  return failureOf(error2);
26219
26333
  }
@@ -26224,18 +26338,20 @@ var notesUpdateParameters = typebox_exports.Object({
26224
26338
  address: typebox_exports.String(),
26225
26339
  edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
26226
26340
  origin: ORIGIN,
26341
+ ...POLICY_PARAMETERS,
26227
26342
  crumpled: CRUMPLED_PARAMETER,
26228
26343
  replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
26229
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." })),
26230
26345
  cwd: CWD_PARAMETER
26231
26346
  }, { additionalProperties: false });
26232
26347
  function renderUpdateData(data) {
26233
- 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);
26234
26350
  }
26235
26351
  var notesUpdate = {
26236
26352
  name: "notes_update",
26237
26353
  label: "Notes update",
26238
- 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}`,
26239
26355
  parameters: notesUpdateParameters,
26240
26356
  outputSchema: resultSchema(NotesUpdateDataSchema),
26241
26357
  executionMode: "sequential",
@@ -26244,11 +26360,11 @@ var notesUpdate = {
26244
26360
  const identity = notesIdentityForCall(context2, params.cwd);
26245
26361
  const store = createNotesStore(identity);
26246
26362
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
26247
- 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 });
26248
26364
  onChange?.(change);
26249
26365
  const from = noteIdentity(identity, params.address).address;
26250
26366
  const to = noteIdentity(identity, renameTo ?? params.address);
26251
- 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 });
26252
26368
  } catch (error2) {
26253
26369
  return failureOf(error2);
26254
26370
  }
@@ -26257,8 +26373,8 @@ var notesUpdate = {
26257
26373
  };
26258
26374
  var notesReadParameters = typebox_exports.Object({ address: typebox_exports.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
26259
26375
  function renderReadData(data) {
26260
- return `${renderIdentity(data)}
26261
- ${renderMetadata(data.metadata)}
26376
+ return withWarnings(`${renderIdentity(data)}
26377
+ ${renderMetadata(data.metadata)}`, data) + `
26262
26378
 
26263
26379
  ${renderTextWindow(data)}`;
26264
26380
  }
@@ -26276,8 +26392,9 @@ var notesRead = {
26276
26392
  if (!note) return failure2("not_found", `No note at ${resolved.address}.`);
26277
26393
  const totalChars = Array.from(note.body).length;
26278
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.`);
26279
- const metadata = noteMetadata(note.meta);
26280
- 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));
26281
26398
  } catch (error2) {
26282
26399
  return failureOf(error2);
26283
26400
  }
@@ -26288,7 +26405,8 @@ var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit:
26288
26405
  function renderListData(data) {
26289
26406
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
26290
26407
  for (const file of data.files) {
26291
- 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}`));
26292
26410
  }
26293
26411
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
26294
26412
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
@@ -26315,7 +26433,8 @@ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Opti
26315
26433
  function renderSearchData(data) {
26316
26434
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
26317
26435
  for (const file of data.files) {
26318
- 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}`));
26319
26438
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
26320
26439
  }
26321
26440
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -26421,7 +26540,7 @@ function prepareSelection(projection, params) {
26421
26540
  const folds = !params.roles && params.query === void 0;
26422
26541
  const candidates = [];
26423
26542
  let run = [];
26424
- for (const event of filteredItems(projection, params, false)) {
26543
+ for (const event of filteredItems(projection, params)) {
26425
26544
  if (folds && (event.role === "tool" || event.role === "context")) {
26426
26545
  run.push(event);
26427
26546
  continue;
@@ -26471,7 +26590,7 @@ function corpusSelection(params) {
26471
26590
  return resolveSelection(params);
26472
26591
  }
26473
26592
  function sessionRepresentative(projection, scoped) {
26474
- 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) !== "");
26475
26594
  if (scoped.roles) return events.at(-1);
26476
26595
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
26477
26596
  }
@@ -26515,7 +26634,7 @@ var CorpusCollector = class {
26515
26634
  /** Returns whether this session contributes an overview representative. */
26516
26635
  add(session, projection) {
26517
26636
  if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
26518
- for (const event of filteredItems(projection, this.scoped, false)) {
26637
+ for (const event of filteredItems(projection, this.scoped)) {
26519
26638
  const document = eventDocument(event);
26520
26639
  if ((event.role === "user" || event.role === "assistant") && document === "") continue;
26521
26640
  const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
@@ -26551,10 +26670,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
26551
26670
  break;
26552
26671
  }
26553
26672
  const page = pageData(prepared, start, end, maxChars);
26554
- if (!fits(page)) {
26555
- 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";
26556
- 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}.`);
26557
- }
26673
+ if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
26558
26674
  return success(page);
26559
26675
  }
26560
26676
 
@@ -26682,6 +26798,12 @@ function renderRead(data) {
26682
26798
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
26683
26799
  }
26684
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
+ }
26685
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." }));
26686
26808
  var historyListParameters = typebox_exports.Object({
26687
26809
  session: sessionParameter,
@@ -26704,7 +26826,7 @@ var historyList = {
26704
26826
  async execute(params, context2, wrapText = plainText) {
26705
26827
  const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
26706
26828
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
26707
- 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));
26708
26830
  const selector = parseSessionSelector(params.session);
26709
26831
  if (!selector.ok) return selector;
26710
26832
  const corpus = "corpus" in context2 ? context2.corpus : void 0;
@@ -26733,7 +26855,7 @@ var historyList = {
26733
26855
  }
26734
26856
  }
26735
26857
  const notice2 = notices.length ? { notice: notices.join("") } : {};
26736
- const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
26858
+ const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
26737
26859
  return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
26738
26860
  }
26739
26861
  const target = await resolveSession(corpus, selector.data);
@@ -26741,7 +26863,7 @@ var historyList = {
26741
26863
  const loaded = await loadHistorySession(target.data);
26742
26864
  if (!loaded.ok) return loaded;
26743
26865
  const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
26744
- 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));
26745
26867
  return result.ok ? success({ ...result.data, ...notice }) : result;
26746
26868
  },
26747
26869
  render: (result) => renderOutcome(result, renderPage)
@@ -28115,8 +28237,6 @@ function localHistoryCorpus(options) {
28115
28237
 
28116
28238
  // src/boot/text.ts
28117
28239
  var SHELF_FRESH_LIMIT = 3;
28118
- var CHEATSHEET_BOOT_MAX_CHARS = 1536;
28119
- var MAP_BOOT_MAX_CHARS = 4096;
28120
28240
  var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
28121
28241
  var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
28122
28242
  var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -28159,9 +28279,15 @@ Still a tie? *shrugs* You've got a brain. Use it.
28159
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\`.
28160
28280
  ${NOTES_PROTOCOL_CLOSE_TAG}`;
28161
28281
  var MAPS_BLOCK = `<notesoup:maps>
28162
- Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
28163
- Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
28164
- 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.
28165
28291
 
28166
28292
  - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
28167
28293
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -28240,20 +28366,22 @@ function notesIndex(snapshot2, tools2, agentName, modelName) {
28240
28366
  continue;
28241
28367
  }
28242
28368
  const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
28243
- const pinned = ["CHEATSHEET.md", "MAP.md"].flatMap((path) => {
28244
- const row = rows.find((row2) => row2.path === path);
28245
- return row?.body ? [row] : [];
28246
- });
28247
- 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) => {
28248
28372
  const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
28249
28373
  const title = feedTitle(row.body);
28250
28374
  return title === void 0 ? ` ${locator}` : ` ${title}
28251
28375
  ${locator}`;
28252
28376
  });
28253
28377
  if (pinned.length === 0 && fresh.length === 0) continue;
28254
- 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}
28255
28381
 
28256
- ${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}.`));
28257
28385
  if (fresh.length > 0) parts.push(`recent
28258
28386
 
28259
28387
  ${fresh.join("\n\n")}`);
@@ -28261,13 +28389,7 @@ ${fresh.join("\n\n")}`);
28261
28389
  }
28262
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.";
28263
28391
  }
28264
- function pinnedBodyForBoot(address, body, maxChars) {
28265
- const chars = Array.from(body);
28266
- if (chars.length <= maxChars) return body;
28267
- return `${chars.slice(0, maxChars).join("")}
28268
- [truncated at ${maxChars} chars; slim this page down, full body at \`${address}\`]`;
28269
- }
28270
- function renderBootBlock(data) {
28392
+ function renderIdentity2(data) {
28271
28393
  const shown2 = /* @__PURE__ */ new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
28272
28394
  const windows = data.tree.windows.filter((_window, index) => shown2.has(index));
28273
28395
  const width = Math.max(8, ...windows.map((window) => window.shortName.length));
@@ -28281,10 +28403,12 @@ function renderBootBlock(data) {
28281
28403
  return `${window.isCurrent ? "\u2514\u2500" : "\u251C\u2500"} ${name}${range}${window.isCurrent ? " \u2190 you are here" : ""}`;
28282
28404
  })
28283
28405
  ];
28284
- const identity = `${WINDOW_IDENTITY_OPEN_TAG}
28406
+ return `${WINDOW_IDENTITY_OPEN_TAG}
28285
28407
  ${lines.join("\n")}
28286
28408
  ${WINDOW_IDENTITY_CLOSE_TAG}`;
28287
- 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");
28288
28412
  }
28289
28413
 
28290
28414
  // plugins/codex/src/text.ts
@@ -28410,13 +28534,6 @@ function successFor(bound, outcome) {
28410
28534
  ...outcome.ok ? {} : { isError: true }
28411
28535
  };
28412
28536
  }
28413
- function paramProblem(schema, params) {
28414
- const first = Errors2(schema, params).find((error2) => error2.keyword !== "boolean");
28415
- if (!first) return "unrecognized shape";
28416
- const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
28417
- const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28418
- return `${field ? `${field} ` : ""}${first.message}${extra}`;
28419
- }
28420
28537
  function metaFacts(meta2, binding) {
28421
28538
  const rootSessionId = rootSessionIdOf(meta2);
28422
28539
  if (binding.rootSessionId !== rootSessionId) {