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,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
  import type { NotesIdentity } from "./identity.js";
6
7
 
7
8
  export type Scope = "session" | "project" | "human" | "agent" | "model";
@@ -15,10 +16,29 @@ export function slugify(value: string): string {
15
16
  return slug.length > 0 ? slug : "root";
16
17
  }
17
18
 
18
- /** `<basename(absGitRoot)-sha1(absGitRoot)[:8]>`, or the same formula over cwd with no git root. */
19
+ /**
20
+ * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
21
+ * segment. Both the address decoder and the physical-path builder enforce it here, so a
22
+ * caller that reaches a path without going through an address still cannot escape a home.
23
+ */
24
+ export function assertVirtualPath(value: unknown): string {
25
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
26
+ 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.`);
27
+ const parts = value.split("/");
28
+ 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.`);
29
+ return value;
30
+ }
31
+
32
+ /**
33
+ * `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
34
+ * with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
35
+ * so canonicalizing here is what keeps one repository — and its worktrees — on one home.
36
+ */
19
37
  export function projectKey(cwd: string): string {
20
38
  const absolute = resolve(cwd);
21
- const root = gitRoot(absolute) ?? absolute;
39
+ const spelled = gitRoot(absolute) ?? absolute;
40
+ let root = spelled;
41
+ try { root = realpathSync(spelled); } catch { /* An unresolvable path keeps its spelling. */ }
22
42
  const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
23
43
  return `${basename(root)}-${digest}`;
24
44
  }
@@ -103,7 +123,5 @@ export function noteFileName(vpath: string): string {
103
123
 
104
124
  /** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
105
125
  export function physicalPath(scope: Scope, vpath: string, identity: NotesIdentity, who?: string): string {
106
- if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/")) throw new TypeError("path must be a safe virtual relative path");
107
- if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === "..")) throw new TypeError("path contains an unsupported component");
108
126
  return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
109
127
  }
@@ -40,6 +40,7 @@ export type NoteChange =
40
40
  | { kind: "body" | "metadata"; before: string; after: string };
41
41
  export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
42
42
  export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
43
+ /** A home, or one unreadable note inside it, that a status-reporting query could not read. */
43
44
  export type NoteQueryStatus = { homesUnavailable: string[] };
44
45
  export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
45
46
 
@@ -114,11 +115,6 @@ async function walkMarkdown(dir: string, base = dir): Promise<string[]> {
114
115
  return paths;
115
116
  }
116
117
 
117
- function matcherFor(pattern: unknown): RegExp | undefined {
118
- const normalized = assertGlobPattern(pattern);
119
- return normalized === undefined ? undefined : globToRegExp(normalized);
120
- }
121
-
122
118
  /** Which homes one call iterates; reserved heads narrow traversal before any file is read. */
123
119
  type HomeRef = { scope: Scope; who?: string };
124
120
 
@@ -146,11 +142,6 @@ function normalizePattern(pattern: string | undefined, identity: NotesIdentity):
146
142
  return pattern;
147
143
  }
148
144
 
