notesoup 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.js +1 -1
  4. package/dist/src/budget/parse.d.ts +14 -0
  5. package/dist/src/budget/parse.js +36 -0
  6. package/dist/src/budget/policy.js +2 -7
  7. package/dist/src/budget/text.d.ts +2 -0
  8. package/dist/src/budget/text.js +2 -0
  9. package/dist/src/claude/helper.js +1 -2
  10. package/dist/src/claude/thresholds.js +45 -66
  11. package/dist/src/dream/lock.js +6 -13
  12. package/dist/src/dream/report.js +5 -15
  13. package/dist/src/history/history.js +4 -2
  14. package/dist/src/history/query.js +10 -22
  15. package/dist/src/notes/address.d.ts +0 -1
  16. package/dist/src/notes/address.js +5 -17
  17. package/dist/src/notes/errors.d.ts +2 -0
  18. package/dist/src/notes/errors.js +5 -0
  19. package/dist/src/notes/frontmatter.js +16 -2
  20. package/dist/src/notes/identity.js +0 -3
  21. package/dist/src/notes/paths.d.ts +11 -1
  22. package/dist/src/notes/paths.js +28 -7
  23. package/dist/src/notes/store.d.ts +1 -0
  24. package/dist/src/notes/store.js +38 -37
  25. package/dist/src/pi/boot.js +1 -5
  26. package/dist/src/pi/budget.d.ts +3 -3
  27. package/dist/src/pi/budget.js +11 -11
  28. package/dist/src/pi/dream/cli.js +43 -11
  29. package/dist/src/pi/estimate.d.ts +1 -5
  30. package/dist/src/pi/estimate.js +4 -4
  31. package/dist/src/pi/history.js +1 -4
  32. package/dist/src/pi/notes/adapter.d.ts +1 -1
  33. package/dist/src/pi/notes/adapter.js +2 -2
  34. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  35. package/dist/src/pi/reset/artifacts.js +4 -4
  36. package/dist/src/pi/reset/committed.js +2 -2
  37. package/dist/src/pi/runtime.js +8 -5
  38. package/dist/src/pi/thresholds.js +5 -9
  39. package/dist/src/pi/tool-result.d.ts +1 -4
  40. package/dist/src/pi/tool-result.js +1 -1
  41. package/dist/src/pi/window.d.ts +5 -0
  42. package/dist/src/pi/window.js +7 -0
  43. package/dist/src/settings.d.ts +2 -0
  44. package/dist/src/settings.js +4 -3
  45. package/dist/src/tools/history.js +4 -7
  46. package/dist/src/tools/notes.d.ts +0 -4
  47. package/dist/src/tools/notes.js +6 -16
  48. package/dist/src/tools/output.d.ts +0 -3
  49. package/dist/src/tools/output.js +1 -9
  50. package/dist/src/tools/result.d.ts +1 -0
  51. package/dist/src/tools/result.js +14 -20
  52. package/dist/src/tools/schema.d.ts +0 -1
  53. package/dist/src/tools/schema.js +0 -1
  54. package/dist/test/agent-loop.test.js +1 -2
  55. package/dist/test/boot.integration.test.js +1 -1
  56. package/dist/test/claude-mod.test.js +221 -9
  57. package/dist/test/claude-validation.test.d.ts +1 -0
  58. package/dist/test/claude-validation.test.js +73 -0
  59. package/dist/test/dream-skill.test.js +2 -4
  60. package/dist/test/dream.test.js +14 -0
  61. package/dist/test/helpers/extension.js +1 -1
  62. package/dist/test/history.integration.test.js +2 -1
  63. package/dist/test/host-neutral.test.js +15 -0
  64. package/dist/test/notes-library.test.js +30 -1
  65. package/dist/test/notes.integration.test.js +7 -7
  66. package/dist/test/notes.test.js +24 -5
  67. package/dist/test/reset-lifecycle.test.js +1 -1
  68. package/docs/claude-code-mod.md +5 -3
  69. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  70. package/mods/notesoup/dist/claude/helper.js +147 -173
  71. package/mods/notesoup/hooks/register.ts +158 -67
  72. package/mods/notesoup/playbook.md +1 -1
  73. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  74. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  75. package/package.json +5 -3
  76. package/playbook.md +1 -1
  77. package/skills/dream/SKILL.md +1 -1
  78. package/skills/memory/SKILL.md +1 -1
  79. package/src/boot/render.ts +11 -21
  80. package/src/boot/snapshot.ts +2 -7
  81. package/src/boot/text.ts +1 -1
  82. package/src/budget/parse.ts +39 -0
  83. package/src/budget/policy.ts +2 -6
  84. package/src/budget/text.ts +3 -0
  85. package/src/claude/helper.ts +2 -2
  86. package/src/claude/thresholds.ts +45 -62
  87. package/src/dream/lock.ts +3 -9
  88. package/src/dream/report.ts +5 -10
  89. package/src/history/history.ts +4 -2
  90. package/src/history/query.ts +10 -23
  91. package/src/notes/address.ts +4 -16
  92. package/src/notes/errors.ts +6 -0
  93. package/src/notes/frontmatter.ts +12 -2
  94. package/src/notes/identity.ts +0 -2
  95. package/src/notes/paths.ts +23 -5
  96. package/src/notes/store.ts +33 -36
  97. package/src/pi/boot.ts +1 -13
  98. package/src/pi/budget.ts +10 -11
  99. package/src/pi/dream/cli.ts +35 -10
  100. package/src/pi/estimate.ts +4 -4
  101. package/src/pi/history.ts +1 -5
  102. package/src/pi/notes/adapter.ts +2 -2
  103. package/src/pi/reset/artifacts.ts +4 -4
  104. package/src/pi/reset/committed.ts +2 -2
  105. package/src/pi/runtime.ts +7 -6
  106. package/src/pi/thresholds.ts +5 -11
  107. package/src/pi/tool-result.ts +1 -1
  108. package/src/pi/window.ts +8 -0
  109. package/src/settings.ts +4 -3
  110. package/src/tools/history.ts +4 -8
  111. package/src/tools/notes.ts +7 -20
  112. package/src/tools/output.ts +1 -12
  113. package/src/tools/result.ts +14 -19
  114. package/src/tools/schema.ts +0 -1
  115. package/dist/src/dream/playbook.d.ts +0 -1
  116. package/dist/src/dream/playbook.js +0 -2
  117. package/dist/src/pi/reset/text.d.ts +0 -4
  118. package/dist/src/pi/reset/text.js +0 -7
  119. package/src/dream/playbook.ts +0 -3
  120. package/src/pi/reset/text.ts +0 -9
