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
@@ -8,14 +8,9 @@ function writeList(writes: DreamWrite[]): string {
8
8
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
9
9
  }
10
10
 
11
- /** Best-effort text write; returns the failure message instead of throwing. */
12
- function writeText(path: string, content: string): string | undefined {
13
- try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); return undefined; }
14
- catch (error) { return errorMessage(error); }
15
- }
16
-
17
- function appendText(path: string, content: string): string | undefined {
18
- try { appendFileSync(path, content); return undefined; }
11
+ /** Best-effort filesystem step; returns the failure message instead of throwing. */
12
+ function attempt(action: () => void): string | undefined {
13
+ try { action(); return undefined; }
19
14
  catch (error) { return errorMessage(error); }
20
15
  }
21
16
 
@@ -26,11 +21,11 @@ function appendText(path: string, content: string): string | undefined {
26
21
  */
27
22
  export function finishDream(home: string, stamp: string, reportPath: string, failed: boolean, body: string, writes: DreamWrite[]): number {
28
23
  const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
29
- let reportError = writeText(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`);
24
+ let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
30
25
  const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
31
26
  if (!audit.ok) {
32
27
  console.error(`dream: final audit failed: ${audit.error}`);
33
- reportError ??= appendText(reportPath, `\n## Final audit failed\n\n${audit.error}\n`);
28
+ reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
34
29
  }
35
30
  if (reportError) console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
36
31
  return failed || !audit.ok || reportError !== undefined ? 1 : 0;
@@ -239,14 +239,16 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
239
239
  const document = eventDocument(event);
240
240
  const chars = Array.from(document);
241
241
  const start = matchOffset ?? 0;
242
- const truncated = start > 0 || start + maxChars < chars.length;
242
+ // A negative budget would cut the tail and still call the result a prefix.
243
+ const limit = Math.max(0, maxChars);
244
+ const truncated = start > 0 || start + limit < chars.length;
243
245
  return {
244
246
  seq: event.seq,
245
247
  window_id: event.windowId,
246
248
  role: event.role,
247
249
  created_at: event.createdAt ?? null,
248
250
  ...toolSummary(event),
249
- content: truncated ? chars.slice(start, start + maxChars).join("") : document,
251
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
250
252
  truncated,
251
253
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
252
254
  };
@@ -259,7 +261,7 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
259
261
  export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
260
262
  if (typeof params.window_id !== "string") return undefined;
261
263
  const known = projection.windows.map((current) => current.windowId);
262
- return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
264
+ return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
263
265
  }
264
266
 
265
267
  /**
@@ -1,7 +1,8 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type, type Static } from "typebox";
3
3
  import { failure, success, type Outcome } from "../tools/result.js";
4
- import { earliestMatchOffsetChars, prefixFit } from "../tools/output.js";
4
+ import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
+ import { earliestMatchOffsetChars } from "../text-match.js";
5
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
7
  import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
7
8
 
@@ -28,19 +29,12 @@ export type HistorySelection = HistoryFilter & {
28
29
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
29
30
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
30
31
 
31
- /** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
32
- function isoUtcMs(value: string): number | undefined {
33
- const match = ISO_8601.exec(value);
34
- if (match === null) return undefined;
35
- const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
36
- return Number.isNaN(at) ? undefined : at;
37
- }
38
-
39
32
  /** Epoch ms for one optional time param, or a refusal naming it. */
40
33
  function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
41
34
  if (value === undefined) return success(undefined);
42
- const at = isoUtcMs(value);
43
- return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
35
+ const match = ISO_8601.exec(value);
36
+ const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
37
+ return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
44
38
  }
45
39
 
46
40
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
@@ -50,7 +44,7 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
50
44
  const until = timeBound("until", params.until);
51
45
  if (!until.ok) return until;
52
46
  if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
53
- return failure("invalid_time", "since must be earlier than until");
47
+ return failure("invalid_time", "`since` must be earlier than `until`.");
54
48
  }
55
49
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
56
50
  }
