notesoup 0.42.0 → 0.44.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 (126) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.d.ts +2 -0
  3. package/dist/src/boot/snapshot.js +4 -5
  4. package/dist/src/boot/text.js +4 -2
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +2 -0
  9. package/dist/src/budget/text.js +2 -0
  10. package/dist/src/claude/helper.js +3 -4
  11. package/dist/src/claude/thresholds.js +45 -66
  12. package/dist/src/dream/lock.js +6 -13
  13. package/dist/src/dream/report.js +5 -15
  14. package/dist/src/history/history.js +4 -2
  15. package/dist/src/history/query.js +10 -22
  16. package/dist/src/notes/address.d.ts +2 -3
  17. package/dist/src/notes/address.js +10 -22
  18. package/dist/src/notes/errors.d.ts +2 -0
  19. package/dist/src/notes/errors.js +5 -0
  20. package/dist/src/notes/frontmatter.js +16 -2
  21. package/dist/src/notes/identity.js +2 -4
  22. package/dist/src/notes/paths.d.ts +7 -2
  23. package/dist/src/notes/paths.js +18 -60
  24. package/dist/src/notes/project-home.d.ts +25 -0
  25. package/dist/src/notes/project-home.js +231 -0
  26. package/dist/src/notes/store.d.ts +4 -2
  27. package/dist/src/notes/store.js +52 -45
  28. package/dist/src/pi/boot.js +17 -9
  29. package/dist/src/pi/budget.d.ts +3 -3
  30. package/dist/src/pi/budget.js +11 -11
  31. package/dist/src/pi/dream/cli.js +43 -11
  32. package/dist/src/pi/estimate.d.ts +1 -5
  33. package/dist/src/pi/estimate.js +4 -4
  34. package/dist/src/pi/history.js +1 -4
  35. package/dist/src/pi/notes/adapter.d.ts +1 -1
  36. package/dist/src/pi/notes/adapter.js +3 -3
  37. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  38. package/dist/src/pi/reset/artifacts.js +4 -4
  39. package/dist/src/pi/reset/committed.js +2 -2
  40. package/dist/src/pi/runtime.js +8 -5
  41. package/dist/src/pi/thresholds.js +5 -9
  42. package/dist/src/pi/tool-result.d.ts +1 -4
  43. package/dist/src/pi/tool-result.js +1 -1
  44. package/dist/src/pi/window.d.ts +5 -0
  45. package/dist/src/pi/window.js +7 -0
  46. package/dist/src/settings.d.ts +2 -0
  47. package/dist/src/settings.js +4 -3
  48. package/dist/src/tools/history.js +4 -7
  49. package/dist/src/tools/notes.d.ts +47 -21
  50. package/dist/src/tools/notes.js +20 -19
  51. package/dist/src/tools/output.d.ts +0 -3
  52. package/dist/src/tools/output.js +1 -9
  53. package/dist/src/tools/result.d.ts +1 -0
  54. package/dist/src/tools/result.js +14 -20
  55. package/dist/src/tools/schema.d.ts +0 -1
  56. package/dist/src/tools/schema.js +0 -1
  57. package/dist/test/agent-loop.test.js +1 -2
  58. package/dist/test/boot.integration.test.js +1 -1
  59. package/dist/test/claude-mod.test.js +253 -10
  60. package/dist/test/claude-validation.test.d.ts +1 -0
  61. package/dist/test/claude-validation.test.js +73 -0
  62. package/dist/test/dream-skill.test.js +2 -4
  63. package/dist/test/dream.test.js +14 -0
  64. package/dist/test/helpers/extension.js +1 -1
  65. package/dist/test/history.integration.test.js +2 -1
  66. package/dist/test/host-neutral.test.js +15 -0
  67. package/dist/test/notes-library.test.js +30 -1
  68. package/dist/test/notes.integration.test.js +7 -7
  69. package/dist/test/notes.test.js +36 -14
  70. package/dist/test/project-home.test.d.ts +1 -0
  71. package/dist/test/project-home.test.js +134 -0
  72. package/dist/test/reset-lifecycle.test.js +1 -1
  73. package/docs/claude-code-mod.md +5 -3
  74. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  75. package/mods/notesoup/dist/claude/helper.js +359 -218
  76. package/mods/notesoup/hooks/register.ts +158 -67
  77. package/mods/notesoup/playbook.md +1 -1
  78. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  79. package/mods/notesoup/skills/memory/SKILL.md +62 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +2 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +5 -5
  86. package/src/boot/text.ts +4 -2
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +3 -0
  90. package/src/claude/helper.ts +4 -4
  91. package/src/claude/thresholds.ts +45 -62
  92. package/src/dream/lock.ts +3 -9
  93. package/src/dream/report.ts +5 -10
  94. package/src/history/history.ts +4 -2
  95. package/src/history/query.ts +10 -23
  96. package/src/notes/address.ts +9 -21
  97. package/src/notes/errors.ts +6 -0
  98. package/src/notes/frontmatter.ts +12 -2
  99. package/src/notes/identity.ts +1 -3
  100. package/src/notes/paths.ts +14 -52
  101. package/src/notes/project-home.ts +197 -0
  102. package/src/notes/store.ts +46 -45
  103. package/src/pi/boot.ts +15 -17
  104. package/src/pi/budget.ts +10 -11
  105. package/src/pi/dream/cli.ts +35 -10
  106. package/src/pi/estimate.ts +4 -4
  107. package/src/pi/history.ts +1 -5
  108. package/src/pi/notes/adapter.ts +3 -3
  109. package/src/pi/reset/artifacts.ts +4 -4
  110. package/src/pi/reset/committed.ts +2 -2
  111. package/src/pi/runtime.ts +7 -6
  112. package/src/pi/thresholds.ts +5 -11
  113. package/src/pi/tool-result.ts +1 -1
  114. package/src/pi/window.ts +8 -0
  115. package/src/settings.ts +4 -3
  116. package/src/tools/history.ts +4 -8
  117. package/src/tools/notes.ts +22 -25
  118. package/src/tools/output.ts +1 -12
  119. package/src/tools/result.ts +14 -19
  120. package/src/tools/schema.ts +0 -1
  121. package/dist/src/dream/playbook.d.ts +0 -1
  122. package/dist/src/dream/playbook.js +0 -2
  123. package/dist/src/pi/reset/text.d.ts +0 -4
  124. package/dist/src/pi/reset/text.js +0 -7
  125. package/src/dream/playbook.ts +0 -3
  126. package/src/pi/reset/text.ts +0 -9
