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
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
 
@@ -26,8 +26,8 @@ export function notesIdentityFromPi(ctx: ExtensionContext, home = notesRoot()):
26
26
  return {
27
27
  home,
28
28
  sessionId: ctx.sessionManager.getSessionId(),
29
- projectKey: projectKey(ctx.cwd),
30
- agent: agentSlug(ctx),
29
+ projectKey: projectKey(ctx.cwd, home),
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. */
@@ -1,6 +1,6 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type, type Static } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
3
+ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
6
  import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
@@ -54,10 +54,6 @@ function renderPageItem(item: HistoryPageItem): string {
54
54
  return lines.join("\n");
55
55
  }
56
56
 
57
- function isFoldedRow(item: HistoryPageItem | HistoryFoldedRow): item is HistoryFoldedRow {
58
- return "folded" in item;
59
- }
60
-
61
57
  function renderFoldedRow(row: HistoryFoldedRow): string {
62
58
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
63
59
  const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
@@ -67,7 +63,7 @@ function renderFoldedRow(row: HistoryFoldedRow): string {
67
63
  function renderPage(page: HistoryPage): string {
68
64
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
69
65
  if (page.items.length === 0) return "No events match these filters.";
70
- const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
66
+ const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
71
67
  const cursors = [
72
68
  page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
73
69
  page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
@@ -161,8 +157,8 @@ export const historyListParameters = Type.Object({
161
157
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
162
158
  from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
163
159
  window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
164
- limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
165
- max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
160
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
161
+ max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
166
162
  }, { additionalProperties: false });
167
163
 
168
164
  export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
@@ -2,7 +2,7 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
3
  import { localIso } from "../notes/frontmatter.js";
4
4
  import { isFilesystemError } from "../notes/fs-error.js";
5
- import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow, type Scope } from "../notes/index.js";
5
+ import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow } from "../notes/index.js";
6
6
  import { prefixFit, TOOL_OUTPUT_LIMIT } from "./output.js";
7
7
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema, type Outcome } from "./result.js";
8
8
  import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
@@ -15,12 +15,7 @@ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional)
15
15
  const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
16
16
  const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
17
17
  const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
18
- const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
19
-
20
- /** The one receipt field a caller cannot derive from the address itself. */
21
- function projectKeyField(scope: Scope, projectKey: string): { project_key?: string } {
22
- return scope === "project" ? { project_key: projectKey } : {};
23
- }
18
+ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
24
19
 
25
20
  /**
26
21
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
@@ -34,22 +29,13 @@ function failureOf(error: unknown): Outcome<never> {
34
29
  throw error;
35
30
  }
36
31
 
37
- function byRecent<T extends { address: string; meta: { updatedAt: number } }>(a: T, b: T): number {
38
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
39
- }
40
-
41
32
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
42
33
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
43
34
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
44
- export const MAX_METADATA_ENTRY_BYTES = 1024;
35
+ const MAX_METADATA_ENTRY_BYTES = 1024;
45
36
  const MAX_METADATA_VERBATIM_BYTES = 2048;
46
37
  /** An extra value that cannot be carried is named in place, never silently dropped. */
47
- export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
48
-
49
- /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
50
- function extraEntryBytes(key: string, value: unknown): number {
51
- return structuredBytes(key) + 1 + structuredBytes(value);
52
- }
38
+ const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
53
39
 