@@ -67,8 +61,8 @@ export const HistoryNewerSchema = Type.Object({
67
61
 
68
62
  export const HistoryPageSchema = Type.Object({
69
63
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
70
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
71
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
64
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
65
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
72
66
  }, { additionalProperties: false });
73
67
 
74
68
  /** One whole page payload, before it becomes an outcome. */
@@ -180,16 +174,6 @@ function selectionCandidates(projection: HistoryProjection, params: HistorySelec
180
174
  .filter((candidate) => candidate.matchOffset >= 0));
181
175
  }
182
176
 
183
- /**
184
- * Take the limit from the end `from` names, starting there so a budget for one row keeps the most
185
- * important row. The selection is already filtered to its range; `from` never states a direction.
186
- */
187
- function orderedCandidates(vis: Candidate[], params: HistorySelection, limit: number): Candidate[] {
188
- const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
189
- const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
190
- return params.from === "oldest" ? selected : selected.reverse();
191
- }
192
-
193
177
  /**
194
178
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
195
179
  * Grow the page in selection order; shorten the first preview only when no full row fits.
@@ -201,9 +185,12 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
201
185
  const candidates = selectionCandidates(projection, scoped);
202
186
  if (!candidates.ok) return candidates;
203
187
  const vis = candidates.data;
204
- const limit = scoped.limit ?? 20;
188
+ // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
189
+ // At least one: `slice(-0)` would otherwise return the whole selection.
190
+ const limit = Math.max(1, scoped.limit ?? 20);
205
191
  const folds = foldsRuns(scoped);
206
- const ordered = orderedCandidates(vis, scoped, limit);
192
+ const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
193
+ const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
207
194
  const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
208
195
  const kept: Candidate[] = [];
209
196
  for (const candidate of ordered) {
@@ -216,7 +203,7 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
216
203
  }
217
204
  const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
218
205
  if (!fits(page)) {
219
- return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow with before_seq/after_seq or since/until, or read one seq`);
206
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
220
207
  }
221
208
  return success(page);
222
209
  }
@@ -1,24 +1,10 @@
1
- import { NoteError } from "./errors.js";
1
+ import { NoteError, shown } from "./errors.js";
2
2
  import type { NotesIdentity } from "./identity.js";
3
- import { SLUG_PATTERN, type Scope } from "./paths.js";
3
+ import { assertVirtualPath, SLUG_PATTERN, type Scope } from "./paths.js";
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
8
-
9
- /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
10
- function shown(value: unknown): string {
11
- const json = JSON.stringify(value);
12
- return json === undefined ? String(value) : json;
13
- }
14
-
15
- export function assertVirtualPath(value: unknown): string {
16
- if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
17
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
18
- const parts = value.split("/");
19
- if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
20
- return value;
21
- }
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
22
8
 
23
9
  /**
24
10
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
@@ -39,6 +25,8 @@ export function globToRegExp(pattern: string): RegExp {
39
25
  } else {
40
26
  source += "[^/]*";
41
27
  }
28
+ } else if (char === "?") {
29
+ source += "[^/]";
42
30
  } else {
43
31
  source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
44
32
  }
@@ -49,8 +37,8 @@ export function globToRegExp(pattern: string): RegExp {
49
37
  /** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
50
38
  export function assertGlobPattern(value: unknown): string | undefined {
51
39
  if (value === undefined || value === null || value === "") return undefined;
52
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
53
- if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
40
+ if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
41
+ if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
54
42
  return value;
55
43
  }
56
44
 
@@ -59,7 +47,7 @@ export function assertGlobPattern(value: unknown): string | undefined {
59
47
  * are relative; explicit agents/models addresses always name a canonical slug.
60
48
  */
61
49
  export function assertAddress(value: unknown): NoteAddress {
62
- if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
50
+ if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
63
51
  let scope: Scope = "session";
64
52
  let path = value;
65
53
  let who: string | undefined;
@@ -76,16 +64,16 @@ export function assertAddress(value: unknown): NoteAddress {
76
64
  else if (head === "agents" || head === "models") {
77
65
  const nameEnd = tail.indexOf("/");
78
66
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
79
- if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
67
+ if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
80
68
  scope = head === "agents" ? "agent" : "model";
81
69
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
82
70
  } else {
83
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
71
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
84
72
  }
85
- if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
86
- if (path === "" && who === undefined) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
73
+ if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
74
+ if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
87
75
  }
88
- if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
76
+ if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
89
77
  assertVirtualPath(path);
90
78
  return { scope, path, who };
91
79
  }
@@ -13,3 +13,9 @@ export class NoteError extends Error {
13
13
  this.editIndex = extra.editIndex;
14
14
  }
15
15
  }
