notesoup 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.js +1 -1
  4. package/dist/src/budget/parse.d.ts +14 -0
  5. package/dist/src/budget/parse.js +36 -0
  6. package/dist/src/budget/policy.js +2 -7
  7. package/dist/src/budget/text.d.ts +2 -0
  8. package/dist/src/budget/text.js +2 -0
  9. package/dist/src/claude/helper.js +1 -2
  10. package/dist/src/claude/thresholds.js +45 -66
  11. package/dist/src/dream/lock.js +6 -13
  12. package/dist/src/dream/report.js +5 -15
  13. package/dist/src/history/history.js +4 -2
  14. package/dist/src/history/query.js +10 -22
  15. package/dist/src/notes/address.d.ts +0 -1
  16. package/dist/src/notes/address.js +5 -17
  17. package/dist/src/notes/errors.d.ts +2 -0
  18. package/dist/src/notes/errors.js +5 -0
  19. package/dist/src/notes/frontmatter.js +16 -2
  20. package/dist/src/notes/identity.js +0 -3
  21. package/dist/src/notes/paths.d.ts +11 -1
  22. package/dist/src/notes/paths.js +28 -7
  23. package/dist/src/notes/store.d.ts +1 -0
  24. package/dist/src/notes/store.js +38 -37
  25. package/dist/src/pi/boot.js +1 -5
  26. package/dist/src/pi/budget.d.ts +3 -3
  27. package/dist/src/pi/budget.js +11 -11
  28. package/dist/src/pi/dream/cli.js +43 -11
  29. package/dist/src/pi/estimate.d.ts +1 -5
  30. package/dist/src/pi/estimate.js +4 -4
  31. package/dist/src/pi/history.js +1 -4
  32. package/dist/src/pi/notes/adapter.d.ts +1 -1
  33. package/dist/src/pi/notes/adapter.js +2 -2
  34. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  35. package/dist/src/pi/reset/artifacts.js +4 -4
  36. package/dist/src/pi/reset/committed.js +2 -2
  37. package/dist/src/pi/runtime.js +8 -5
  38. package/dist/src/pi/thresholds.js +5 -9
  39. package/dist/src/pi/tool-result.d.ts +1 -4
  40. package/dist/src/pi/tool-result.js +1 -1
  41. package/dist/src/pi/window.d.ts +5 -0
  42. package/dist/src/pi/window.js +7 -0
  43. package/dist/src/settings.d.ts +2 -0
  44. package/dist/src/settings.js +4 -3
  45. package/dist/src/tools/history.js +4 -7
  46. package/dist/src/tools/notes.d.ts +0 -4
  47. package/dist/src/tools/notes.js +6 -16
  48. package/dist/src/tools/output.d.ts +0 -3
  49. package/dist/src/tools/output.js +1 -9
  50. package/dist/src/tools/result.d.ts +1 -0
  51. package/dist/src/tools/result.js +14 -20
  52. package/dist/src/tools/schema.d.ts +0 -1
  53. package/dist/src/tools/schema.js +0 -1
  54. package/dist/test/agent-loop.test.js +1 -2
  55. package/dist/test/boot.integration.test.js +1 -1
  56. package/dist/test/claude-mod.test.js +221 -9
  57. package/dist/test/claude-validation.test.d.ts +1 -0
  58. package/dist/test/claude-validation.test.js +73 -0
  59. package/dist/test/dream-skill.test.js +2 -4
  60. package/dist/test/dream.test.js +14 -0
  61. package/dist/test/helpers/extension.js +1 -1
  62. package/dist/test/history.integration.test.js +2 -1
  63. package/dist/test/host-neutral.test.js +15 -0
  64. package/dist/test/notes-library.test.js +30 -1
  65. package/dist/test/notes.integration.test.js +7 -7
  66. package/dist/test/notes.test.js +24 -5
  67. package/dist/test/reset-lifecycle.test.js +1 -1
  68. package/docs/claude-code-mod.md +5 -3
  69. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  70. package/mods/notesoup/dist/claude/helper.js +147 -173
  71. package/mods/notesoup/hooks/register.ts +158 -67
  72. package/mods/notesoup/playbook.md +1 -1
  73. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  74. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  75. package/package.json +5 -3
  76. package/playbook.md +1 -1
  77. package/skills/dream/SKILL.md +1 -1
  78. package/skills/memory/SKILL.md +1 -1
  79. package/src/boot/render.ts +11 -21
  80. package/src/boot/snapshot.ts +2 -7
  81. package/src/boot/text.ts +1 -1
  82. package/src/budget/parse.ts +39 -0
  83. package/src/budget/policy.ts +2 -6
  84. package/src/budget/text.ts +3 -0
  85. package/src/claude/helper.ts +2 -2
  86. package/src/claude/thresholds.ts +45 -62
  87. package/src/dream/lock.ts +3 -9
  88. package/src/dream/report.ts +5 -10
  89. package/src/history/history.ts +4 -2
  90. package/src/history/query.ts +10 -23
  91. package/src/notes/address.ts +4 -16
  92. package/src/notes/errors.ts +6 -0
  93. package/src/notes/frontmatter.ts +12 -2
  94. package/src/notes/identity.ts +0 -2
  95. package/src/notes/paths.ts +23 -5
  96. package/src/notes/store.ts +33 -36
  97. package/src/pi/boot.ts +1 -13
  98. package/src/pi/budget.ts +10 -11
  99. package/src/pi/dream/cli.ts +35 -10
  100. package/src/pi/estimate.ts +4 -4
  101. package/src/pi/history.ts +1 -5
  102. package/src/pi/notes/adapter.ts +2 -2
  103. package/src/pi/reset/artifacts.ts +4 -4
  104. package/src/pi/reset/committed.ts +2 -2
  105. package/src/pi/runtime.ts +7 -6
  106. package/src/pi/thresholds.ts +5 -11
  107. package/src/pi/tool-result.ts +1 -1
  108. package/src/pi/window.ts +8 -0
  109. package/src/settings.ts +4 -3
  110. package/src/tools/history.ts +4 -8
  111. package/src/tools/notes.ts +7 -20
  112. package/src/tools/output.ts +1 -12
  113. package/src/tools/result.ts +14 -19
  114. package/src/tools/schema.ts +0 -1
  115. package/dist/src/dream/playbook.d.ts +0 -1
  116. package/dist/src/dream/playbook.js +0 -2
  117. package/dist/src/pi/reset/text.d.ts +0 -4
  118. package/dist/src/pi/reset/text.js +0 -7
  119. package/src/dream/playbook.ts +0 -3
  120. package/src/pi/reset/text.ts +0 -9