@@ -1,15 +1,4 @@
1
1
  import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock } from "./text.js";
2
- /** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
3
- function identityBlock(agentName, modelName, firstWindowId, currentWindowId, previousWindowId) {
4
- const lines = [
5
- `Agent name: ${agentName} (brain: ${modelName})`,
6
- `First context window id: ${firstWindowId}`,
7
- `Current context window id: ${currentWindowId}`,
8
- ];
9
- if (previousWindowId)
10
- lines.push(`Previous context window id: ${previousWindowId}`);
11
- return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
12
- }
13
2
  function relativeTime(timestamp, now) {
14
3
  const seconds = Math.trunc((timestamp - now) / 1000);
15
4
  if (seconds === 0)
@@ -19,9 +8,6 @@ function relativeTime(timestamp, now) {
19
8
  const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
20
9
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
21
10
  }
22
- function rowsFor(snapshot, scope) {
23
- return snapshot.homes.get(scope) ?? [];
24
- }
25
11
  /** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
26
12
  const FEED_TITLE_MAX_CHARS = 40;
27
13
  function feedTitle(body) {
@@ -56,7 +42,7 @@ function notesIndex(snapshot, tools) {
56
42
  shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
57
43
  continue;
58
44
  }
59
- const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
45
+ const rows = (snapshot.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
60
46
  const map = rows.find((row) => row.path === "MAP.md");
61
47
  const fresh = rows
62
48
  .filter((row) => row.path !== "MAP.md")
@@ -87,9 +73,14 @@ function mapBodyForBoot(address, body) {
87
73
  return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
88
74
  }
89
75
  export function renderBootBlock(data) {
90
- const parts = [];
91
- parts.push(identityBlock(data.agentName, data.modelName, data.firstWindowId, data.currentWindowId, data.previousWindowId));
92
- parts.push(renderProtocolBlock(data.tools));
93
- parts.push(notesIndex(data.notes, data.tools));
94
- return parts.join("\n\n");
76
+ // Codex-style <context_window> identity block: the resolved agent and model names plus
77
+ // first/current/previous window ids.
78
+ const lines = [
79
+ `Agent name: ${data.agentName} (brain: ${data.modelName})`,
80
+ `First context window id: ${data.firstWindowId}`,
81
+ `Current context window id: ${data.currentWindowId}`,
82
+ ...(data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []),
83
+ ];
84
+ const identity = `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
85
+ return [identity, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
95
86
  }
@@ -7,18 +7,13 @@ const NOTES_HOMES = [
7
7
  { scope: "agent", label: "@self" },
8
8
  { scope: "model", label: "@model" },
9
9
  ];
10
- function queryForScope(scope) {
11
- if (scope === "agent" || scope === "model")
12
- return { scope };
13
- return { scope };
14
- }
15
10
  /**
16
11
  * Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
17
12
  * malformed note data and unrelated construction errors remain visible to the caller.
18
13
  */