16
+
17
+ /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
18
+ export function shown(value: unknown): string {
19
+ const json = JSON.stringify(value);
20
+ return json === undefined ? String(value) : json;
21
+ }
@@ -132,15 +132,25 @@ export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body
132
132
  return { meta: meta as NoteMeta, body };
133
133
  }
134
134
 
135
- /** Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise. */
135
+ /**
136
+ * Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
137
+ * A quoted string must not come back as another type: a value that `JSON.parse` reads as a
138
+ * non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
139
+ * with its type intact.
140
+ */
136
141
  function yamlScalar(value: unknown): string {
137
142
  if (typeof value === "string") {
138
143
  const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
139
- if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase())) return value;
144
+ if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
140
145
  }
141
146
  return JSON.stringify(value);
142
147
  }
143
148
 
149
+ /** True when a bare scalar would be read back as a number, boolean or null instead of text. */
150
+ function parsesAsNonString(text: string): boolean {
151
+ try { return typeof JSON.parse(text) !== "string"; } catch { return false; }
152
+ }
153
+
144
154
  /** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
145
155
  export function serializeNote(meta: NoteMeta, body: string): string {
146
156
  const lines: string[] = [];
@@ -24,8 +24,6 @@ function assertDirectoryComponent(field: string, value: string): void {
24
24
  /** Validate and snapshot caller identity; no global or environment defaults are consulted. */
25
25
  export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
26
26
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("notes context must be a plain object");
27
- const prototype = Object.getPrototypeOf(value);
28
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("notes context must be a plain object");
29
27
  const homeValue = requireString("home", value.home);
30
28
  const sessionId = requireString("sessionId", value.sessionId);
31
29
  const projectKey = requireString("projectKey", value.projectKey);
@@ -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");
@@ -228,12 +220,17 @@ async function atomicWrite(path: string, content: string): Promise<void> {
228
220
  /** The byte cap is a write-time boundary rule, never a path-jail rule. */
229
221
  function assertWritablePath(vpath: string): void {
230
222
  const bytes = Buffer.byteLength(vpath, "utf8");
231
- if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
223
+ if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
224
+ }
225
+
226
+ /** Rounded up, so a note just over the limit never reads as exactly at it. */
227
+ function megabytes(bytes: number): string {
228
+ return `${Math.ceil(bytes / 10_000) / 100} MB`;
232
229
  }
233
230
 
234
231
  function assertSerializedSize(content: string): void {
235
232
  const bytes = Buffer.byteLength(content, "utf8");
236
- if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
233
+ if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `This note would be ${megabytes(bytes)}, over the ${megabytes(MAX_NOTE_BYTES)} limit per note; split it into several notes.`);
237
234
  }
238
235
 
239
236
  /** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
@@ -247,15 +244,7 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
247
244
  const current = scope === "agent" ? identity.agent : identity.model;
248
245
  if (who === current) return;
249
246
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
250
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
251
- }
252
-
253
- /** Normalize parsed metadata exactly as a read does, including its access mutation. */
254
- function accessedMeta(meta: NoteMeta, scope: Scope, now: number): NoteMeta {
255
- const next = { ...meta, scope };
256
- next.lastAccessed = now;
257
- next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
258
- return next;
247
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
259
248
  }
260
249
 
261
250
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
@@ -268,7 +257,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
268
257
  assertWritablePath(destination.path);
269
258
  const scope = destination.scope;
270
259
  assertWritableHome(scope, destination.who, identity);
271
- 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);
272
263
  const path = physicalPath(scope, destination.path, identity, destination.who);
