notesoup 0.53.2 → 0.54.1

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 (186) hide show
  1. package/README.md +6 -4
  2. package/dist/plugins/claude/src/helper.d.ts +2 -1
  3. package/dist/plugins/claude/src/helper.js +21 -24
  4. package/dist/plugins/claude/src/history.d.ts +3 -14
  5. package/dist/plugins/claude/src/history.js +2 -298
  6. package/dist/plugins/claude/src/text.d.ts +0 -1
  7. package/dist/plugins/claude/src/text.js +0 -1
  8. package/dist/plugins/codex/src/history.d.ts +3 -8
  9. package/dist/plugins/codex/src/history.js +2 -238
  10. package/dist/plugins/codex/src/hooks.js +1 -1
  11. package/dist/plugins/codex/src/identity.d.ts +1 -1
  12. package/dist/plugins/codex/src/identity.js +3 -3
  13. package/dist/plugins/codex/src/mcp.js +9 -8
  14. package/dist/plugins/codex/src/text.d.ts +1 -1
  15. package/dist/plugins/codex/src/text.js +2 -2
  16. package/dist/plugins/codex/src/transcript.d.ts +3 -39
  17. package/dist/plugins/codex/src/transcript.js +2 -313
  18. package/dist/plugins/dsh/engine.js +2 -2
  19. package/dist/plugins/dsh/history.d.ts +3 -0
  20. package/dist/plugins/dsh/history.js +15 -0
  21. package/dist/plugins/dsh/tools.js +12 -12
  22. package/dist/plugins/dsh/window.d.ts +1 -0
  23. package/dist/plugins/dsh/window.js +7 -3
  24. package/dist/plugins/pi/history-tools.d.ts +1 -1
  25. package/dist/plugins/pi/history-tools.js +9 -5
  26. package/dist/plugins/pi/history.d.ts +2 -3
  27. package/dist/plugins/pi/history.js +4 -147
  28. package/dist/plugins/pi/notes/tools.js +8 -6
  29. package/dist/plugins/pi/render.js +7 -4
  30. package/dist/plugins/pi/runtime.js +2 -2
  31. package/dist/plugins/pi/window.js +21 -7
  32. package/dist/src/boot/render.js +9 -11
  33. package/dist/src/boot/snapshot.d.ts +7 -7
  34. package/dist/src/boot/snapshot.js +17 -17
  35. package/dist/src/boot/text.d.ts +5 -3
  36. package/dist/src/boot/text.js +18 -10
  37. package/dist/src/dream/git.d.ts +2 -11
  38. package/dist/src/dream/git.js +6 -23
  39. package/dist/src/dream/lock.d.ts +2 -2
  40. package/dist/src/dream/lock.js +3 -3
  41. package/dist/src/history/claude.d.ts +16 -0
  42. package/dist/src/history/claude.js +336 -0
  43. package/dist/src/history/codex-transcript.d.ts +39 -0
  44. package/dist/src/history/codex-transcript.js +315 -0
  45. package/dist/src/history/codex.d.ts +8 -0
  46. package/dist/src/history/codex.js +238 -0
  47. package/dist/src/history/corpus.d.ts +35 -0
  48. package/dist/src/history/corpus.js +54 -0
  49. package/dist/src/history/history.d.ts +4 -8
  50. package/dist/src/history/history.js +3 -11
  51. package/dist/src/history/local.d.ts +17 -0
  52. package/dist/src/history/local.js +101 -0
  53. package/dist/src/history/pi.d.ts +36 -0
  54. package/dist/src/history/pi.js +202 -0
  55. package/dist/src/history/query.d.ts +15 -5
  56. package/dist/src/history/query.js +42 -13
  57. package/dist/src/index.d.ts +6 -3
  58. package/dist/src/index.js +6 -4
  59. package/dist/src/notes/address.d.ts +8 -8
  60. package/dist/src/notes/address.js +13 -13
  61. package/dist/src/notes/errors.d.ts +1 -1
  62. package/dist/src/notes/frontmatter.js +2 -2
  63. package/dist/src/notes/index.d.ts +1 -1
  64. package/dist/src/notes/index.js +1 -1
  65. package/dist/src/notes/paths.d.ts +6 -6
  66. package/dist/src/notes/paths.js +9 -9
  67. package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
  68. package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
  69. package/dist/src/notes/store.d.ts +4 -4
  70. package/dist/src/notes/store.js +55 -52
  71. package/dist/src/tools/dream.d.ts +21 -3
  72. package/dist/src/tools/dream.js +54 -16
  73. package/dist/src/tools/history.d.ts +7 -19
  74. package/dist/src/tools/history.js +80 -93
  75. package/dist/src/tools/notes-context.d.ts +10 -0
  76. package/dist/src/tools/notes-context.js +27 -0
  77. package/dist/src/tools/notes.d.ts +69 -20
  78. package/dist/src/tools/notes.js +40 -31
  79. package/dist/test/boot.integration.test.js +2 -3
  80. package/dist/test/claude-history.test.js +47 -34
  81. package/dist/test/claude-mod.test.js +96 -50
  82. package/dist/test/codex-history.test.js +4 -10
  83. package/dist/test/codex-plugin.test.js +50 -12
  84. package/dist/test/context-edit-budget.test.js +121 -0
  85. package/dist/test/dependencies.test.js +73 -6
  86. package/dist/test/dream-tools.test.js +153 -8
  87. package/dist/test/dsh.test.js +88 -19
  88. package/dist/test/helpers/dsh.d.ts +4 -1
  89. package/dist/test/helpers/dsh.js +20 -4
  90. package/dist/test/helpers/extension.d.ts +5 -1
  91. package/dist/test/helpers/extension.js +33 -2
  92. package/dist/test/helpers/history-corpus.d.ts +7 -0
  93. package/dist/test/helpers/history-corpus.js +26 -0
  94. package/dist/test/history-corpus.test.js +307 -0
  95. package/dist/test/history.integration.test.js +40 -48
  96. package/dist/test/host-neutral.test.js +20 -33
  97. package/dist/test/model-facing-text.test.js +14 -8
  98. package/dist/test/notes-cwd.test.d.ts +1 -0
  99. package/dist/test/notes-cwd.test.js +114 -0
  100. package/dist/test/notes-library.test.js +4 -4
  101. package/dist/test/notes-query-namespaces.test.d.ts +1 -0
  102. package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
  103. package/dist/test/notes.integration.test.js +73 -24
  104. package/dist/test/notes.test.js +51 -21
  105. package/dist/test/pi-render.test.js +33 -1
  106. package/dist/test/project-namespace.test.d.ts +1 -0
  107. package/dist/test/project-namespace.test.js +324 -0
  108. package/docs/architecture.md +19 -12
  109. package/docs/claude-code-mod.md +7 -5
  110. package/docs/codex.md +6 -6
  111. package/docs/dsh.md +9 -9
  112. package/docs/history-sessions.md +52 -0
  113. package/docs/notes-library.md +9 -5
  114. package/docs/skills.md +3 -3
  115. package/docs/tool-results.md +14 -8
  116. package/package.json +4 -6
  117. package/playbook.md +6 -6
  118. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  119. package/plugins/claude/dist/claude/helper.js +2164 -1341
  120. package/plugins/claude/hooks/register.ts +19 -11
  121. package/plugins/claude/playbook.md +6 -6
  122. package/plugins/claude/skills/memory/SKILL.md +9 -7
  123. package/plugins/claude/src/helper.ts +22 -25
  124. package/plugins/claude/src/history.ts +3 -257
  125. package/plugins/claude/src/text.ts +0 -1
  126. package/plugins/codex/README.md +1 -1
  127. package/plugins/codex/dist/codex/notesoup.js +1582 -969
  128. package/plugins/codex/src/history.ts +3 -193
  129. package/plugins/codex/src/hooks.ts +1 -1
  130. package/plugins/codex/src/identity.ts +3 -3
  131. package/plugins/codex/src/mcp.ts +9 -8
  132. package/plugins/codex/src/text.ts +2 -2
  133. package/plugins/codex/src/transcript.ts +3 -275
  134. package/plugins/dsh/engine.ts +2 -2
  135. package/plugins/dsh/history.ts +17 -0
  136. package/plugins/dsh/tools.ts +12 -12
  137. package/plugins/dsh/window.ts +8 -3
  138. package/plugins/paseo/OVERVIEW.md +4 -4
  139. package/plugins/paseo/README.md +1 -1
  140. package/plugins/paseo/client/brain-empty-card.tsx +3 -4
  141. package/plugins/paseo/client/markdown.tsx +159 -0
  142. package/plugins/paseo/client/notes-op-card.tsx +35 -34
  143. package/plugins/paseo/client/notes-op-transformer.ts +17 -68
  144. package/plugins/paseo/client/paper-card.tsx +8 -19
  145. package/plugins/paseo/client/paper-palette.ts +40 -0
  146. package/plugins/paseo/client/sticky-card.tsx +6 -4
  147. package/plugins/paseo/package.json +3 -0
  148. package/plugins/paseo/paseo-plugin.json +2 -2
  149. package/plugins/paseo/shared/notes-op.ts +13 -9
  150. package/plugins/paseo/test/notes-op.test.ts +52 -73
  151. package/plugins/paseo/test/paper-palette.test.ts +54 -0
  152. package/plugins/pi/history-tools.ts +11 -5
  153. package/plugins/pi/history.ts +8 -157
  154. package/plugins/pi/notes/tools.ts +8 -6
  155. package/plugins/pi/render.ts +6 -4
  156. package/plugins/pi/runtime.ts +2 -2
  157. package/plugins/pi/window.ts +22 -7
  158. package/skills/memory/SKILL.md +9 -7
  159. package/src/boot/render.ts +10 -13
  160. package/src/boot/snapshot.ts +20 -20
  161. package/src/boot/text.ts +18 -10
  162. package/src/dream/git.ts +7 -24
  163. package/src/dream/lock.ts +3 -3
  164. package/src/history/claude.ts +286 -0
  165. package/src/history/codex-transcript.ts +276 -0
  166. package/src/history/codex.ts +193 -0
  167. package/src/history/corpus.ts +69 -0
  168. package/src/history/history.ts +5 -12
  169. package/src/history/local.ts +93 -0
  170. package/src/history/pi.ts +199 -0
  171. package/src/history/query.ts +45 -15
  172. package/src/index.ts +8 -5
  173. package/src/notes/address.ts +13 -13
  174. package/src/notes/errors.ts +1 -1
  175. package/src/notes/frontmatter.ts +2 -2
  176. package/src/notes/index.ts +1 -1
  177. package/src/notes/paths.ts +9 -9
  178. package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
  179. package/src/notes/store.ts +61 -58
  180. package/src/tools/dream.ts +63 -16
  181. package/src/tools/history.ts +71 -101
  182. package/src/tools/notes-context.ts +29 -0
  183. package/src/tools/notes.ts +39 -29
  184. package/dist/test/project-home.test.js +0 -134
  185. /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
  186. /package/dist/test/{project-home.test.d.ts → history-corpus.test.d.ts} +0 -0
