notesoup 0.54.0 → 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 (96) hide show
  1. package/README.md +4 -2
  2. package/dist/plugins/claude/src/helper.d.ts +2 -1
  3. package/dist/plugins/claude/src/helper.js +19 -23
  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/mcp.js +7 -7
  11. package/dist/plugins/codex/src/transcript.d.ts +3 -39
  12. package/dist/plugins/codex/src/transcript.js +2 -313
  13. package/dist/plugins/dsh/history.d.ts +3 -0
  14. package/dist/plugins/dsh/history.js +15 -0
  15. package/dist/plugins/dsh/tools.js +4 -5
  16. package/dist/plugins/pi/history-tools.d.ts +1 -1
  17. package/dist/plugins/pi/history-tools.js +9 -5
  18. package/dist/plugins/pi/history.d.ts +2 -3
  19. package/dist/plugins/pi/history.js +4 -147
  20. package/dist/src/boot/render.js +2 -4
  21. package/dist/src/boot/text.d.ts +3 -1
  22. package/dist/src/boot/text.js +11 -5
  23. package/dist/src/history/claude.d.ts +16 -0
  24. package/dist/src/history/claude.js +336 -0
  25. package/dist/src/history/codex-transcript.d.ts +39 -0
  26. package/dist/src/history/codex-transcript.js +315 -0
  27. package/dist/src/history/codex.d.ts +8 -0
  28. package/dist/src/history/codex.js +238 -0
  29. package/dist/src/history/corpus.d.ts +35 -0
  30. package/dist/src/history/corpus.js +54 -0
  31. package/dist/src/history/history.d.ts +4 -8
  32. package/dist/src/history/history.js +3 -11
  33. package/dist/src/history/local.d.ts +17 -0
  34. package/dist/src/history/local.js +101 -0
  35. package/dist/src/history/pi.d.ts +36 -0
  36. package/dist/src/history/pi.js +202 -0
  37. package/dist/src/history/query.d.ts +15 -5
  38. package/dist/src/history/query.js +42 -13
  39. package/dist/src/index.d.ts +4 -2
  40. package/dist/src/index.js +4 -3
  41. package/dist/src/tools/history.d.ts +7 -19
  42. package/dist/src/tools/history.js +80 -93
  43. package/dist/test/boot.integration.test.js +1 -2
  44. package/dist/test/claude-history.test.js +47 -34
  45. package/dist/test/claude-mod.test.js +7 -7
  46. package/dist/test/codex-history.test.js +4 -10
  47. package/dist/test/codex-plugin.test.js +32 -11
  48. package/dist/test/dependencies.test.js +3 -3
  49. package/dist/test/dsh.test.js +26 -4
  50. package/dist/test/helpers/extension.d.ts +0 -1
  51. package/dist/test/helpers/history-corpus.d.ts +7 -0
  52. package/dist/test/helpers/history-corpus.js +26 -0
  53. package/dist/test/history-corpus.test.d.ts +1 -0
  54. package/dist/test/history-corpus.test.js +307 -0
  55. package/dist/test/history.integration.test.js +40 -48
  56. package/dist/test/host-neutral.test.js +3 -18
  57. package/dist/test/model-facing-text.test.js +2 -0
  58. package/dist/test/notes.integration.test.js +1 -1
  59. package/dist/test/notes.test.js +1 -1
  60. package/docs/architecture.md +7 -5
  61. package/docs/claude-code-mod.md +7 -5
  62. package/docs/codex.md +3 -3
  63. package/docs/dsh.md +2 -2
  64. package/docs/history-sessions.md +52 -0
  65. package/docs/notes-library.md +1 -1
  66. package/docs/skills.md +1 -1
  67. package/docs/tool-results.md +8 -6
  68. package/package.json +1 -1
  69. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  70. package/plugins/claude/dist/claude/helper.js +1507 -746
  71. package/plugins/claude/skills/memory/SKILL.md +5 -3
  72. package/plugins/claude/src/helper.ts +19 -23
  73. package/plugins/claude/src/history.ts +3 -257
  74. package/plugins/claude/src/text.ts +0 -1
  75. package/plugins/codex/dist/codex/notesoup.js +705 -154
  76. package/plugins/codex/src/history.ts +3 -193
  77. package/plugins/codex/src/mcp.ts +7 -7
  78. package/plugins/codex/src/transcript.ts +3 -275
  79. package/plugins/dsh/history.ts +17 -0
  80. package/plugins/dsh/tools.ts +4 -5
  81. package/plugins/paseo/client/markdown.tsx +19 -39
  82. package/plugins/pi/history-tools.ts +11 -5
  83. package/plugins/pi/history.ts +8 -157
  84. package/skills/memory/SKILL.md +5 -3
  85. package/src/boot/render.ts +2 -5
  86. package/src/boot/text.ts +11 -5
  87. package/src/history/claude.ts +286 -0
  88. package/src/history/codex-transcript.ts +276 -0
  89. package/src/history/codex.ts +193 -0
  90. package/src/history/corpus.ts +69 -0
  91. package/src/history/history.ts +5 -12
  92. package/src/history/local.ts +93 -0
  93. package/src/history/pi.ts +199 -0
  94. package/src/history/query.ts +45 -15
  95. package/src/index.ts +5 -3
  96. package/src/tools/history.ts +71 -101