@@ -1,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
@@ -51,7 +51,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
51
51
 
52
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\`.
53
53
 
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 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.
55
55
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
56
56
 
57
57
  /** Logical tool names are supplied by the composing host, not discovered here. */
@@ -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;
@@ -15,6 +15,9 @@ export const WARNING_BODY =
15
15
 
16
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
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
+
18
21
  /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
19
22
  export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
20
23
 
@@ -30,6 +30,7 @@ function identity(input: ClaudeIdentityInput): NotesIdentity {
30
30
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
31
31
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
32
32
  }
33
+
33
34
  /** The first schema violation, named by parameter so the model can fix that one field. */
34
35
  function paramProblem(schema: TSchema, params: unknown): string {
35
36
  // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
@@ -39,7 +40,6 @@ function paramProblem(schema: TSchema, params: unknown): string {
39
40
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
40
41
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
41
42
  }
42
- function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
43
43
 
44
44
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
45
45
  function boundOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
@@ -75,7 +75,7 @@ const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
75
75
  export async function dispatch(request: unknown): Promise<unknown> {
76
76
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
77
77
  const value = request as Record<string, unknown>;
78
- 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
79
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
80
80
  // cannot drift apart. The hooks module caches one copy per session.
81
81
  if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
@@ -1,5 +1,6 @@
1
1
  import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
- import { mergeNotesoupSettings } from "../settings.js";
2
+ import { percent, positiveInteger, positiveNumber, presenceFlag } from "../budget/parse.js";
3
+ import { isPlainObject, mergeNotesoupSettings } from "../settings.js";
3
4
 
4
5
  /**
5
6
  * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
@@ -16,6 +17,14 @@ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
16
17
  export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
17
18
  /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
18
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;
19
28
  /**
20
29
  * The percent fallback assumes the classic 200K model window: it is reached only when
21
30
  * `usage()` reports no window and no breakdown, and it reproduces the token maths below
@@ -41,42 +50,12 @@ export type ClaudeLimits = {
41
50
  readonly warningRunway: number;
42
51
  };
43
52
 
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;
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;
80
59
  }
81
60
 
82
61
  /**
@@ -86,18 +65,18 @@ function settingFlag(settings: unknown, key: string): boolean | undefined {
86
65
  */
87
66
  function configuredWindow(settings: unknown, env: Record<string, unknown>, model: unknown): number | undefined {
88
67
  const windows: number[] = [];
89
- const fromEnv = positiveNumberOf(env.autoCompactWindow);
68
+ const fromEnv = positiveNumber(env.autoCompactWindow);
90
69
  if (fromEnv !== undefined) windows.push(fromEnv);
91
- if (typeof model === "string" && model.length > 0 && isObject(settings)) {
92
- const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
70
+ if (typeof model === "string" && model.length > 0 && isPlainObject(settings)) {
71
+ const modelSettings = isPlainObject(settings.modelSettings) ? settings.modelSettings : {};
93
72
  const perModel = modelSettings[model];
94
- if (isObject(perModel)) {
95
- const value = positiveNumberOf(perModel.autoCompactWindow);
73
+ if (isPlainObject(perModel)) {
74
+ const value = positiveNumber(perModel.autoCompactWindow);
96
75
  if (value !== undefined) windows.push(value);
97
76
  }
98
77
  }
99
- if (isObject(settings)) {
100
- const value = positiveNumberOf(settings.autoCompactWindow);
78
+ if (isPlainObject(settings)) {
79
+ const value = positiveNumber(settings.autoCompactWindow);
101
80
  if (value !== undefined) windows.push(value);
102
81
  }
103
82
  return windows.length === 0 ? undefined : Math.min(...windows);
@@ -105,10 +84,10 @@ function configuredWindow(settings: unknown, env: Record<string, unknown>, model
105
84
 
106
85
  function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: number, resetMargin: number, warningRunway: number): ClaudeLimits {
107
86
  const tokens = Math.max(0, Math.floor(native));
108
- const reset = Math.max(0, tokens - resetMargin);
87
+ const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
109
88
  return {
110
89
  source, autoCompact, unit: "tokens",
111
- native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
90
+ native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
112
91
  };
113
92
  }
114
93
 
@@ -116,10 +95,10 @@ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: nu
116
95
  function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
117
96
  const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
118
97
  const native = pct === undefined ? base : Math.min(pct, base);
119
- const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
98
+ const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
120
99
  return {
121
100
  source: "percent", autoCompact, unit: "percent",
122
- native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
101
+ native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
123
102
  };
124
103
  }
125
104
 
@@ -130,39 +109,43 @@ function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargi
130
109
  * helper boundary, where nothing is typed.
131
110
  */
132
111
  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 : {};
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 : {};
137
116
  const settings = root.settings;
138
117
 
118
+ // The host hands over its merged settings, so there is no separate project scope to name.
139
119
  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;
120
+ const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
121
+ const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
142
122
 
143
- const autoCompact = settingFlag(settings, "autoCompactEnabled") !== false
144
- && !flagOn(env.disableAutoCompact)
123
+ const autoCompact = settingFlag(settings) !== false
124
+ && !presenceFlag(env.disableAutoCompact)
145
125
  && breakdown.isAutoCompactEnabled !== false;
146
- const pct = percentOf(env.pctOverride);
126
+ const pct = percent(env.pctOverride);
147
127
 
148
128
  // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
149
129
  // 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);
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);
152
133
  if (autoCompact && threshold !== undefined) {
153
134
  const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
154
135
  if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
155
136
  }
156
137
 
157
- // (b) The same point computed from the reported window plus settings and environment.
158
- const window = positiveNumberOf(usage.window);
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);
159
142
  if (window !== undefined) {
160
143
  const configured = configuredWindow(settings, env, breakdown.model);
161
144
  const effective = Math.min(configured ?? window, window);
162
145
  const native = autoCompact
163
146
  ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
164
147
  : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
165
- if (native > 0) return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
148
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
166
149
  }
167
150
 
168
151
  // (c) Nothing usable but percentages.
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" });
@@ -8,14 +8,9 @@ function writeList(writes: DreamWrite[]): string {
8
8
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
9
9
  }
10
10
 
11
- /** Best-effort text write; returns the failure message instead of throwing. */
12
- function writeText(path: string, content: string): string | undefined {
13
- try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); return undefined; }
14
- catch (error) { return errorMessage(error); }
15
- }
16
-
17
- function appendText(path: string, content: string): string | undefined {
18
- try { appendFileSync(path, content); return undefined; }
11
+ /** Best-effort filesystem step; returns the failure message instead of throwing. */
12
+ function attempt(action: () => void): string | undefined {
13
+ try { action(); return undefined; }
19
14
  catch (error) { return errorMessage(error); }
20
15
  }
21
16
 
@@ -26,11 +21,11 @@ function appendText(path: string, content: string): string | undefined {
26
21
  */
27
22
  export function finishDream(home: string, stamp: string, reportPath: string, failed: boolean, body: string, writes: DreamWrite[]): number {
28
23
  const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
29
- let reportError = writeText(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`);
24
+ let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
30
25
  const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
