notesoup 0.41.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 (127) 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.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  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 +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -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 +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -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
  }
@@ -182,7 +184,7 @@ export function registerContext(pi, settingsManager) {
182
184
  parameters: Type.Object({}, { additionalProperties: false }),
183
185
  async execute(_id, _params, _signal, _update, ctx) {
184
186
  if (!enabled)
185
- return output({ error: "notesoup is off (/notesoup on to enable)" });
187
+ return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
186
188
  return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
187
189
  },
188
190
  }));
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  import { deriveThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager } 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
  function readThresholdSettingsFromManager(ctx, settingsManager) {
@@ -16,17 +16,13 @@ function readThresholdSettingsFromManager(ctx, settingsManager) {
16
16
  */
17
17
  export function readThresholdSettings(ctx, settingsManager) {
18
18
  try {
19
- if (settingsManager)
20
- return readThresholdSettingsFromManager(ctx, settingsManager);
21
- return readThresholdSettingsFromManager(ctx, SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }));
19
+ const manager = settingsManager ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
20
+ return readThresholdSettingsFromManager(ctx, manager);
22
21
  }
23
22
  catch (error) {
24
23
  return {
25
- thresholds: {
26
- reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
27
- reserve: DEFAULT_RESERVE_TOKENS,
28
- warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
29
- },
24
+ // The same derivation over Pi's default reserve, so the fallback cannot drift from it.
25
+ thresholds: deriveThresholds(DEFAULT_RESERVE_TOKENS, {}).thresholds,
30
26
  automatic: true,
31
27
  warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
32
28
  };
@@ -1,10 +1,7 @@
1
1
  /** Pi transport for host-neutral operations. */
2
2
  import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
3
  import type { Static, TSchema } from "typebox";
5
- import { type Operation, type Outcome, type Renderer } from "../tools/result.js";
6
- /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
7
- export declare function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined>;
4
+ import { type Operation, type Outcome } from "../tools/result.js";
8
5
  export type ToolNamespace = {
9
6
  name: string;
10
7
  description: string;
@@ -2,7 +2,7 @@
2
2
  import { defineTool } from "@earendil-works/pi-coding-agent";
3
3
  import { wireResult } from "../tools/result.js";
4
4
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
- export function piOperationResult(render, outcome) {
5
+ function piOperationResult(render, outcome) {
6
6
  return {
7
7
  content: [{ type: "text", text: render(outcome) }],
8
8
  structuredContent: wireResult(outcome),
@@ -10,8 +10,8 @@ export function piOperationResult(render, outcome) {
10
10
  details: undefined,
11
11
  };
12
12
  }
13
- export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See /skill:memory." };
14
- export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See /skill:memory." };
13
+ export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
14
+ export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
15
15
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
16
16
  export function registerOperation(pi, operation, run, namespace) {
17
17
  pi.registerTool(defineTool({
@@ -21,6 +21,11 @@ export declare function hasWindowMessage(ctx: SessionReader, customType: string)
21
21
  export declare function currentWindowId(ctx: SessionReader): string;
22
22
  /** The durable window active just before the marker: the last earlier marker, else the root window. */
23
23
  export declare function previousWindowId(ctx: SessionReader, markerId: string): string;
24
+ /**
25
+ * An entry that cannot appear between a reset marker and its boot/continuation without
26
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
27
+ */
28
+ export declare function isForeignResetTailEntry(entry: SessionEntry): boolean;
24
29
  /** Match a provider-facing boot message, optionally by window identity. */
25
30
  export declare function isWindowBoot(message: AgentMessage, windowId?: string): boolean;
26
31
  /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
@@ -64,6 +64,13 @@ function hasWindowId(details, windowId) {
64
64
  typeof details.windowId === "string" &&
65
65
  details.windowId === windowId;
66
66
  }
67
+ /**
68
+ * An entry that cannot appear between a reset marker and its boot/continuation without
69
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
70
+ */
71
+ export function isForeignResetTailEntry(entry) {
72
+ return isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary";
73
+ }
67
74
  /** Match a provider-facing boot message, optionally by window identity. */
68
75
  export function isWindowBoot(message, windowId) {
69
76
  return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
@@ -1,9 +1,19 @@
1
1
  export declare const NOTESOUP_SETTINGS_KEY = "notesoup";
2
2
  /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
3
  export declare const NOTESOUP_DREAMER_KEY = "dreamer";
4
+ /**
5
+ * The one notesoup settings shape both hosts read. `reminderMarginTokens` is Pi's early
6
+ * reminder margin; `resetMarginTokens` and `warningRunwayTokens` are the Claude mod's
7
+ * margins against Claude's own auto-compact point (see src/claude/thresholds.ts). A host
8
+ * ignores the keys it does not use; every value is validated where it is consumed.
9
+ */
4
10
  export type NotesoupSettings = {
5
11
  reminderMarginTokens?: unknown;
12
+ resetMarginTokens?: unknown;
13
+ warningRunwayTokens?: unknown;
6
14
  dreamer?: unknown;
7
15
  };
16
+ /** A plain settings object; arrays and null are not one. */
17
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
8
18
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
9
19
  export declare function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings;
@@ -1,18 +1,24 @@
1
1
  export const NOTESOUP_SETTINGS_KEY = "notesoup";
2
2
  /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
3
  export const NOTESOUP_DREAMER_KEY = "dreamer";
4
- function isSettingsObject(value) {
4
+ /** A plain settings object; arrays and null are not one. */
5
+ export function isPlainObject(value) {
5
6
  return typeof value === "object" && value !== null && !Array.isArray(value);
6
7
  }
7
8
  /** Read the raw "notesoup" object from one parsed settings scope. */
8
9
  function notesoupSettings(settings) {
9
- if (!isSettingsObject(settings))
10
+ if (!isPlainObject(settings))
10
11
  return {};
11
12
  const value = settings[NOTESOUP_SETTINGS_KEY];
12
- return isSettingsObject(value) ? value : {};
13
+ return isPlainObject(value) ? value : {};
13
14
  }
14
15
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
15
16
  export function mergeNotesoupSettings(globalSettings, projectSettings) {
16
17
  const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
17
- return { reminderMarginTokens: merged.reminderMarginTokens, dreamer: merged.dreamer };
18
+ return {
19
+ reminderMarginTokens: merged.reminderMarginTokens,
20
+ resetMarginTokens: merged.resetMarginTokens,
21
+ warningRunwayTokens: merged.warningRunwayTokens,
22
+ dreamer: merged.dreamer,
23
+ };
18
24
  }