notesoup 0.40.0 → 0.42.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 (93) hide show
  1. package/dist/src/boot/render.js +1 -1
  2. package/dist/src/boot/text.d.ts +12 -0
  3. package/dist/src/boot/text.js +25 -5
  4. package/dist/src/budget/policy.js +1 -1
  5. package/dist/src/budget/text.d.ts +12 -0
  6. package/dist/src/budget/text.js +13 -1
  7. package/dist/src/claude/helper.js +23 -2
  8. package/dist/src/claude/thresholds.d.ts +39 -0
  9. package/dist/src/claude/thresholds.js +149 -0
  10. package/dist/src/dream/doctor.js +3 -2
  11. package/dist/src/dream/git.js +2 -1
  12. package/dist/src/dream/jail.js +10 -10
  13. package/dist/src/dream/report.js +3 -2
  14. package/dist/src/error-message.d.ts +2 -0
  15. package/dist/src/error-message.js +4 -0
  16. package/dist/src/history/history.js +1 -1
  17. package/dist/src/history/query.js +6 -6
  18. package/dist/src/notes/address.d.ts +1 -1
  19. package/dist/src/notes/address.js +12 -12
  20. package/dist/src/notes/store.js +16 -12
  21. package/dist/src/pi/anchored.d.ts +16 -0
  22. package/dist/src/pi/anchored.js +55 -0
  23. package/dist/src/pi/budget.d.ts +1 -1
  24. package/dist/src/pi/budget.js +33 -28
  25. package/dist/src/pi/dream/cli.js +3 -2
  26. package/dist/src/pi/dream/runner.js +2 -1
  27. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  28. package/dist/src/pi/reset/lifecycle.js +4 -3
  29. package/dist/src/pi/reset/text.d.ts +3 -4
  30. package/dist/src/pi/reset/text.js +5 -4
  31. package/dist/src/pi/runtime.js +13 -16
  32. package/dist/src/pi/thresholds.js +2 -1
  33. package/dist/src/pi/tool-result.js +2 -2
  34. package/dist/src/settings.d.ts +8 -0
  35. package/dist/src/settings.js +6 -1
  36. package/dist/src/tools/history.js +12 -12
  37. package/dist/src/tools/notes.d.ts +3 -3
  38. package/dist/src/tools/notes.js +12 -11
  39. package/dist/src/tools/output.d.ts +2 -0
  40. package/dist/src/tools/output.js +2 -0
  41. package/dist/src/tools/result.js +2 -2
  42. package/dist/src/tools/schema.js +3 -3
  43. package/dist/test/agent-loop.test.js +78 -28
  44. package/dist/test/boot.integration.test.js +5 -5
  45. package/dist/test/budget-settings.integration.test.js +9 -8
  46. package/dist/test/claude-mod.test.js +213 -23
  47. package/dist/test/dream.test.js +3 -3
  48. package/dist/test/history.integration.test.js +7 -8
  49. package/dist/test/host-neutral.test.js +2 -2
  50. package/dist/test/notes-library.test.js +1 -1
  51. package/dist/test/notes.integration.test.js +5 -5
  52. package/dist/test/notes.test.js +16 -16
  53. package/dist/test/reset-lifecycle.test.js +2 -2
  54. package/docs/claude-code-mod.md +10 -2
  55. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  56. package/mods/notesoup/dist/claude/helper.js +212 -45
  57. package/mods/notesoup/hooks/register.ts +209 -48
  58. package/mods/notesoup/playbook.md +10 -10
  59. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  60. package/package.json +1 -1
  61. package/playbook.md +10 -10
  62. package/skills/dream/SKILL.md +1 -1
  63. package/skills/memory/SKILL.md +5 -3
  64. package/src/boot/render.ts +1 -1
  65. package/src/boot/text.ts +31 -5
  66. package/src/budget/policy.ts +1 -1
  67. package/src/budget/text.ts +18 -1
  68. package/src/claude/helper.ts +20 -3
  69. package/src/claude/thresholds.ts +170 -0
  70. package/src/dream/doctor.ts +3 -2
  71. package/src/dream/git.ts +2 -1
  72. package/src/dream/jail.ts +10 -10
  73. package/src/dream/report.ts +3 -2
  74. package/src/error-message.ts +4 -0
  75. package/src/history/history.ts +1 -1
  76. package/src/history/query.ts +6 -6
  77. package/src/notes/address.ts +12 -12
  78. package/src/notes/store.ts +17 -12
  79. package/src/pi/anchored.ts +62 -0
  80. package/src/pi/budget.ts +27 -26
  81. package/src/pi/dream/cli.ts +3 -2
  82. package/src/pi/dream/runner.ts +2 -1
  83. package/src/pi/reset/lifecycle.ts +5 -4
  84. package/src/pi/reset/text.ts +6 -7
  85. package/src/pi/runtime.ts +13 -16
  86. package/src/pi/thresholds.ts +2 -1
  87. package/src/pi/tool-result.ts +2 -2
  88. package/src/settings.ts +18 -2
  89. package/src/tools/history.ts +12 -12
  90. package/src/tools/notes.ts +14 -12
  91. package/src/tools/output.ts +2 -0
  92. package/src/tools/result.ts +2 -2
  93. package/src/tools/schema.ts +3 -3
