notesoup 0.41.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 (127) 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.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.41.0",
3
+ "version": "0.43.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -43,14 +43,16 @@
43
43
  "README.md",
44
44
  "playbook.md",
45
45
  "skills",
46
- "mods"
46
+ "mods",
47
+ "!mods/notesoup/types",
48
+ "!mods/notesoup/tsconfig.json"
47
49
  ],
48
50
  "bin": {
49
51
  "dream": "dist/src/pi/dream/cli.js"
50
52
  },
51
53
  "scripts": {
52
54
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs && node -e \"require('node:fs').chmodSync('dist/src/pi/dream/cli.js', 0o755)\"",
53
- "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p mods/notesoup/tsconfig.json",
54
56
  "test": "npm run build && node --test dist/test/*.test.js",
55
57
  "prepublishOnly": "npm run typecheck",
56
58
  "prepack": "npm run build"
package/playbook.md CHANGED
@@ -24,7 +24,7 @@ The homes serve different readers:
24
24
  4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is reversible: do it, don't propose it. Propose only when the destination home itself is unclear.
25
25
  5. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
26
26
  6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
27
- 7. **Keep maps useful.** Each writable home's MAP.md lists its durable notes, one line per entry, with an unambiguous address and a short gist in your own words. Add promoted notes and drop entries that no longer hold. Maps follow the same size budget.
27
+ 7. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
28
28
  8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and it has been crumpled and untouched for more than 7 days. With raw frontmatter, judge by `lastAccessed`, falling back to `crumpledAt`. With only `notes_*` tools, judge by `crumpled_at`. If no date is readable, keep the note and report it. Never read a raw note through `notes_read` to get the date: it refreshes `lastAccessed`. A venue that cannot delete files lists the doomed addresses in its report instead of blanking them. Preserve existing metadata and provenance.
29
29
 
30
30
  ## Report
@@ -5,7 +5,7 @@ description: Review and consolidate durable notes using notesoup's shared dream
5
5
 
6
6
  # Dream
7
7
 
8
- Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes.
8
+ Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes. MAP may include a short Cheatsheet of rules that apply in every window (about 5 lines); the rest stays the note index, for lookup.
9
9
 
10
10
  Dream in this agent's current session. Do not start another agent or model unless the human asks.
11
11
 
@@ -30,7 +30,7 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
30
30
 
31
31
  `@` addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`. That creates a stray directory instead of a note.
32
32
 
33
- `MAP.md` at the root of each `@` home is its index: one line per durable note, address and gist. Update it whenever you add, move or crumple a durable note.
33
+ `MAP.md` at the root of each `@` home is a page you wake up with. It may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest is the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note.
34
34
 
35
35
  Write only what git and history cannot give back. Crumple notes that are no longer true; a stale note is worse than none.
36
36
 
@@ -1,17 +1,6 @@
1
1
  import type { NotesHome, NotesSnapshot } from "./snapshot.js";
2
2
  import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
3
3
 
4
- /** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
5
- function identityBlock(agentName: string, modelName: string, firstWindowId: string, currentWindowId: string, previousWindowId?: string): string {
6
- const lines = [
7
- `Agent name: ${agentName} (brain: ${modelName})`,
8
- `First context window id: ${firstWindowId}`,
9
- `Current context window id: ${currentWindowId}`,
10
- ];
11
- if (previousWindowId) lines.push(`Previous context window id: ${previousWindowId}`);
12
- return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
13
- }
14
-
15
4
  function relativeTime(timestamp: number, now: number): string {
16
5
  const seconds = Math.trunc((timestamp - now) / 1000);
17
6
  if (seconds === 0) return "just now";
@@ -21,10 +10,6 @@ function relativeTime(timestamp: number, now: number): string {
21
10
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
22
11
  }
23
12
 
24
- function rowsFor(snapshot: NotesSnapshot, scope: NotesHome["scope"]) {
25
- return snapshot.homes.get(scope) ?? [];
26
- }
27
-
28
13
  /** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
29
14
  const FEED_TITLE_MAX_CHARS = 40;
30
15
 
@@ -63,7 +48,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
63
48
  shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
64
49
  continue;
65
50
  }
66
- const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
51
+ const rows = (snapshot.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
67
52
  const map = rows.find((row) => row.path === "MAP.md");
68
53
  const fresh = rows
69
54
  .filter((row) => row.path !== "MAP.md")
@@ -107,9 +92,14 @@ export type BootRenderData = {
107
92
  };
108
93
 
109
94
  export function renderBootBlock(data: BootRenderData): string {
110
- const parts: string[] = [];
111
- parts.push(identityBlock(data.agentName, data.modelName, data.firstWindowId, data.currentWindowId, data.previousWindowId));
112
- parts.push(renderProtocolBlock(data.tools));
113
- parts.push(notesIndex(data.notes, data.tools));
114
- return parts.join("\n\n");
95
+ // Codex-style <context_window> identity block: the resolved agent and model names plus
96
+ // first/current/previous window ids.
97
+ const lines = [
98
+ `Agent name: ${data.agentName} (brain: ${data.modelName})`,
99
+ `First context window id: ${data.firstWindowId}`,
100
+ `Current context window id: ${data.currentWindowId}`,
101
+ ...(data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []),
102
+ ];
103
+ const identity = `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
104
+ return [identity, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
115
105
  }
@@ -1,6 +1,6 @@
1
1
  import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { isFilesystemError } from "../notes/fs-error.js";
3
- import { createNotesStore, type NoteRow, type NotesQuery, type Scope } from "../notes/index.js";
3
+ import { createNotesStore, type NoteRow, type Scope } from "../notes/index.js";
4
4
 
5
5
  const NOTES_HOMES = [
6
6
  { scope: "session", label: "this session" },
@@ -19,18 +19,13 @@ export type NotesSnapshot = {
19
19
  readonly unavailable: readonly NotesHome[];
20
20
  };
21
21
 
22
- function queryForScope(scope: Scope): NotesQuery {
23
- if (scope === "agent" || scope === "model") return { scope };
24
- return { scope };
25
- }
26
-
27
22
  /**
28
23
  * Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
29
24
  * malformed note data and unrelated construction errors remain visible to the caller.
30
25
  */
31
26
  export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot> {
32
27
  const store = createNotesStore(identity);
33
- const load = loadHome ?? ((scope: Scope) => store.list(queryForScope(scope)));
28
+ const load = loadHome ?? ((scope: Scope) => store.list({ scope }));
34
29
  const homes = new Map<Scope, readonly NoteRow[]>();
35
30
  const unavailable: NotesHome[] = [];
36
31
  for (const home of NOTES_HOMES) {
package/src/boot/text.ts CHANGED
@@ -6,6 +6,14 @@ 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`.";
16
+
9
17
  /**
10
18
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
11
19
  * notesoup's tool names. It lives once per window in the persisted boot block;
@@ -27,7 +35,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
27
35
  *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
28
36
  Something's not true anymore? Cross it out! Write the right thing!
29
37
 
30
- \`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.
38
+ \`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}
31
39
 
32
40
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
33
41
 
@@ -43,7 +51,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
43
51
 
44
52
  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\`.
45
53
 
46
- \`@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.
54
+ \`@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.
47
55
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
48
56
 
49
57
  /** Logical tool names are supplied by the composing host, not discovered here. */
@@ -53,6 +61,11 @@ export type BootToolNames = Readonly<{
53
61
  history: string;
54
62
  remaining: string;
55
63
  wipe: string;
64
+ /**
65
+ * Replaces the whole voluntary-wipe sentence (PROTOCOL_WIPE_SENTENCE) when the host has
66
+ * no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
67
+ */
68
+ wipeSentence?: string;
56
69
  }>;
57
70
 
58
71
  export function renderProtocolBlock(tools: BootToolNames): string {
@@ -62,5 +75,10 @@ export function renderProtocolBlock(tools: BootToolNames): string {
62
75
  get_context_remaining: tools.remaining,
63
76
  clear_memory: tools.wipe,
64
77
  };
65
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
78
+ // The sentence is replaced before name substitution, so a replacement may speak the host's
79
+ // own words (a command line, a tool name) instead of any `notes_*`-style token.
80
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
81
+ ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
82
+ : PROTOCOL_BLOCK;
83
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
66
84
  }
@@ -0,0 +1,39 @@
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
+
7
+ /** A finite number, from a typed value or an environment string; anything else is unknown. */
8
+ export function numberOf(value: unknown): number | undefined {
9
+ if (typeof value === "number") 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
+
17
+ export function positiveNumber(value: unknown): number | undefined {
18
+ const parsed = numberOf(value);
19
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
20
+ }
21
+
22
+ /** A margin or window is usable only as a positive safe integer. */
23
+ export function positiveInteger(value: unknown): number | undefined {
24
+ const parsed = numberOf(value);
25
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
26
+ }
27
+
28
+ /** A percentage override is usable only in (0, 100]. */
29
+ export function percent(value: unknown): number | undefined {
30
+ const parsed = numberOf(value);
31
+ return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
32
+ }
33
+
34
+ /** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
35
+ export function presenceFlag(value: unknown): boolean {
36
+ if (typeof value !== "string") return false;
37
+ const text = value.trim().toLowerCase();
38
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
39
+ }
@@ -1,12 +1,8 @@
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, type NotesoupSettings } from "../settings.js";
3
4
 
4
5
  export type ResolvedThresholds = { reminder: number; reserve: number; warning: number };
5
- /** A margin is usable only as a positive integer; anything else is ignored. */
6
- function validMargin(raw: unknown): number | undefined {
7
- if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0) return undefined;
8
- return raw;
9
- }
10
6
 
11
7
  /**
12
8
  * Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
@@ -21,7 +17,7 @@ export function deriveThresholds(reserveTokens: number, margins: NotesoupSetting
21
17
  let reminderMargin: number;
22
18
  if (margins.reminderMarginTokens === undefined) reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
23
19
  else {
24
- const parsed = validMargin(margins.reminderMarginTokens);
20
+ const parsed = positiveInteger(margins.reminderMarginTokens);
25
21
  if (parsed === undefined) {
26
22
  warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
27
23
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
@@ -1,6 +1,26 @@
1
1
  export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
3
 
4
+ /**
5
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
6
+ */
7
+ 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*";
8
+
9
+ /**
10
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
11
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
12
+ */
13
+ export const WARNING_BODY =
14
+ "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.";
15
+
16
+ export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
17
+
18
+ /** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
19
+ export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
20
+
21
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
22
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
23
+
4
24
  /**
5
25
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
6
26
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
@@ -1,15 +1,17 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import type { Static, TSchema } from "typebox";
4
- import { Check } from "typebox/value";
4
+ import { Check, Errors } from "typebox/value";
5
5
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
6
6
  import { loadNotesSnapshot } from "../boot/snapshot.js";
7
7
  import { renderBootBlock } from "../boot/render.js";
8
+ import { CLAUDE_WIPE_SENTENCE, type BootToolNames } from "../boot/text.js";
9
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
10
+ import { resolveClaudeLimits } from "./thresholds.js";
8
11
  import { projectKey } from "../notes/paths.js";
9
12
  import { snapshotNotesIdentity, type NotesIdentity } from "../notes/identity.js";
10
13
  import type { NoteChange } from "../notes/store.js";
11
14
  import type { Operation, Outcome } from "../tools/result.js";
12
- import type { BootToolNames } from "../boot/text.js";
13
15
 
14
16
  const MAX_REQUEST_BYTES = 512 * 1024;
15
17
  const MAX_RESPONSE_BYTES = 1024 * 1024;
@@ -28,7 +30,16 @@ function identity(input: ClaudeIdentityInput): NotesIdentity {
28
30
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
29
31
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
30
32
  }
31
- function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
33
+
34
+ /** The first schema violation, named by parameter so the model can fix that one field. */
35
+ function paramProblem(schema: TSchema, params: unknown): string {
36
+ // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
37
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
38
+ if (!first) return "unrecognized shape";
39
+ const extra = first.keyword === "additionalProperties" ? `: ${(first.params as { additionalProperties: string[] }).additionalProperties.join(", ")}` : "";
40
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
41
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
42
+ }
32
43
 
33
44
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
34
45
  function boundOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
@@ -40,7 +51,7 @@ function boundOperation<TParams extends TSchema, TData, TRest extends readonly u
40
51
  parameters: operation.parameters,
41
52
  async call(params, id) {
42
53
  // Refuse before the operation can act: a rejected shape never reaches a write.
43
- if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters`);
54
+ if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
44
55
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
45
56
  const outcome = await operation.execute(params as Static<TParams>, id, ...rest);
46
57
  return { text: operation.render(outcome), outcome };
@@ -64,7 +75,13 @@ const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
64
75
  export async function dispatch(request: unknown): Promise<unknown> {
65
76
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
66
77
  const value = request as Record<string, unknown>;
67
- if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
78
+ if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
79
+ // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
80
+ // cannot drift apart. The hooks module caches one copy per session.
81
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
82
+ // Threshold derivation crosses the boundary as raw facts: everything the engine could
83
+ // read, unvalidated. resolveClaudeLimits guards every field and never throws.
84
+ if (value.op === "limits") return resolveClaudeLimits(value.facts);
68
85
  if (value.op === "tool") {
69
86
  if (typeof value.tool !== "string" || !(TOOL_NAMES as readonly string[]).includes(value.tool)) throw new Error("unknown tool");
70
87
  const id = identity(value.identity as ClaudeIdentityInput);
@@ -0,0 +1,153 @@
1
+ import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
+ import { percent, positiveInteger, positiveNumber, presenceFlag } from "../budget/parse.js";
3
+ import { isPlainObject, mergeNotesoupSettings } from "../settings.js";
4
+
5
+ /**
6
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
7
+ *
8
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
9
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
10
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
11
+ * notesoup can resolve the same point from settings and environment alone when the
12
+ * undocumented `usage({breakdown:true})` field is missing.
13
+ */
14
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
15
+ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
16
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
17
+ export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
18
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
19
+ export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
20
+ /**
21
+ * A point is never expressed as zero: the mod reads `measured >= reset` as due, so a zero point
22
+ * would clear memory on every turn, including a fresh window. A window smaller than Claude's own
23
+ * reserves therefore resets at the smallest expressible point instead.
24
+ */
25
+ const MIN_POINT_TOKENS = 1;
26
+ /** The same floor in percent units, for the no-window fallback. */
27
+ const MIN_POINT_PERCENT = 0.1;
28
+ /**
29
+ * The percent fallback assumes the classic 200K model window: it is reached only when
30
+ * `usage()` reports no window and no breakdown, and it reproduces the token maths below
31
+ * on that window (about 83.5% / 79.4% / 71.2%).
32
+ */
33
+ const ASSUMED_WINDOW_TOKENS = 200_000;
34
+
35
+ export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
36
+ export type ClaudeLimits = {
37
+ /** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
38
+ readonly source: ClaudeLimitSource;
39
+ /** False when automatic compaction is off, so the point sits at the hard window instead. */
40
+ readonly autoCompact: boolean;
41
+ /** Which measured field the points are expressed in. */
42
+ readonly unit: "tokens" | "percent";
43
+ /** Claude's effective auto-compact point. */
44
+ readonly native: number;
45
+ /** Where notesoup resets: native minus the reset margin. */
46
+ readonly reset: number;
47
+ /** Where the one warning per window fires: reset minus the warning runway. */
48
+ readonly warn: number;
49
+ readonly resetMargin: number;
50
+ readonly warningRunway: number;
51
+ };
52
+
53
+ /**
54
+ * The active auto-compact flag: absent means Claude's default (on), and only an explicit
55
+ * boolean counts. Settings are read from one host-supplied scope, so the flag is top-level.
56
+ */
57
+ function settingFlag(settings: unknown): boolean | undefined {
58
+ return isPlainObject(settings) && typeof settings.autoCompactEnabled === "boolean" ? settings.autoCompactEnabled : undefined;
59
+ }
60
+
61
+ /**
62
+ * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
63
+ * modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
64
+ * smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
65
+ */
66
+ function configuredWindow(settings: unknown, env: Record<string, unknown>, model: unknown): number | undefined {
67
+ const windows: number[] = [];
68
+ const fromEnv = positiveNumber(env.autoCompactWindow);
69
+ if (fromEnv !== undefined) windows.push(fromEnv);
70
+ if (typeof model === "string" && model.length > 0 && isPlainObject(settings)) {
71
+ const modelSettings = isPlainObject(settings.modelSettings) ? settings.modelSettings : {};
72
+ const perModel = modelSettings[model];
73
+ if (isPlainObject(perModel)) {
74
+ const value = positiveNumber(perModel.autoCompactWindow);
75
+ if (value !== undefined) windows.push(value);
76
+ }
77
+ }
78
+ if (isPlainObject(settings)) {
79
+ const value = positiveNumber(settings.autoCompactWindow);
80
+ if (value !== undefined) windows.push(value);
81
+ }
82
+ return windows.length === 0 ? undefined : Math.min(...windows);
83
+ }
84
+
85
+ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: number, resetMargin: number, warningRunway: number): ClaudeLimits {
86
+ const tokens = Math.max(0, Math.floor(native));
87
+ const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
88
+ return {
89
+ source, autoCompact, unit: "tokens",
90
+ native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
91
+ };
92
+ }
93
+
94
+ /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
95
+ function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
96
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
97
+ const native = pct === undefined ? base : Math.min(pct, base);
98
+ const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
99
+ return {
100
+ source: "percent", autoCompact, unit: "percent",
101
+ native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
107
+ * so a missing or malformed one degrades to the next source and finally to the percent
108
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
109
+ * helper boundary, where nothing is typed.
110
+ */
111
+ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
112
+ const root = isPlainObject(facts) ? facts : {};
113
+ const usage = isPlainObject(root.usage) ? root.usage : {};
114
+ const breakdown = isPlainObject(root.breakdown) ? root.breakdown : {};
115
+ const env = isPlainObject(root.env) ? root.env : {};
116
+ const settings = root.settings;
117
+
118
+ // The host hands over its merged settings, so there is no separate project scope to name.
119
+ const margins = mergeNotesoupSettings(settings, undefined);
120
+ const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
121
+ const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
122
+
123
+ const autoCompact = settingFlag(settings) !== false
124
+ && !presenceFlag(env.disableAutoCompact)
125
+ && breakdown.isAutoCompactEnabled !== false;
126
+ const pct = percent(env.pctOverride);
127
+
128
+ // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
129
+ // the percent override is applied separately, on the window-after-output-reserve it is
130
+ // minted from (threshold + summary buffer). A malformed override that floors the point to
131
+ // zero is not a point at all, so it degrades to the next source instead of resetting always.
132
+ const threshold = positiveNumber(breakdown.autoCompactThreshold);
133
+ if (autoCompact && threshold !== undefined) {
134
+ const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
135
+ if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
136
+ }
137
+
138
+ // (b) The same point computed from the reported window plus settings and environment. A real
139
+ // window always answers here: falling through to the percent fallback would express the
140
+ // points on an assumed 200K window, which is later than the window notesoup can see.
141
+ const window = positiveNumber(usage.window);
142
+ if (window !== undefined) {
143
+ const configured = configuredWindow(settings, env, breakdown.model);
144
+ const effective = Math.min(configured ?? window, window);
145
+ const native = autoCompact
146
+ ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
147
+ : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
148
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
149
+ }
150
+
151
+ // (c) Nothing usable but percentages.
152
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
153
+ }
@@ -54,7 +54,7 @@ export function doctor(home: string): string[] {
54
54
  : root;
55
55
  if (!targetHome) { report(path, `${address}: project context unavailable; use a resolvable reference`); continue; }
56
56
  if (!existsSync(join(targetHome, parsed.path))) report(path, `${address}: target missing; update or remove the reference`);
57
- } catch { report(path, `${address}: invalid address; ${ADDRESS_FORMS}`); }
57
+ } catch { report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`); }
58
58
  }
59
59
  };
60
60
  const walk = (dir: string, root: string, project?: string) => {
package/src/dream/jail.ts CHANGED
@@ -12,11 +12,11 @@ export async function jailWritePath(notesHome: string, path: string, options: {
12
12
  try {
13
13
  realNotesHome = await realpath(notesHome);
14
14
  } catch {
15
- throw new Error(`write jail: cannot resolve notes home ${notesHome}`);
15
+ throw new Error(`Can't open the notes home ${notesHome}.`);
16
16
  }
17
17
  const target = resolve(realNotesHome, path);
18
18
  const targetParent = dirname(target);
19
- if (isOutside(realNotesHome, targetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
19
+ if (isOutside(realNotesHome, targetParent)) 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.
@@ -25,25 +25,25 @@ export async function jailWritePath(notesHome: string, path: string, options: {
25
25
  try {
26
26
  realTargetParent = await realpath(targetParent);
27
27
  } catch {
28
- throw new Error(`write jail: cannot resolve target parent in notes home ${notesHome}`);
28
+ throw new Error(`Can't open the folder of ${path} in the notes home.`);
29
29
  }
30
- if (isOutside(realNotesHome, realTargetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
30
+ if (isOutside(realNotesHome, realTargetParent)) throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
31
31
  let targetStats;
32
32
  try {
33
33
  targetStats = await lstat(target);
34
34
  } catch (error: any) {
35
- if (error.code !== "ENOENT") throw new Error(`write jail: cannot inspect target in notes home ${notesHome}`);
35
+ if (error.code !== "ENOENT") throw new Error(`Can't check ${path} in the notes home.`);
36
36
  }
37
37
  if (targetStats?.isSymbolicLink()) {
38
38
  let realTarget: string;
39
39
  try {
40
40
  realTarget = await realpath(target);
41
41
  } catch {
42
- throw new Error(`write jail: cannot resolve target in notes home ${notesHome}`);
42
+ throw new Error(`Can't follow the link at ${path} in the notes home.`);
43
43
  }
44
- if (isOutside(realNotesHome, realTarget)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
44
+ if (isOutside(realNotesHome, realTarget)) throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
45
45
  }
46
- if (targetStats && targetStats.nlink > 1) throw new Error(`write jail: ${path} has hard links and is not allowed in notes home ${notesHome}`);
46
+ if (targetStats && targetStats.nlink > 1) throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
47
47
  return target;
48
48
  }
49
49
 
@@ -54,9 +54,9 @@ export async function deleteCrumpledNote(notesHome: string, path: string) {
54
54
  try {
55
55
  raw = await readFile(target, "utf8");
56
56
  } catch (error: any) {
57
- throw new Error(`delete: cannot read ${path} in notes home: ${error.message}`);
57
+ throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
58
58
  }
59
- if (parseNote(raw).meta.crumpledAt === undefined) throw new Error(`delete: ${path} is not a crumpled note; only the wastebasket rule permits deletion`);
59
+ if (parseNote(raw).meta.crumpledAt === undefined) throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
60
60
  await unlink(target);
61
61
  return { content: [{ type: "text" as const, text: `deleted ${path}` }], details: undefined };
62
62
  }
package/src/dream/lock.ts CHANGED
@@ -25,14 +25,6 @@ function readText(path: string): string | undefined {
25
25
  try { return readFileSync(path, "utf8"); } catch { return undefined; }
26
26
  }
27
27
 
28
- function stampMtime(stampPath: string): number | undefined {
29
- try { return statSync(stampPath).mtimeMs; } catch { return undefined; }
30
- }
31
-
32
- /**
33
- * Cleanup ownership: only the exact marker this run wrote may be removed. The token is
34
- * diagnostic and guards cleanup; it never grants permission to take an existing lock.
35
- */
36
28
  function ownsLock(lock: LockState): boolean {
37
29
  if (!lock.held || !lock.token) return false;
38
30
  return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
@@ -46,7 +38,9 @@ function ownsLock(lock: LockState): boolean {
46
38
  */
47
39
  export function acquireLock(path: string): LockState {
48
40
  const now = Date.now();
49
- const priorStampMtime = stampMtime(lastRunPath(path));
41
+ // The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
42
+ let priorStampMtime: number | undefined;
43
+ try { priorStampMtime = statSync(lastRunPath(path)).mtimeMs; } catch { /* no sidecar yet */ }
50
44
  const token = randomUUID();
51
45
  try {
52
46
  writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });