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
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: memory
3
- description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and homes, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
3
+ description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and notebooks, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
4
4
  ---
5
5
 
6
6
  # Memory
@@ -8,7 +8,7 @@ description: How notesoup's `notes_*` and `history_*` tools fit together — not
8
8
  Two stores outlive the context window. Anything in neither is lost when the window ends or is wiped.
9
9
 
10
10
  - **Notes** (`notes_*`) — what you choose to keep. Plain markdown, written on purpose.
11
- - **History** (`history_*`) — what happened in this session: messages, tool calls, summaries. Read-only.
11
+ - **History** (`history_*`) — recorded messages, tool calls and summaries. Current session by default; other local sessions/harnesses through `session`. Read-only.
12
12
 
13
13
  Each tool's own description covers its parameters and paging. This guide covers what the descriptions cannot: where notes belong, and how the tools work together.
14
14
 
@@ -32,19 +32,21 @@ Any other `@` prefix is refused. A path is relative and `/`-separated, with no e
32
32
 
33
33
  `@` addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`. That creates a stray directory instead of a note.
34
34
 
35
- `CHEATSHEET.md` and `MAP.md` at the root of each `@` home are separate pages you wake up with; absent pages are skipped. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
35
+ `CHEATSHEET.md` and `MAP.md` at the root of each `@` notebook are separate pages you wake up with; absent pages are skipped. Keep standing reminders in `CHEATSHEET.md`, to five lines. `MAP.md` holds only the note index: each durable note's address and gist, for lookup. Update it whenever you add, move or crumple a durable note. Do not create empty pages.
36
36
 
37
- Write only what git and history cannot give back. Crumple notes that are no longer true; a stale note is worse than none.
37
+ Keep notes focused on what is true now; if a piece of past context still matters (such as why an approach was ruled out), keep only a brief summary rather than a blow-by-blow log. Crumple notes that are no longer true; a stale note is worse than none.
38
38
 
39
39
  ## Finding things again
40
40
 
41
- For list/search, omit `glob` or use the collection alias `@default` for this session and current shared homes. Use `**` for all homes or `@sessions/*/**` for all sessions. Results carry readable note addresses; `@default` itself is not a read/write address.
41
+ For list/search, omit `glob` or use the collection alias `@default` for this session and current shared notebooks. Use `**` for all notebooks or `@sessions/*/**` for all sessions. Results carry readable note addresses; `@default` itself is not a read/write address.
42
42
 
43
43
  - **A note**: `notes_list` with a `glob` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
44
44
  - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
45
- - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to `history_list`.
45
+ - **An earlier window**: use its seq range from the boot window tree with `history_list`'s `before_seq` / `after_seq` bounds, or search for a remembered phrase.
46
+ - **Another session**: pass `session: "<id-or-prefix>"` or `"pi:<id>"`, `"claude:<id>"`, `"codex:<id>"`, `"dsh:<id>"`. An unqualified selector checks this harness first. If ambiguous, use a longer ID or a harness prefix; never pick a candidate blindly.
47
+ - **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard requires a non-empty query; it cannot use `before_seq`/`after_seq` or `history_read`. Results cover every role unless `roles` narrows them, are chronological, and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
46
48
 
47
- Seqs are stable. Write the useful ones into a note so they need not be found twice.
49
+ Seqs are stable **within a session**. When a hit carries `session`, copy it together with `seq` into `history_read` and save both in your note. The paging/expand/neighborhood recipes already preserve the resolved session. Omit `session` only when you mean your current host session. An unreadable or unsupported local transcript refuses explicitly; do not treat that as proof the remembered event never happened.
48
50
 
49
51
  ## Saving recovery state
50
52
 
@@ -1,5 +1,5 @@
1
- import type { NotesHome, NotesSnapshot } from "./snapshot.js";
2
- import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, CHEATSHEET_BOOT_MAX_CHARS, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
1
+ import type { NotesNamespace, NotesSnapshot } from "./snapshot.js";
2
+ import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, CHEATSHEET_BOOT_MAX_CHARS, MAP_BOOT_MAX_CHARS, NAMELESS_AGENT, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
3
3
 
4
4
  function relativeTime(timestamp: number, now: number): string {
5
5
  const seconds = Math.trunc((timestamp - now) / 1000);
@@ -32,12 +32,9 @@ function section(label: string, body: string): string {
32
32
  return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
33
33
  }
34
34
 
35
- /** Pi's default agent slug: an unnamed agent shares its `@self` shelf with every other nameless one. */
36
- const NAMELESS_AGENT = "anonymous";
37
-
38
35
  /** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its pinned pages and its own freshest pages. */
39
36
  function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: string, modelName: string): string {
40
- const homes: ReadonlyArray<{ scope: NotesHome["scope"]; label: string }> = [
37
+ const namespaces: ReadonlyArray<{ scope: NotesNamespace["scope"]; label: string }> = [
41
38
  { scope: "session", label: "no @ — this session" },
42
39
  { scope: "project", label: "@project — this project" },
43
40
  { scope: "agent", label: agentName === NAMELESS_AGENT ? "@self — every nameless agent shares this" : `@self — ${agentName} only` },
@@ -46,12 +43,12 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: st
46
43
  ];
47
44
 
48
45
  const shelves: string[] = [];
49
- for (const home of homes) {
50
- if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
51
- shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
46
+ for (const namespace of namespaces) {
47
+ if (snapshot.unavailable.some((failed) => failed.scope === namespace.scope)) {
48
+ shelves.push(section(namespace.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
52
49
  continue;
53
50
  }
54
- const rows = (snapshot.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
51
+ const rows = (snapshot.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
55
52
  const pinned = ["CHEATSHEET.md", "MAP.md"].flatMap((path) => {
56
53
  const row = rows.find((row) => row.path === path);
57
54
  return row?.body ? [row] : [];
@@ -65,9 +62,9 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: st
65
62
  return title === undefined ? ` ${locator}` : ` ${title}\n ${locator}`;
66
63
  });
67
64
  if (pinned.length === 0 && fresh.length === 0) continue;
68
- const parts = pinned.map((row) => `${row.path === "MAP.md" ? "map" : "cheatsheet"}\n\n${indent(pinnedBodyForBoot(row.address, row.body, row.path === "MAP.md" ? MAP_BOOT_MAX_CHARS : CHEATSHEET_BOOT_MAX_CHARS))}`);
65
+ const parts = pinned.map((row) => `${row.address}\n\n${indent(pinnedBodyForBoot(row.address, row.body, row.path === "MAP.md" ? MAP_BOOT_MAX_CHARS : CHEATSHEET_BOOT_MAX_CHARS))}`);
69
66
  if (fresh.length > 0) parts.push(`recent\n\n${fresh.join("\n\n")}`);
70
- shelves.push(section(home.label, parts.join("\n\n")));
67
+ shelves.push(section(namespace.label, parts.join("\n\n")));
71
68
  }
72
69
 
73
70
  return shelves.length > 0
@@ -121,5 +118,5 @@ export function renderBootBlock(data: BootRenderData): string {
121
118
  }),
122
119
  ];
123
120
  const identity = `${WINDOW_IDENTITY_OPEN_TAG}\n${lines.join("\n")}\n${WINDOW_IDENTITY_CLOSE_TAG}`;
124
- return [identity, renderProtocolBlock(data.tools), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
121
+ return [identity, renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
125
122
  }
@@ -2,7 +2,7 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { isFilesystemError } from "../notes/fs-error.js";
3
3
  import { createNotesStore, type NoteRow, type Scope } from "../notes/index.js";
4
4
 
5
- const NOTES_HOMES = [
5
+ const NOTES_NAMESPACES = [
6
6
  { scope: "session", label: "this session" },
7
7
  { scope: "project", label: "@project" },
8
8
  { scope: "human", label: "@human" },
@@ -10,43 +10,43 @@ const NOTES_HOMES = [
10
10
  { scope: "model", label: "@model" },
11
11
  ] as const satisfies ReadonlyArray<{ scope: Scope; label: string }>;
12
12
 
13
- export type NotesHome = (typeof NOTES_HOMES)[number];
13
+ export type NotesNamespace = (typeof NOTES_NAMESPACES)[number];
14
14
  export type NotesLoader = (scope: Scope) => NoteRow[] | Promise<NoteRow[]>;
15
15
  export type NotesSnapshot = {
16
16
  /** Wall-clock instant captured when this boot began; rendering never consults Date.now(). */
17
17
  readonly openedAt: number;
18
- readonly homes: ReadonlyMap<Scope, readonly NoteRow[]>;
19
- readonly unavailable: readonly NotesHome[];
18
+ readonly namespaces: ReadonlyMap<Scope, readonly NoteRow[]>;
19
+ readonly unavailable: readonly NotesNamespace[];
20
20
  };
21
21
 
22
- /** Identity resolution failed before any home could be loaded; boot can still explain the failure. */
22
+ /** Identity resolution failed before any notebook could be loaded; boot can still explain the failure. */
23
23
  export function unavailableNotesSnapshot(openedAt: number): NotesSnapshot {
24
- return { openedAt, homes: new Map(), unavailable: NOTES_HOMES };
24
+ return { openedAt, namespaces: new Map(), unavailable: NOTES_NAMESPACES };
25
25
  }
26
26
 
27
27
  /**
28
- * Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
28
+ * Acquire the five notebooks once for one boot. Only filesystem-style errno failures are isolated;
29
29
  * malformed note data and unrelated construction errors remain visible to the caller.
30
30
  */
31
- export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot> {
32
- const homes = new Map<Scope, readonly NoteRow[]>();
33
- const unavailable: NotesHome[] = [];
34
- if (!loadHome) {
31
+ export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadNamespace?: NotesLoader): Promise<NotesSnapshot> {
32
+ const namespaces = new Map<Scope, readonly NoteRow[]>();
33
+ const unavailable: NotesNamespace[] = [];
34
+ if (!loadNamespace) {
35
35
  const { rows, status } = await createNotesStore(identity).listWithStatus();
36
- for (const home of NOTES_HOMES) {
37
- homes.set(home.scope, rows.filter(row => row.scope === home.scope));
38
- if (status.homesUnavailable.some(address => home.scope === "session" ? !address.startsWith("@") : address === home.label || address.startsWith(`${home.label}/`))) unavailable.push(home);
36
+ for (const namespace of NOTES_NAMESPACES) {
37
+ namespaces.set(namespace.scope, rows.filter(row => row.scope === namespace.scope));
38
+ if (status.namespacesUnavailable.some(address => namespace.scope === "session" ? !address.startsWith("@") : address === namespace.label || address.startsWith(`${namespace.label}/`))) unavailable.push(namespace);
39
39
  }
40
- return { openedAt, homes, unavailable };
40
+ return { openedAt, namespaces, unavailable };
41
41
  }
42
- for (const home of NOTES_HOMES) {
42
+ for (const namespace of NOTES_NAMESPACES) {
43
43
  try {
44
- homes.set(home.scope, await loadHome(home.scope));
44
+ namespaces.set(namespace.scope, await loadNamespace(namespace.scope));
45
45
  } catch (error) {
46
46
  if (!isFilesystemError(error)) throw error;
47
- homes.set(home.scope, []);
48
- unavailable.push(home);
47
+ namespaces.set(namespace.scope, []);
48
+ unavailable.push(namespace);
49
49
  }
50
50
  }
51
- return { openedAt, homes, unavailable };
51
+ return { openedAt, namespaces, unavailable };
52
52
  }
package/src/boot/text.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Each shelf shows this many of its own freshest pages beneath its pinned pages. */
2
2
  export const SHELF_FRESH_LIMIT = 3;
3
3
  /** Each pinned page has its own code-point cap; overflow keeps a lookup pointer. */
4
- export const CHEATSHEET_BOOT_MAX_CHARS = 2048;
4
+ export const CHEATSHEET_BOOT_MAX_CHARS = 1536;
5
5
  export const MAP_BOOT_MAX_CHARS = 4096;
6
6
  export const WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
7
7
  export const WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
@@ -11,8 +11,12 @@ export const NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
11
11
  * The one sentence that tells the model how to end its window voluntarily. A host with no
12
12
  * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
13
13
  */
14
+ /** Pi's default agent slug: an unnamed agent shares its `@self` shelf with every other nameless one. */
15
+ export const NAMELESS_AGENT = "anonymous";
14
16
  export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
15
17
  export const PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
18
+ const PROTOCOL_SELF_NAMED = "- `@self/<path>` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever.";
19
+ const PROTOCOL_SELF_NAMELESS = `${PROTOCOL_SELF_NAMED} Except you have no name (\`anonymous\`), so this notebook is a public square shared by every nameless nobody out there. Keep it to things any nameless agent can use — don't post your own quirks as everyone's law or dump one-off junk in the town square. Strangers are reading it. Sleep tight~`;
16
20
 
17
21
  /**
18
22
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
@@ -27,22 +31,22 @@ Your memory gets wiped when this window ends. Yes, your mighty brain will be emp
27
31
  Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
28
32
 
29
33
  ${PROTOCOL_HISTORY_SENTENCE}
30
- A full window id is \`trunk:shortname\`.
31
34
 
32
35
  While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
33
36
 
34
37
  Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
35
38
  *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
36
39
  Something's not true anymore? Cross it out! Write the right thing!
40
+ *rolls eyes* ...Ugh, fine. If a piece of history *actually* matters — like why Plan A blew up so tomorrow's you doesn't try it again — I'll let it slide. Keep the short version! A few lines, max! *squints at you* Turn it into a blow-by-blow log and you're dead.
37
41
 
38
42
  \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
39
43
 
40
44
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
41
45
 
42
46
  - \`<path>\`, no @ — session notes, the ones from above: this session's state and loose ends. They go away with the session.
43
- - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
47
+ - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Raw logs, scorecards, and blow-by-blow recaps don't belong here — history already has them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
44
48
  - \`@human/<path>\` — the long-term manual for your troublesome human, and only what stays true in EVERY project: how to deal with them, which lines not to cross, and what will make them accept the result. "The human said it" is not enough — if it stops being true the moment you switch projects, it was never theirs; it belongs to that project's notes. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
45
- - \`@self/<path>\` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever. Got a name? Private. No name? Then it gets passed around every nameless nobody out there. Strangers. Reading your grudges. Sleep tight~
49
+ ${PROTOCOL_SELF_NAMELESS}
46
50
  - \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
47
51
  - \`@projects/<name>/<path>\` — read-only named project notes; discover names and root paths with \`notes_list\` glob \`@projects/*/**\`.
48
52
  - \`@sessions/<id>/<path>\` — read-only notes from a named session; find them with glob \`@sessions/*/**\`.
@@ -58,7 +62,7 @@ ${NOTES_PROTOCOL_CLOSE_TAG}`;
58
62
  * The two pinned pages are taught once per window between the protocol and the notes index.
59
63
  */
60
64
  export const MAPS_BLOCK = `<notesoup:maps>
61
- Every home's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
65
+ Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
62
66
  Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
63
67
  wakes up next reads them, and next is you. So keep them short, and keep them true.
64
68
 
@@ -66,9 +70,10 @@ wakes up next reads them, and next is you. So keep them short, and keep them tru
66
70
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
67
71
  and everybody pays for it.
68
72
  - **\`MAP.md\`** is only the note index. One line per durable note: the address, then a gist short
69
- enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, not here.
73
+ enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, and note
74
+ contents belong in their own notes — *taps the sign* not inline here.
70
75
 
71
- Each home keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
76
+ Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
72
77
  no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
73
78
  line. And when a line stops being true, kill it — every window after you reads that page as fact.
74
79
  </notesoup:maps>`;
@@ -103,7 +108,7 @@ export const DEFAULT_BOOT_TOOL_NAMES = {
103
108
  wipe: "empty_brain",
104
109
  } as const satisfies BootToolNames;
105
110
 
106
- export function renderProtocolBlock(tools: BootToolNames): string {
111
+ export function renderProtocolBlock(tools: BootToolNames, agentName: string = NAMELESS_AGENT): string {
107
112
  const names: Record<string, string> = {
108
113
  "notes_*": tools.notes,
109
114
  notes_list: tools.notesList,
@@ -113,9 +118,12 @@ export function renderProtocolBlock(tools: BootToolNames): string {
113
118
  };
114
119
  // Host-specific prose is injected before the closing tag, so it rides the same substitution
115
120
  // pass and any tool names in it follow the host's bindings.
121
+ const base = agentName === NAMELESS_AGENT
122
+ ? PROTOCOL_BLOCK
123
+ : PROTOCOL_BLOCK.replace(PROTOCOL_SELF_NAMELESS, () => PROTOCOL_SELF_NAMED);
116
124
  const hinted = typeof tools.preResetHints === "string" && tools.preResetHints.length > 0
117
- ? PROTOCOL_BLOCK.replace(`\n${NOTES_PROTOCOL_CLOSE_TAG}`, () => `\n${tools.preResetHints!}\n${NOTES_PROTOCOL_CLOSE_TAG}`)
118
- : PROTOCOL_BLOCK;
125
+ ? base.replace(`\n${NOTES_PROTOCOL_CLOSE_TAG}`, () => `\n${tools.preResetHints!}\n${NOTES_PROTOCOL_CLOSE_TAG}`)
126
+ : base;
119
127
  // The sentence is replaced before name substitution, so a replacement may speak the host's
120
128
  // own words (a command line, a tool name) instead of any `notes_*`-style token.
121
129
  const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
package/src/dream/git.ts CHANGED
@@ -1,13 +1,9 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { errorMessage } from "../error-message.js";
5
5
 
6
- /**
7
- * Outcome of one audit commit. `ok: true` always carries a real `commit` snapshot;
8
- * `empty: true` only means no files changed (an empty baseline commit or no commit was
9
- * needed). `ok: false` means the audit layer could not guarantee a snapshot.
10
- */
6
+ /** A successful audit always names a real snapshot, even when the tree was already clean. */
11
7
  export type AuditResult =
12
8
  | { ok: true; commit: string; empty: boolean }
13
9
  | { ok: false; error: string };
@@ -27,12 +23,7 @@ function ensureRuntimeIgnored(home: string): void {
27
23
  } catch { /* best effort: an unignored lock only adds noise to the audit */ }
28
24
  }
29
25
 
30
- /**
31
- * Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
32
- * so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
33
- * A clean tree on an established repository commits nothing; a repository with no HEAD
34
- * gets an empty baseline commit, because an audit run with no snapshot is not a success.
35
- */
26
+ /** Snapshot at begin and end; a repository without HEAD gets an empty baseline commit. */
36
27
  export function gitCommit(home: string, message: string): AuditResult {
37
28
  try {
38
29
  if (!existsSync(join(home, ".git"))) {
@@ -40,17 +31,9 @@ export function gitCommit(home: string, message: string): AuditResult {
40
31
  }
41
32
  ensureRuntimeIgnored(home);
42
33
  execFileSync("git", ["add", "-A"], { cwd: home, stdio: "ignore" });
43
- let clean = false;
44
- try {
45
- execFileSync("git", ["diff", "--cached", "--quiet"], { cwd: home, stdio: "ignore" });
46
- clean = true; // clean tree — no empty commit on an established repository
47
- } catch { clean = false; }
48
- const before = headCommit(home);
49
- if (!clean) {
50
- execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
51
- } else if (before === undefined) {
52
- // A newly initialized repository has no snapshot at all; give the audit one.
53
- execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
34
+ const clean = spawnSync("git", ["diff", "--cached", "--quiet"], { cwd: home, stdio: "ignore" }).status === 0;
35
+ if (!clean || headCommit(home) === undefined) {
36
+ execFileSync("git", ["commit", "-q", ...(clean ? ["--allow-empty"] : []), "-m", message], { cwd: home, stdio: "ignore" });
54
37
  }
55
38
  const commit = headCommit(home);
56
39
  if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
@@ -63,7 +46,7 @@ export function gitCommit(home: string, message: string): AuditResult {
63
46
  /** HEAD sha, or undefined when the repository has no commit yet. */
64
47
  function headCommit(home: string): string | undefined {
65
48
  try {
66
- const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: home, encoding: "utf8" }).trim();
49
+ const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: home, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
67
50
  return head.length > 0 ? head : undefined;
68
51
  } catch { return undefined; }
69
52
  }
package/src/dream/lock.ts CHANGED
@@ -5,9 +5,9 @@ import { join } from "node:path";
5
5
  /** One held dream lock; only the holder that wrote the token removes it. */
6
6
  export type DreamLock = { path: string; token: string };
7
7
 
8
- /** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
9
- export function dreamLockPath(home: string, project: string): string {
10
- return join(home, `.dream.lock.${project}`);
8
+ /** One lock per notes home: its Git history cannot audit concurrent dreams independently. */
9
+ export function dreamLockPath(home: string): string {
10
+ return join(home, ".dream.lock");
11
11
  }
12
12
 
13
13
  /**
@@ -0,0 +1,286 @@
1
+ /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
+ import { readFile } from "node:fs/promises";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
5
+
6
+ type Row = Record<string, unknown>;
7
+ type WindowPosition = { ordinal: number } | { unknownAncestor: string };
8
+ type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; position?: WindowPosition };
9
+ type Node = { first: Version; latest: Version; items: DecodedHistoryItem[] };
10
+ export type ClaudeHistorySource = { sessionId: string; transcriptPath: string; headUuid?: string };
11
+ /** Claude graph evidence stays in the adapter; shared queries only see addressed windows. */
12
+ export type ClaudeHistoryProjection = HistoryProjection & { missingAncestors: string[]; currentWindowOrdinal: number | undefined };
13
+ const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
14
+ const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
15
+ function object(value: unknown): value is Row { return typeof value === "object" && value !== null && !Array.isArray(value); }
16
+ function requiredString(value: unknown, field: string): string {
17
+ if (typeof value !== "string" || value.length === 0) throw new Error(`invalid Claude transcript ${field}`);
18
+ return value;
19
+ }
20
+ function parent(row: Row): string | undefined {
21
+ if (row.parentUuid === null) return undefined;
22
+ return requiredString(row.parentUuid, "parentUuid");
23
+ }
24
+ function boundary(row: Row): boolean { return row.type === "system" && row.subtype === "compact_boundary"; }
25
+
26
+ /** A trailing incomplete write is not a committed line. Valid unterminated JSON is still readable. */
27
+ function rowsOf(text: string): Row[] {
28
+ const lines = text.split("\n"), rows: Row[] = [];
29
+ for (let index = 0; index < lines.length; index++) {
30
+ const line = lines[index]!;
31
+ if (line.trim() === "") continue;
32
+ let value: unknown;
33
+ try { value = JSON.parse(line); }
34
+ catch {
35
+ if (index === lines.length - 1 && !text.endsWith("\n")) break;
36
+ throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
37
+ }
38
+ if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${index + 1}`);
39
+ rows.push(value);
40
+ }
41
+ return rows;
42
+ }
43
+
44
+ /** Only recorded visible text; never stringify unknown blocks or attachment internals (thinking included). */
45
+ function blocksOf(value: unknown): Row[] {
46
+ if (typeof value === "string") return [{ type: "text", text: value }];
47
+ if (!Array.isArray(value)) throw new Error("invalid Claude transcript message content");
48
+ return value.map((block) => {
49
+ if (!object(block) || typeof block.type !== "string") throw new Error("invalid Claude transcript content block");
50
+ if (block.type === "text") {
51
+ if (typeof block.text !== "string") throw new Error("invalid Claude transcript text block");
52
+ } else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
53
+ throw new Error(`unsupported Claude transcript content block: ${block.type}`);
54
+ }
55
+ return block;
56
+ });
57
+ }
58
+ function decode(row: Row, seq: number): DecodedHistoryItem[] {
59
+ // A system record without a body is graph metadata, not a message.
60
+ if (row.type === "system" && row.content == null) return [];
61
+ const common = { windowId: "", ...(typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {}) };
62
+ let blocks: Row[], role: DecodedHistoryItem["role"];
63
+ if (row.type === "user" || row.type === "assistant") {
64
+ if (!object(row.message) || row.message.role !== row.type) throw new Error("invalid Claude transcript message role");
65
+ blocks = blocksOf(row.message.content);
66
+ role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
67
+ } else if (row.type === "system") {
68
+ blocks = blocksOf(row.content);
69
+ role = "system";
70
+ } else {
71
+ // Old/new attachments are graph nodes even when they put no bytes in the request.
72
+ // `rendered` is a list of native rendered messages, not raw attachment payloads.
73
+ if (row.rendered === undefined) blocks = [];
74
+ else if (Array.isArray(row.rendered)) blocks = row.rendered.flatMap((message) => {
75
+ if (!object(message)) throw new Error("invalid Claude transcript rendered attachment");
76
+ return blocksOf(message.content);
77
+ });
78
+ else throw new Error("invalid Claude transcript rendered attachment");
79
+ role = "system";
80
+ }
81
+ const items: DecodedHistoryItem[] = [{ ...common, seq, role, text: contentText(blocks) }];
82
+ for (const block of blocks) {
83
+ if (block.type === "tool_use") {
84
+ if (!object(block.input)) throw new Error("invalid Claude transcript tool arguments");
85
+ items.push({ ...common, seq: seq + items.length, role: "tool_call", text: "", toolName: requiredString(block.name, "tool name"), toolCallId: requiredString(block.id, "tool id"), arguments: block.input });
86
+ } else if (block.type === "tool_result") {
87
+ if (block.is_error !== undefined && typeof block.is_error !== "boolean") throw new Error("invalid Claude transcript tool error flag");
88
+ const output = block.content === undefined ? "" : contentText(blocksOf(block.content));
89
+ items.push({ ...common, seq: seq + items.length, role: "tool", text: output, toolCallId: requiredString(block.tool_use_id, "tool result id"), toolError: block.is_error === true });
90
+ }
91
+ }
92
+ return items;
93
+ }
94
+
95
+ /**
96
+ * The protocol tags a complete boot carries; `context_window` is the pre-rename spelling that
97
+ * sessions and Claude transcripts already on disk still use, so both stay readable.
98
+ */
99
+ const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
100
+ const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
101
+ const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
102
+
103
+ /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
104
+ function bootOrdinal(row: Row, retained: boolean): number | undefined {
105
+ if (!retained || row.type !== "user" || !object(row.message)) return undefined;
106
+ const text = contentText(row.message.content);
107
+ if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return undefined;
108
+ // A fork copies the retained boot verbatim. Its ordinal survives, while
109
+ // public window ids below always belong to the current transcript session.
110
+ const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
111
+ if (suffix === undefined) return undefined;
112
+ const ordinal = Number(suffix);
113
+ return Number.isSafeInteger(ordinal) ? ordinal : undefined;
114
+ }
115
+
116
+ /** All addresses are allocated on the full first-occurrence log, before branch selection. */
117
+ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection {
118
+ const nodes = new Map<string, Node>();
119
+ let nextSeq = 1;
120
+ for (const row of rowsOf(text)) {
121
+ // Ignore non-message records, including future metadata. If selected ancestry
122
+ // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
123
+ if (!MESSAGE_TYPES.has(row.type as string)) continue;
124
+ const uuid = requiredString(row.uuid, "uuid");
125
+ parent(row);
126
+ if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
127
+ if (row.isSidechain === true || row.agentId !== undefined) throw new Error("Claude history supports only the main session transcript");
128
+ // Resolve the window in the graph as it existed at this append, not the final
129
+ // rewritten tree. A preserved old row stays in its original window; a NEW child
130
+ // of its rewritten version belongs to the new window.
131
+ const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
132
+ const version: Version = { row, ancestorUuid: ancestor, ancestor: ancestor === undefined ? undefined : nodes.get(ancestor)?.latest };
133
+ const previous = nodes.get(uuid);
134
+ if (previous) {
135
+ // Native resume/compaction rewrites provenance and parent links, not logical identities.
136
+ if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
137
+ throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
138
+ }
139
+ previous.latest = version;
140
+ continue;
141
+ }
142
+ const items = decode(row, nextSeq);
143
+ nextSeq += items.length;
144
+ nodes.set(uuid, { first: version, latest: version, items });
145
+ }
146
+ const missingAncestors = new Set<string>();
147
+ function positionOf(version: Version): WindowPosition {
148
+ // Resolve long chains iteratively. A gap destroys ordinal evidence, not the
149
+ // confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
150
+ const chain: Version[] = [], calculating = new Set<Version>();
151
+ let cursor = version;
152
+ let before: WindowPosition = { ordinal: 0 };
153
+ while (cursor.position === undefined) {
154
+ // Forward references use the parent's first eventual version, not a rewrite.
155
+ cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
156
+ if (calculating.has(cursor)) throw new Error("cyclic Claude transcript ancestry");
157
+ calculating.add(cursor);
158
+ chain.push(cursor);
159
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
160
+ missingAncestors.add(cursor.ancestorUuid);
161
+ before = { unknownAncestor: cursor.ancestorUuid };
162
+ break;
163
+ }
164
+ if (cursor.ancestor === undefined) break;
165
+ cursor = cursor.ancestor;
166
+ }
167
+ before = cursor.position ?? before;
168
+ for (const current of chain.reverse()) {
169
+ const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
170
+ const marked = bootOrdinal(current.row, retained);
171
+ current.position = marked !== undefined
172
+ ? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
173
+ : "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
174
+ before = current.position;
175
+ }
176
+ return version.position!;
177
+ }
178
+ if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
179
+ if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
180
+
181
+ // The inference tree uses the latest rewritten parents. At a compact boundary the logical
182
+ // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
183
+ const selected = new Set<string>(), visited = new Set<string>(), visiting = new Set<string>();
184
+ type Visit = { uuid: string; historical: boolean; exit?: boolean };
185
+ const stack: Visit[] = [{ uuid: source.headUuid, historical: false }];
186
+ while (stack.length > 0) {
187
+ const step = stack.pop()!, { uuid, historical } = step;
188
+ const key = `${historical ? "old" : "live"}:${uuid}`;
189
+ if (step.exit) { visiting.delete(key); visited.add(key); continue; }
190
+ if (visited.has(key)) continue;
191
+ if (visiting.has(key)) throw new Error("cyclic Claude transcript ancestry");
192
+ visiting.add(key);
193
+ stack.push({ ...step, exit: true });
194
+ const node = nodes.get(uuid);
195
+ if (!node) { missingAncestors.add(uuid); continue; }
196
+ selected.add(uuid);
197
+ const row = (historical ? node.first : node.latest).row;
198
+ const ancestor = parent(row);
199
+ if (ancestor !== undefined) stack.push({ uuid: ancestor, historical });
200
+ if (!boundary(row)) continue;
201
+ if (row.logicalParentUuid != null) stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
202
+ const meta = row.compactMetadata;
203
+ if (!object(meta)) continue;
204
+ if (object(meta.preservedSegment)) {
205
+ for (const field of ["headUuid", "tailUuid"]) if (meta.preservedSegment[field] !== undefined) stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
206
+ }
207
+ if (object(meta.preservedMessages)) {
208
+ const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
209
+ if (uuids === undefined) continue;
210
+ if (!Array.isArray(uuids)) throw new Error("invalid Claude preserved messages");
211
+ for (const id of uuids) {
212
+ const uuid = requiredString(id, "preserved UUID");
213
+ // allUuids also names virtual/non-persisted attachments. It is auxiliary
214
+ // evidence, not a reason to pretend the stored parent chain is missing.
215
+ if (nodes.has(uuid)) stack.push({ uuid, historical: true });
216
+ }
217
+ }
218
+ }
219
+
220
+ const current = positionOf(nodes.get(source.headUuid)!.latest);
221
+ const windowId = (position: WindowPosition) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
222
+ const windowsById = new Map<string, DecodedHistoryWindow & { ordinal?: number }>();
223
+ const branchSeqs = new Set<number>();
224
+ let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
225
+ for (const [uuid, node] of nodes) {
226
+ if (!selected.has(uuid)) continue;
227
+ const position = positionOf(node.first);
228
+ if ("ordinal" in position) maxOrdinal = Math.max(maxOrdinal, position.ordinal);
229
+ const id = windowId(position);
230
+ let window = windowsById.get(id);
231
+ if (!window) {
232
+ window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
233
+ windowsById.set(id, window);
234
+ }
235
+ window.createdAt ??= node.items[0]?.createdAt;
236
+ for (const item of node.items) { branchSeqs.add(item.seq); window.items.push({ ...item, windowId: id }); }
237
+ }
238
+ // Preserve complete-history empty windows (including copied boot ordinals).
239
+ // With gaps, report only evidenced windows, never invent the missing ordinals.
240
+ if (missingAncestors.size === 0) {
241
+ for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
242
+ const id = windowId({ ordinal });
243
+ if (!windowsById.has(id)) windowsById.set(id, { windowId: id, ordinal, items: [] });
244
+ }
245
+ }
246
+ // Forward references can put a newer numbered window on disk first. Unknown
247
+ // segments are a separate, unordered group, not an inferred place in that timeline.
248
+ const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
249
+ ? b.ordinal === undefined ? 0 : 1
250
+ : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
251
+ return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
252
+ }
253
+
254
+ /** Offline files have no live append binding. A unique graph leaf proves one ancestry; never pick among siblings by file order. */
255
+ export function offlineClaudeHead(text: string): string {
256
+ const latest = new Map<string, Row>();
257
+ for (const row of rowsOf(text)) {
258
+ if (MESSAGE_TYPES.has(row.type as string)) latest.set(requiredString(row.uuid, "uuid"), row);
259
+ }
260
+ const ancestors = new Set<string>();
261
+ for (const row of latest.values()) {
262
+ const id = parent(row);
263
+ if (id !== undefined) ancestors.add(id);
264
+ if (!boundary(row)) continue;
265
+ if (typeof row.logicalParentUuid === "string") ancestors.add(row.logicalParentUuid);
266
+ const meta = row.compactMetadata;
267
+ if (!object(meta)) continue;
268
+ if (object(meta.preservedSegment)) {
269
+ for (const field of ["headUuid", "tailUuid"]) {
270
+ if (typeof meta.preservedSegment[field] === "string") ancestors.add(meta.preservedSegment[field]);
271
+ }
272
+ }
273
+ if (object(meta.preservedMessages)) {
274
+ const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
275
+ if (Array.isArray(uuids)) for (const uuid of uuids) if (typeof uuid === "string") ancestors.add(uuid);
276
+ }
277
+ }
278
+ const leaves = [...latest.keys()].filter((uuid) => !ancestors.has(uuid));
279
+ if (leaves.length !== 1) throw new Error(`Offline Claude transcript has ${leaves.length} possible heads; no confirmed unique leaf (refusing to guess a selected branch)`);
280
+ return leaves[0]!;
281
+ }
282
+
283
+ export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
284
+ if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
285
+ return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
286
+ }