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
@@ -14,9 +14,6 @@ function assertDirectoryComponent(field, value) {
14
14
  export function snapshotNotesIdentity(value) {
15
15
  if (typeof value !== "object" || value === null || Array.isArray(value))
16
16
  throw new TypeError("notes context must be a plain object");
17
- const prototype = Object.getPrototypeOf(value);
18
- if (prototype !== Object.prototype && prototype !== null)
19
- throw new TypeError("notes context must be a plain object");
20
17
  const homeValue = requireString("home", value.home);
21
18
  const sessionId = requireString("sessionId", value.sessionId);
22
19
  const projectKey = requireString("projectKey", value.projectKey);
@@ -4,7 +4,17 @@ export type Scope = "session" | "project" | "human" | "agent" | "model";
4
4
  export declare const SLUG_PATTERN: RegExp;
5
5
  /** Slugify a caller-declared identity; identity is never inferred from note content. */
6
6
  export declare function slugify(value: string): string;
7
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
7
+ /**
8
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
9
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
10
+ * caller that reaches a path without going through an address still cannot escape a home.
11
+ */
12
+ export declare function assertVirtualPath(value: unknown): string;
13
+ /**
14
+ * `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
15
+ * with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
16
+ * so canonicalizing here is what keeps one repository — and its worktrees — on one home.
17
+ */
8
18
  export declare function projectKey(cwd: string): string;
9
19
  /** Absolute directory holding the per-session note homes. */
10
20
  export declare function sessionHomesRoot(home: string): string;
@@ -1,7 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { readdir } from "node:fs/promises";
4
4
  import { basename, dirname, join, resolve, sep } from "node:path";
5
+ import { NoteError, shown } from "./errors.js";
5
6
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
6
7
  export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
7
8
  /** Slugify a caller-declared identity; identity is never inferred from note content. */
@@ -9,10 +10,34 @@ export function slugify(value) {
9
10
  const slug = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
10
11
  return slug.length > 0 ? slug : "root";
11
12
  }
12
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
13
+ /**
14
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
15
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
16
+ * caller that reaches a path without going through an address still cannot escape a home.
17
+ */
18
+ export function assertVirtualPath(value) {
19
+ if (typeof value !== "string" || value.length === 0)
20
+ throw new NoteError("invalid_address", "The address is empty; give the note a path.");
21
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
22
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
23
+ const parts = value.split("/");
24
+ if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
25
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
26
+ return value;
27
+ }
28
+ /**
29
+ * `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
30
+ * with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
31
+ * so canonicalizing here is what keeps one repository — and its worktrees — on one home.
32
+ */
13
33
  export function projectKey(cwd) {
14
34
  const absolute = resolve(cwd);
15
- const root = gitRoot(absolute) ?? absolute;
35
+ const spelled = gitRoot(absolute) ?? absolute;
36
+ let root = spelled;
37
+ try {
38
+ root = realpathSync(spelled);
39
+ }
40
+ catch { /* An unresolvable path keeps its spelling. */ }
16
41
  const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
17
42
  return `${basename(root)}-${digest}`;
18
43
  }
@@ -105,9 +130,5 @@ export function noteFileName(vpath) {
105
130
  }
106
131
  /** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
107
132
  export function physicalPath(scope, vpath, identity, who) {
108
- if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/"))
109
- throw new TypeError("path must be a safe virtual relative path");
110
- if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === ".."))
111
- throw new TypeError("path contains an unsupported component");
112
133
  return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
113
134
  }
@@ -76,6 +76,7 @@ export type NoteRenameResult = {
76
76
  meta: NoteMeta;
77
77
  replacedCrumpledTarget: boolean;
78
78
  };
79
+ /** A home, or one unreadable note inside it, that a status-reporting query could not read. */
79
80
  export type NoteQueryStatus = {
80
81
  homesUnavailable: string[];
81
82
  };
@@ -75,10 +75,6 @@ async function walkMarkdown(dir, base = dir) {
75
75
  }
76
76
  return paths;
77
77
  }
78
- function matcherFor(pattern) {
79
- const normalized = assertGlobPattern(pattern);
80
- return normalized === undefined ? undefined : globToRegExp(normalized);
81
- }
82
78
  async function homesForPattern(pattern, identity) {
83
79
  if (!pattern || !pattern.startsWith("@"))
84
80
  return undefined;
@@ -110,11 +106,6 @@ function normalizePattern(pattern, identity) {
110
106
  return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
111
107
  return pattern;
112
108
  }
113
- function assertScope(value) {
114
- if (!isScope(value))
115
- throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(value)})`);
116
- return value;
117
- }
118
109
  function assertOrigin(value) {
119
110
  if (!isOrigin(value))
120
111
  throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
@@ -128,7 +119,9 @@ function assertWho(value) {
128
119
  }
129
120
  async function homesFor(identity, opts) {
130
121
  if (opts.scope !== undefined) {
131
- const scope = assertScope(opts.scope);
122
+ if (!isScope(opts.scope))
123
+ throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
124
+ const scope = opts.scope;
132
125
  if (opts.who !== undefined) {
133
126
  const who = assertWho(opts.who);
134
127
  if (scope !== "agent" && scope !== "model")
@@ -220,13 +213,6 @@ function assertWritableHome(scope, who, identity) {
220
213
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
221
214
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
222
215
  }
223
- /** Normalize parsed metadata exactly as a read does, including its access mutation. */
224
- function accessedMeta(meta, scope, now) {
225
- const next = { ...meta, scope };
226
- next.lastAccessed = now;
227
- next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
228
- return next;
229
- }
230
216
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
231
217
  export function createNotesStore(input) {
232
218
  const identity = snapshotNotesIdentity(input);
@@ -236,7 +222,9 @@ export function createNotesStore(input) {
236
222
  assertWritablePath(destination.path);
237
223
  const scope = destination.scope;
238
224
  assertWritableHome(scope, destination.who, identity);
239
- const origin = assertOrigin(stableOptions.origin ?? "self");
225
+ // Absent means "keep whatever the note already says": replacing a note must not silently
226
+ // re-attribute a user-written note to the agent that happened to rewrite it.
227
+ const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
240
228
  const path = physicalPath(scope, destination.path, identity, destination.who);
241
229
  return withPathQueue(path, async () => {
242
230
  const now = writeStamp();
@@ -246,7 +234,7 @@ export function createNotesStore(input) {
246
234
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
247
235
  const meta = existing ?? {
248
236
  scope,
249
- origin,
237
+ origin: origin ?? "self",
250
238
  createdAt: now,
251
239
  updatedAt: now,
252
240
  lastAccessed: now,
@@ -254,7 +242,8 @@ export function createNotesStore(input) {
254
242
  ...(scope === "session" ? { project: identity.projectKey } : {}),
255
243
  };
256
244
  meta.scope = scope;
257
- meta.origin = origin;
245
+ if (origin !== undefined)
246
+ meta.origin = origin;
258
247
  delete meta.crumpledAt;
259
248
  meta.updatedAt = now;
260
249
  const serialized = serializeNote(meta, cleanBody);
@@ -273,7 +262,8 @@ export function createNotesStore(input) {
273
262
  return undefined;
274
263
  const now = Date.now();
275
264
  const parsed = parseNote(raw, now);
276
- const meta = accessedMeta(parsed.meta, scope, now);
265
+ // A read records its own access, exactly as a write records an edit.
266
+ const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
277
267
  await atomicWrite(path, serializeNote(meta, parsed.body));
278
268
  return { meta, body: parsed.body, resolvedScope: scope };
279
269
  });
@@ -391,7 +381,9 @@ export function createNotesStore(input) {
391
381
  }));
392
382
  }
393
383
  async function* scan(options, status) {
394
- const matcher = matcherFor(normalizePattern(options.glob, identity));
384
+ const pattern = normalizePattern(options.glob, identity);
385
+ const normalized = assertGlobPattern(pattern);
386
+ const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
395
387
  let homes;
396
388
  try {
397
389
  homes = await homesFor(identity, options);
@@ -405,20 +397,9 @@ export function createNotesStore(input) {
405
397
  for (const home of homes) {
406
398
  const scope = home.scope;
407
399
  const root = scopeDir(scope, identity, home.who);
408
- const homeRows = [];
400
+ let paths;
409
401
  try {
410
- for (const path of await walkMarkdown(root)) {
411
- if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
412
- continue;
413
- const address = addressFor(identity, scope, path, home.who);
414
- const fullPath = join(root, path);
415
- const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
416
- const { meta, body } = parseNote(raw);
417
- meta.scope = scope;
418
- if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
419
- continue;
420
- homeRows.push({ address, scope, path, meta, body });
421
- }
402
+ paths = await walkMarkdown(root);
422
403
  }
423
404
  catch (error) {
424
405
  if (!status || !isFilesystemError(error))
@@ -426,8 +407,28 @@ export function createNotesStore(input) {
426
407
  status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
427
408
  continue;
428
409
  }
429
- for (const row of homeRows)
430
- yield row;
410
+ for (const path of paths) {
411
+ if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
412
+ continue;
413
+ const address = addressFor(identity, scope, path, home.who);
414
+ const fullPath = join(root, path);
415
+ let raw;
416
+ try {
417
+ raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
418
+ }
419
+ catch (error) {
420
+ // One unreadable note is named on its own; its home's readable notes still list.
421
+ if (!status || !isFilesystemError(error))
422
+ throw error;
423
+ status.homesUnavailable.push(address);
424
+ continue;
425
+ }
426
+ const { meta, body } = parseNote(raw);
427
+ meta.scope = scope;
428
+ if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
429
+ continue;
430
+ yield { address, scope, path, meta, body };
431
+ }
431
432
  }
432
433
  }
433
434
  async function list(options = {}) {
@@ -5,10 +5,6 @@ import { BOOT_TYPE } from "./entries.js";
5
5
  import { renderBootBlock } from "../boot/render.js";
6
6
  import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
7
7
  import { repairResetTail } from "./reset/artifacts.js";
8
- /** Render the boot block from one pre-await identity and acquired notes snapshot. */
9
- function bootContent(agentName, modelName, firstWindowId, currentId, previousId, notes) {
10
- return renderBootBlock({ agentName, modelName, firstWindowId, currentWindowId: currentId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES });
11
- }
12
8
  /**
13
9
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
14
10
  * fields are captured synchronously before the first filesystem await.
@@ -20,7 +16,7 @@ export async function buildBootMessage(ctx, windowId, previousId, notifyIncomple
20
16
  notifyIncompleteNotes?.(ctx, windowId, notes);
21
17
  return {
22
18
  customType: BOOT_TYPE,
23
- content: bootContent(identity.agent, identity.model, rootWindowId(identity.sessionId), windowId, previousId, notes),
19
+ content: renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId: rootWindowId(identity.sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
24
20
  display: false,
25
21
  details: { windowId },
26
22
  };
@@ -1,10 +1,10 @@
1
1
  import { type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
2
- /** Remaining tokens in the provider's active window, or null without a usable estimate. */
3
- export declare function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">): number | null;
4
- export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager, onCloseOut?: (windowId: string) => void): {
2
+ export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager): {
5
3
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
6
4
  hardReserveDue: (ctx: ExtensionContext) => boolean;
7
5
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
6
+ /** The reset owner wires its close-out here once the lifecycle reducer exists. */
7
+ setCloseOut: (handler: (windowId: string) => void) => void;
8
8
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
9
9
  statusFor: (ctx: ExtensionContext) => {
10
10
  remaining: number | null;
@@ -3,20 +3,23 @@ import { remainingBudget } from "../budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
6
- import { WARNING_CONTENT } from "./reset/text.js";
6
+ import { WARNING_CONTENT } from "../budget/text.js";
7
7
  import { readThresholdSettings } from "./thresholds.js";
8
8
  import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
10
10
  import { arrangeAnchoredReminders } from "./anchored.js";
11
11
  import { output } from "../tools/output.js";
12
12
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
13
- export function remainingTokens(ctx) {
13
+ function remainingTokens(ctx) {
14
14
  const usage = windowUsage(ctx);
15
15
  return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
16
16
  }
17
- export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () => { }) {
17
+ export function registerBudget(pi, isEnabled, settingsManager) {
18
18
  let cachedPolicy;
19
19
  const notifiedWarnings = new Set();
20
+ // The reset owner is wired after both sides exist, so no handler can observe a
21
+ // half-constructed pair (a close-out request cannot arrive before registration ends).
22
+ let onCloseOut = () => { };
20
23
  const resolvePolicy = (ctx) => {
21
24
  if (!settingsManager && cachedPolicy)
22
25
  return { ...cachedPolicy, warnings: [] };
@@ -31,19 +34,14 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
31
34
  cachedPolicy = { thresholds: resolution.thresholds, automatic: resolution.automatic };
32
35
  return resolution;
33
36
  };
34
- const thresholdsFor = (ctx) => {
35
- return resolvePolicy(ctx).thresholds;
36
- };
37
- const automaticResetEnabled = (ctx) => {
38
- return resolvePolicy(ctx).automatic;
39
- };
37
+ const thresholdsFor = (ctx) => resolvePolicy(ctx).thresholds;
38
+ const automaticResetEnabled = (ctx) => resolvePolicy(ctx).automatic;
40
39
  const hardReserveDue = (ctx) => {
41
40
  if (!automaticResetEnabled(ctx))
42
41
  return false;
43
42
  const usage = windowUsage(ctx);
44
43
  return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
45
44
  };
46
- const invalidateThresholds = () => { cachedPolicy = undefined; };
47
45
  let pendingGuidance;
48
46
  let pendingWarning;
49
47
  let pendingNotices = new Map();
@@ -81,7 +79,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
81
79
  const resetForTransition = () => {
82
80
  clearStaged();
83
81
  pendingNotices.clear();
84
- invalidateThresholds();
82
+ cachedPolicy = undefined;
85
83
  notifiedWarnings.clear();
86
84
  };
87
85
  const consumeTurnEnd = (ctx, anchorEntryId) => {
@@ -176,6 +174,8 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
176
174
  automaticResetEnabled,
177
175
  hardReserveDue,
178
176
  consumeTurnEnd,
177
+ /** The reset owner wires its close-out here once the lifecycle reducer exists. */
178
+ setCloseOut: (handler) => { onCloseOut = handler; },
179
179
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
180
180
  statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
181
181
  clear: () => { clearStaged(); pendingNotices.clear(); },
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { finishDream } from "../../dream/report.js";
3
- import { loadPlaybook } from "../../dream/playbook.js";
4
- import { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
3
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
5
4
  import { dirname, join, resolve } from "node:path";
6
5
  import { fileURLToPath } from "node:url";
7
6
  import { acquireLock, failLock, lastRunPath, releaseLock } from "../../dream/lock.js";
@@ -19,6 +18,23 @@ function args(argv) { const out = {}; for (let i = 0; i < argv.length; i++) {
19
18
  else if (a.startsWith("--"))
20
19
  out[a.slice(2)] = argv[++i] ?? "";
21
20
  } return out; }
21
+ /** A positive whole-number flag, or undefined when the value is not one. */
22
+ function wholeNumberArg(raw) {
23
+ if (raw === undefined)
24
+ return undefined;
25
+ if (typeof raw !== "string" || raw.trim() === "")
26
+ return undefined;
27
+ const value = Number(raw);
28
+ return Number.isInteger(value) && value > 0 ? value : undefined;
29
+ }
30
+ /** A directory flag that must carry a real path, not a missing or flag-looking value. */
31
+ function directoryArg(raw) {
32
+ if (raw === undefined)
33
+ return undefined;
34
+ if (typeof raw !== "string" || raw.trim() === "" || raw.startsWith("--"))
35
+ return undefined;
36
+ return raw;
37
+ }
22
38
  function packageRoot() {
23
39
  let dir = dirname(fileURLToPath(import.meta.url));
24
40
  while (true) {
@@ -37,9 +53,14 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
37
53
  console.log("dream doctor [--notes-home <dir>] — read-only diagnostics; no model or repairs");
38
54
  return 0;
39
55
  }
40
- const home = resolve(String(options["notes-home"] ?? notesRoot()));
41
- const issues = doctor(home);
42
- console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${home})`);
56
+ const home = directoryArg(options["notes-home"]);
57
+ if (options["notes-home"] !== undefined && home === undefined) {
58
+ console.error("dream: --notes-home needs a directory path");
59
+ return 1;
60
+ }
61
+ const root = resolve(home ?? notesRoot());
62
+ const issues = doctor(root);
63
+ console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${root})`);
43
64
  return issues.length ? 1 : 0;
44
65
  }
45
66
  const a = args(argv);
@@ -47,19 +68,30 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
47
68
  console.log("dream doctor [--notes-home <dir>] — read-only diagnostics\ndream --notes-home <dir> [--min-hours 24] [--min-sessions 3] [--force] [--dreamer <model pattern>] [--playbook <path>]\nDreamer model: --dreamer wins, else notesoup.dreamer from settings, else the automatic model. Default playbook: <installed package root>/playbook.md; --playbook overrides it.");
48
69
  return 0;
49
70
  }
50
- const home = resolve(String(a["notes-home"] ?? notesRoot()));
71
+ // Validate every value flag before anything is created or gated on: a typo must refuse
72
+ // loudly instead of reading as "the last dream is too recent" and exiting successfully.
73
+ const homeArg = directoryArg(a["notes-home"]);
74
+ const minHours = wholeNumberArg(a["min-hours"]);
75
+ const minSessions = wholeNumberArg(a["min-sessions"]);
76
+ const badArg = a["notes-home"] !== undefined && homeArg === undefined ? "--notes-home needs a directory path"
77
+ : a["min-hours"] !== undefined && minHours === undefined ? "--min-hours needs a positive whole number"
78
+ : a["min-sessions"] !== undefined && minSessions === undefined ? "--min-sessions needs a positive whole number"
79
+ : undefined;
80
+ if (badArg) {
81
+ console.error(`dream: ${badArg}`);
82
+ return 1;
83
+ }
84
+ const home = resolve(homeArg ?? notesRoot());
51
85
  process.env.PI_NOTES_HOME = home;
52
86
  mkdirSync(home, { recursive: true });
53
87
  const lockPath = join(home, ".dream.lock");
54
88
  const stampPath = lastRunPath(lockPath);
55
- const minHours = Number(a["min-hours"] ?? 24);
56
- const minSessions = Number(a["min-sessions"] ?? 3);
57
- const time = timeGate(stampPath, minHours);
89
+ const time = timeGate(stampPath, minHours ?? 24);
58
90
  console.log(time.reason);
59
91
  if (!a.force && !time.ok)
60
92
  return 0;
61
93
  const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
62
- const material = materialGate(home, since, minSessions);
94
+ const material = materialGate(home, since, minSessions ?? 3);
63
95
  console.log(material.reason);
64
96
  if (!a.force && !material.ok)
65
97
  return 0;
@@ -99,7 +131,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
99
131
  const playbookPath = String(a.playbook ?? defaultBook);
100
132
  let result;
101
133
  try {
102
- const playbook = loadPlaybook(playbookPath);
134
+ const playbook = readFileSync(playbookPath, "utf8");
103
135
  result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
104
136
  }
105
137
  catch (e) {
@@ -1,4 +1,4 @@
1
- import type { ImageContent, Message, TextContent, TranscriptContext, Usage } from "@earendil-works/pi-ai";
1
+ import type { Message, TranscriptContext } from "@earendil-works/pi-ai";
2
2
  export interface ContextUsageEstimate {
3
3
  /** Estimated total context tokens. */
4
4
  tokens: number;
@@ -9,8 +9,4 @@ export interface ContextUsageEstimate {
9
9
  /** Index of the applicable message that provided usage, or null when none exists. */
10
10
  lastUsageIndex: number | null;
11
11
  }
12
- export declare function calculateContextTokens(usage: Usage): number;
13
- export declare function estimateTextTokens(text: string): number;
14
- export declare function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number;
15
- export declare function estimateMessageTokens(message: Message): number;
16
12
  export declare function estimateContextTokens(context: TranscriptContext | readonly Message[]): ContextUsageEstimate;
@@ -7,7 +7,7 @@
7
7
  import { getSystemMessageText } from "@earendil-works/pi-ai";
8
8
  const CHARS_PER_TOKEN = 3.5;
9
9
  const ESTIMATED_IMAGE_CHARS = 4800;
10
- export function calculateContextTokens(usage) {
10
+ function calculateContextTokens(usage) {
11
11
  return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
12
12
  }
13
13
  function safeJsonStringify(value) {
@@ -26,13 +26,13 @@ function estimateTextAndImageContentChars(content) {
26
26
  chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
27
27
  return chars;
28
28
  }
29
- export function estimateTextTokens(text) {
29
+ function estimateTextTokens(text) {
30
30
  return Math.ceil(text.length / CHARS_PER_TOKEN);
31
31
  }
32
- export function estimateTextAndImageContentTokens(content) {
32
+ function estimateTextAndImageContentTokens(content) {
33
33
  return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
34
34
  }
35
- export function estimateMessageTokens(message) {
35
+ function estimateMessageTokens(message) {
36
36
  let chars = 0;
37
37
  if (message.role === "system") {
38
38
  return (estimateTextTokens(getSystemMessageText(message)) +
@@ -14,14 +14,11 @@ function mapRole(role) {
14
14
  function isToolCall(part) {
15
15
  return typeof part === "object" && part !== null && part.type === "toolCall";
16
16
  }
17
- function mappedMessage(message) {
18
- return mapRole(message.role) !== undefined;
19
- }
20
17
  /** Seq allocation depends on entry kind and role, never on visible content. */
21
18
  function sequenceCount(entry) {
22
19
  if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message")
23
20
  return 1;
24
- if (entry.type !== "message" || !mappedMessage(entry.message))
21
+ if (entry.type !== "message" || mapRole(entry.message.role) === undefined)
25
22
  return 0;
26
23
  if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content))
27
24
  return 1;
@@ -3,7 +3,7 @@ import type { NotesIdentity } from "../../notes/identity.js";
3
3
  /** Pi's default notes root; environment access stays on the host side of the library boundary. */
4
4
  export declare function notesRoot(): string;
5
5
  /** Translate the current Pi runtime into a fresh, explicit identity snapshot. */
6
- export declare function agentSlug(_ctx: ExtensionContext): string;
6
+ export declare function agentSlug(): string;
7
7
  /** Pi's active model identity is resolved live so a mid-session switch retargets @model. */
8
8
  export declare function modelSlug(ctx: ExtensionContext): string;
9
9
  /** Translate the current Pi runtime into one explicit notes identity snapshot. */
@@ -7,7 +7,7 @@ export function notesRoot() {
7
7
  return override && override.length > 0 ? resolve(override) : join(homedir(), ".agents", "notes");
8
8
  }
9
9
  /** Translate the current Pi runtime into a fresh, explicit identity snapshot. */
10
- export function agentSlug(_ctx) {
10
+ export function agentSlug() {
11
11
  return slugify(process.env.PI_NOTES_AGENT ?? "anonymous");
12
12
  }
13
13
  /** Pi's active model identity is resolved live so a mid-session switch retargets @model. */
@@ -21,7 +21,7 @@ export function notesIdentityFromPi(ctx, home = notesRoot()) {
21
21
  home,
22
22
  sessionId: ctx.sessionManager.getSessionId(),
23
23
  projectKey: projectKey(ctx.cwd),
24
- agent: agentSlug(ctx),
24
+ agent: agentSlug(),
25
25
  model: modelSlug(ctx),
26
26
  };
27
27
  }
@@ -7,8 +7,6 @@ export type ResetTailState = {
7
7
  };
8
8
  /** Match the hidden continuation entry that carries the one reset message. */
9
9
  export declare function isWindowContinuationEntry(entry: SessionEntry): boolean;
10
- /** The single continuation sender: the only reset prose persisted for a window. */
11
- export declare function sendContinuation(pi: ExtensionAPI): void;
12
10
  /**
13
11
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
14
12
  * continuation, then an optional command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
@@ -1,14 +1,14 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { BOOT_TYPE, CONTINUATION_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
3
- import { CONTINUATION } from "./text.js";
4
- import { currentWindowId, isWindowBootEntry, isWindowMarker, previousWindowId } from "../window.js";
3
+ import { CONTINUATION } from "../../budget/text.js";
4
+ import { currentWindowId, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, previousWindowId } from "../window.js";
5
5
  import { buildBootMessage, sendBoot } from "../boot.js";
6
6
  /** Match the hidden continuation entry that carries the one reset message. */
7
7
  export function isWindowContinuationEntry(entry) {
8
8
  return entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE;
9
9
  }
10
10
  /** The single continuation sender: the only reset prose persisted for a window. */
11
- export function sendContinuation(pi) {
11
+ function sendContinuation(pi) {
12
12
  pi.sendMessage({ customType: CONTINUATION_TYPE, content: CONTINUATION, display: false }, { triggerTurn: false });
13
13
  }
14
14
  /**
@@ -60,7 +60,7 @@ export function inspectResetTail(ctx, markerId, windowId) {
60
60
  continuation = true;
61
61
  continue;
62
62
  }
63
- if (isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary") {
63
+ if (isForeignResetTailEntry(entry)) {
64
64
  return undefined;
65
65
  }
66
66
  }
@@ -1,4 +1,4 @@
1
- import { isCheckpointBackedReset, isWindowBootEntry, isWindowMarker } from "../window.js";
1
+ import { isCheckpointBackedReset, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker } from "../window.js";
2
2
  import { isWindowContinuationEntry } from "./artifacts.js";
3
3
  /**
4
4
  * Confirm a native boundary on this branch, independent of whether its suffix is still
@@ -21,7 +21,7 @@ export function resetBoundaryCommitted(ctx, markerId, windowId) {
21
21
  }
22
22
  if (isWindowContinuationEntry(entry))
23
23
  return boot && entry.type === "custom_message" && entry.display === false;
24
- if (isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary")
24
+ if (isForeignResetTailEntry(entry))
25
25
  return false;
26
26
  }
27
27
  return false;
@@ -8,15 +8,15 @@ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, i
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
9
  import { buildResetDrafts } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
- import { WARNING_CONTENT } from "./reset/text.js";
11
+ import { WARNING_CONTENT } from "../budget/text.js";
12
12
  import { ensureBoot } from "./boot.js";
13
13
  import { errorMessage } from "../error-message.js";
14
14
  function readPackageVersion() {
15
15
  for (const up of ["../../package.json", "../../../package.json"]) {
16
16
  try {
17
- const parsed = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8"));
18
- if (parsed.version)
19
- return parsed.version;
17
+ const { version } = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8"));
18
+ if (version)
19
+ return version;
20
20
  }
21
21
  catch { /* try the next candidate */ }
22
22
  }
@@ -61,7 +61,7 @@ export function registerContext(pi, settingsManager) {
61
61
  const homes = snapshot.unavailable.map((home) => home.label).join(", ");
62
62
  ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
63
63
  };
64
- const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
64
+ const budget = registerBudget(pi, () => enabled, settingsManager);
65
65
  pi.on("session_start", async (_event, ctx) => {
66
66
  const generation = ++lifecycleGeneration;
67
67
  if (!enabled)
@@ -128,6 +128,8 @@ export function registerContext(pi, settingsManager) {
128
128
  enabled = false;
129
129
  lifecycleGeneration++;
130
130
  pendingResetNotices.clear();
131
+ incompleteNotesNotified.clear();
132
+ missingBootNotice = undefined;
131
133
  budget.clear();
132
134
  resets.clear();
133
135
  }
@@ -200,4 +202,5 @@ export function registerContext(pi, settingsManager) {
200
202
  },
201
203
  budget,
202
204
  });
205
+ budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
203
206
  }