@@ -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
 
@@ -42,9 +42,11 @@ For list/search, omit `glob` or use the collection alias `@default` for this ses
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
 
@@ -3,13 +3,14 @@ import { pathToFileURL } from "node:url";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { Check, Errors } from "typebox/value";
5
5
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
6
- import { historyList, historyRead, historyWindows, type HistoryTextWrapper } from "../../../src/tools/history.js";
6
+ import { historyList, historyRead, type HistoryTextWrapper } from "../../../src/tools/history.js";
7
+ import { localHistoryCorpus, type LocalHistoryOptions } from "../../../src/history/local.js";
7
8
  import { readClaudeHistory, type ClaudeHistorySource } from "./history.js";
8
9
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
9
10
  import { renderBootBlock } from "../../../src/boot/render.js";
10
11
  import type { BootToolNames } from "../../../src/boot/text.js";
11
12
  import { selectContinuation } from "../../../src/budget/text.js";
12
- import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_PREVIOUS, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
13
+ import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
13
14
  import { resolveClaudeLimits } from "./thresholds.js";
14
15
  import { projectKey, snapshotNotesIdentity, type NotesIdentity } from "../../../src/notes/index.js";
15
16
  import type { Operation } from "../../../src/tools/result.js";
@@ -67,7 +68,6 @@ const OPERATIONS: Record<string, BoundOperation<[NotesToolContext]>> = {
67
68
  const HISTORY_OPERATIONS = {
68
69
  history_list: boundOperation(historyList),
69
70
  history_read: boundOperation(historyRead),
70
- history_windows: boundOperation(historyWindows),
71
71
  };
72
72
  function historySource(value: unknown, sessionId: string): ClaudeHistorySource {
73
73
  if (!value || typeof value !== "object") throw new Error("Claude history transcript_path is unavailable");
@@ -76,7 +76,7 @@ function historySource(value: unknown, sessionId: string): ClaudeHistorySource {
76
76
  return source;
77
77
  }
78
78
 
79
- export async function dispatch(request: unknown): Promise<unknown> {
79
+ export async function dispatch(request: unknown, historyOptions: Pick<LocalHistoryOptions, "roots" | "home" | "env"> = {}): Promise<unknown> {
80
80
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
81
81
  const value = request as Record<string, unknown>;
82
82
  if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
@@ -99,30 +99,26 @@ export async function dispatch(request: unknown): Promise<unknown> {
99
99
  const id = identity(value.identity as ClaudeIdentityInput);
100
100
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
101
101
  const tool = value.tool as keyof typeof HISTORY_OPERATIONS;
102
+ if ((value.params as { session?: string }).session !== undefined) {
103
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
104
+ const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
105
+ const projection = await current();
106
+ const notice = claudeHistoryGapNotice(projection.missingAncestors);
107
+ return { projection, ...(notice ? { notice } : {}) };
108
+ } } });
109
+ return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
110
+ }
102
111
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
103
112
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
104
113
  const wrapText: HistoryTextWrapper = (text) => notice + text;
105
- let params = value.params;
106
- if (projection.missingAncestors.length > 0) {
107
- // An unknown segment is not evidence for the window before the current
108
- // one. Resolve the exact ordinal, never array adjacency across a gap.
109
- if ((params as { window_id?: string }).window_id === "@previous") {
110
- const previous = projection.currentWindowOrdinal === undefined ? undefined : `claude:${id.sessionId}:${projection.currentWindowOrdinal - 1}`;
111
- if (!projection.windows.some((window) => window.windowId === previous)) {
112
- return { ok: false, text: wrapText(CLAUDE_HISTORY_UNKNOWN_PREVIOUS) };
113
- }
114
- params = { ...params as object, window_id: previous };
115
- }
116
- if (value.tool === "history_read") {
117
- const { seq } = params as { seq: number };
118
- if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
119
- return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
120
- }
114
+ const params = value.params;
115
+ if (projection.missingAncestors.length > 0 && tool === "history_read") {
116
+ const { seq } = params as { seq: number };
117
+ if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
118
+ return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
121
119
  }
122
120
  }
123
- const result = tool === "history_windows"
124
- ? await HISTORY_OPERATIONS[tool].call(params, projection, id.sessionId, wrapText)
125
- : await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
121
+ const result = await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
126
122
  return { ...result, text: wrapText(result.text) };
127
123
  }
128
124
  return OPERATIONS[value.tool]!.call(value.params, notesToolContext(id, (value.identity as ClaudeIdentityInput).cwd));
@@ -1,257 +1,3 @@
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 "../../../src/history/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
- export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
255
- if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
256
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
257
- }
1
+ /** Claude's SDK-facing entry; the persisted wire decoder is shared with the local corpus. */
2
+ export { claudeHistoryFromJsonl, readClaudeHistory } from "../../../src/history/claude.js";
3
+ export type { ClaudeHistorySource, ClaudeHistoryProjection } from "../../../src/history/claude.js";
@@ -7,7 +7,6 @@ export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in t
7
7
  export const CLAUDE_WARNING_PROMPT = warningNotice();
8
8
 
9
9
  export const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
10
- export const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = 'Cannot resolve "@previous": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.';
11
10
  export function claudeHistoryUnconfirmedSeq(seq: number): string {
12
11
  return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
13
12
  }