19
14
  export async function loadNotesSnapshot(identity, openedAt, loadHome) {
20
15
  const store = createNotesStore(identity);
21
- const load = loadHome ?? ((scope) => store.list(queryForScope(scope)));
16
+ const load = loadHome ?? ((scope) => store.list({ scope }));
22
17
  const homes = new Map();
23
18
  const unavailable = [];
24
19
  for (const home of NOTES_HOMES) {
@@ -50,7 +50,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
50
50
 
51
51
  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\`.
52
52
 
53
- \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
53
+ \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each may carry a short Cheatsheet of rules that always apply (about 5 lines); the rest is the note index, with addresses and gists for lookup. Keep each one current.
54
54
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
55
55
  export function renderProtocolBlock(tools) {
56
56
  const names = {
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Scalar guards shared by the budget derivations. Settings and environment values arrive
3
+ * untyped from either host, so numbers, percentages and presence flags are validated here
4
+ * once instead of once per call site.
5
+ */
6
+ /** A finite number, from a typed value or an environment string; anything else is unknown. */
7
+ export declare function numberOf(value: unknown): number | undefined;
8
+ export declare function positiveNumber(value: unknown): number | undefined;
9
+ /** A margin or window is usable only as a positive safe integer. */
10
+ export declare function positiveInteger(value: unknown): number | undefined;
11
+ /** A percentage override is usable only in (0, 100]. */
12
+ export declare function percent(value: unknown): number | undefined;
13
+ /** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
14
+ export declare function presenceFlag(value: unknown): boolean;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Scalar guards shared by the budget derivations. Settings and environment values arrive
3
+ * untyped from either host, so numbers, percentages and presence flags are validated here
4
+ * once instead of once per call site.
5
+ */
6
+ /** A finite number, from a typed value or an environment string; anything else is unknown. */
7
+ export function numberOf(value) {
8
+ if (typeof value === "number")
9
+ return Number.isFinite(value) ? value : undefined;
10
+ if (typeof value === "string" && value.trim() !== "") {
11
+ const parsed = Number(value);
12
+ return Number.isFinite(parsed) ? parsed : undefined;
13
+ }
14
+ return undefined;
15
+ }
16
+ export function positiveNumber(value) {
17
+ const parsed = numberOf(value);
18
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
19
+ }
20
+ /** A margin or window is usable only as a positive safe integer. */
21
+ export function positiveInteger(value) {
22
+ const parsed = numberOf(value);
23
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
24
+ }
25
+ /** A percentage override is usable only in (0, 100]. */
26
+ export function percent(value) {
27
+ const parsed = numberOf(value);
28
+ return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
29
+ }
30
+ /** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
31
+ export function presenceFlag(value) {
32
+ if (typeof value !== "string")
33
+ return false;
34
+ const text = value.trim().toLowerCase();
35
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
36
+ }
@@ -1,11 +1,6 @@
1
1
  import { DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "./constants.js";
2
+ import { positiveInteger } from "./parse.js";
2
3
  import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
3
- /** A margin is usable only as a positive integer; anything else is ignored. */
4
- function validMargin(raw) {
5
- if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0)
6
- return undefined;
7
- return raw;
8
- }
9
4
  /**
10
5
  * Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
11
6
  * plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
@@ -20,7 +15,7 @@ export function deriveThresholds(reserveTokens, margins) {
20
15
  if (margins.reminderMarginTokens === undefined)
21
16
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
22
17
  else {
23
- const parsed = validMargin(margins.reminderMarginTokens);
18
+ const parsed = positiveInteger(margins.reminderMarginTokens);
24
19
  if (parsed === undefined) {
25
20
  warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
26
21
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
@@ -10,6 +10,8 @@ export declare const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea
10
10
  */
11
11
  export declare const WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
12
12
  export declare const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
13
+ /** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
14
+ export declare const WARNING_CONTENT = "<context_window_guidance>\nThis context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.\n</context_window_guidance>";
13
15
  /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
16
  export declare const CLAUDE_WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, end your turn; the reset runs after it.";
15
17
  /**
@@ -10,6 +10,8 @@ export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Defini
10
10
  */
11
11
  export const WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
12
12
  export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
13
+ /** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
14
+ export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
13
15
  /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
16
  export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
15
17
  /**
@@ -27,7 +27,6 @@ function paramProblem(schema, params) {
27
27
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
28
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
29
  }
30
- function jsonValue(value) { return JSON.parse(JSON.stringify(value)); }
31
30
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
32
31
  function boundOperation(operation, ...rest) {
33
32
  return {
@@ -59,7 +58,7 @@ export async function dispatch(request) {
59
58
  throw new Error("malformed request");
60
59
  const value = request;
61
60
  if (value.op === "schemas")
62
- return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
61
+ return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
63
62
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
64
63
  // cannot drift apart. The hooks module caches one copy per session.
65
64
  if (value.op === "texts")
@@ -1,5 +1,6 @@
1
1
  import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
- import { mergeNotesoupSettings } from "../settings.js";
2
+ import { percent, positiveInteger, positiveNumber, presenceFlag } from "../budget/parse.js";
3
+ import { isPlainObject, mergeNotesoupSettings } from "../settings.js";
3
4
  /**
4
5
  * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
5
6
  *
@@ -15,51 +16,26 @@ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
15
16
  export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
16
17
  /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
17
18
  export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
19
+ /**
20
+ * A point is never expressed as zero: the mod reads `measured >= reset` as due, so a zero point
21
+ * would clear memory on every turn, including a fresh window. A window smaller than Claude's own
22
+ * reserves therefore resets at the smallest expressible point instead.
23
+ */
24
+ const MIN_POINT_TOKENS = 1;
25
+ /** The same floor in percent units, for the no-window fallback. */
26
+ const MIN_POINT_PERCENT = 0.1;
18
27
  /**
19
28
  * The percent fallback assumes the classic 200K model window: it is reached only when
20
29
  * `usage()` reports no window and no breakdown, and it reproduces the token maths below
21
30
  * on that window (about 83.5% / 79.4% / 71.2%).
22
31
  */
23
32
  const ASSUMED_WINDOW_TOKENS = 200_000;
24
- function isObject(value) {
25
- return typeof value === "object" && value !== null && !Array.isArray(value);
26
- }
27
- /** Numbers may arrive typed or as environment strings; anything else is unknown. */
28
- function numberOf(value) {
29
- if (typeof value === "number")
30
- return Number.isFinite(value) ? value : undefined;
31
- if (typeof value === "string" && value.trim() !== "") {
32
- const parsed = Number(value);
33
- return Number.isFinite(parsed) ? parsed : undefined;
34
- }
35
- return undefined;
36
- }
37
- function positiveNumberOf(value) {
38
- const parsed = numberOf(value);
39
- return parsed !== undefined && parsed > 0 ? parsed : undefined;
40
- }
41
- /** A margin is usable only as a positive integer, matching Pi's budget policy. */
42
- function positiveIntegerOf(value) {
43
- const parsed = numberOf(value);
44
- return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
45
- }
46
- /** Claude accepts a percent override only in (0, 100]. */
47
- function percentOf(value) {
48
- const parsed = numberOf(value);
49
- return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
50
- }
51
- /** Presence-style flags (DISABLE_AUTO_COMPACT): any value but an explicit no counts as on. */
52
- function flagOn(value) {
53
- if (typeof value !== "string")
54
- return false;
55
- const text = value.trim().toLowerCase();
56
- return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
57
- }
58
- function settingFlag(settings, key) {
59
- if (!isObject(settings))
60
- return undefined;
61
- const value = settings[key];
62
- return typeof value === "boolean" ? value : undefined;
33
+ /**
34
+ * The active auto-compact flag: absent means Claude's default (on), and only an explicit
35
+ * boolean counts. Settings are read from one host-supplied scope, so the flag is top-level.
36
+ */
37
+ function settingFlag(settings) {
38
+ return isPlainObject(settings) && typeof settings.autoCompactEnabled === "boolean" ? settings.autoCompactEnabled : undefined;
63
39
  }
64
40
  /**
65
41
  * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
@@ -68,20 +44,20 @@ function settingFlag(settings, key) {
68
44
  */
69
45
  function configuredWindow(settings, env, model) {
70
46
  const windows = [];
71
- const fromEnv = positiveNumberOf(env.autoCompactWindow);
47
+ const fromEnv = positiveNumber(env.autoCompactWindow);
72
48
  if (fromEnv !== undefined)
73
49
  windows.push(fromEnv);
74
- if (typeof model === "string" && model.length > 0 && isObject(settings)) {
75
- const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
50
+ if (typeof model === "string" && model.length > 0 && isPlainObject(settings)) {
51
+ const modelSettings = isPlainObject(settings.modelSettings) ? settings.modelSettings : {};
76
52
  const perModel = modelSettings[model];
77
- if (isObject(perModel)) {
78
- const value = positiveNumberOf(perModel.autoCompactWindow);
53
+ if (isPlainObject(perModel)) {
54
+ const value = positiveNumber(perModel.autoCompactWindow);
79
55
  if (value !== undefined)
80
56
  windows.push(value);
81
57
  }
82
58
  }
83
- if (isObject(settings)) {
84
- const value = positiveNumberOf(settings.autoCompactWindow);
59
+ if (isPlainObject(settings)) {
60
+ const value = positiveNumber(settings.autoCompactWindow);
85
61
  if (value !== undefined)
86
62
  windows.push(value);
87
63
  }
@@ -89,20 +65,20 @@ function configuredWindow(settings, env, model) {
89
65
  }
90
66
  function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
91
67
  const tokens = Math.max(0, Math.floor(native));
92
- const reset = Math.max(0, tokens - resetMargin);
68
+ const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
93
69
  return {
94
70
  source, autoCompact, unit: "tokens",
95
- native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
71
+ native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
96
72
  };
97
73
  }
98
74
  /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
99
75
  function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
100
76
  const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
101
77
  const native = pct === undefined ? base : Math.min(pct, base);
102
- const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
78
+ const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
103
79
  return {
104
80
  source: "percent", autoCompact, unit: "percent",
105
- native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
81
+ native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
106
82
  };
107
83
  }
108
84
  /**
@@ -112,37 +88,40 @@ function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
112
88
  * helper boundary, where nothing is typed.
113
89
  */
114
90
  export function resolveClaudeLimits(facts) {
115
- const root = isObject(facts) ? facts : {};
116
- const usage = isObject(root.usage) ? root.usage : {};
117
- const breakdown = isObject(root.breakdown) ? root.breakdown : {};
118
- const env = isObject(root.env) ? root.env : {};
91
+ const root = isPlainObject(facts) ? facts : {};
92
+ const usage = isPlainObject(root.usage) ? root.usage : {};
93
+ const breakdown = isPlainObject(root.breakdown) ? root.breakdown : {};
94
+ const env = isPlainObject(root.env) ? root.env : {};
119
95
  const settings = root.settings;
96
+ // The host hands over its merged settings, so there is no separate project scope to name.
120
97
  const margins = mergeNotesoupSettings(settings, undefined);
121
- const resetMargin = positiveIntegerOf(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
122
- const warningRunway = positiveIntegerOf(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
123
- const autoCompact = settingFlag(settings, "autoCompactEnabled") !== false
124
- && !flagOn(env.disableAutoCompact)
98
+ const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
99
+ const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
100
+ const autoCompact = settingFlag(settings) !== false
101
+ && !presenceFlag(env.disableAutoCompact)
125
102
  && breakdown.isAutoCompactEnabled !== false;
126
- const pct = percentOf(env.pctOverride);
103
+ const pct = percent(env.pctOverride);
127
104
  // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
128
105
  // the percent override is applied separately, on the window-after-output-reserve it is
129
- // minted from (threshold + summary buffer).
130
- const threshold = positiveNumberOf(breakdown.autoCompactThreshold);
106
+ // minted from (threshold + summary buffer). A malformed override that floors the point to
107
+ // zero is not a point at all, so it degrades to the next source instead of resetting always.
108
+ const threshold = positiveNumber(breakdown.autoCompactThreshold);
131
109
  if (autoCompact && threshold !== undefined) {
132
110
  const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
133
111
  if (native > 0)
134
112
  return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
135
113
  }
136
- // (b) The same point computed from the reported window plus settings and environment.
137
- const window = positiveNumberOf(usage.window);
114
+ // (b) The same point computed from the reported window plus settings and environment. A real
115
+ // window always answers here: falling through to the percent fallback would express the
116
+ // points on an assumed 200K window, which is later than the window notesoup can see.
117
+ const window = positiveNumber(usage.window);
138
118
  if (window !== undefined) {
139
119
  const configured = configuredWindow(settings, env, breakdown.model);
140
120
  const effective = Math.min(configured ?? window, window);
141
121
  const native = autoCompact
142
122
  ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
143
123
  : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
144
- if (native > 0)
145
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
124
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
146
125
  }
147
126
  // (c) Nothing usable but percentages.
148
127
  return percentLimits(autoCompact, pct, resetMargin, warningRunway);
@@ -16,18 +16,6 @@ function readText(path) {
16
16
  return undefined;
17
17
  }
18
18
  }
19
- function stampMtime(stampPath) {
20
- try {
21
- return statSync(stampPath).mtimeMs;
22
- }
23
- catch {
24
- return undefined;
25
- }
26
- }
27
- /**
28
- * Cleanup ownership: only the exact marker this run wrote may be removed. The token is
29
- * diagnostic and guards cleanup; it never grants permission to take an existing lock.
30
- */
31
19
  function ownsLock(lock) {
32
20
  if (!lock.held || !lock.token)
33
21
  return false;
@@ -41,7 +29,12 @@ function ownsLock(lock) {
41
29
  */
42
30
  export function acquireLock(path) {
43
31
  const now = Date.now();
44
- const priorStampMtime = stampMtime(lastRunPath(path));
32
+ // The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
33
+ let priorStampMtime;
34
+ try {
35
+ priorStampMtime = statSync(lastRunPath(path)).mtimeMs;
36
+ }
37
+ catch { /* no sidecar yet */ }
45
38
  const token = randomUUID();
46
39
  try {
47
40
  writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
@@ -5,20 +5,10 @@ import { errorMessage } from "../error-message.js";
5
5
  function writeList(writes) {
6
6
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
7
7
  }
8
- /** Best-effort text write; returns the failure message instead of throwing. */
9
- function writeText(path, content) {
8
+ /** Best-effort filesystem step; returns the failure message instead of throwing. */
9
+ function attempt(action) {
10
10
  try {
11
- mkdirSync(dirname(path), { recursive: true });
12
- writeFileSync(path, content);
13
- return undefined;
14
- }
15
- catch (error) {
16
- return errorMessage(error);
17
- }
18
- }
19
- function appendText(path, content) {
20
- try {
21
- appendFileSync(path, content);
11
+ action();
22
12
  return undefined;
23
13
  }
24
14
  catch (error) {
@@ -32,11 +22,11 @@ function appendText(path, content) {
32
22
  */
33
23
  export function finishDream(home, stamp, reportPath, failed, body, writes) {
34
24
  const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
35
- let reportError = writeText(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`);
25
+ let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
36
26
  const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
37
27
  if (!audit.ok) {
38
28
  console.error(`dream: final audit failed: ${audit.error}`);
39
- reportError ??= appendText(reportPath, `\n## Final audit failed\n\n${audit.error}\n`);
29
+ reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
40
30
  }
41
31
  if (reportError)
42
32
  console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
@@ -161,14 +161,16 @@ export function visibleItem(event, maxChars, matchOffset) {
161
161
  const document = eventDocument(event);
162
162
  const chars = Array.from(document);
163
163
  const start = matchOffset ?? 0;
164
- const truncated = start > 0 || start + maxChars < chars.length;
164
+ // A negative budget would cut the tail and still call the result a prefix.
165
+ const limit = Math.max(0, maxChars);
166
+ const truncated = start > 0 || start + limit < chars.length;
165
167
  return {
166
168
  seq: event.seq,
167
169
  window_id: event.windowId,
168
170
  role: event.role,
169
171
  created_at: event.createdAt ?? null,
170
172
  ...toolSummary(event),
171
- content: truncated ? chars.slice(start, start + maxChars).join("") : document,
173
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
172
174
  truncated,
173
175
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
174
176
  };
@@ -1,25 +1,19 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type } from "typebox";
3
3
  import { failure, success } from "../tools/result.js";
4
- import { earliestMatchOffsetChars, prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
4
+ import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
+ import { earliestMatchOffsetChars } from "../text-match.js";
5
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
7
  import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
7
8
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
8
9
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
9
- /** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
10
- function isoUtcMs(value) {
11
- const match = ISO_8601.exec(value);
12
- if (match === null)
13
- return undefined;
14
- const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
15
- return Number.isNaN(at) ? undefined : at;
16
- }
17
10
  /** Epoch ms for one optional time param, or a refusal naming it. */
18
11
  function timeBound(name, value) {
19
12
  if (value === undefined)
20
13
  return success(undefined);
21
- const at = isoUtcMs(value);
22
- return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
14
+ const match = ISO_8601.exec(value);
15
+ const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
16
+ return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
23
17
  }
24
18
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
25
19
  function resolveTimeBounds(params) {
@@ -157,15 +151,6 @@ function selectionCandidates(projection, params) {
157
151
  .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
158
152
  .filter((candidate) => candidate.matchOffset >= 0));
159
153
  }
160
- /**
161
- * Take the limit from the end `from` names, starting there so a budget for one row keeps the most
162
- * important row. The selection is already filtered to its range; `from` never states a direction.
163
- */
164
- function orderedCandidates(vis, params, limit) {
165
- const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
166
- const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
167
- return params.from === "oldest" ? selected : selected.reverse();
168
- }
169
154
  /**
170
155
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
171
156
  * Grow the page in selection order; shorten the first preview only when no full row fits.
@@ -179,9 +164,12 @@ export function selectPage(projection, params, fits, maxChars) {
179
164
  if (!candidates.ok)
180
165
  return candidates;
181
166
  const vis = candidates.data;
182
- const limit = scoped.limit ?? 20;
167
+ // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
168
+ // At least one: `slice(-0)` would otherwise return the whole selection.
169
+ const limit = Math.max(1, scoped.limit ?? 20);
183
170
  const folds = foldsRuns(scoped);
184
- const ordered = orderedCandidates(vis, scoped, limit);
171
+ const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
172
+ const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
185
173
  const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
186
174
  const kept = [];
187
175
  for (const candidate of ordered) {
@@ -6,7 +6,6 @@ export type NoteAddress = {
6
6
  who?: string;
7
7
  };
8
8
  export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
9
- export declare function assertVirtualPath(value: unknown): string;
10
9
  /**
11
10
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
12
11
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -1,21 +1,6 @@
1
- import { NoteError } from "./errors.js";
2
- import { SLUG_PATTERN } from "./paths.js";
1
+ import { NoteError, shown } from "./errors.js";
2
+ import { assertVirtualPath, SLUG_PATTERN } from "./paths.js";
3
3
  export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
4
- /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
5
- function shown(value) {
6
- const json = JSON.stringify(value);
7
- return json === undefined ? String(value) : json;
8
- }
9
- export function assertVirtualPath(value) {
10
- if (typeof value !== "string" || value.length === 0)
11
- throw new NoteError("invalid_address", "The address is empty; give the note a path.");
12
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
13
- throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
14
- const parts = value.split("/");
15
- if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
16
- throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
17
- return value;
18
- }
19
4
  /**
20
5
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
21
6
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -37,6 +22,9 @@ export function globToRegExp(pattern) {
37
22
  source += "[^/]*";
38
23
  }
39
24
  }
25
+ else if (char === "?") {
26
+ source += "[^/]";
27
+ }
40
28
  else {
41
29
  source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
42
30
  }
@@ -9,3 +9,5 @@ export declare class NoteError extends Error {
9
9
  editIndex?: number;
10
10
  });
11
11
  }
12
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
13
+ export declare function shown(value: unknown): string;
@@ -11,3 +11,8 @@ export class NoteError extends Error {
11
11
  this.editIndex = extra.editIndex;
12
12
  }
13
13
  }
14
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
15
+ export function shown(value) {
16
+ const json = JSON.stringify(value);
17
+ return json === undefined ? String(value) : json;
18
+ }
@@ -107,15 +107,29 @@ export function parseNote(raw, now = Date.now()) {
107
107
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
108
108
  return { meta: meta, body };
109
109
  }
110
- /** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
110
+ /**
111
+ * Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
112
+ * A quoted string must not come back as another type: a value that `JSON.parse` reads as a
113
+ * non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
114
+ * with its type intact.
115
+ */
111
116
  function yamlScalar(value) {
112
117
  if (typeof value === "string") {
113
118
  const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
114
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()))
119
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value))
115
120
  return value;
116
121
  }
117
122
  return JSON.stringify(value);
118
123
  }
124
+ /** True when a bare scalar would be read back as a number, boolean or null instead of text. */
125
+ function parsesAsNonString(text) {
126
+ try {
127
+ return typeof JSON.parse(text) !== "string";
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
119
133
  /** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
120
134
  export function serializeNote(meta, body) {
121
135
  const lines = [];