@@ -9,6 +9,7 @@ import { NoteError } from "./errors.js";
9
9
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
10
10
  import { isOrigin, isScope, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
11
11
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, SLUG_PATTERN } from "./paths.js";
12
+ import { projectHomes, projectReceipt } from "./project-home.js";
12
13
  // Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
13
14
  let lastWriteStamp = 0;
14
15
  function writeStamp() {
@@ -16,12 +17,12 @@ function writeStamp() {
16
17
  lastWriteStamp = now > lastWriteStamp ? now : lastWriteStamp + 1;
17
18
  return lastWriteStamp;
18
19
  }
19
- /** Public identity resolved for an operation, never a filesystem path. */
20
+ /** Public note identity; named projects also carry their display root and sibling hints. */
20
21
  export function noteIdentity(identity, address) {
21
22
  const resolved = assertAddress(address);
22
23
  return {
23
24
  address: addressFor(identity, resolved.scope, noteFileName(resolved.path), resolved.who),
24
- ...(resolved.scope === "project" ? { project_key: identity.projectKey } : {}),
25
+ ...(resolved.scope !== "project" ? {} : resolved.who === undefined ? { project_key: identity.projectKey } : projectReceipt(identity.home, resolved.who)),
25
26
  };
26
27
  }
27
28
  const SCOPE_ORDER = ["session", "project", "human", "agent", "model"];
@@ -75,10 +76,6 @@ async function walkMarkdown(dir, base = dir) {
75
76
  }
76
77
  return paths;
77
78
  }
