notesoup 0.0.0-stage → 0.39.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +21 -0
  8. package/dist/src/boot/text.js +52 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +104 -0
  58. package/dist/src/notes/store.js +478 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +10 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +11 -0
  98. package/dist/src/pi/tool-names.js +11 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +79 -0
  114. package/dist/src/tools/result.js +130 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +368 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +66 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +270 -0
  188. package/src/history/query.ts +147 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +497 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +12 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +13 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,497 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Dirent } from "node:fs";
3
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { earliestMatchOffsetChars } from "../text-match.js";
6
+ import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp } from "./address.js";
7
+ import { isFilesystemError } from "./fs-error.js";
8
+ import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
+ import { NoteError } from "./errors.js";
10
+ import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
+ import { isOrigin, isScope, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
+ import { namespaceSlugs, noteFileName, physicalPath, scopeDir, SLUG_PATTERN, type Scope } from "./paths.js";
13
+
14
+ export type { NoteMeta, Origin, Scope };
15
+
16
+ export type NoteRow = { address: string; scope: Scope; path: string; meta: NoteMeta; body: string; sizeBytes: number };
17
+
18
+ // Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
19
+ let lastWriteStamp = 0;
20
+ function writeStamp(): number {
21
+ const now = Date.now();
22
+ lastWriteStamp = now > lastWriteStamp ? now : lastWriteStamp + 1;
23
+ return lastWriteStamp;
24
+ }
25
+ export type NoteMatch = { line: number; text: string; /** Code-point offset into the note body, not into the serialized file. */ offsetChars: number };
26
+ export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; matches: NoteMatch[] };
27
+ export type EditOperation = { oldText: string; newText: string };
28
+ export type WriteOptions = { origin?: Origin };
29
+ export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: boolean };
30
+ export type NotesQuery = (
31
+ | { scope?: undefined; who?: never }
32
+ | { scope: "session" | "project" | "human"; who?: never }
33
+ | { scope: "agent" | "model"; who?: string }
34
+ ) & { pattern?: string; wastebasket?: boolean };
35
+ /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
36
+ export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
37
+ export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
38
+ export type NoteChange =
39
+ | { kind: "none"; before: ""; after: "" }
40
+ | { kind: "body" | "metadata" | "file"; before: string; after: string };
41
+ export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
42
+ export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
43
+ export type NoteQueryStatus = { crumpledExcluded: number; homesUnavailable: string[] };
44
+ export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
45
+
46
+ /** Public identity resolved for an operation, never a filesystem path. */
47
+ export function noteIdentity(identity: NotesIdentity, address: string): { address: string; project_key?: string } {
48
+ const resolved = assertAddress(address);
49
+ return {
50
+ address: addressFor(identity, resolved.scope, noteFileName(resolved.path), resolved.who),
51
+ ...(resolved.scope === "project" ? { project_key: identity.projectKey } : {}),
52
+ };
53
+ }
54
+
55
+ /** Host-neutral, filesystem-backed notes API. */
56
+ export interface NotesStore {
57
+ write(address: string, content: string, options?: WriteOptions): Promise<NoteWriteResult>;
58
+ read(address: string): Promise<NoteReadResult | undefined>;
59
+ update(address: string, edits?: EditOperation[], options?: EditOptions): Promise<NoteEditResult>;
60
+ rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult>;
61
+ list(options?: NotesQuery): Promise<NoteRow[]>;
62
+ search(queries: string[], options?: NotesQuery): Promise<NoteSearchRow[]>;
63
+ listWithStatus(options?: NotesQuery): Promise<NoteQueryResult<NoteRow>>;
64
+ searchWithStatus(queries: string[], options?: NotesQuery): Promise<NoteQueryResult<NoteSearchRow>>;
65
+ }
66
+
67
+ const SCOPE_ORDER: readonly Scope[] = ["session", "project", "human", "agent", "model"];
68
+
69
+ /** Mutations and read-modify-write reads serialize by physical file across all store instances. */
70
+ const pathQueues = new Map<string, Promise<void>>();
71
+
72
+ function withPathQueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
73
+ const key = resolve(path);
74
+ const previous = pathQueues.get(key) ?? Promise.resolve();
75
+ const result = previous.then(operation);
76
+ const tail = result.then(() => undefined, () => undefined);
77
+ pathQueues.set(key, tail);
78
+ void tail.then(() => {
79
+ if (pathQueues.get(key) === tail) pathQueues.delete(key);
80
+ });
81
+ return result;
82
+ }
83
+
84
+ function errno(error: unknown): string | undefined {
85
+ return typeof error === "object" && error !== null ? (error as NodeJS.ErrnoException).code : undefined;
86
+ }
87
+
88
+ async function readFileIfExists(path: string): Promise<string | undefined> {
89
+ try {
90
+ return await readFile(path, "utf8");
91
+ } catch (error) {
92
+ if (errno(error) === "ENOENT") return undefined;
93
+ throw error;
94
+ }
95
+ }
96
+
97
+ /** Recursively list `.md` files under `dir` as forward-slash virtual paths relative to `base`. */
98
+ async function walkMarkdown(dir: string, base = dir): Promise<string[]> {
99
+ let entries: Dirent[];
100
+ try {
101
+ entries = await readdir(dir, { withFileTypes: true });
102
+ } catch (error) {
103
+ // A home that has never been created is normal. Other failures must reach the
104
+ // boot snapshot boundary instead of masquerading as an empty home.
105
+ if (errno(error) === "ENOENT") return [];
106
+ throw error;
107
+ }
108
+ const paths: string[] = [];
109
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
110
+ const child = join(dir, entry.name);
111
+ if (entry.isDirectory()) paths.push(...await walkMarkdown(child, base));
112
+ else if (entry.isFile() && entry.name.endsWith(".md")) paths.push(child.slice(base.length + 1).split("\\").join("/"));
113
+ }
114
+ return paths;
115
+ }
116
+
117
+ function matcherFor(pattern: unknown): RegExp | undefined {
118
+ const normalized = assertGlobPattern(pattern);
119
+ return normalized === undefined ? undefined : globToRegExp(normalized);
120
+ }
121
+
122
+ /** Which homes one call iterates; reserved heads narrow traversal before any file is read. */
123
+ type HomeRef = { scope: Scope; who?: string };
124
+
125
+ async function homesForPattern(pattern: string | undefined, identity: NotesIdentity): Promise<HomeRef[] | undefined> {
126
+ if (!pattern || !pattern.startsWith("@")) return undefined;
127
+ const head = /^@([^/]+)\//.exec(pattern)?.[1];
128
+ if (head === "project") return [{ scope: "project" }];
129
+ if (head === "human") return [{ scope: "human" }];
130
+ if (head === "self") return [{ scope: "agent" }];
131
+ if (head === "model") return [{ scope: "model" }];
132
+ if (head === "agents" || head === "models") {
133
+ const scope: Scope = head === "agents" ? "agent" : "model";
134
+ const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
135
+ if (name.length > 0 && !/[*?]/.test(name)) return [{ scope, who: assertWho(name) }];
136
+ return (await namespaceSlugs(head, identity.home)).map((who) => ({ scope, who }));
137
+ }
138
+ return [];
139
+ }
140
+
141
+ /** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
142
+ function normalizePattern(pattern: string | undefined, identity: NotesIdentity): string | undefined {
143
+ if (!pattern) return pattern;
144
+ if (pattern.startsWith("@self/")) return `@agents/${identity.agent}/${pattern.slice("@self/".length)}`;
145
+ if (pattern.startsWith("@model/")) return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
146
+ return pattern;
147
+ }
148
+
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
+ function assertOrigin(value: unknown): Origin {
155
+ if (!isOrigin(value)) throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
156
+ return value;
157
+ }
158
+
159
+ function assertWho(value: unknown): string {
160
+ if (typeof value !== "string" || !SLUG_PATTERN.test(value)) {
161
+ throw new NoteError("invalid_scope", "who must be a canonical lowercase slug");
162
+ }
163
+ return value;
164
+ }
165
+
166
+ async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<HomeRef[]> {
167
+ if (opts.scope !== undefined) {
168
+ const scope = assertScope(opts.scope);
169
+ if (opts.who !== undefined) {
170
+ const who = assertWho(opts.who);
171
+ if (scope !== "agent" && scope !== "model") throw new NoteError("invalid_scope", "who is only valid with agent or model scope");
172
+ return [{ scope, who }];
173
+ }
174
+ return [{ scope }];
175
+ }
176
+ if (opts.who !== undefined) throw new NoteError("invalid_scope", "who requires agent or model scope");
177
+ return await homesForPattern(normalizePattern(opts.pattern, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
178
+ }
179
+
180
+ /**
181
+ * Line numbers (1-based) of every occurrence of `needle` in `body`. The scan walks forward
182
+ * once, counting newlines as it goes, so a body that repeats one anchor thousands of times
183
+ * costs one pass instead of one reslice per match.
184
+ */
185
+ function matchLineNumbers(body: string, needle: string): number[] {
186
+ const lines: number[] = [];
187
+ let line = 1;
188
+ let cursor = 0;
189
+ let scanned = 0;
190
+ for (;;) {
191
+ const index = body.indexOf(needle, cursor);
192
+ if (index === -1) break;
193
+ for (; scanned < index; scanned++) {
194
+ if (body.charCodeAt(scanned) === 10) line++;
195
+ }
196
+ lines.push(line);
197
+ cursor = index + Math.max(needle.length, 1);
198
+ }
199
+ return lines;
200
+ }
201
+
202
+ /**
203
+ * How many match lines a refusal names inline. A body can repeat one anchor thousands of
204
+ * times, so the message carries a bounded sample plus the exact total; the typed error keeps
205
+ * the complete list, and the wire bounds what it repeats of it.
206
+ */
207
+ const MAX_ANCHOR_LINES = 8;
208
+
209
+ function anchorLines(lines: number[]): string {
210
+ const named = lines.slice(0, MAX_ANCHOR_LINES);
211
+ const rest = lines.length - named.length;
212
+ return `lines ${named.join(", ")}${rest > 0 ? `, and ${rest} more` : ""}`;
213
+ }
214
+
215
+ /** Every mutation uses a tmp file renamed into place in the same directory. */
216
+ async function atomicWrite(path: string, content: string): Promise<void> {
217
+ await mkdir(dirname(path), { recursive: true });
218
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
219
+ try {
220
+ await writeFile(tmp, content);
221
+ await rename(tmp, path);
222
+ } catch (error) {
223
+ try { await rm(tmp, { force: true }); } catch { /* Preserve the original write/rename failure. */ }
224
+ throw error;
225
+ }
226
+ }
227
+
228
+ /** The byte cap is a write-time boundary rule, never a path-jail rule. */
229
+ function assertWritablePath(vpath: string): void {
230
+ 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})`);
232
+ }
233
+
234
+ function assertSerializedSize(content: string): void {
235
+ 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})`);
237
+ }
238
+
239
+ /** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
240
+ function frontmatterOf(meta: NoteMeta): string {
241
+ return serializeNote(meta, "").slice(0, -2);
242
+ }
243
+
244
+ /** Named agent/model homes are read-only to whoever is not running there. */
245
+ function assertWritableHome(scope: Scope, who: string | undefined, identity: NotesIdentity): void {
246
+ if (who === undefined) return;
247
+ const current = scope === "agent" ? identity.agent : identity.model;
248
+ if (who === current) return;
249
+ 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;
259
+ }
260
+
261
+ /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
262
+ export function createNotesStore(input: NotesIdentity): NotesStore {
263
+ const identity = snapshotNotesIdentity(input);
264
+
265
+ async function write(address: string, content: string, options: WriteOptions = {}): Promise<NoteWriteResult> {
266
+ const stableOptions = { ...options };
267
+ const destination = assertAddress(address);
268
+ assertWritablePath(destination.path);
269
+ const scope = destination.scope;
270
+ assertWritableHome(scope, destination.who, identity);
271
+ const origin = assertOrigin(stableOptions.origin ?? "self");
272
+ const path = physicalPath(scope, destination.path, identity, destination.who);
273
+ return withPathQueue(path, async () => {
274
+ const now = writeStamp();
275
+ const cleanBody = stripLeadingFrontmatter(content);
276
+ const existingRaw = await readFileIfExists(path);
277
+ const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
278
+ const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
279
+ const meta: NoteMeta = existing ?? {
280
+ scope,
281
+ origin,
282
+ createdAt: now,
283
+ updatedAt: now,
284
+ lastAccessed: now,
285
+ accessCount: 0,
286
+ ...(scope === "session" ? { project: identity.projectKey } : {}),
287
+ };
288
+ meta.scope = scope;
289
+ meta.origin = origin;
290
+ delete meta.crumpledAt;
291
+ meta.updatedAt = now;
292
+ const serialized = serializeNote(meta, cleanBody);
293
+ assertSerializedSize(serialized);
294
+ await atomicWrite(path, serialized);
295
+ return { meta, outcome };
296
+ });
297
+ }
298
+
299
+ async function read(address: string): Promise<NoteReadResult | undefined> {
300
+ const destination = assertAddress(address);
301
+ const scope = destination.scope;
302
+ const path = physicalPath(scope, destination.path, identity, destination.who);
303
+ return withPathQueue(path, async () => {
304
+ const raw = await readFileIfExists(path);
305
+ if (raw === undefined) return undefined;
306
+ const now = Date.now();
307
+ const parsed = parseNote(raw, now);
308
+ const meta = accessedMeta(parsed.meta, scope, now);
309
+ await atomicWrite(path, serializeNote(meta, parsed.body));
310
+ return { meta, body: parsed.body, resolvedScope: scope };
311
+ });
312
+ }
313
+
314
+ async function update(address: string, edits?: EditOperation[], options: EditOptions = {}): Promise<NoteEditResult> {
315
+ const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
316
+ const stableOptions = { ...options };
317
+ const destination = assertAddress(address);
318
+ assertWritablePath(destination.path);
319
+ const scope = destination.scope;
320
+ assertWritableHome(scope, destination.who, identity);
321
+ 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");
323
+ }
324
+ const path = physicalPath(scope, destination.path, identity, destination.who);
325
+ return withPathQueue(path, async () => {
326
+ const raw = await readFileIfExists(path);
327
+ if (raw === undefined) throw new NoteError("not_found", "note not found");
328
+ const { meta, body } = parseNote(raw);
329
+ meta.scope = scope;
330
+ const beforeMeta: NoteMeta = { ...meta };
331
+ let next = body;
332
+ let applied = 0;
333
+ operations.forEach((operation, index) => {
334
+ const oldText = operation?.oldText;
335
+ 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 });
338
+ 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 });
340
+ 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 });
342
+ }
343
+ if (oldText !== newText) applied++;
344
+ // Positional splicing preserves user replacement text byte-for-byte.
345
+ if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
346
+ else {
347
+ const matchIndex = next.indexOf(oldText);
348
+ next = next.substring(0, matchIndex) + newText + next.substring(matchIndex + oldText.length);
349
+ }
350
+ });
351
+ if (stableOptions.origin !== undefined) meta.origin = assertOrigin(stableOptions.origin);
352
+ if (stableOptions.crumpled === true && meta.crumpledAt === undefined) meta.crumpledAt = localIso(Date.now());
353
+ if (stableOptions.crumpled === false) delete meta.crumpledAt;
354
+ const bodyChanged = body !== next;
355
+ const originChanged = beforeMeta.origin !== meta.origin;
356
+ if (bodyChanged || originChanged) meta.updatedAt = writeStamp();
357
+ const serialized = serializeNote(meta, next);
358
+ assertSerializedSize(serialized);
359
+ const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
360
+ let change: NoteChange;
361
+ if (bodyChanged && metadataChanged) change = { kind: "file", before: raw, after: serialized };
362
+ else if (bodyChanged) change = { kind: "body", before: body, after: next };
363
+ else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
364
+ else change = { kind: "none", before: "", after: "" };
365
+ await atomicWrite(path, serialized);
366
+ return { meta, applied, resolvedScope: scope, change };
367
+ });
368
+ }
369
+
370
+ /**
371
+ * Move one note to a new address with every metadata key preserved. Both ends must be
372
+ * writable; a live target refuses, a crumpled target is replaced. Locks both paths in
373
+ * sorted order so crossed renames cannot deadlock.
374
+ */
375
+ async function rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult> {
376
+ const from = assertAddress(fromAddress);
377
+ const to = assertAddress(toAddress);
378
+ const fromScope = from.scope;
379
+ const toScope = to.scope;
380
+ assertWritablePath(to.path);
381
+ assertWritableHome(fromScope, from.who, identity);
382
+ assertWritableHome(toScope, to.who, identity);
383
+ const fromPath = physicalPath(fromScope, from.path, identity, from.who);
384
+ const toPath = physicalPath(toScope, to.path, identity, to.who);
385
+ if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
386
+ const [first, second] = [fromPath, toPath].sort();
387
+ return withPathQueue(first!, () => withPathQueue(second!, async () => {
388
+ const raw = await readFileIfExists(fromPath);
389
+ if (raw === undefined) throw new NoteError("not_found", "note not found");
390
+ const targetRaw = await readFileIfExists(toPath);
391
+ if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
392
+ throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
393
+ }
394
+ const { meta, body } = parseNote(raw);
395
+ meta.scope = toScope;
396
+ // Project ownership only changes when the move crosses the session boundary.
397
+ if (fromScope !== "session" && toScope === "session") meta.project = identity.projectKey;
398
+ if (fromScope === "session" && toScope !== "session") delete meta.project;
399
+ meta.updatedAt = writeStamp();
400
+ const serialized = serializeNote(meta, body);
401
+ assertSerializedSize(serialized);
402
+ await atomicWrite(toPath, serialized);
403
+ await rm(fromPath, { force: true });
404
+ return { meta, replacedCrumpledTarget: targetRaw !== undefined };
405
+ }));
406
+ }
407
+
408
+ async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
409
+ const matcher = matcherFor(normalizePattern(options.pattern, identity));
410
+ let homes: HomeRef[];
411
+ try {
412
+ homes = await homesFor(identity, options);
413
+ } catch (error) {
414
+ if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.pattern ?? "")) throw error;
415
+ status.homesUnavailable.push(options.pattern!.startsWith("@agents/") ? "@agents" : "@models");
416
+ return;
417
+ }
418
+ for (const home of homes) {
419
+ const scope = home.scope;
420
+ const root = scopeDir(scope, identity, home.who);
421
+ const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
422
+ let excluded = 0;
423
+ try {
424
+ for (const path of await walkMarkdown(root)) {
425
+ if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
426
+ const address = addressFor(identity, scope, path, home.who);
427
+ const fullPath = join(root, path);
428
+ const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
429
+ const { meta, body } = parseNote(raw);
430
+ meta.scope = scope;
431
+ if ((meta.crumpledAt !== undefined) !== (options.wastebasket === true)) {
432
+ if (meta.crumpledAt !== undefined) excluded++;
433
+ continue;
434
+ }
435
+ homeRows.push({ address, scope, path, meta, body });
436
+ }
437
+ } catch (error) {
438
+ if (!status || !isFilesystemError(error)) throw error;
439
+ status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
440
+ continue;
441
+ }
442
+ if (status) status.crumpledExcluded += excluded;
443
+ for (const row of homeRows) yield row;
444
+ }
445
+ }
446
+
447
+ async function list(options: NotesQuery = {}): Promise<NoteRow[]> {
448
+ return (await listRows(options)).rows;
449
+ }
450
+
451
+ async function listRows(options: NotesQuery, status?: NoteQueryStatus): Promise<NoteQueryResult<NoteRow>> {
452
+ const stableOptions = { ...options } as NotesQuery;
453
+ const rows: NoteRow[] = [];
454
+ for await (const row of scan(stableOptions, status)) {
455
+ rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
456
+ }
457
+ rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
458
+ return { rows, status: status ?? { crumpledExcluded: 0, homesUnavailable: [] } };
459
+ }
460
+
461
+ function listWithStatus(options: NotesQuery = {}): Promise<NoteQueryResult<NoteRow>> {
462
+ return listRows(options, { crumpledExcluded: 0, homesUnavailable: [] });
463
+ }
464
+
465
+ async function search(queries: string[], options: NotesQuery = {}): Promise<NoteSearchRow[]> {
466
+ return (await searchRows(queries, options)).rows;
467
+ }
468
+
469
+ async function searchRows(queries: string[], options: NotesQuery, status?: NoteQueryStatus): Promise<NoteQueryResult<NoteSearchRow>> {
470
+ const stableQueries = [...queries];
471
+ const stableOptions = { ...options } as NotesQuery;
472
+ const rows: NoteSearchRow[] = [];
473
+ for await (const note of scan(stableOptions, status)) {
474
+ const { address, path, scope, meta, body } = note;
475
+ // Offsets address the note body alone: no frontmatter length is predicted, so an
476
+ // access-counter rewrite cannot move a match out from under the caller.
477
+ let baseChars = 0;
478
+ const matches: NoteMatch[] = [];
479
+ for (const [index, line] of body.split("\n").entries()) {
480
+ const offset = earliestMatchOffsetChars(line, stableQueries);
481
+ if (offset >= 0) {
482
+ matches.push({ line: index + 1, text: line, offsetChars: baseChars + offset });
483
+ }
484
+ baseChars += Array.from(line).length + 1;
485
+ }
486
+ if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
487
+ }
488
+ rows.sort((a, b) => a.address.localeCompare(b.address));
489
+ return { rows, status: status ?? { crumpledExcluded: 0, homesUnavailable: [] } };
490
+ }
491
+
492
+ function searchWithStatus(queries: string[], options: NotesQuery = {}): Promise<NoteQueryResult<NoteSearchRow>> {
493
+ return searchRows(queries, options, { crumpledExcluded: 0, homesUnavailable: [] });
494
+ }
495
+
496
+ return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
497
+ }
package/src/pi/boot.ts ADDED
@@ -0,0 +1,88 @@
1
+ import { PI_TOOL_NAMES } from "./tool-names.js";
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { notesIdentityFromPi } from "./notes/adapter.js";
4
+ import { loadNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
5
+ import { BOOT_TYPE } from "./entries.js";
6
+ import { renderBootBlock } from "../boot/render.js";
7
+ import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
8
+ import { repairResetTail } from "./reset/artifacts.js";
9
+
10
+ export type IncompleteNotesNotifier = (ctx: ExtensionContext, windowId: string, snapshot: NotesSnapshot) => void;
11
+
12
+ /** The boot custom message: identity, notes snapshot, and static protocol; never reset prose. */
13
+ export type BootMessage = {
14
+ readonly customType: string;
15
+ readonly content: string;
16
+ readonly display: false;
17
+ readonly details: { windowId: string };
18
+ };
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
+ /**
33
+ * Acquire one notes snapshot and build the boot custom message for a window. All identity
34
+ * fields are captured synchronously before the first filesystem await.
35
+ */
36
+ export async function buildBootMessage(
37
+ ctx: ExtensionContext,
38
+ windowId: string,
39
+ previousId: string | undefined,
40
+ notifyIncompleteNotes?: IncompleteNotesNotifier,
41
+ isCurrent: () => boolean = () => true,
42
+ ): Promise<BootMessage> {
43
+ const identity = notesIdentityFromPi(ctx);
44
+ const notes = await loadNotesSnapshot(identity, Date.now());
45
+ if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
46
+ return {
47
+ customType: BOOT_TYPE,
48
+ content: bootContent(identity.agent, identity.model, rootWindowId(identity.sessionId), windowId, previousId, notes),
49
+ display: false,
50
+ details: { windowId },
51
+ };
52
+ }
53
+
54
+ /** Persist one hidden boot message without triggering a model turn. */
55
+ export function sendBoot(pi: ExtensionAPI, boot: BootMessage): void {
56
+ pi.sendMessage(
57
+ { customType: boot.customType, content: boot.content, display: boot.display, details: boot.details },
58
+ { triggerTurn: false },
59
+ );
60
+ }
61
+
62
+ /**
63
+ * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
64
+ * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
65
+ */
66
+ export async function ensureBoot(
67
+ pi: ExtensionAPI,
68
+ ctx: ExtensionContext,
69
+ notifyIncompleteNotes?: IncompleteNotesNotifier,
70
+ isCurrent: () => boolean = () => true,
71
+ ): Promise<void> {
72
+ const sessionId = ctx.sessionManager.getSessionId();
73
+ const reset = currentReset(ctx);
74
+ const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
75
+ const stillCurrent = () => isCurrent() &&
76
+ ctx.signal?.aborted !== true &&
77
+ ctx.sessionManager.getSessionId() === sessionId &&
78
+ currentWindowId(ctx) === windowId;
79
+ if (reset) {
80
+ await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
81
+ return;
82
+ }
83
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
84
+ const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
85
+ if (!stillCurrent()) return;
86
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
87
+ sendBoot(pi, boot);
88
+ }