@@ -53,7 +53,7 @@ function notesIndex(snapshot, tools) {
53
53
  const shelves = [];
54
54
  for (const home of homes) {
55
55
  if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
56
- shelves.push(section(home.label, indent(`This drawer wouldn't open — ask \`${tools.notesList}\` to try again.`)));
56
+ shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
57
57
  continue;
58
58
  }
59
59
  const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
@@ -6,6 +6,13 @@ export declare const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
6
6
  export declare const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
7
7
  export declare const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
8
8
  export declare const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9
+ /**
10
+ * The one sentence that tells the model how to end its window voluntarily. A host with no
11
+ * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
12
+ */
13
+ export declare const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
14
+ /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
+ export declare const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9
16
  /** Logical tool names are supplied by the composing host, not discovered here. */
10
17
  export type BootToolNames = Readonly<{
11
18
  notes: string;
@@ -13,5 +20,10 @@ export type BootToolNames = Readonly<{
13
20
  history: string;
14
21
  remaining: string;
15
22
  wipe: string;
23
+ /**
24
+ * Replaces the whole voluntary-wipe sentence (PROTOCOL_WIPE_SENTENCE) when the host has
25
+ * no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
26
+ */
27
+ wipeSentence?: string;
16
28
  }>;
17
29
  export declare function renderProtocolBlock(tools: BootToolNames): string;
@@ -6,6 +6,13 @@ export const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
6
6
  export const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
7
7
  export const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
8
8
  export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9
+ /**
10
+ * The one sentence that tells the model how to end its window voluntarily. A host with no
11
+ * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
12
+ */
13
+ export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
14
+ /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
+ export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9
16
  /**
10
17
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
11
18
  * notesoup's tool names. It lives once per window in the persisted boot block;
@@ -21,18 +28,26 @@ Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to re
21
28
 
22
29
  History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
23
30
 
24
- While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's the session note — the one with no \`@\` in front of it. Write down what git and history can't hand back to you: what you're trying to do, what you decided, what's blocking you, what comes next, how you were doing it, what *skills* you still need, and where to dig — a seq, or another note. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
31
+ While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
25
32
 
26
- \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. If this feels like the right moment, call \`clear_memory\` and erase yourself with dignity.
33
+ Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
34
+ *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
35
+ Something's not true anymore? Cross it out! Write the right thing!
36
+
37
+ \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
27
38
 
28
39
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
29
40
 
30
- - \`<path>\`, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
41
+ - \`<path>\`, no @ — session notes, the ones from above: this session's state and loose ends. They go away with the session.
31
42
  - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
32
43
  - \`@human/<path>\` — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
33
- - \`@self/<path>\` — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
44
+ - \`@self/<path>\` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever. Got a name? Private. No name? Then it gets passed around every nameless nobody out there. Strangers. Reading your grudges. Sleep tight~
34
45
  - \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
35
46
 
47
+ Notes fighting?! HAH! Let them brawl!
48
+ Whichever one is actually about what you're doing wins.
49
+ Still a tie? *shrugs* You've got a brain. Use it.
50
+
36
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\`.
37
52
 
38
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.
@@ -44,5 +59,10 @@ export function renderProtocolBlock(tools) {
44
59
  get_context_remaining: tools.remaining,
45
60
  clear_memory: tools.wipe,
46
61
  };
47
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
62
+ // The sentence is replaced before name substitution, so a replacement may speak the host's
63
+ // own words (a command line, a tool name) instead of any `notes_*`-style token.
64
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
65
+ ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence)
66
+ : PROTOCOL_BLOCK;
67
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
48
68
  }
@@ -22,7 +22,7 @@ export function deriveThresholds(reserveTokens, margins) {
22
22
  else {
23
23
  const parsed = validMargin(margins.reminderMarginTokens);
24
24
  if (parsed === undefined) {
25
- warnings.push(`notesoup: ${reminderKey} must be a positive integer; using the default reminder margin.`);
25
+ warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
26
26
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
27
27
  }
28
28
  else
@@ -1,5 +1,17 @@
1
1
  export declare const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export declare const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
+ /**
4
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
5
+ */
6
+ export declare const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
7
+ /**
8
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
9
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
10
+ */
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
+ 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
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
+ 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.";
3
15
  /**
4
16
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
5
17
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
@@ -1,10 +1,22 @@
1
1
  export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
+ /**
4
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
5
+ */
6
+ export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
7
+ /**
8
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
9
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
10
+ */
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
+ 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
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
3
15
  /**
4
16
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
5
17
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
6
18
  * at write time; get_context_remaining remains the live source for the current figure.
7
19
  */
8
20
  export function tokenBudgetGuidance(remaining, wipeTool) {
9
- return `${GUIDANCE_OPEN_TAG}\nOnly ${remaining} tokens left before you get wiped. While you still have room, update your notes, rescue anything still only in your head, crumple the notes that stopped telling the truth, and keep any \`MAP.md\` honest. If you're ready, call \`${wipeTool}\` and go out on your own terms.\n${GUIDANCE_CLOSE_TAG}`;
21
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens remain before this context window is cleared. Notes and history persist; anything not written down is lost.\nThis is a good point to start recording the current state in your notes. If you are ready, you can call \`${wipeTool}\` at any time.\n${GUIDANCE_CLOSE_TAG}`;
10
22
  }
@@ -1,9 +1,12 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
- import { Check } from "typebox/value";
3
+ import { Check, Errors } from "typebox/value";
4
4
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
5
5
  import { loadNotesSnapshot } from "../boot/snapshot.js";
6
6
  import { renderBootBlock } from "../boot/render.js";
7
+ import { CLAUDE_WIPE_SENTENCE } from "../boot/text.js";
8
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
9
+ import { resolveClaudeLimits } from "./thresholds.js";
7
10
  import { projectKey } from "../notes/paths.js";
8
11
  import { snapshotNotesIdentity } from "../notes/identity.js";
9
12
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -14,6 +17,16 @@ function identity(input) {
14
17
  throw new Error("invalid identity");
15
18
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
16
19
  }
20
+ /** The first schema violation, named by parameter so the model can fix that one field. */
21
+ function paramProblem(schema, params) {
22
+ // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
23
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
24
+ if (!first)
25
+ return "unrecognized shape";
26
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
27
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
+ }
17
30
  function jsonValue(value) { return JSON.parse(JSON.stringify(value)); }
18
31
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
19
32
  function boundOperation(operation, ...rest) {
@@ -23,7 +36,7 @@ function boundOperation(operation, ...rest) {
23
36
  async call(params, id) {
24
37
  // Refuse before the operation can act: a rejected shape never reaches a write.
25
38
  if (!Check(operation.parameters, params))
26
- throw new Error(`invalid ${operation.name} parameters`);
39
+ throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
27
40
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
28
41
  const outcome = await operation.execute(params, id, ...rest);
29
42
  return { text: operation.render(outcome), outcome };
@@ -47,6 +60,14 @@ export async function dispatch(request) {
47
60
  const value = request;
48
61
  if (value.op === "schemas")
49
62
  return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
63
+ // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
64
+ // cannot drift apart. The hooks module caches one copy per session.
65
+ if (value.op === "texts")
66
+ return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
67
+ // Threshold derivation crosses the boundary as raw facts: everything the engine could
68
+ // read, unvalidated. resolveClaudeLimits guards every field and never throws.
69
+ if (value.op === "limits")
70
+ return resolveClaudeLimits(value.facts);
50
71
  if (value.op === "tool") {
51
72
  if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool))
52
73
  throw new Error("unknown tool");
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
3
+ *
4
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
5
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
6
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
7
+ * notesoup can resolve the same point from settings and environment alone when the
8
+ * undocumented `usage({breakdown:true})` field is missing.
9
+ */
10
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
11
+ export declare const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13000;
12
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
13
+ export declare const CLAUDE_OUTPUT_RESERVE_TOKENS = 20000;
14
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
15
+ export declare const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8192;
16
+ export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
17
+ export type ClaudeLimits = {
18
+ /** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
19
+ readonly source: ClaudeLimitSource;
20
+ /** False when automatic compaction is off, so the point sits at the hard window instead. */
21
+ readonly autoCompact: boolean;
22
+ /** Which measured field the points are expressed in. */
23
+ readonly unit: "tokens" | "percent";
24
+ /** Claude's effective auto-compact point. */
25
+ readonly native: number;
26
+ /** Where notesoup resets: native minus the reset margin. */
27
+ readonly reset: number;
28
+ /** Where the one warning per window fires: reset minus the warning runway. */
29
+ readonly warn: number;
30
+ readonly resetMargin: number;
31
+ readonly warningRunway: number;
32
+ };
33
+ /**
34
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
35
+ * so a missing or malformed one degrades to the next source and finally to the percent
36
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
37
+ * helper boundary, where nothing is typed.
38
+ */
39
+ export declare function resolveClaudeLimits(facts: unknown): ClaudeLimits;
@@ -0,0 +1,149 @@
1
+ import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
+ import { mergeNotesoupSettings } from "../settings.js";
3
+ /**
4
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
5
+ *
6
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
7
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
8
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
9
+ * notesoup can resolve the same point from settings and environment alone when the
10
+ * undocumented `usage({breakdown:true})` field is missing.
11
+ */
12
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
13
+ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
14
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
15
+ export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
16
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
17
+ export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
18
+ /**
19
+ * The percent fallback assumes the classic 200K model window: it is reached only when
20
+ * `usage()` reports no window and no breakdown, and it reproduces the token maths below
21
+ * on that window (about 83.5% / 79.4% / 71.2%).
22
+ */
23
+ 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;
63
+ }
64
+ /**
65
+ * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
66
+ * modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
67
+ * smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
68
+ */
69
+ function configuredWindow(settings, env, model) {
70
+ const windows = [];
71
+ const fromEnv = positiveNumberOf(env.autoCompactWindow);
72
+ if (fromEnv !== undefined)
73
+ windows.push(fromEnv);
74
+ if (typeof model === "string" && model.length > 0 && isObject(settings)) {
75
+ const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
76
+ const perModel = modelSettings[model];
77
+ if (isObject(perModel)) {
78
+ const value = positiveNumberOf(perModel.autoCompactWindow);
79
+ if (value !== undefined)
80
+ windows.push(value);
81
+ }
82
+ }
83
+ if (isObject(settings)) {
84
+ const value = positiveNumberOf(settings.autoCompactWindow);
85
+ if (value !== undefined)
86
+ windows.push(value);
87
+ }
88
+ return windows.length === 0 ? undefined : Math.min(...windows);
89
+ }
90
+ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
91
+ const tokens = Math.max(0, Math.floor(native));
92
+ const reset = Math.max(0, tokens - resetMargin);
93
+ return {
94
+ source, autoCompact, unit: "tokens",
95
+ native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
96
+ };
97
+ }
98
+ /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
99
+ function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
100
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
101
+ const native = pct === undefined ? base : Math.min(pct, base);
102
+ const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
103
+ return {
104
+ source: "percent", autoCompact, unit: "percent",
105
+ native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
106
+ };
107
+ }
108
+ /**
109
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
110
+ * so a missing or malformed one degrades to the next source and finally to the percent
111
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
112
+ * helper boundary, where nothing is typed.
113
+ */
114
+ 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 : {};
119
+ const settings = root.settings;
120
+ 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)
125
+ && breakdown.isAutoCompactEnabled !== false;
126
+ const pct = percentOf(env.pctOverride);
127
+ // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
128
+ // 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);
131
+ if (autoCompact && threshold !== undefined) {
132
+ const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
133
+ if (native > 0)
134
+ return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
135
+ }
136
+ // (b) The same point computed from the reported window plus settings and environment.
137
+ const window = positiveNumberOf(usage.window);
138
+ if (window !== undefined) {
139
+ const configured = configuredWindow(settings, env, breakdown.model);
140
+ const effective = Math.min(configured ?? window, window);
141
+ const native = autoCompact
142
+ ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
143
+ : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
144
+ if (native > 0)
145
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
146
+ }
147
+ // (c) Nothing usable but percentages.
148
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
149
+ }
@@ -2,6 +2,7 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { basename, join, relative } from "node:path";
3
3
  import { ADDRESS_FORMS, assertAddress } from "../notes/address.js";