@@ -0,0 +1,93 @@
1
+ /** Local read-only corpus. Wire decoders have no SDK dependencies; DSH supplies its query service. */
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { piHistoryFromJsonl } from "./pi.js";
6
+ import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
7
+ import { readCodexHistory } from "./codex.js";
8
+ import { sessionIdentity, type HistoryCorpus, type HistoryHarness, type HistorySession, type HistorySessionData } from "./corpus.js";
9
+
10
+ export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
11
+ export type LocalHistoryOptions = {
12
+ current: { harness: HistoryHarness; id: string; load(): Promise<HistorySessionData> };
13
+ /** Undefined uses the harness default; null disables that harness's filesystem discovery. */
14
+ roots?: LocalHistoryRoots;
15
+ home?: string;
16
+ env?: NodeJS.ProcessEnv;
17
+ /** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
18
+ dshSessions?: () => Promise<HistorySession[]>;
19
+ };
20
+
21
+ function rootsFor(options: LocalHistoryOptions): LocalHistoryRoots {
22
+ const env = options.env ?? process.env;
23
+ const home = options.home ?? env.HOME ?? homedir();
24
+ return {
25
+ pi: options.roots?.pi !== undefined ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join(env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent"), "sessions"),
26
+ claude: options.roots?.claude !== undefined ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects"),
27
+ codex: options.roots?.codex !== undefined ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join(env.CODEX_HOME ?? join(home, ".codex"), "sessions"),
28
+ };
29
+ }
30
+
31
+ /** Match the native layouts, without following symlinks or wandering into subagent/attachment stores. */
32
+ async function filesAt(root: string, depth: number): Promise<string[]> {
33
+ let entries;
34
+ try { entries = await readdir(root, { withFileTypes: true }); }
35
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
36
+ const paths: string[] = [];
37
+ for (const entry of entries) {
38
+ const path = join(root, entry.name);
39
+ if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
40
+ else if (entry.isFile() && depth === 0) paths.push(path);
41
+ }
42
+ return paths;
43
+ }
44
+
45
+ async function localSessions(harness: "pi" | "claude" | "codex", root: string): Promise<HistorySession[]> {
46
+ const paths = await filesAt(root, harness === "codex" ? 3 : 1);
47
+ const sessions: HistorySession[] = [];
48
+ for (const path of paths) {
49
+ const name = path.split(/[\\/]/).at(-1)!;
50
+ const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
51
+ : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
52
+ : /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
53
+ if (!id) continue;
54
+ let modifiedAt: number;
55
+ try { modifiedAt = (await stat(path)).mtimeMs; }
56
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
57
+ sessions.push({
58
+ harness, id, modifiedAt,
59
+ async load() {
60
+ if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
61
+ const text = await readFile(path, "utf8");
62
+ if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
63
+ const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
64
+ const missing = projection.missingAncestors;
65
+ return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
66
+ },
67
+ });
68
+ }
69
+ return sessions;
70
+ }
71
+
72
+ /** Fresh discovery per call; a live binding wins over its persisted descriptor. No transcript writes. */
73
+ export function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus {
74
+ return {
75
+ currentHarness: options.current.harness,
76
+ async sessions(onlyHarness) {
77
+ const roots = rootsFor(options);
78
+ const discovered: HistorySession[] = [];
79
+ for (const harness of ["pi", "claude", "codex"] as const) {
80
+ if (onlyHarness !== undefined && onlyHarness !== harness) continue;
81
+ const root = roots[harness];
82
+ if (root != null) discovered.push(...await localSessions(harness, root));
83
+ }
84
+ if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
85
+ discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
86
+ const unique = new Map<string, HistorySession>();
87
+ for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
88
+ const current = { ...options.current, modifiedAt: Date.now() };
89
+ if (onlyHarness === undefined || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
90
+ return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,199 @@
1
+ /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
+ import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection, type RecordedNestedCalls, type ToolCallStatus } from "./history.js";
3
+
4
+ type ToolCall = { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> };
5
+ /** Structural views also accept native SDK values without converting or allocating seqs twice. */
6
+ type Message = {
7
+ role: string; content?: unknown; output?: string; summary?: string; command?: string;
8
+ cancelled?: boolean; exitCode?: number; truncated?: boolean; fullOutputPath?: string;
9
+ toolName?: string; toolCallId?: string; isError?: boolean; nestedCalls?: RecordedNestedCalls;
10
+ };
11
+ export type PiHistoryEntry = {
12
+ type: string; id: string; parentId?: string | null; timestamp?: string;
13
+ message?: Message; summary?: string; customType?: string; data?: unknown; content?: unknown;
14
+ };
15
+
16
+ function mapRole(role: string): DecodedHistoryItem["role"] | undefined {
17
+ if (role === "user" || role === "assistant") return role;
18
+ if (role === "toolResult" || role === "bashExecution") return "tool";
19
+ if (role === "custom") return "developer";
20
+ if (role === "compactionSummary" || role === "branchSummary") return "system";
21
+ return undefined;
22
+ }
23
+
24
+ function isToolCall(part: unknown): part is ToolCall {
25
+ return typeof part === "object" && part !== null && (part as { type?: unknown }).type === "toolCall";
26
+ }
27
+
28
+ /** Seq allocation depends on entry kind and role, never on visible content. */
29
+ export function piSequenceCount(entry: Pick<PiHistoryEntry, "type" | "message">): number {
30
+ if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
31
+ if (entry.type !== "message" || !entry.message || mapRole(entry.message.role) === undefined) return 0;
32
+ if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
33
+ return 1 + entry.message.content.filter(isToolCall).length;
34
+ }
35
+
36
+ function messageContent(message: Message): string {
37
+ switch (message.role) {
38
+ case "bashExecution":
39
+ return message.output ?? "";
40
+ case "branchSummary":
41
+ case "compactionSummary":
42
+ return message.summary ?? "";
43
+ default:
44
+ return contentText(message.content);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Pass the host's nested-call record through as recorded. It is evidence about calls this run made,
50
+ * not a second transcript: the host stores no nested results, and this lane invents none.
51
+ */
52
+ function nestedCallsOf(message: Message): RecordedNestedCalls | undefined {
53
+ if (message.role !== "toolResult" || message.nestedCalls === undefined) return undefined;
54
+ return { calls: message.nestedCalls.calls, complete: message.nestedCalls.complete };
55
+ }
56
+
57
+ function toolInfo(message: Message): Pick<DecodedHistoryItem, "toolName" | "arguments" | "outputTruncated" | "fullOutputPath" | "toolError" | "toolCallId" | "nestedCalls" | "recordedStatus"> {
58
+ if (message.role === "bashExecution") {
59
+ // A standalone bash run records its own outcome, so its status is read here rather than
60
+ // inferred from a result message that will never arrive: a cancelled or nonzero run is an
61
+ // error, and a run with no recorded exit code stays unknown instead of being called ok.
62
+ const status: ToolCallStatus = message.cancelled === true ? "error" : typeof message.exitCode === "number" ? (message.exitCode === 0 ? "ok" : "error") : "unfinished";
63
+ // A truncated run is only half the record without the on-disk path: surface both.
64
+ return { toolName: "bash", arguments: { command: message.command }, recordedStatus: status, outputTruncated: message.truncated || undefined, fullOutputPath: message.truncated ? message.fullOutputPath : undefined };
65
+ }
66
+ if (message.role !== "toolResult") return {};
67
+ const nestedCalls = nestedCallsOf(message);
68
+ return {
69
+ toolName: message.toolName,
70
+ toolCallId: message.toolCallId,
71
+ toolError: message.isError === true ? true : undefined,
72
+ ...(nestedCalls ? { nestedCalls } : {}),
73
+ };
74
+ }
75
+
76
+ function toolCallItems(windowId: string, entry: { id: string; timestamp?: string }, message: Message, entrySeq: number): DecodedHistoryItem[] {
77
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
78
+ const items: DecodedHistoryItem[] = [];
79
+ let callIndex = 0;
80
+ for (const part of message.content) {
81
+ if (!isToolCall(part)) continue;
82
+ items.push({
83
+ seq: entrySeq + callIndex + 1,
84
+ windowId,
85
+ role: "tool_call",
86
+ text: "",
87
+ createdAt: entry.timestamp,
88
+ toolName: part.name,
89
+ toolCallId: part.id,
90
+ arguments: part.arguments,
91
+ });
92
+ callIndex += 1;
93
+ }
94
+ return items;
95
+ }
96
+
97
+ /** Build stable internal addresses, then project the active branch into public events. */
98
+ export function piHistoryFromEntries(sessionId: string, entries: readonly PiHistoryEntry[], branch: readonly PiHistoryEntry[]): HistoryProjection {
99
+ const seqByEntryId = new Map<string, number>();
100
+ let nextSeq = 1;
101
+ for (const entry of entries) {
102
+ const count = piSequenceCount(entry);
103
+ if (count === 0) continue;
104
+ seqByEntryId.set(entry.id, nextSeq);
105
+ nextSeq += count;
106
+ }
107
+ const highestSeq = nextSeq - 1;
108
+
109
+ let window: DecodedHistoryWindow = { windowId: `pcw:${sessionId.slice(0, 8)}:root`, items: [] };
110
+ const rawWindows = [window];
111
+ const branchSeqs = new Set<number>();
112
+
113
+ for (const entry of branch) {
114
+ if (entry.type === "custom" && entry.customType === "notesoup/reset-marker" && typeof entry.data === "object" && entry.data !== null && "windowId" in entry.data && typeof entry.data.windowId === "string" && entry.data.windowId.length > 0) {
115
+ window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
116
+ rawWindows.push(window);
117
+ continue;
118
+ }
119
+ const entrySeq = seqByEntryId.get(entry.id);
120
+ if (entrySeq === undefined) continue;
121
+ branchSeqs.add(entrySeq);
122
+
123
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
124
+ window.items.push({ seq: entrySeq, windowId: window.windowId, role: "system", text: entry.summary ?? "", createdAt: entry.timestamp });
125
+ continue;
126
+ }
127
+ if (entry.type === "message" && entry.message) {
128
+ const role = mapRole(entry.message.role);
129
+ if (!role) continue;
130
+ window.items.push({
131
+ seq: entrySeq,
132
+ windowId: window.windowId,
133
+ role,
134
+ text: messageContent(entry.message),
135
+ createdAt: entry.timestamp,
136
+ ...toolInfo(entry.message),
137
+ });
138
+ const calls = toolCallItems(window.windowId, entry, entry.message, entrySeq);
139
+ for (const call of calls) branchSeqs.add(call.seq);
140
+ window.items.push(...calls);
141
+ continue;
142
+ }
143
+ if (entry.type === "custom_message") {
144
+ window.items.push({
145
+ seq: entrySeq,
146
+ windowId: window.windowId,
147
+ role: "developer",
148
+ text: contentText(entry.content),
149
+ createdAt: entry.timestamp,
150
+ });
151
+ }
152
+ }
153
+
154
+ return projectHistory(rawWindows, highestSeq, branchSeqs);
155
+ }
156
+
157
+ /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
158
+ export function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection {
159
+ const lines = text.split("\n");
160
+ const entries: PiHistoryEntry[] = [];
161
+ let header = false;
162
+ for (let index = 0; index < lines.length; index++) {
163
+ const line = lines[index]!;
164
+ if (line.trim() === "") continue;
165
+ let row: PiHistoryEntry;
166
+ try { row = JSON.parse(line) as PiHistoryEntry; }
167
+ catch {
168
+ if (index === lines.length - 1 && !text.endsWith("\n")) break;
169
+ throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
170
+ }
171
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
172
+ if (!header) {
173
+ if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
174
+ header = true;
175
+ continue;
176
+ }
177
+ if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
178
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
179
+ entries.push(row);
180
+ }
181
+ if (!header) throw new Error("Pi transcript has no session header");
182
+ const byId = new Map<string, PiHistoryEntry>();
183
+ for (const entry of entries) {
184
+ if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
185
+ byId.set(entry.id, entry);
186
+ }
187
+ const branch: PiHistoryEntry[] = [], seen = new Set<string>();
188
+ let cursor = entries.at(-1);
189
+ while (cursor) {
190
+ if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
191
+ seen.add(cursor.id);
192
+ branch.push(cursor);
193
+ if (cursor.parentId === null) break;
194
+ const parent = byId.get(cursor.parentId!);
195
+ if (!parent) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
196
+ cursor = parent;
197
+ }
198
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
199
+ }
@@ -6,8 +6,8 @@ import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
7
7
  import { eventDocument, filteredItems, 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";
8
8
 
9
- type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
- type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow };
9
+ type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean };
11
11
 
12
12
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
13
13
  export type HistoryOrder = "newest" | "oldest";
@@ -18,6 +18,7 @@ export type HistoryOrder = "newest" | "oldest";
18
18
  * every role, with no folded rows.
19
19
  */
20
20
  export type HistorySelection = HistoryFilter & {
21
+ session?: string;
21
22
  from?: HistoryOrder;
22
23
  limit?: number;
23
24
  query?: string | string[];
@@ -51,15 +52,18 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
51
52
 
52
53
  /** The params to merge into the previous call to continue toward older events. */
53
54
  export const HistoryOlderSchema = Type.Object({
55
+ session: Type.Optional(Type.String()),
54
56
  before_seq: Type.Integer({ minimum: 1 }),
55
57
  }, { additionalProperties: false });
56
58
  /** The params to merge into the previous call to continue toward newer events. */
57
59
  export const HistoryNewerSchema = Type.Object({
60
+ session: Type.Optional(Type.String()),
58
61
  after_seq: Type.Integer({ minimum: 1 }),
59
62
  from: Type.Literal("oldest"),
60
63
  }, { additionalProperties: false });
61
64
 
62
65
  export const HistoryPageSchema = Type.Object({
66
+ notice: Type.Optional(Type.String()),
63
67
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
64
68
  page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
65
69
  page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
@@ -84,7 +88,7 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
84
88
  }
85
89
 
86
90
  /** Summarize one already ordered gap; omitted tool names never change its exact count. */
87
- function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
91
+ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow | undefined {
88
92
  if (events.length === 0) return undefined;
89
93
  const counts = new Map<string, number>();
90
94
  for (const event of events) {
@@ -95,7 +99,7 @@ function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
95
99
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
96
100
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
97
101
  const tools = Object.fromEntries(entries);
98
- return { folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
102
+ return { ...(session === undefined ? {} : { session }), folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
99
103
  }
100
104
 
101
105
  /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
@@ -112,26 +116,27 @@ function prepareSelection(projection: HistoryProjection, params: HistorySelectio
112
116
  if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
113
117
  const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
114
118
  if (matchOffset !== undefined && matchOffset < 0) continue;
115
- candidates.push({ event, matchOffset, before: foldedRun(run) });
119
+ candidates.push({ event, ...(params.session === undefined ? {} : { session: params.session }), matchOffset, before: foldedRun(run, params.session) });
116
120
  run = [];
117
121
  }
118
- return { candidates, tail: foldedRun(run) };
122
+ return { candidates, session: params.session, tail: foldedRun(run, params.session) };
119
123
  }
120
124
 
121
125
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
122
126
  function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
123
127
  const { candidates, tail } = prepared;
128
+ const identity = prepared.session === undefined ? {} : { session: prepared.session };
124
129
  const items: HistoryPage["items"] = [];
125
130
  for (let index = start; index < end; index++) {
126
131
  const candidate = candidates[index]!;
127
132
  if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
128
- items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
133
+ items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
129
134
  }
130
135
  if (end === candidates.length && tail) items.push(tail);
131
136
  return {
132
137
  items,
133
- page_older: start > 0 && start < end ? { before_seq: candidates[start]!.event.seq } : null,
134
- page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
138
+ page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start]!.event.seq } : null,
139
+ page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
135
140
  };
136
141
  }
137
142
 
@@ -139,18 +144,42 @@ function pageData(prepared: PreparedSelection, start: number, end: number, maxCh
139
144
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
140
145
  * Grow the page in selection order; shorten the first preview only when no full row fits.
141
146
  */
142
- export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
147
+ function resolveSelection(params: HistorySelection): Outcome<HistorySelection> {
143
148
  const bounds = resolveTimeBounds(params);
144
149
  if (!bounds.ok) return bounds;
145
- let queries: string[];
146
150
  try {
147
- queries = searchQueries(params.query);
151
+ const queries = searchQueries(params.query);
152
+ return success({ ...params, ...bounds.data, query: queries.length ? queries : undefined });
148
153
  } catch (error) {
149
154
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
150
155
  throw error;
151
156
  }
152
- const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
153
- const prepared = prepareSelection(projection, scoped);
157
+ }
158
+
159
+ export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
160
+ const scoped = resolveSelection(params);
161
+ if (!scoped.ok) return scoped;
162
+ return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
163
+ }
164
+
165
+ /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
166
+ export function corpusSelection(params: HistorySelection): Outcome<HistorySelection> {
167
+ const scoped = resolveSelection(params);
168
+ if (!scoped.ok) return scoped;
169
+ if (scoped.data.query === undefined) return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
170
+ if (params.before_seq !== undefined || params.after_seq !== undefined) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
171
+ return scoped;
172
+ }
173
+
174
+ /** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
175
+ export function selectCorpusPage(sessions: { session: string; projection: HistoryProjection }[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
176
+ const candidates = sessions.flatMap(({ session, projection }) => prepareSelection(projection, { ...scoped, session }).candidates);
177
+ const time = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
178
+ candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq));
179
+ return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
180
+ }
181
+
182
+ function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
154
183
  const { candidates } = prepared;
155
184
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
156
185
  const newest = scoped.from !== "oldest";
@@ -175,7 +204,8 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
175
204
  }
176
205
  const page = pageData(prepared, start, end, maxChars);
177
206
  if (!fits(page)) {
178
- 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.`);
207
+ const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
208
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
179
209
  }
180
210
  return success(page);
181
211
  }
package/src/index.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  * Host-neutral core entry.
3
3
  *
4
4
  * Everything under `src/` is independent of any host SDK: notes, boot, history, budget and the
5
- * shared operations know nothing about Pi, Claude Code or dsh. Each plugin under `plugins/`
5
+ * shared operations use explicit facts, not live Pi, Claude Code or dsh services. History's
6
+ * read-only wire decoders understand persisted formats without importing those hosts. Each plugin under `plugins/`
6
7
  * composes these domains into that host's registration and owns that host's text, lifecycle and
7
8
  * SDK types. Nothing here imports a plugin.
8
9
  *
@@ -29,20 +30,22 @@ export type {
29
30
  Scope,
30
31
  } from "./notes/index.js";
31
32
 
32
- // Boot: five homes captured once, rendered from explicit logical tool names.
33
+ // Boot: five notebooks captured once, rendered from explicit logical tool names.
33
34
  export { loadNotesSnapshot, unavailableNotesSnapshot } from "./boot/snapshot.js";
34
- export type { NotesHome, NotesSnapshot } from "./boot/snapshot.js";
35
+ export type { NotesNamespace, NotesSnapshot } from "./boot/snapshot.js";
35
36
  export { renderBootBlock } from "./boot/render.js";
36
37
  export type { BootRenderData, BootWindowTree } from "./boot/render.js";
37
38
  export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
38
39
  export type { BootToolNames } from "./boot/text.js";
39
40
 
40
41
  // Operations: the schemas and typed outcomes a host registers as its own tools, over a
41
- // host-supplied notes identity or decoded history projection.
42
+ // host-supplied notes tool context or decoded history projection/lazy corpus context.
42
43
  export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
43
- export { historyList, historyRead, historyWindows } from "./tools/history.js";
44
+ export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
45
+ export { historyList, historyRead } from "./tools/history.js";
44
46
  export { projectHistory } from "./history/history.js";
45
47
  export type { HistoryProjection } from "./history/history.js";
48
+ export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
46
49
  export type { Operation, OperationError, Outcome, Renderer, TextWindow } from "./tools/result.js";
47
50
 
48
51
  // Budget: pure thresholds and the approved reset prose.
@@ -4,18 +4,18 @@ import { assertVirtualPath, isSessionId, SLUG_PATTERN, type Scope } from "./path
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> and @sessions/<id>/<path> read named homes.";
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> and @sessions/<id>/<path> read named notebooks.";
8
8
 
9
- /** The one home-head vocabulary: the scope each public `@head` names, and the home directory family a head with `home` lists. */
10
- export const HOME_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly home?: "sessions" | "project" | "agents" | "models" }> = new Map([
9
+ /** The one namespace-head vocabulary: the scope each public `@head` names, and the directory family a head with `dir` lists. */
10
+ export const NAMESPACE_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly dir?: "sessions" | "project" | "agents" | "models" }> = new Map([
11
11
  ["project", { scope: "project" }],
12
12
  ["human", { scope: "human" }],
13
13
  ["self", { scope: "agent" }],
14
14
  ["model", { scope: "model" }],
15
- ["sessions", { scope: "session", home: "sessions" }],
16
- ["projects", { scope: "project", home: "project" }],
17
- ["agents", { scope: "agent", home: "agents" }],
18
- ["models", { scope: "model", home: "models" }],
15
+ ["sessions", { scope: "session", dir: "sessions" }],
16
+ ["projects", { scope: "project", dir: "project" }],
17
+ ["agents", { scope: "agent", dir: "agents" }],
18
+ ["models", { scope: "model", dir: "models" }],
19
19
  ]);
20
20
 
21
21
  /**
@@ -55,7 +55,7 @@ export function assertGlobPattern(value: unknown): string | undefined {
55
55
  }
56
56
 
57
57
  /**
58
- * Decode one public note address into its physical home and virtual path. @self and @model
58
+ * Decode one public note address into its physical namespace and virtual path. @self and @model
59
59
  * are relative; projects/agents/models name a canonical slug, sessions a directory component.
60
60
  */
61
61
  export function assertAddress(value: unknown): NoteAddress {
@@ -65,10 +65,10 @@ export function assertAddress(value: unknown): NoteAddress {
65
65
  let who: string | undefined;
66
66
  if (value.startsWith("@")) {
67
67
  const [rawHead, ...tail] = value.slice(1).split("/");
68
- const head = HOME_HEADS.get(rawHead!);
68
+ const head = NAMESPACE_HEADS.get(rawHead!);
69
69
  if (head === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
70
70
  scope = head.scope;
71
- if (head.home === undefined) path = tail.join("/");
71
+ if (head.dir === undefined) path = tail.join("/");
72
72
  else {
73
73
  who = tail[0] ?? "";
74
74
  if (!(scope === "session" ? isSessionId(who) : SLUG_PATTERN.test(who))) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -91,9 +91,9 @@ export function canonicalAddressFor(identity: NotesIdentity, scope: Scope, path:
91
91
  }
92
92
 
93
93
  /**
94
- * Render the address a caller sees. The current agent and model homes read as @self/ and
95
- * @model/. Current session and project homes retain bare paths and @project/; explicitly
96
- * named session/project homes keep their read-only addresses, even for the current identity.
94
+ * Render the address a caller sees. The current agent and model notebooks read as @self/ and
95
+ * @model/. Current session and project notebooks retain bare paths and @project/; explicitly
96
+ * named session/project notebooks keep their read-only addresses, even for the current identity.
97
97
  */
98
98
  export function addressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string {
99
99
  if (scope === "session" && who === undefined) return path;
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "invalid_cwd" | "io_error" | "internal_error";
2
2
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {
@@ -123,7 +123,7 @@ function parseFrontmatter(raw: string): { fields: Record<string, unknown>; body:
123
123
  export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body: string } {
124
124
  const { fields, body } = parseFrontmatter(raw);
125
125
  const meta = { ...fields } as Record<string, unknown>;
126
- // scope is a legacy on-disk field: store callers derive it from the file's home and
126
+ // scope is a legacy on-disk field: store callers derive it from the file's notebook and
127
127
  // overwrite it after parsing, so an absent or outdated value just falls back.
128
128
  meta.scope = isScope(meta.scope) ? meta.scope : "session";
129
129
  meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
@@ -161,7 +161,7 @@ export function serializeNote(meta: NoteMeta, body: string): string {
161
161
  else lines.push(`${key}: ${yamlScalar(value)}`);
162
162
  }
163
163
  for (const key of Object.keys(meta)) {
164
- // scope is a legacy on-disk field. Store callers derive it from the home's location,
164
+ // scope is a legacy on-disk field. Store callers derive it from the notebook's location,
165
165
  // but serialization intentionally drops it on the next write.
166
166
  if (key === "scope" || (KNOWN_KEYS as readonly string[]).includes(key)) continue;
167
167
  if (meta[key] === undefined) continue;
@@ -1,6 +1,6 @@
1
1
  export { createNotesStore, noteIdentity } from "./store.js";
2
2
  export { NoteError, type NoteErrorCode } from "./errors.js";
3
- export { projectKey } from "./project-home.js";
3
+ export { projectKey } from "./project-namespace.js";
4
4
  export { slugify } from "./paths.js";
5
5
  export { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
6
6
  export { isFilesystemError } from "./fs-error.js";
@@ -5,7 +5,7 @@ import type { NotesIdentity } from "./identity.js";
5
5
 
6
6
  export type Scope = "session" | "project" | "human" | "agent" | "model";
7
7
 
8
- /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
8
+ /** The one legal namespace-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
9
9
  export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
10
10
 
11
11
  /** Session identities use the same single-directory-component grammar as NotesIdentity, not slugs. */
@@ -22,7 +22,7 @@ export function slugify(value: string): string {
22
22
  /**
23
23
  * The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
24
24
  * segment. Both the address decoder and the physical-path builder enforce it here, so a
25
- * caller that reaches a path without going through an address still cannot escape a home.
25
+ * caller that reaches a path without going through an address still cannot escape a namespace.
26
26
  */
27
27
  export function assertVirtualPath(value: unknown): string {
28
28
  if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
@@ -32,8 +32,8 @@ export function assertVirtualPath(value: unknown): string {
32
32
  return value;
33
33
  }
34
34
 
35
- /** Absolute directory holding the per-session note homes. */
36
- export function sessionHomesRoot(home: string): string {
35
+ /** Absolute directory holding the per-session note namespaces. */
36
+ export function sessionNamespacesRoot(home: string): string {
37
37
  return join(home, "pi", "session");
38
38
  }
39
39
 
@@ -45,15 +45,15 @@ export function scopeDir(scope: Scope, identity: NotesIdentity, who?: string): s
45
45
  if (scope === "project") return join(identity.home, "project", who ?? identity.projectKey);
46
46
  if (scope === "agent") return join(identity.home, "agents", who ?? identity.agent);
47
47
  if (scope === "model") return join(identity.home, "models", who ?? identity.model);
48
- return join(sessionHomesRoot(identity.home), who ?? identity.sessionId);
48
+ return join(sessionNamespacesRoot(identity.home), who ?? identity.sessionId);
49
49
  }
50
50
 
51
- /** Every addressable home directory in a namespace; sessions keep their original identity spelling. */
52
- export async function namespaceSlugs(namespace: "sessions" | "project" | "agents" | "models", home: string): Promise<string[]> {
53
- const root = namespace === "sessions" ? sessionHomesRoot(home) : join(home, namespace);
51
+ /** Every addressable directory of a namespace family; sessions keep their original identity spelling. */
52
+ export async function namespaceSlugs(family: "sessions" | "project" | "agents" | "models", home: string): Promise<string[]> {
53
+ const root = family === "sessions" ? sessionNamespacesRoot(home) : join(home, family);
54
54
  try {
55
55
  return (await readdir(root, { withFileTypes: true }))
56
- .filter((entry) => entry.isDirectory() && (namespace === "sessions" ? isSessionId(entry.name) : SLUG_PATTERN.test(entry.name)))
56
+ .filter((entry) => entry.isDirectory() && (family === "sessions" ? isSessionId(entry.name) : SLUG_PATTERN.test(entry.name)))
57
57
  .map((entry) => entry.name)
58
58
  .sort();
59
59
  } catch (error) {