31
26
  if (!audit.ok) {
32
27
  console.error(`dream: final audit failed: ${audit.error}`);
33
- reportError ??= appendText(reportPath, `\n## Final audit failed\n\n${audit.error}\n`);
28
+ reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
34
29
  }
35
30
  if (reportError) console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
36
31
  return failed || !audit.ok || reportError !== undefined ? 1 : 0;
@@ -239,14 +239,16 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
239
239
  const document = eventDocument(event);
240
240
  const chars = Array.from(document);
241
241
  const start = matchOffset ?? 0;
242
- const truncated = start > 0 || start + maxChars < chars.length;
242
+ // A negative budget would cut the tail and still call the result a prefix.
243
+ const limit = Math.max(0, maxChars);
244
+ const truncated = start > 0 || start + limit < chars.length;
243
245
  return {
244
246
  seq: event.seq,
245
247
  window_id: event.windowId,
246
248
  role: event.role,
247
249
  created_at: event.createdAt ?? null,
248
250
  ...toolSummary(event),
249
- content: truncated ? chars.slice(start, start + maxChars).join("") : document,
251
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
250
252
  truncated,
251
253
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
252
254
  };
@@ -1,7 +1,8 @@
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, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
4
+ import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
+ import { earliestMatchOffsetChars } from "../text-match.js";
5
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
7
  import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
7
8
 
@@ -28,19 +29,12 @@ export type HistorySelection = HistoryFilter & {
28
29
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
29
30
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
30
31
 
31
- /** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
32
- function isoUtcMs(value: string): number | undefined {
33
- const match = ISO_8601.exec(value);
34
- if (match === null) return undefined;
35
- const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
36
- return Number.isNaN(at) ? undefined : at;
37
- }
38
-
39
32
  /** Epoch ms for one optional time param, or a refusal naming it. */
40
33
  function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
41
34
  if (value === undefined) return success(undefined);
42
- const at = isoUtcMs(value);
43
- return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
35
+ const match = ISO_8601.exec(value);
36
+ const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
37
+ return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
44
38
  }
45
39
 
46
40
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
@@ -180,16 +174,6 @@ function selectionCandidates(projection: HistoryProjection, params: HistorySelec
180
174
  .filter((candidate) => candidate.matchOffset >= 0));
181
175
  }
182
176
 
183
- /**
184
- * Take the limit from the end `from` names, starting there so a budget for one row keeps the most
185
- * important row. The selection is already filtered to its range; `from` never states a direction.
186
- */
187
- function orderedCandidates(vis: Candidate[], params: HistorySelection, limit: number): Candidate[] {
188
- const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
189
- const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
190
- return params.from === "oldest" ? selected : selected.reverse();
191
- }
192
-
193
177
  /**
194
178
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
195
179
  * Grow the page in selection order; shorten the first preview only when no full row fits.
@@ -201,9 +185,12 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
201
185
  const candidates = selectionCandidates(projection, scoped);
202
186
  if (!candidates.ok) return candidates;
203
187
  const vis = candidates.data;
204
- const limit = scoped.limit ?? 20;
188
+ // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
189
+ // At least one: `slice(-0)` would otherwise return the whole selection.
190
+ const limit = Math.max(1, scoped.limit ?? 20);
205
191
  const folds = foldsRuns(scoped);
206
- const ordered = orderedCandidates(vis, scoped, limit);
192
+ const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
193
+ const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
207
194
  const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
208
195
  const kept: Candidate[] = [];
209
196
  for (const candidate of ordered) {
@@ -1,25 +1,11 @@
1
- import { NoteError } from "./errors.js";
1
+ import { NoteError, shown } from "./errors.js";
2
2
  import type { NotesIdentity } from "./identity.js";
3
- import { SLUG_PATTERN, type Scope } from "./paths.js";
3
+ import { assertVirtualPath, SLUG_PATTERN, type Scope } from "./paths.js";
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
7
  export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8
8
 
9
- /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
10
- function shown(value: unknown): string {
11
- const json = JSON.stringify(value);
12
- return json === undefined ? String(value) : json;
13
- }
14
-
15
- export function assertVirtualPath(value: unknown): string {
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
- const parts = value.split("/");
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
- return value;
21
- }
22
-
23
9
  /**
24
10
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
25
11
  * `/`), `**` matches any run across segments (a leading double-star followed by a
@@ -39,6 +25,8 @@ export function globToRegExp(pattern: string): RegExp {
39
25
  } else {
40
26
  source += "[^/]*";
41
27
  }
28
+ } else if (char === "?") {
29
+ source += "[^/]";
42
30
  } else {
43
31
  source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
44
32
  }
@@ -13,3 +13,9 @@ export class NoteError extends Error {
13
13
  this.editIndex = extra.editIndex;
14
14
  }
15
15
  }
16
+
17
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
18
+ export function shown(value: unknown): string {
19
+ const json = JSON.stringify(value);
20
+ return json === undefined ? String(value) : json;
21
+ }
@@ -132,15 +132,25 @@ export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body
132
132
  return { meta: meta as NoteMeta, body };
133
133
  }
134
134
 
135
- /** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
135
+ /**
136
+ * Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
137
+ * A quoted string must not come back as another type: a value that `JSON.parse` reads as a
138
+ * non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
139
+ * with its type intact.
140
+ */
136
141
  function yamlScalar(value: unknown): string {
137
142
  if (typeof value === "string") {
138
143
  const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
139
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase())) return value;
144
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
140
145
  }
141
146
  return JSON.stringify(value);
142
147
  }
143
148
 
149
+ /** True when a bare scalar would be read back as a number, boolean or null instead of text. */
150
+ function parsesAsNonString(text: string): boolean {
151
+ try { return typeof JSON.parse(text) !== "string"; } catch { return false; }
152
+ }
153
+
144
154
  /** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
145
155
  export function serializeNote(meta: NoteMeta, body: string): string {
146
156
  const lines: string[] = [];
@@ -24,8 +24,6 @@ function assertDirectoryComponent(field: string, value: string): void {
24
24
  /** Validate and snapshot caller identity; no global or environment defaults are consulted. */
25
25
  export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
26
26
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("notes context must be a plain object");
27
- const prototype = Object.getPrototypeOf(value);
28
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("notes context must be a plain object");
29
27
  const homeValue = requireString("home", value.home);
30
28
  const sessionId = requireString("sessionId", value.sessionId);
31
29
  const projectKey = requireString("projectKey", value.projectKey);