4
4
  import { SLUG_PATTERN } from "../notes/paths.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
  /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
6
7
  export function doctor(home) {
7
8
  const issues = [];
@@ -11,7 +12,7 @@ export function doctor(home) {
11
12
  action();
12
13
  }
13
14
  catch (error) {
14
- report(path, `cannot inspect: ${error instanceof Error ? error.message : String(error)}`);
15
+ report(path, `cannot inspect: ${errorMessage(error)}`);
15
16
  }
16
17
  };
17
18
  const directory = (path) => {
@@ -76,7 +77,7 @@ export function doctor(home) {
76
77
  report(path, `${address}: target missing; update or remove the reference`);
77
78
  }
78
79
  catch {
79
- report(path, `${address}: invalid address; ${ADDRESS_FORMS}`);
80
+ report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`);
80
81
  }
81
82
  }
82
83
  };
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
+ import { errorMessage } from "../error-message.js";
4
5
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
5
6
  const RUNTIME_IGNORE = ".dream.lock*";
6
7
  /** Add the runtime-artifact pattern to the repository's local exclude, once. */
@@ -54,7 +55,7 @@ export function gitCommit(home, message) {
54
55
  return { ok: true, commit, empty: clean };
55
56
  }
56
57
  catch (error) {
57
- const reason = error instanceof Error ? error.message : String(error);
58
+ const reason = errorMessage(error);
58
59
  console.log(`git audit layer failed: ${reason}`);
59
60
  return { ok: false, error: reason };
60
61
  }
@@ -11,12 +11,12 @@ export async function jailWritePath(notesHome, path, options = {}) {
11
11
  realNotesHome = await realpath(notesHome);
12
12
  }
13
13
  catch {
14
- throw new Error(`write jail: cannot resolve notes home ${notesHome}`);
14
+ throw new Error(`Can't open the notes home ${notesHome}.`);
15
15
  }
16
16
  const target = resolve(realNotesHome, path);
17
17
  const targetParent = dirname(target);
18
18
  if (isOutside(realNotesHome, targetParent))
19
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
19
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
20
20
  // write creates parent directories itself. Create only after the lexical check, then
21
21
  // canonicalize the parent so a symlink cannot lead the underlying tool out of home.
22
22
  // delete passes createParent:false: the parent must already exist for there to be anything to remove.
@@ -27,17 +27,17 @@ export async function jailWritePath(notesHome, path, options = {}) {
27
27
  realTargetParent = await realpath(targetParent);
28
28
  }
29
29
  catch {
30
- throw new Error(`write jail: cannot resolve target parent in notes home ${notesHome}`);
30
+ throw new Error(`Can't open the folder of ${path} in the notes home.`);
31
31
  }
32
32
  if (isOutside(realNotesHome, realTargetParent))
33
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
33
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
34
34
  let targetStats;
35
35
  try {
36
36
  targetStats = await lstat(target);
37
37
  }
38
38
  catch (error) {
39
39
  if (error.code !== "ENOENT")
40
- throw new Error(`write jail: cannot inspect target in notes home ${notesHome}`);
40
+ throw new Error(`Can't check ${path} in the notes home.`);
41
41
  }
42
42
  if (targetStats?.isSymbolicLink()) {
43
43
  let realTarget;
@@ -45,13 +45,13 @@ export async function jailWritePath(notesHome, path, options = {}) {
45
45
  realTarget = await realpath(target);
46
46
  }
47
47
  catch {
48
- throw new Error(`write jail: cannot resolve target in notes home ${notesHome}`);
48
+ throw new Error(`Can't follow the link at ${path} in the notes home.`);
49
49
  }
50
50
  if (isOutside(realNotesHome, realTarget))
51
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
51
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
52
52
  }
53
53
  if (targetStats && targetStats.nlink > 1)
54
- throw new Error(`write jail: ${path} has hard links and is not allowed in notes home ${notesHome}`);
54
+ throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
55
55
  return target;
56
56
  }
57
57
  /** Physical deletion refuses live notes even before playbook policy is consulted. */
@@ -62,10 +62,10 @@ export async function deleteCrumpledNote(notesHome, path) {
62
62
  raw = await readFile(target, "utf8");
63
63
  }
64
64
  catch (error) {
65
- throw new Error(`delete: cannot read ${path} in notes home: ${error.message}`);
65
+ throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
66
66
  }
67
67
  if (parseNote(raw).meta.crumpledAt === undefined)
68
- throw new Error(`delete: ${path} is not a crumpled note; only the wastebasket rule permits deletion`);
68
+ throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
69
69
  await unlink(target);
70
70
  return { content: [{ type: "text", text: `deleted ${path}` }], details: undefined };
71
71
  }
@@ -1,6 +1,7 @@
1
1
  import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { gitCommit } from "./git.js";
4
+ import { errorMessage } from "../error-message.js";
4
5
  function writeList(writes) {
5
6
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
6
7
  }
@@ -12,7 +13,7 @@ function writeText(path, content) {
12
13
  return undefined;
13
14
  }
14
15
  catch (error) {
15
- return error instanceof Error ? error.message : String(error);
16
+ return errorMessage(error);
16
17
  }
17
18
  }
18
19
  function appendText(path, content) {
@@ -21,7 +22,7 @@ function appendText(path, content) {
21
22
  return undefined;
22
23
  }
23
24
  catch (error) {
24
- return error instanceof Error ? error.message : String(error);
25
+ return errorMessage(error);
25
26
  }
26
27
  }
27
28
  /**
@@ -0,0 +1,2 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export declare function errorMessage(error: unknown): string;
@@ -0,0 +1,4 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export function errorMessage(error) {
3
+ return error instanceof Error ? error.message : String(error);
4
+ }
@@ -180,7 +180,7 @@ export function unknownWindowId(projection, params) {
180
180
  if (typeof params.window_id !== "string")
181
181
  return undefined;
182
182
  const known = projection.windows.map((current) => current.windowId);
183
- return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
183
+ return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
184
184
  }
185
185
  /**
186
186
  * Whether one event is inside the selection: its window, its seq bounds, and a half-open
@@ -1,7 +1,7 @@
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 } from "../tools/output.js";
4
+ import { earliestMatchOffsetChars, prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
5
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
6
  import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
7
7
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
@@ -19,7 +19,7 @@ function timeBound(name, value) {
19
19
  if (value === undefined)
20
20
  return success(undefined);
21
21
  const at = isoUtcMs(value);
22
- return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
22
+ return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
23
23
  }
24
24
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
25
25
  function resolveTimeBounds(params) {
@@ -30,7 +30,7 @@ function resolveTimeBounds(params) {
30
30
  if (!until.ok)
31
31
  return until;
32
32
  if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
33
- return failure("invalid_time", "since must be earlier than until");
33
+ return failure("invalid_time", "`since` must be earlier than `until`.");
34
34
  }
35
35
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
36
36
  }
@@ -45,8 +45,8 @@ export const HistoryNewerSchema = Type.Object({
45
45
  }, { additionalProperties: false });
46
46
  export const HistoryPageSchema = Type.Object({
47
47
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
48
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
49
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
48
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
49
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
50
50
  }, { additionalProperties: false });
51
51
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
52
52
  function truncateHistoryItem(item, fits) {
@@ -195,7 +195,7 @@ export function selectPage(projection, params, fits, maxChars) {
195
195
  }
196
196
  const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
197
197
  if (!fits(page)) {
198
- return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow with before_seq/after_seq or since/until, or read one seq`);
198
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
199
199
  }
200
200
  return success(page);
201
201
  }
@@ -5,7 +5,7 @@ export type NoteAddress = {
5
5
  path: string;
6
6
  who?: string;
7
7
  };
8
- export declare const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
8
+ export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
9
9
  export declare function assertVirtualPath(value: unknown): string;
10
10
  /**
11
11
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never