149
- function assertScope(value: unknown): Scope {
150
- if (!isScope(value)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(value)})`);
151
- return value;
152
- }
153
-
154
145
  function assertOrigin(value: unknown): Origin {
155
146
  if (!isOrigin(value)) throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
156
147
  return value;
@@ -165,7 +156,8 @@ function assertWho(value: unknown): string {
165
156
 
166
157
  async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<HomeRef[]> {
167
158
  if (opts.scope !== undefined) {
168
- const scope = assertScope(opts.scope);
159
+ if (!isScope(opts.scope)) throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
160
+ const scope = opts.scope;
169
161
  if (opts.who !== undefined) {
170
162
  const who = assertWho(opts.who);
171
163
  if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
@@ -255,14 +247,6 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
255
247
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
256
248
  }
257
249
 
258
- /** Normalize parsed metadata exactly as a read does, including its access mutation. */
259
- function accessedMeta(meta: NoteMeta, scope: Scope, now: number): NoteMeta {
260
- const next = { ...meta, scope };
261
- next.lastAccessed = now;
262
- next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
263
- return next;
264
- }
265
-
266
250
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
267
251
  export function createNotesStore(input: NotesIdentity): NotesStore {
268
252
  const identity = snapshotNotesIdentity(input);
@@ -273,7 +257,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
273
257
  assertWritablePath(destination.path);
274
258
  const scope = destination.scope;
275
259
  assertWritableHome(scope, destination.who, identity);
276
- const origin = assertOrigin(stableOptions.origin ?? "self");
260
+ // Absent means "keep whatever the note already says": replacing a note must not silently
261
+ // re-attribute a user-written note to the agent that happened to rewrite it.
262
+ const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
277
263
  const path = physicalPath(scope, destination.path, identity, destination.who);
278
264
  return withPathQueue(path, async () => {
279
265
  const now = writeStamp();
@@ -283,7 +269,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
283
269
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
284
270
  const meta: NoteMeta = existing ?? {
285
271
  scope,
286
- origin,
272
+ origin: origin ?? "self",
287
273
  createdAt: now,
288
274
  updatedAt: now,
289
275
  lastAccessed: now,
@@ -291,7 +277,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
291
277
  ...(scope === "session" ? { project: identity.projectKey } : {}),
292
278
  };
293
279
  meta.scope = scope;
294
- meta.origin = origin;
280
+ if (origin !== undefined) meta.origin = origin;
295
281
  delete meta.crumpledAt;
296
282
  meta.updatedAt = now;
297
283
  const serialized = serializeNote(meta, cleanBody);
@@ -310,7 +296,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
310
296
  if (raw === undefined) return undefined;
311
297
  const now = Date.now();
312
298
  const parsed = parseNote(raw, now);
313
- const meta = accessedMeta(parsed.meta, scope, now);
299
+ // A read records its own access, exactly as a write records an edit.
300
+ const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
314
301
  await atomicWrite(path, serializeNote(meta, parsed.body));
315
302
  return { meta, body: parsed.body, resolvedScope: scope };
316
303
  });
@@ -413,7 +400,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
413
400
  }
414
401
 
415
402
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
416
- const matcher = matcherFor(normalizePattern(options.glob, identity));
403
+ const pattern = normalizePattern(options.glob, identity);
404
+ const normalized = assertGlobPattern(pattern);
405
+ const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
417
406
  let homes: HomeRef[];
418
407
  try {
419
408
  homes = await homesFor(identity, options);
@@ -425,24 +414,32 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
425
414
  for (const home of homes) {
426
415
  const scope = home.scope;
427
416
  const root = scopeDir(scope, identity, home.who);
428
- const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
417
+ let paths: string[];
429
418
  try {
430
- for (const path of await walkMarkdown(root)) {
431
- if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
432
- const address = addressFor(identity, scope, path, home.who);
433
- const fullPath = join(root, path);
434
- const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
435
- const { meta, body } = parseNote(raw);
436
- meta.scope = scope;
437
- if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
438
- homeRows.push({ address, scope, path, meta, body });
439
- }
419
+ paths = await walkMarkdown(root);
440
420
  } catch (error) {
441
421
  if (!status || !isFilesystemError(error)) throw error;
442
422
  status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
443
423
  continue;
444
424
  }
445
- for (const row of homeRows) yield row;
425
+ for (const path of paths) {
426
+ if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
427
+ const address = addressFor(identity, scope, path, home.who);
428
+ const fullPath = join(root, path);
429
+ let raw: string;
430
+ try {
431
+ raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
432
+ } catch (error) {
433
+ // One unreadable note is named on its own; its home's readable notes still list.
434
+ if (!status || !isFilesystemError(error)) throw error;
435
+ status.homesUnavailable.push(address);
436
+ continue;
437
+ }
438
+ const { meta, body } = parseNote(raw);
439
+ meta.scope = scope;
440
+ if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
441
+ yield { address, scope, path, meta, body };
442
+ }
446
443
  }
447
444
  }
448
445
 
package/src/pi/boot.ts CHANGED
@@ -17,18 +17,6 @@ export type BootMessage = {
17
17
  readonly details: { windowId: string };
18
18
  };
19
19
 
20
- /** Render the boot block from one pre-await identity and acquired notes snapshot. */
21
- function bootContent(
22
- agentName: string,
23
- modelName: string,
24
- firstWindowId: string,
25
- currentId: string,
26
- previousId: string | undefined,
27
- notes: NotesSnapshot,
28
- ): string {
29
- return renderBootBlock({ agentName, modelName, firstWindowId, currentWindowId: currentId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES });
30
- }
31
-
32
20
  /**
33
21
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
34
22
  * fields are captured synchronously before the first filesystem await.
@@ -45,7 +33,7 @@ export async function buildBootMessage(
45
33
  if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
46
34
  return {
47
35
  customType: BOOT_TYPE,
48
- content: bootContent(identity.agent, identity.model, rootWindowId(identity.sessionId), windowId, previousId, notes),
36
+ content: renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId: rootWindowId(identity.sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
49
37
  display: false,
50
38
  details: { windowId },
51
39
  };
package/src/pi/budget.ts CHANGED
@@ -3,7 +3,7 @@ import { remainingBudget, type ResolvedThresholds } from "../budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } 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, type ThresholdSettingsResolution } from "./thresholds.js";
8
8
  import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
@@ -11,7 +11,7 @@ import { arrangeAnchoredReminders, type AnchorDetails } from "./anchored.js";
11
11
  import { output } from "../tools/output.js";
12
12
 
13
13
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
14
- export function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">): number | null {
14
+ function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">): number | null {
15
15
  const usage = windowUsage(ctx);
16
16
  return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
17
17
  }
@@ -20,10 +20,12 @@ export function registerBudget(
20
20
  pi: ExtensionAPI,
21
21
  isEnabled: () => boolean,
22
22
  settingsManager?: SettingsManager,
23
- onCloseOut: (windowId: string) => void = () => {},
24
23
  ) {
25
24
  let cachedPolicy: { thresholds: ResolvedThresholds; automatic: boolean } | undefined;
26
25
  const notifiedWarnings = new Set<string>();
26
+ // The reset owner is wired after both sides exist, so no handler can observe a
27
+ // half-constructed pair (a close-out request cannot arrive before registration ends).
28
+ let onCloseOut: (windowId: string) => void = () => {};
27
29
  const resolvePolicy = (ctx: ExtensionContext): ThresholdSettingsResolution => {
28
30
  if (!settingsManager && cachedPolicy) return { ...cachedPolicy, warnings: [] };
29
31
  const resolution = readThresholdSettings(ctx, settingsManager);
@@ -35,18 +37,13 @@ export function registerBudget(
35
37
  if (!settingsManager) cachedPolicy = { thresholds: resolution.thresholds, automatic: resolution.automatic };
36
38
  return resolution;
37
39
  };
38
- const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds => {
39
- return resolvePolicy(ctx).thresholds;
40
- };
41
- const automaticResetEnabled = (ctx: ExtensionContext): boolean => {
42
- return resolvePolicy(ctx).automatic;
43
- };
40
+ const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds => resolvePolicy(ctx).thresholds;
41
+ const automaticResetEnabled = (ctx: ExtensionContext): boolean => resolvePolicy(ctx).automatic;
44
42
  const hardReserveDue = (ctx: ExtensionContext): boolean => {
45
43
  if (!automaticResetEnabled(ctx)) return false;
46
44
  const usage = windowUsage(ctx);
47
45
  return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
48
46
  };
49
- const invalidateThresholds = () => { cachedPolicy = undefined; };
50
47
  let pendingGuidance: { windowId: string; content: string } | undefined;
51
48
  let pendingWarning: { windowId: string; content: string } | undefined;
52
49
  let pendingNotices = new Map<string, { sessionId: string; windowId: string }>();
@@ -82,7 +79,7 @@ export function registerBudget(
82
79
  const resetForTransition = () => {
83
80
  clearStaged();
84
81
  pendingNotices.clear();
85
- invalidateThresholds();
82
+ cachedPolicy = undefined;
86
83
  notifiedWarnings.clear();
87
84
  };
88
85
 
@@ -172,6 +169,8 @@ export function registerBudget(
172
169
  automaticResetEnabled,
173
170
  hardReserveDue,
174
171
  consumeTurnEnd,
172
+ /** The reset owner wires its close-out here once the lifecycle reducer exists. */
173
+ setCloseOut: (handler: (windowId: string) => void) => { onCloseOut = handler; },
175
174
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
176
175
  statusFor: (ctx: ExtensionContext): { remaining: number | null } => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
177
176
  clear: () => { clearStaged(); pendingNotices.clear(); },
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { finishDream } from "../../dream/report.js";
3
3
  import type { DreamerSetting } from "../../dream/settings.js";
4
- import { loadPlaybook } from "../../dream/playbook.js";
5
4
  import type { DreamResult } from "../../dream/result.js";
6
- import { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
5
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
7
6
  import { dirname, join, resolve } from "node:path";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { acquireLock, failLock, lastRunPath, releaseLock } from "../../dream/lock.js";
@@ -16,6 +15,21 @@ import { notesRoot } from "../notes/adapter.js";
16
15
  import { errorMessage } from "../../error-message.js";
17
16
 
18
17
  function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
18
+
19
+ /** A positive whole-number flag, or undefined when the value is not one. */
20
+ function wholeNumberArg(raw: string | boolean | undefined): number | undefined {
21
+ if (raw === undefined) return undefined;
22
+ if (typeof raw !== "string" || raw.trim() === "") return undefined;
23
+ const value = Number(raw);
24
+ return Number.isInteger(value) && value > 0 ? value : undefined;
25
+ }
26
+
27
+ /** A directory flag that must carry a real path, not a missing or flag-looking value. */
28
+ function directoryArg(raw: string | boolean | undefined): string | undefined {
29
+ if (raw === undefined) return undefined;
30
+ if (typeof raw !== "string" || raw.trim() === "" || raw.startsWith("--")) return undefined;
31
+ return raw;
32
+ }
19
33
  function packageRoot(): string {
20
34
  let dir = dirname(fileURLToPath(import.meta.url));
21
35
  while (true) { if (existsSync(join(dir, "package.json"))) return dir; const parent = dirname(dir); if (parent === dir) throw new Error("could not locate installed package root"); dir = parent; }
@@ -32,18 +46,29 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
32
46
  if (argv[0] === "doctor") {
33
47
  const options = args(argv.slice(1));
34
48
  if (options.help) { console.log("dream doctor [--notes-home <dir>] — read-only diagnostics; no model or repairs"); return 0; }
35
- const home = resolve(String(options["notes-home"] ?? notesRoot()));
36
- const issues = doctor(home);
37
- console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${home})`);
49
+ const home = directoryArg(options["notes-home"]);
50
+ if (options["notes-home"] !== undefined && home === undefined) { console.error("dream: --notes-home needs a directory path"); return 1; }
51
+ const root = resolve(home ?? notesRoot());
52
+ const issues = doctor(root);
53
+ console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${root})`);
38
54
  return issues.length ? 1 : 0;
39
55
  }
40
56
  const a = args(argv); if (a.help) { 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."); return 0; }
41
- const home = resolve(String(a["notes-home"] ?? notesRoot())); process.env.PI_NOTES_HOME = home; mkdirSync(home, { recursive: true });
57
+ // Validate every value flag before anything is created or gated on: a typo must refuse
58
+ // loudly instead of reading as "the last dream is too recent" and exiting successfully.
59
+ const homeArg = directoryArg(a["notes-home"]);
60
+ const minHours = wholeNumberArg(a["min-hours"]);
61
+ const minSessions = wholeNumberArg(a["min-sessions"]);
62
+ const badArg = a["notes-home"] !== undefined && homeArg === undefined ? "--notes-home needs a directory path"
63
+ : a["min-hours"] !== undefined && minHours === undefined ? "--min-hours needs a positive whole number"
64
+ : a["min-sessions"] !== undefined && minSessions === undefined ? "--min-sessions needs a positive whole number"
65
+ : undefined;
66
+ if (badArg) { console.error(`dream: ${badArg}`); return 1; }
67
+ const home = resolve(homeArg ?? notesRoot()); process.env.PI_NOTES_HOME = home; mkdirSync(home, { recursive: true });
42
68
  const lockPath = join(home, ".dream.lock"); const stampPath = lastRunPath(lockPath);
43
- const minHours = Number(a["min-hours"] ?? 24); const minSessions = Number(a["min-sessions"] ?? 3);
44
- const time = timeGate(stampPath, minHours); console.log(time.reason); if (!a.force && !time.ok) return 0;
69
+ const time = timeGate(stampPath, minHours ?? 24); console.log(time.reason); if (!a.force && !time.ok) return 0;
45
70
  const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
46
- const material = materialGate(home, since, minSessions); console.log(material.reason); if (!a.force && !material.ok) return 0;
71
+ const material = materialGate(home, since, minSessions ?? 3); console.log(material.reason); if (!a.force && !material.ok) return 0;
47
72
  let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
48
73
  const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
49
74
  let succeeded = false;
@@ -65,7 +90,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
65
90
  const playbookPath = String(a.playbook ?? defaultBook);
66
91
  let result: DreamResult;
67
92
  try {
68
- const playbook = loadPlaybook(playbookPath);
93
+ const playbook = readFileSync(playbookPath, "utf8");
69
94
  result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
70
95
  } catch (e) {
71
96
  const message = errorMessage(e);
@@ -21,7 +21,7 @@ export interface ContextUsageEstimate {
21
21
  lastUsageIndex: number | null;
22
22
  }
23
23
 
24
- export function calculateContextTokens(usage: Usage): number {
24
+ function calculateContextTokens(usage: Usage): number {
25
25
  return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
26
26
  }
27
27
 
@@ -40,15 +40,15 @@ function estimateTextAndImageContentChars(content: string | Array<TextContent |
40
40
  return chars;
41
41
  }
42
42
 
43
- export function estimateTextTokens(text: string): number {
43
+ function estimateTextTokens(text: string): number {
44
44
  return Math.ceil(text.length / CHARS_PER_TOKEN);
45
45
  }
46
46
 
47
- export function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number {
47
+ function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number {
48
48
  return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
49
49
  }
50
50
 
51
- export function estimateMessageTokens(message: Message): number {
51
+ function estimateMessageTokens(message: Message): number {
52
52
  let chars = 0;
53
53
  if (message.role === "system") {
54
54
  return (
package/src/pi/history.ts CHANGED
@@ -27,14 +27,10 @@ function isToolCall(part: unknown): part is ToolCall {
27
27
  return typeof part === "object" && part !== null && (part as { type?: unknown }).type === "toolCall";
28
28
  }
29
29
 
30
- function mappedMessage(message: AgentMessage): boolean {
31
- return mapRole(message.role) !== undefined;
32
- }
33
-
34
30
  /** Seq allocation depends on entry kind and role, never on visible content. */
35
31
  function sequenceCount(entry: SessionEntry): number {
36
32
  if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
37
- if (entry.type !== "message" || !mappedMessage(entry.message)) return 0;
33
+ if (entry.type !== "message" || mapRole(entry.message.role) === undefined) return 0;
38
34
  if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
39
35
  return 1 + entry.message.content.filter(isToolCall).length;
40
36
  }
@@ -11,7 +11,7 @@ export function notesRoot(): string {
11
11
  }
12
12
 
13
13
  /** Translate the current Pi runtime into a fresh, explicit identity snapshot. */
14
- export function agentSlug(_ctx: ExtensionContext): string {
14
+ export function agentSlug(): string {
15
15
  return slugify(process.env.PI_NOTES_AGENT ?? "anonymous");
16
16
  }
17
17
 
@@ -27,7 +27,7 @@ export function notesIdentityFromPi(ctx: ExtensionContext, home = notesRoot()):
27
27
  home,
28
28
  sessionId: ctx.sessionManager.getSessionId(),
29
29
  projectKey: projectKey(ctx.cwd),
30
- agent: agentSlug(ctx),
30
+ agent: agentSlug(),
31
31
  model: modelSlug(ctx),
32
32
  };
33
33
  }
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
3
3
  import { BOOT_TYPE, CONTINUATION_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
4
- import { CONTINUATION } from "./text.js";
5
- import { currentWindowId, isWindowBootEntry, isWindowMarker, previousWindowId, type WindowMarker } from "../window.js";
4
+ import { CONTINUATION } from "../../budget/text.js";
5
+ import { currentWindowId, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, previousWindowId, type WindowMarker } from "../window.js";
6
6
  import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "../boot.js";
7
7
 
8
8
  export type ResetTailState = { readonly boot: boolean; readonly continuation: boolean };
@@ -13,7 +13,7 @@ export function isWindowContinuationEntry(entry: SessionEntry): boolean {
13
13
  }
14
14
 
15
15
  /** The single continuation sender: the only reset prose persisted for a window. */
16
- export function sendContinuation(pi: ExtensionAPI): void {
16
+ function sendContinuation(pi: ExtensionAPI): void {
17
17
  pi.sendMessage(
18
18
  { customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
19
19
  { triggerTurn: false },
@@ -74,7 +74,7 @@ export function inspectResetTail(ctx: ExtensionContext, markerId: string, window
74
74
  continuation = true;
75
75
  continue;
76
76
  }
77
- if (isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary") {
77
+ if (isForeignResetTailEntry(entry)) {
78
78
  return undefined;
79
79
  }
80
80
  }
@@ -1,5 +1,5 @@
1
1
  import type { SessionReader } from "../session-reader.js";
2
- import { isCheckpointBackedReset, isWindowBootEntry, isWindowMarker } from "../window.js";
2
+ import { isCheckpointBackedReset, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker } from "../window.js";
3
3
  import { isWindowContinuationEntry } from "./artifacts.js";
4
4
 
5
5
  /**
@@ -20,7 +20,7 @@ export function resetBoundaryCommitted(ctx: SessionReader, markerId: string, win
20
20
  continue;
21
21
  }
22
22
  if (isWindowContinuationEntry(entry)) return boot && entry.type === "custom_message" && entry.display === false;
23
- if (isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary") return false;
23
+ if (isForeignResetTailEntry(entry)) return false;
24
24
  }
25
25
  return false;
26
26
  }
package/src/pi/runtime.ts CHANGED
@@ -8,16 +8,14 @@ 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, type IncompleteNotesNotifier } from "./boot.js";
13
13
  import { errorMessage } from "../error-message.js";
14
14
 
15
15
  function readPackageVersion(): string {
16
16
  for (const up of ["../../package.json", "../../../package.json"]) {
17
- try {
18
- const parsed = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8")) as { version?: string };
19
- if (parsed.version) return parsed.version;
20
- } catch { /* try the next candidate */ }
17
+ try { const { version } = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8")) as { version?: string }; if (version) return version; }
18
+ catch { /* try the next candidate */ }
21
19
  }
22
20
  return "dev";
23
21
  }
@@ -59,7 +57,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
59
57
  const homes = snapshot.unavailable.map((home) => home.label).join(", ");
60
58
  ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
61
59
  };
62
- const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
60
+ const budget = registerBudget(pi, () => enabled, settingsManager);
63
61
 
64
62
  pi.on("session_start", async (_event, ctx) => {
65
63
  const generation = ++lifecycleGeneration;
@@ -124,6 +122,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
124
122
  enabled = false;
125
123
  lifecycleGeneration++;
126
124
  pendingResetNotices.clear();
125
+ incompleteNotesNotified.clear();
126
+ missingBootNotice = undefined;
127
127
  budget.clear();
128
128
  resets.clear();
129
129
  } else if (arg !== "") {
@@ -194,4 +194,5 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
194
194
  },
195
195
  budget,
196
196
  });
197
+ budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
197
198
  }
@@ -1,6 +1,6 @@
1
1
  import { deriveThresholds, type ResolvedThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
3
+ import { DEFAULT_RESERVE_TOKENS } from "../budget/constants.js";
4
4
  import { mergeNotesoupSettings } from "../settings.js";
5
5
  import { errorMessage } from "../error-message.js";
6
6
 
@@ -32,18 +32,12 @@ function readThresholdSettingsFromManager(ctx: ExtensionContext, settingsManager
32
32
  */
33
33
  export function readThresholdSettings(ctx: ExtensionContext, settingsManager?: SettingsManager): ThresholdSettingsResolution {
34
34
  try {
35
- if (settingsManager) return readThresholdSettingsFromManager(ctx, settingsManager);
36
- return readThresholdSettingsFromManager(
37
- ctx,
38
- SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }),
39
- );
35
+ const manager = settingsManager ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
36
+ return readThresholdSettingsFromManager(ctx, manager);
40
37
  } catch (error) {
41
38
  return {
42
- thresholds: {
43
- reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
44
- reserve: DEFAULT_RESERVE_TOKENS,
45
- warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
46
- },
39
+ // The same derivation over Pi's default reserve, so the fallback cannot drift from it.
40
+ thresholds: deriveThresholds(DEFAULT_RESERVE_TOKENS, {}).thresholds,
47
41
  automatic: true,
48
42
  warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
49
43
  };
@@ -6,7 +6,7 @@ import type { Static, TSchema } from "typebox";
6
6
  import { wireResult, type Operation, type Outcome, type Renderer } from "../tools/result.js";
7
7
 
8
8
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
9
- export function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined> {
9
+ function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined> {
10
10
  return {
11
11
  content: [{ type: "text", text: render(outcome) }],
12
12
  structuredContent: wireResult(outcome) as unknown as JsonValue,
package/src/pi/window.ts CHANGED
@@ -71,6 +71,14 @@ function hasWindowId(details: unknown, windowId: string): boolean {
71
71
  (details as { windowId: string }).windowId === windowId;
72
72
  }
73
73
 
74
+ /**
75
+ * An entry that cannot appear between a reset marker and its boot/continuation without
76
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
77
+ */
78
+ export function isForeignResetTailEntry(entry: SessionEntry): boolean {
79
+ return isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary";
80
+ }
81
+
74
82
  /** Match a provider-facing boot message, optionally by window identity. */
75
83
  export function isWindowBoot(message: AgentMessage, windowId?: string): boolean {
76
84
  return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
package/src/settings.ts CHANGED
@@ -15,15 +15,16 @@ export type NotesoupSettings = {
15
15
  dreamer?: unknown;
16
16
  };
17
17
 
18
- function isSettingsObject(value: unknown): value is Record<string, unknown> {
18
+ /** A plain settings object; arrays and null are not one. */
19
+ export function isPlainObject(value: unknown): value is Record<string, unknown> {
19
20
  return typeof value === "object" && value !== null && !Array.isArray(value);
20
21
  }
21
22
 
22
23
  /** Read the raw "notesoup" object from one parsed settings scope. */
23
24
  function notesoupSettings(settings: unknown): Record<string, unknown> {
24
- if (!isSettingsObject(settings)) return {};
25
+ if (!isPlainObject(settings)) return {};
25
26
  const value = settings[NOTESOUP_SETTINGS_KEY];
26
- return isSettingsObject(value) ? value : {};
27
+ return isPlainObject(value) ? value : {};
27
28
  }
28
29
 
29
30
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */