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
@@ -1,11 +1,28 @@
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
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
19
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
20
+
4
21
  /**
5
22
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
6
23
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
7
24
  * at write time; get_context_remaining remains the live source for the current figure.
8
25
  */
9
26
  export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
10
- 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}`;
27
+ 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}`;
11
28
  }
@@ -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,6 +30,15 @@ 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
  }
33
+ /** The first schema violation, named by parameter so the model can fix that one field. */
34
+ function paramProblem(schema: TSchema, params: unknown): string {
35
+ // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
36
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
37
+ if (!first) return "unrecognized shape";
38
+ const extra = first.keyword === "additionalProperties" ? `: ${(first.params as { additionalProperties: string[] }).additionalProperties.join(", ")}` : "";
39
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
40
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
41
+ }
31
42
  function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
32
43
 
33
44
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
@@ -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 };
@@ -65,6 +76,12 @@ 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
78
  if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(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,170 @@
1
+ import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
+ import { mergeNotesoupSettings } from "../settings.js";
3
+
4
+ /**
5
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
6
+ *
7
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
8
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
9
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
10
+ * notesoup can resolve the same point from settings and environment alone when the
11
+ * undocumented `usage({breakdown:true})` field is missing.
12
+ */
13
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
14
+ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
15
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
16
+ export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
17
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
18
+ export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
19
+ /**
20
+ * The percent fallback assumes the classic 200K model window: it is reached only when
21
+ * `usage()` reports no window and no breakdown, and it reproduces the token maths below
22
+ * on that window (about 83.5% / 79.4% / 71.2%).
23
+ */
24
+ const ASSUMED_WINDOW_TOKENS = 200_000;
25
+
26
+ export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
27
+ export type ClaudeLimits = {
28
+ /** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
29
+ readonly source: ClaudeLimitSource;
30
+ /** False when automatic compaction is off, so the point sits at the hard window instead. */
31
+ readonly autoCompact: boolean;
32
+ /** Which measured field the points are expressed in. */
33
+ readonly unit: "tokens" | "percent";
34
+ /** Claude's effective auto-compact point. */
35
+ readonly native: number;
36
+ /** Where notesoup resets: native minus the reset margin. */
37
+ readonly reset: number;
38
+ /** Where the one warning per window fires: reset minus the warning runway. */
39
+ readonly warn: number;
40
+ readonly resetMargin: number;
41
+ readonly warningRunway: number;
42
+ };
43
+
44
+ function isObject(value: unknown): value is Record<string, unknown> {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46
+ }
47
+ /** Numbers may arrive typed or as environment strings; anything else is unknown. */
48
+ function numberOf(value: unknown): number | undefined {
49
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
50
+ if (typeof value === "string" && value.trim() !== "") {
51
+ const parsed = Number(value);
52
+ return Number.isFinite(parsed) ? parsed : undefined;
53
+ }
54
+ return undefined;
55
+ }
56
+ function positiveNumberOf(value: unknown): number | undefined {
57
+ const parsed = numberOf(value);
58
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
59
+ }
60
+ /** A margin is usable only as a positive integer, matching Pi's budget policy. */
61
+ function positiveIntegerOf(value: unknown): number | undefined {
62
+ const parsed = numberOf(value);
63
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
64
+ }
65
+ /** Claude accepts a percent override only in (0, 100]. */
66
+ function percentOf(value: unknown): number | undefined {
67
+ const parsed = numberOf(value);
68
+ return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
69
+ }
70
+ /** Presence-style flags (DISABLE_AUTO_COMPACT): any value but an explicit no counts as on. */
71
+ function flagOn(value: unknown): boolean {
72
+ if (typeof value !== "string") return false;
73
+ const text = value.trim().toLowerCase();
74
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
75
+ }
76
+ function settingFlag(settings: unknown, key: string): boolean | undefined {
77
+ if (!isObject(settings)) return undefined;
78
+ const value = settings[key];
79
+ return typeof value === "boolean" ? value : undefined;
80
+ }
81
+
82
+ /**
83
+ * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
84
+ * modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
85
+ * smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
86
+ */
87
+ function configuredWindow(settings: unknown, env: Record<string, unknown>, model: unknown): number | undefined {
88
+ const windows: number[] = [];
89
+ const fromEnv = positiveNumberOf(env.autoCompactWindow);
90
+ if (fromEnv !== undefined) windows.push(fromEnv);
91
+ if (typeof model === "string" && model.length > 0 && isObject(settings)) {
92
+ const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
93
+ const perModel = modelSettings[model];
94
+ if (isObject(perModel)) {
95
+ const value = positiveNumberOf(perModel.autoCompactWindow);
96
+ if (value !== undefined) windows.push(value);
97
+ }
98
+ }
99
+ if (isObject(settings)) {
100
+ const value = positiveNumberOf(settings.autoCompactWindow);
101
+ if (value !== undefined) windows.push(value);
102
+ }
103
+ return windows.length === 0 ? undefined : Math.min(...windows);
104
+ }
105
+
106
+ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: number, resetMargin: number, warningRunway: number): ClaudeLimits {
107
+ const tokens = Math.max(0, Math.floor(native));
108
+ const reset = Math.max(0, tokens - resetMargin);
109
+ return {
110
+ source, autoCompact, unit: "tokens",
111
+ native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
112
+ };
113
+ }
114
+
115
+ /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
116
+ function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
117
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
118
+ const native = pct === undefined ? base : Math.min(pct, base);
119
+ const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
120
+ return {
121
+ source: "percent", autoCompact, unit: "percent",
122
+ native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
128
+ * so a missing or malformed one degrades to the next source and finally to the percent
129
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
130
+ * helper boundary, where nothing is typed.
131
+ */
132
+ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
133
+ const root = isObject(facts) ? facts : {};
134
+ const usage = isObject(root.usage) ? root.usage : {};
135
+ const breakdown = isObject(root.breakdown) ? root.breakdown : {};
136
+ const env = isObject(root.env) ? root.env : {};
137
+ const settings = root.settings;
138
+
139
+ const margins = mergeNotesoupSettings(settings, undefined);
140
+ const resetMargin = positiveIntegerOf(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
141
+ const warningRunway = positiveIntegerOf(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
142
+
143
+ const autoCompact = settingFlag(settings, "autoCompactEnabled") !== false
144
+ && !flagOn(env.disableAutoCompact)
145
+ && breakdown.isAutoCompactEnabled !== false;
146
+ const pct = percentOf(env.pctOverride);
147
+
148
+ // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
149
+ // the percent override is applied separately, on the window-after-output-reserve it is
150
+ // minted from (threshold + summary buffer).
151
+ const threshold = positiveNumberOf(breakdown.autoCompactThreshold);
152
+ if (autoCompact && threshold !== undefined) {
153
+ const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
154
+ if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
155
+ }
156
+
157
+ // (b) The same point computed from the reported window plus settings and environment.
158
+ const window = positiveNumberOf(usage.window);
159
+ if (window !== undefined) {
160
+ const configured = configuredWindow(settings, env, breakdown.model);
161
+ const effective = Math.min(configured ?? window, window);
162
+ const native = autoCompact
163
+ ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
164
+ : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
165
+ if (native > 0) return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
166
+ }
167
+
168
+ // (c) Nothing usable but percentages.
169
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
170
+ }
@@ -2,13 +2,14 @@ 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
 
6
7
  /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
7
8
  export function doctor(home: string): string[] {
8
9
  const issues: string[] = [];
9
10
  const report = (path: string, message: string) => issues.push(`${relative(home, path) || "."}: ${message}`);
10
11
  const inspect = (path: string, action: () => void) => {
11
- try { action(); } catch (error) { report(path, `cannot inspect: ${error instanceof Error ? error.message : String(error)}`); }
12
+ try { action(); } catch (error) { report(path, `cannot inspect: ${errorMessage(error)}`); }
12
13
  };
13
14
  const directory = (path: string): boolean => {
14
15
  const stat = lstatSync(path);
@@ -53,7 +54,7 @@ export function doctor(home: string): string[] {
53
54
  : root;
54
55
  if (!targetHome) { report(path, `${address}: project context unavailable; use a resolvable reference`); continue; }
55
56
  if (!existsSync(join(targetHome, parsed.path))) report(path, `${address}: target missing; update or remove the reference`);
56
- } catch { report(path, `${address}: invalid address; ${ADDRESS_FORMS}`); }
57
+ } catch { report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`); }
57
58
  }
58
59
  };
59
60
  const walk = (dir: string, root: string, project?: string) => {
package/src/dream/git.ts CHANGED
@@ -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
 
5
6
  /**
6
7
  * Outcome of one audit commit. `ok: true` always carries a real `commit` snapshot;
@@ -58,7 +59,7 @@ export function gitCommit(home: string, message: string): AuditResult {
58
59
  if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
59
60
  return { ok: true, commit, empty: clean };
60
61
  } catch (error) {
61
- const reason = error instanceof Error ? error.message : String(error);
62
+ const reason = errorMessage(error);
62
63
  console.log(`git audit layer failed: ${reason}`);
63
64
  return { ok: false, error: reason };
64
65
  }
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
  }
@@ -2,6 +2,7 @@ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { gitCommit } from "./git.js";
4
4
  import type { DreamWrite } from "./result.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
 
6
7
  function writeList(writes: DreamWrite[]): string {
7
8
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
@@ -10,12 +11,12 @@ function writeList(writes: DreamWrite[]): string {
10
11
  /** Best-effort text write; returns the failure message instead of throwing. */
11
12
  function writeText(path: string, content: string): string | undefined {
12
13
  try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); return undefined; }
13
- catch (error) { return error instanceof Error ? error.message : String(error); }
14
+ catch (error) { return errorMessage(error); }
14
15
  }
15
16
 
16
17
  function appendText(path: string, content: string): string | undefined {
17
18
  try { appendFileSync(path, content); return undefined; }
18
- catch (error) { return error instanceof Error ? error.message : String(error); }
19
+ catch (error) { return errorMessage(error); }
19
20
  }
20
21
 
21
22
  /**
@@ -0,0 +1,4 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export function errorMessage(error: unknown): string {
3
+ return error instanceof Error ? error.message : String(error);
4
+ }
@@ -259,7 +259,7 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
259
259
  export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
260
260
  if (typeof params.window_id !== "string") return undefined;
261
261
  const known = projection.windows.map((current) => current.windowId);
262
- return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
262
+ return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
263
263
  }
264
264
 
265
265
  /**
@@ -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, type Static } from "typebox";
3
3
  import { failure, success, type Outcome } 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, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
7
7
 
@@ -40,7 +40,7 @@ function isoUtcMs(value: string): number | undefined {
40
40
  function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
41
41
  if (value === undefined) return success(undefined);
42
42
  const at = isoUtcMs(value);
43
- return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
43
+ return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
44
44
  }
45
45
 
46
46
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
@@ -50,7 +50,7 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
50
50
  const until = timeBound("until", params.until);
51
51
  if (!until.ok) return until;
52
52
  if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
53
- return failure("invalid_time", "since must be earlier than until");
53
+ return failure("invalid_time", "`since` must be earlier than `until`.");
54
54
  }
55
55
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
56
56
  }
@@ -67,8 +67,8 @@ export const HistoryNewerSchema = Type.Object({
67
67
 
68
68
  export const HistoryPageSchema = Type.Object({
69
69
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
70
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
71
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
70
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
71
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
72
72
  }, { additionalProperties: false });
73
73
 
74
74
  /** One whole page payload, before it becomes an outcome. */
@@ -216,7 +216,7 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
216
216
  }
217
217
  const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
218
218
  if (!fits(page)) {
219
- 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`);
219
+ 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.`);
220
220
  }
221
221
  return success(page);
222
222
  }
@@ -4,7 +4,7 @@ import { SLUG_PATTERN, type Scope } from "./paths.js";
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8
8
 
9
9
  /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
10
10
  function shown(value: unknown): string {
@@ -13,10 +13,10 @@ function shown(value: unknown): string {
13
13
  }
14
14
 
15
15
  export function assertVirtualPath(value: unknown): string {
16
- if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
17
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
16
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
17
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
18
18
  const parts = value.split("/");
19
- if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
19
+ if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
20
20
  return value;
21
21
  }
22
22
 
@@ -49,8 +49,8 @@ export function globToRegExp(pattern: string): RegExp {
49
49
  /** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
50
50
  export function assertGlobPattern(value: unknown): string | undefined {
51
51
  if (value === undefined || value === null || value === "") return undefined;
52
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
53
- if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
52
+ if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
53
+ if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
54
54
  return value;
55
55
  }
56
56
 
@@ -59,7 +59,7 @@ export function assertGlobPattern(value: unknown): string | undefined {
59
59
  * are relative; explicit agents/models addresses always name a canonical slug.
60
60
  */
61
61
  export function assertAddress(value: unknown): NoteAddress {
62
- if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
62
+ if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
63
63
  let scope: Scope = "session";
64
64
  let path = value;
65
65
  let who: string | undefined;
@@ -76,16 +76,16 @@ export function assertAddress(value: unknown): NoteAddress {
76
76
  else if (head === "agents" || head === "models") {
77
77
  const nameEnd = tail.indexOf("/");
78
78
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
79
- if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
79
+ if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
80
80
  scope = head === "agents" ? "agent" : "model";
81
81
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
82
82
  } else {
83
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
83
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
84
84
  }
85
- if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
86
- if (path === "" && who === undefined) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
85
+ if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
86
+ if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
87
87
  }
88
- if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
88
+ if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
89
89
  assertVirtualPath(path);
90
90
  return { scope, path, who };
91
91
  }
@@ -228,12 +228,17 @@ async function atomicWrite(path: string, content: string): Promise<void> {
228
228
  /** The byte cap is a write-time boundary rule, never a path-jail rule. */
229
229
  function assertWritablePath(vpath: string): void {
230
230
  const bytes = Buffer.byteLength(vpath, "utf8");
231
- if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
231
+ if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
232
+ }
233
+
234
+ /** Rounded up, so a note just over the limit never reads as exactly at it. */
235
+ function megabytes(bytes: number): string {
236
+ return `${Math.ceil(bytes / 10_000) / 100} MB`;
232
237
  }
233
238
 
234
239
  function assertSerializedSize(content: string): void {
235
240
  const bytes = Buffer.byteLength(content, "utf8");
236
- if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
241
+ if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `This note would be ${megabytes(bytes)}, over the ${megabytes(MAX_NOTE_BYTES)} limit per note; split it into several notes.`);
237
242
  }
238
243
 
239
244
  /** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
@@ -247,7 +252,7 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
247
252
  const current = scope === "agent" ? identity.agent : identity.model;
248
253
  if (who === current) return;
249
254
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
250
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
255
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
251
256
  }
252
257
 
253
258
  /** Normalize parsed metadata exactly as a read does, including its access mutation. */
@@ -319,12 +324,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
319
324
  const scope = destination.scope;
320
325
  assertWritableHome(scope, destination.who, identity);
321
326
  if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
322
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
327
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
323
328
  }
324
329
  const path = physicalPath(scope, destination.path, identity, destination.who);
325
330
  return withPathQueue(path, async () => {
326
331
  const raw = await readFileIfExists(path);
327
- if (raw === undefined) throw new NoteError("not_found", "note not found");
332
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
328
333
  const { meta, body } = parseNote(raw);
329
334
  meta.scope = scope;
330
335
  const beforeMeta: NoteMeta = { ...meta };
@@ -333,12 +338,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
333
338
  operations.forEach((operation, index) => {
334
339
  const oldText = operation?.oldText;
335
340
  const newText = operation?.newText;
336
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
337
- if (typeof newText !== "string") throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
341
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
342
+ if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
338
343
  const lines = matchLineNumbers(next, oldText);
339
- if (lines.length === 0) throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
344
+ if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
340
345
  if (lines.length > 1 && !stableOptions.replaceAll) {
341
- throw new NoteError("ambiguous_edit", `edit ${index}: oldText occurs ${lines.length} times (${anchorLines(lines)}); pass replace_all to replace every occurrence`, { lineNumbers: lines, editIndex: index });
346
+ throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
342
347
  }
343
348
  if (oldText !== newText) applied++;
344
349
  // Positional splicing preserves user replacement text byte-for-byte.
@@ -384,14 +389,14 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
384
389
  assertWritableHome(toScope, to.who, identity);
385
390
  const fromPath = physicalPath(fromScope, from.path, identity, from.who);
386
391
  const toPath = physicalPath(toScope, to.path, identity, to.who);
387
- if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
392
+ if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
388
393
  const [first, second] = [fromPath, toPath].sort();
389
394
  return withPathQueue(first!, () => withPathQueue(second!, async () => {
390
395
  const raw = await readFileIfExists(fromPath);
391
- if (raw === undefined) throw new NoteError("not_found", "note not found");
396
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
392
397
  const targetRaw = await readFileIfExists(toPath);
393
398
  if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
394
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
399
+ throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
395
400
  }
396
401
  const { meta, body } = parseNote(raw);
397
402
  meta.scope = toScope;