54
40
  export const NoteMetadataSchema = Type.Object({
55
41
  origin: Type.Union([...ORIGIN_VALUES]),
@@ -73,7 +59,8 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
73
59
  if (NORMALIZED_META_KEYS.has(key) || value === undefined) continue;
74
60
  // A key too large to carry cannot be named at all; an oversized value is named in place.
75
61
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES) continue;
76
- const entryBytes = extraEntryBytes(key, value);
62
+ // The key counts too: hand-written frontmatter can have arbitrarily long keys.
63
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
77
64
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
78
65
  put(key, TOO_LARGE_EXTRA_VALUE);
79
66
  continue;
@@ -104,14 +91,23 @@ function renderMetadata(metadata: NoteMetadata): string {
104
91
  return fields.join(" | ");
105
92
  }
106
93
 
107
- /** Address plus project key in one line; the project key never replaces the address. */
108
- function renderIdentity(identity: { address: string; project_key?: string }): string {
109
- return identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
94
+ /** Keep the address visible, with project context and at most one sibling hint line. */
95
+ function renderIdentity(identity: { address: string; project_key?: string; project_root?: string; project_siblings?: Array<{ name: string; path: string }> }): string {
96
+ let text = identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
97
+ if (identity.project_root !== undefined) text += ` (project_root ${identity.project_root})`;
98
+ if (identity.project_siblings !== undefined) text += `\n Same-basename projects: ${identity.project_siblings.map(sibling => `${sibling.name} (${sibling.path})`).join(", ")}`;
99
+ return text;
110
100
  }
111
101
 
102
+ const ProjectReceiptSchema = {
103
+ project_root: Type.Optional(Type.String()),
104
+ project_siblings: Type.Optional(Type.Array(Type.Object({ name: Type.String(), path: Type.String() }, { additionalProperties: false }))),
105
+ };
106
+
112
107
  const ListedFileSchema = Type.Object({
113
108
  address: Type.String(),
114
109
  project_key: Type.Optional(Type.String()),
110
+ ...ProjectReceiptSchema,
115
111
  updated_at: Type.String(),
116
112
  crumpled_at: Type.Optional(Type.String()),
117
113
  }, { additionalProperties: false });
@@ -151,6 +147,7 @@ export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
151
147
  export const NotesReadDataSchema = Type.Object({
152
148
  address: Type.String(),
153
149
  project_key: Type.Optional(Type.String()),
150
+ ...ProjectReceiptSchema,
154
151
  metadata: NoteMetadataSchema,
155
152
  ...TextWindowSchema.properties,
156
153
  }, { additionalProperties: false });
@@ -198,8 +195,8 @@ function snapshot<T extends { address: string }>(
198
195
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
199
196
  }
200
197
 
201
- function listedFile(row: Pick<NoteRow, "address" | "scope" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
202
- return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
198
+ function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
199
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
203
200
  }
204
201
 
205
202
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
@@ -372,7 +369,7 @@ export const notesSearch = {
372
369
  async execute(params: Static<typeof notesSearchParameters>, identity: NotesIdentity): Promise<Outcome<NotesSearchData>> {
373
370
  try {
374
371
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
375
- const files: NotesSearchData["files"] = rows.sort(byRecent).map(row => ({
372
+ const files: NotesSearchData["files"] = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
376
373
  ...listedFile(row, identity),
377
374
  matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
378
375
  }));
@@ -1,6 +1,4 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
-
4
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
5
3
  /** The per-call limit as the model reads it in refusals. */
6
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
@@ -8,15 +6,6 @@ export const DEFAULT_READ_WINDOW_CHARS = 12000;
8
6
  export const MAX_READ_WINDOW_CHARS = 50000;
9
7
  export const HISTORY_PREVIEW_CHARS = 1200;
10
8
 
11
- function json(value: unknown): string {
12
- return JSON.stringify(value);
13
- }
14
-
15
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
16
- export function withinTextBudget(text: string, budget = TOOL_OUTPUT_MAX_BYTES): boolean {
17
- return Buffer.byteLength(text, "utf8") <= budget;
18
- }
19
-
20
9
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
21
10
  export function prefixFit(text: string, fits: (content: string) => boolean): string {
22
11
  if (fits(text)) return text;
@@ -39,5 +28,5 @@ export function prefixFit(text: string, fits: (content: string) => boolean): str
39
28
  * undefined unless the tool has metadata worth persisting.
40
29
  */
41
30
  export function output(value: unknown, details?: unknown, terminate = false) {
42
- return { content: [{ type: "text" as const, text: json(value) }], details, terminate };
31
+ return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details, terminate };
43
32
  }