273
264
  return withPathQueue(path, async () => {
274
265
  const now = writeStamp();
@@ -278,7 +269,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
278
269
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
279
270
  const meta: NoteMeta = existing ?? {
280
271
  scope,
281
- origin,
272
+ origin: origin ?? "self",
282
273
  createdAt: now,
283
274
  updatedAt: now,
284
275
  lastAccessed: now,
@@ -286,7 +277,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
286
277
  ...(scope === "session" ? { project: identity.projectKey } : {}),
287
278
  };
288
279
  meta.scope = scope;
289
- meta.origin = origin;
280
+ if (origin !== undefined) meta.origin = origin;
290
281
  delete meta.crumpledAt;
291
282
  meta.updatedAt = now;
292
283
  const serialized = serializeNote(meta, cleanBody);
@@ -305,7 +296,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
305
296
  if (raw === undefined) return undefined;
306
297
  const now = Date.now();
307
298
  const parsed = parseNote(raw, now);
308
- 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 };
309
301
  await atomicWrite(path, serializeNote(meta, parsed.body));
310
302
  return { meta, body: parsed.body, resolvedScope: scope };
311
303
  });
@@ -319,12 +311,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
319
311
  const scope = destination.scope;
320
312
  assertWritableHome(scope, destination.who, identity);
321
313
  if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
322
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
314
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
323
315
  }
324
316
  const path = physicalPath(scope, destination.path, identity, destination.who);
325
317
  return withPathQueue(path, async () => {
326
318
  const raw = await readFileIfExists(path);
327
- if (raw === undefined) throw new NoteError("not_found", "note not found");
319
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
328
320
  const { meta, body } = parseNote(raw);
329
321
  meta.scope = scope;
330
322
  const beforeMeta: NoteMeta = { ...meta };
@@ -333,12 +325,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
333
325
  operations.forEach((operation, index) => {
334
326
  const oldText = operation?.oldText;
335
327
  const newText = operation?.newText;
336
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
337
- if (typeof newText !== "string") throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
328
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
329
+ if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
338
330
  const lines = matchLineNumbers(next, oldText);
339
- if (lines.length === 0) throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
331
+ if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
340
332
  if (lines.length > 1 && !stableOptions.replaceAll) {
341
- throw new NoteError("ambiguous_edit", `edit ${index}: oldText occurs ${lines.length} times (${anchorLines(lines)}); pass replace_all to replace every occurrence`, { lineNumbers: lines, editIndex: index });
333
+ throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
342
334
  }
343
335
  if (oldText !== newText) applied++;
344
336
  // Positional splicing preserves user replacement text byte-for-byte.
@@ -384,14 +376,14 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
384
376
  assertWritableHome(toScope, to.who, identity);
385
377
  const fromPath = physicalPath(fromScope, from.path, identity, from.who);
386
378
  const toPath = physicalPath(toScope, to.path, identity, to.who);
387
- if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
379
+ if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
388
380
  const [first, second] = [fromPath, toPath].sort();
389
381
  return withPathQueue(first!, () => withPathQueue(second!, async () => {
390
382
  const raw = await readFileIfExists(fromPath);
391
- if (raw === undefined) throw new NoteError("not_found", "note not found");
383
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
392
384
  const targetRaw = await readFileIfExists(toPath);
393
385
  if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
394
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
386
+ throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
395
387
  }
396
388
  const { meta, body } = parseNote(raw);
397
389
  meta.scope = toScope;
@@ -408,7 +400,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
408
400
  }
409
401
 
410
402
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
411
- 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);
412
406
  let homes: HomeRef[];
413
407
  try {
414
408
  homes = await homesFor(identity, options);
@@ -420,24 +414,32 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
420
414
  for (const home of homes) {
421
415
  const scope = home.scope;
422
416
  const root = scopeDir(scope, identity, home.who);
423
- const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
417
+ let paths: string[];
424
418
  try {
425
- for (const path of await walkMarkdown(root)) {
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
- const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
430
- const { meta, body } = parseNote(raw);
431
- meta.scope = scope;
432
- if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
433
- homeRows.push({ address, scope, path, meta, body });
434
- }
419
+ paths = await walkMarkdown(root);
435
420
  } catch (error) {
436
421
  if (!status || !isFilesystemError(error)) throw error;
437
422
  status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
438
423
  continue;
439
424
  }
440
- 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
+ }
441
443
  }
442
444
  }
443
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
  };