78
- function matcherFor(pattern) {
79
- const normalized = assertGlobPattern(pattern);
80
- return normalized === undefined ? undefined : globToRegExp(normalized);
81
- }
82
79
  async function homesForPattern(pattern, identity) {
83
80
  if (!pattern || !pattern.startsWith("@"))
84
81
  return undefined;
@@ -91,12 +88,13 @@ async function homesForPattern(pattern, identity) {
91
88
  return [{ scope: "agent" }];
92
89
  if (head === "model")
93
90
  return [{ scope: "model" }];
94
- if (head === "agents" || head === "models") {
95
- const scope = head === "agents" ? "agent" : "model";
91
+ if (head === "projects" || head === "agents" || head === "models") {
92
+ const scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
96
93
  const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
97
94
  if (name.length > 0 && !/[*?]/.test(name))
98
95
  return [{ scope, who: assertWho(name) }];
99
- return (await namespaceSlugs(head, identity.home)).map((who) => ({ scope, who }));
96
+ const names = head === "projects" ? projectHomes(identity.home).map(home => home.name) : await namespaceSlugs(head, identity.home);
97
+ return names.map((who) => ({ scope, who }));
100
98
  }
101
99
  return [];
102
100
  }
@@ -110,11 +108,6 @@ function normalizePattern(pattern, identity) {
110
108
  return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
111
109
  return pattern;
112
110
  }
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
111
  function assertOrigin(value) {
119
112
  if (!isOrigin(value))
120
113
  throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
@@ -128,7 +121,9 @@ function assertWho(value) {
128
121
  }
129
122
  async function homesFor(identity, opts) {
130
123
  if (opts.scope !== undefined) {
131
- const scope = assertScope(opts.scope);
124
+ if (!isScope(opts.scope))
125
+ throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
126
+ const scope = opts.scope;
132
127
  if (opts.who !== undefined) {
133
128
  const who = assertWho(opts.who);
134
129
  if (scope !== "agent" && scope !== "model")
@@ -210,23 +205,18 @@ function assertSerializedSize(content) {
210
205
  function frontmatterOf(meta) {
211
206
  return serializeNote(meta, "").slice(0, -2);
212
207
  }
213
- /** Named agent/model homes are read-only to whoever is not running there. */
208
+ /** Explicit project homes are always read-only; agent/model homes allow their owner. */
214
209
  function assertWritableHome(scope, who, identity) {
215
210
  if (who === undefined)
216
211
  return;
212
+ if (scope === "project")
213
+ throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
217
214
  const current = scope === "agent" ? identity.agent : identity.model;
218
215
  if (who === current)
219
216
  return;
220
217
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
221
218
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
222
219
  }
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
220
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
231
221
  export function createNotesStore(input) {
232
222
  const identity = snapshotNotesIdentity(input);
@@ -236,7 +226,9 @@ export function createNotesStore(input) {
236
226
  assertWritablePath(destination.path);
237
227
  const scope = destination.scope;
238
228
  assertWritableHome(scope, destination.who, identity);
239
- const origin = assertOrigin(stableOptions.origin ?? "self");
229
+ // Absent means "keep whatever the note already says": replacing a note must not silently
230
+ // re-attribute a user-written note to the agent that happened to rewrite it.
231
+ const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
240
232
  const path = physicalPath(scope, destination.path, identity, destination.who);
241
233
  return withPathQueue(path, async () => {
242
234
  const now = writeStamp();
@@ -246,7 +238,7 @@ export function createNotesStore(input) {
246
238
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
247
239
  const meta = existing ?? {
248
240
  scope,
249
- origin,
241
+ origin: origin ?? "self",
250
242
  createdAt: now,
251
243
  updatedAt: now,
252
244
  lastAccessed: now,
@@ -254,7 +246,8 @@ export function createNotesStore(input) {
254
246
  ...(scope === "session" ? { project: identity.projectKey } : {}),
255
247
  };
256
248
  meta.scope = scope;
257
- meta.origin = origin;
249
+ if (origin !== undefined)
250
+ meta.origin = origin;
258
251
  delete meta.crumpledAt;
259
252
  meta.updatedAt = now;
260
253
  const serialized = serializeNote(meta, cleanBody);
@@ -273,7 +266,10 @@ export function createNotesStore(input) {
273
266
  return undefined;
274
267
  const now = Date.now();
275
268
  const parsed = parseNote(raw, now);
276
- const meta = accessedMeta(parsed.meta, scope, now);
269
+ if (scope === "project" && destination.who !== undefined)
270
+ return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
271
+ // A read records its own access, exactly as a write records an edit.
272
+ const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
277
273
  await atomicWrite(path, serializeNote(meta, parsed.body));
278
274
  return { meta, body: parsed.body, resolvedScope: scope };
279
275
  });
@@ -391,34 +387,25 @@ export function createNotesStore(input) {
391
387
  }));
392
388
  }
393
389
  async function* scan(options, status) {
394
- const matcher = matcherFor(normalizePattern(options.glob, identity));
390
+ const pattern = normalizePattern(options.glob, identity);
391
+ const normalized = assertGlobPattern(pattern);
392
+ const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
395
393
  let homes;
396
394
  try {
397
395
  homes = await homesFor(identity, options);
398
396
  }
399
397
  catch (error) {
400
- if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.glob ?? ""))
398
+ if (!status || !isFilesystemError(error) || !/^@(projects|agents|models)\//.test(options.glob ?? ""))
401
399
  throw error;
402
- status.homesUnavailable.push(options.glob.startsWith("@agents/") ? "@agents" : "@models");
400
+ status.homesUnavailable.push(options.glob.split("/")[0]);
403
401
  return;
404
402
  }
405
403
  for (const home of homes) {
406
404
  const scope = home.scope;
407
405
  const root = scopeDir(scope, identity, home.who);
408
- const homeRows = [];
406
+ let paths;
409
407
  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
- }
408
+ paths = await walkMarkdown(root);
422
409
  }
423
410
  catch (error) {
424
411
  if (!status || !isFilesystemError(error))
@@ -426,8 +413,28 @@ export function createNotesStore(input) {
426
413
  status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
427
414
  continue;
428
415
  }
429
- for (const row of homeRows)
430
- yield row;
416
+ for (const path of paths) {
417
+ if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
418
+ continue;
419
+ const address = addressFor(identity, scope, path, home.who);
420
+ const fullPath = join(root, path);
421
+ let raw;
422
+ try {
423
+ raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
424
+ }
425
+ catch (error) {
426
+ // One unreadable note is named on its own; its home's readable notes still list.
427
+ if (!status || !isFilesystemError(error))
428
+ throw error;
429
+ status.homesUnavailable.push(address);
430
+ continue;
431
+ }
432
+ const { meta, body } = parseNote(raw);
433
+ meta.scope = scope;
434
+ if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
435
+ continue;
436
+ yield { address, scope, path, meta, body };
437
+ }
431
438
  }
432
439
  }
433
440
  async function list(options = {}) {
@@ -1,26 +1,34 @@
1
1
  import { PI_TOOL_NAMES } from "./tool-names.js";
2
- import { notesIdentityFromPi } from "./notes/adapter.js";
3
- import { loadNotesSnapshot } from "../boot/snapshot.js";
2
+ import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
3
+ import { loadNotesSnapshot, unavailableNotesSnapshot } from "../boot/snapshot.js";
4
+ import { isFilesystemError } from "../notes/fs-error.js";
4
5
  import { BOOT_TYPE } from "./entries.js";
5
6
  import { renderBootBlock } from "../boot/render.js";
6
7
  import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
7
8
  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
9
  /**
13
10
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
14
11
  * fields are captured synchronously before the first filesystem await.
15
12
  */
16
13
  export async function buildBootMessage(ctx, windowId, previousId, notifyIncompleteNotes, isCurrent = () => true) {
17
- const identity = notesIdentityFromPi(ctx);
18
- const notes = await loadNotesSnapshot(identity, Date.now());
14
+ const agentName = agentSlug();
15
+ const modelName = modelSlug(ctx);
16
+ const sessionId = ctx.sessionManager.getSessionId();
17
+ const openedAt = Date.now();
18
+ let notes;
19
+ try {
20
+ notes = await loadNotesSnapshot(notesIdentityFromPi(ctx), openedAt);
21
+ }
22
+ catch (error) {
23
+ if (!isFilesystemError(error))
24
+ throw error;
25
+ notes = unavailableNotesSnapshot(openedAt);
26
+ }
19
27
  if (isCurrent())
20
28
  notifyIncompleteNotes?.(ctx, windowId, notes);
21
29
  return {
22
30
  customType: BOOT_TYPE,
23
- content: bootContent(identity.agent, identity.model, rootWindowId(identity.sessionId), windowId, previousId, notes),
31
+ content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
24
32
  display: false,
25
33
  details: { windowId },
26
34
  };
@@ -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. */
@@ -20,8 +20,8 @@ export function notesIdentityFromPi(ctx, home = notesRoot()) {
20
20
  return {
21
21
  home,
22
22
  sessionId: ctx.sessionManager.getSessionId(),
23
- projectKey: projectKey(ctx.cwd),
24
- agent: agentSlug(ctx),
23
+ projectKey: projectKey(ctx.cwd, home),
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
  }