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,193 +1,3 @@
1
- /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
- import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "../../../src/history/history.js";
3
- import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./transcript.js";
4
- export type { CodexTranscriptSource } from "./transcript.js";
5
- export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection };
6
-
7
- const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
8
- const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
9
- // protocol.rs serializes v1 task_* spellings; turn_* are explicit serde aliases.
10
- const HOST_EVENTS = new Set(["token_count", "thread_goal_updated", "task_started", "task_complete", "turn_started", "turn_complete", "turn_aborted", "thread_settings_applied", "entered_review_mode", "exited_review_mode", "patch_apply_end", "sub_agent_activity"]);
11
- const HOST_ITEMS = new Set(["Plan", "FileChange", "CollabAgentToolCall", "SubAgentActivity", "ImageView", "Extension", "EnteredReviewMode", "ExitedReviewMode"]);
12
- const OPAQUE_RESPONSES = new Set(["reasoning", "compaction", "compaction_summary", "context_compaction", "image_generation_call"]);
13
- const HOST_RESPONSES = new Set(["configuration_update", "tool_search_call", "tool_search_output", "web_search_call"]);
14
- function optionalString(value: unknown, field: string): string | undefined { return value == null ? undefined : str(value, field); }
15
- function array(value: unknown, field: string): unknown[] {
16
- if (!Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an array`);
17
- return value;
18
- }
19
- /** No image/audio decoding, opaque plaintext recovery, or stringification disguised as message text. */
20
- function textContent(value: unknown): string {
21
- return array(value, "content").map((value) => {
22
- const part = obj(value, "content part");
23
- switch (part.type) {
24
- case "input_text": case "output_text": return str(part.text, "content text");
25
- case "input_image": return "[Codex image content omitted]";
26
- case "input_audio": return "[Codex audio content omitted]";
27
- case "encrypted_content": return "[Codex encrypted content unavailable]";
28
- default: throw new Error(`Unsupported Codex content part: ${String(part.type)}`);
29
- }
30
- }).join("\n");
31
- }
32
- function output(value: unknown): string { return typeof value === "string" ? value : textContent(value); }
33
- function argumentsOf(raw: string): NativeObject {
34
- // Custom/invalid/non-object JSON cannot fit the shared object field. Keep the
35
- // original wire string under an explicit raw label rather than lose it.
36
- try {
37
- const parsed: unknown = JSON.parse(raw);
38
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as NativeObject;
39
- } catch { /* Native tool calls may persist unparseable model arguments. */ }
40
- return { raw_arguments: raw };
41
- }
42
- function callKey(record: CodexRecord, callId: string): string { return `${record.owner}:${callId}`; }
43
- function context(record: CodexRecord, text: string): DecodedHistoryItem {
44
- if (!record.windowId) throw new Error(`Unavailable Codex history: native window identity missing at seq ${record.seq}; cannot assign a stable window address`);
45
- return { seq: record.seq, windowId: record.windowId, role: "system", text, createdAt: record.timestamp };
46
- }
47
- function host(record: CodexRecord, kind: string, payload: unknown): DecodedHistoryItem { return context(record, `Codex ${kind}\n${JSON.stringify(payload)}`); }
48
-
49
- type ToolFact = { error?: boolean; text?: string };
50
- /** Presentation records contribute OUTCOME evidence, never duplicate raw tool dialogue. */
51
- function fact(item: NativeObject): ToolFact {
52
- if (item.type === "CommandExecution") {
53
- const status = str(item.status, "CommandExecution.status");
54
- if (!["completed", "failed", "declined", "in_progress"].includes(status)) throw new Error(`Unsupported Codex command status: ${status}`);
55
- return { error: status === "failed" || status === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0), text: optionalString(item.formatted_output, "formatted_output") };
56
- }
57
- if (item.type === "McpToolCall") {
58
- const result = item.result == null ? undefined : obj(item.result, "MCP result");
59
- if (result?.isError != null && typeof result.isError !== "boolean") throw new Error("Invalid Codex MCP isError");
60
- return { error: item.status === "failed" || item.error != null || result?.isError === true, ...(result === undefined ? {} : { text: JSON.stringify(result) }) };
61
- }
62
- if (item.type === "DynamicToolCall") return { error: item.success === false || item.status === "failed" || item.error != null };
63
- if (item.type === "FileChange" || item.type === "CollabAgentToolCall") return { error: item.status === "failed" || item.status === "declined" || item.status === "interrupted" };
64
- return {};
65
- }
66
- function toolDisplay(item: NativeObject): boolean {
67
- return ["CommandExecution", "McpToolCall", "DynamicToolCall", "CollabAgentToolCall", "FileChange", "ImageView", "Extension"].includes(String(item.type));
68
- }
69
- function response(record: CodexRecord, facts: Map<string, ToolFact>): DecodedHistoryItem {
70
- const p = record.payload, type = str(p.type, "response_item.type"), base = context(record, "");
71
- if (type === "message") {
72
- if (!["user", "assistant", "system", "developer"].includes(str(p.role, "message.role"))) throw new Error(`Unsupported Codex message role: ${String(p.role)}`);
73
- return { ...base, role: record.metadata?.compaction_output === true ? "system" : p.role as "user" | "assistant" | "system" | "developer", text: textContent(p.content) };
74
- }
75
- if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
76
- const callId = optionalString(p.call_id, "call_id") ?? (type === "local_shell_call" ? optionalString(p.id, "local shell id") : undefined);
77
- if (!callId) throw new Error("Invalid Codex tool call: missing native call ID");
78
- const name = type === "local_shell_call" ? "local_shell" : str(p.name, "tool name");
79
- const args = type === "local_shell_call" ? obj(p.action, "local shell action") : type === "custom_tool_call" ? { input: str(p.input, "custom tool input") } : argumentsOf(str(p.arguments, "function arguments"));
80
- return { ...base, role: "tool_call", toolName: p.namespace ? `${str(p.namespace, "namespace")}.${name}` : name, toolCallId: callKey(record, callId), arguments: args };
81
- }
82
- if (type === "function_call_output" || type === "custom_tool_call_output") {
83
- const callId = optionalString(p.call_id, "output.call_id"), recorded = callId ? facts.get(callKey(record, callId)) : undefined;
84
- return { ...base, role: "tool", text: output(p.output), ...(callId ? { toolCallId: callKey(record, callId) } : {}), ...(p.name == null ? {} : { toolName: str(p.name, "output.name") }), ...(recorded?.error === undefined ? {} : { toolError: recorded.error }) };
85
- }
86
- if (type === "agent_message") return host(record, "agent_message", { author: p.author, recipient: p.recipient, text: textContent(p.content) });
87
- if (OPAQUE_RESPONSES.has(type)) {
88
- // Preserve recorded summaries and available metadata, not encrypted blobs or image bytes.
89
- const { encrypted_content: _encrypted, result: _image, ...readable } = p;
90
- return host(record, `${type} (opaque content omitted; not recovered plaintext)`, readable);
91
- }
92
- if (HOST_RESPONSES.has(type)) return host(record, type, p);
93
- throw new Error(`Unsupported Codex response item: ${type}`);
94
- }
95
-
96
- /** One display record without a raw equivalent (e.g. user-shell command). */
97
- function standaloneTool(record: CodexRecord, item: NativeObject): DecodedHistoryItem {
98
- const base = context(record, ""), recorded = fact(item);
99
- if (item.type === "CommandExecution") {
100
- array(item.command, "command").forEach((part) => str(part, "command argument"));
101
- return { ...base, role: "tool", toolName: "terminal", arguments: { command: item.command, cwd: item.cwd, source: item.source, ...(item.interaction_input == null ? {} : { interaction_input: item.interaction_input }) }, text: recorded.text ?? JSON.stringify({ stdout: item.stdout, stderr: item.stderr, aggregated_output: item.aggregated_output }), recordedStatus: item.status === "in_progress" ? "unfinished" : recorded.error ? "error" : "ok" };
102
- }
103
- const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
104
- return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
105
- }
106
-
107
- export async function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState> {
108
- const { state, records, highestSeq } = await readCodexTranscript(source);
109
- const facts = new Map<string, ToolFact>(), callsSeen = new Set<string>(), responseIdsSeen = new Set<string>();
110
- const windows = new Map<string, DecodedHistoryWindow>(), branchSeqs = new Set<number>();
111
- const addWindow = (nativeId: string, createdAt?: string): DecodedHistoryWindow => {
112
- const windowId = `codex:${source.threadId}:${nativeId}`;
113
- let window = windows.get(windowId);
114
- if (!window) { window = { windowId, createdAt, items: [] }; windows.set(windowId, window); }
115
- return window;
116
- };
117
- // Outcome inventory can enrich the raw result even when ItemCompleted follows it.
118
- for (const record of records) {
119
- const p = record.payload;
120
- if (record.type === "event_msg" && p.type === "item_completed") {
121
- if (p.thread_id !== record.owner) throw new Error("Invalid Codex ItemCompleted thread identity");
122
- const item = obj(p.item, "ItemCompleted.item");
123
- if (toolDisplay(item)) facts.set(callKey(record, str(item.id, "TurnItem.id")), fact(item));
124
- } else if (record.type === "event_msg" && p.type === "patch_apply_end") {
125
- if (typeof p.success !== "boolean") throw new Error("Invalid Codex patch_apply_end.success");
126
- facts.set(callKey(record, str(p.call_id, "patch call_id")), { error: !p.success });
127
- } else if (record.type === "event_msg" && p.type === "mcp_tool_call_end") {
128
- const result = obj(p.result, "MCP Result envelope");
129
- const ok = result.Ok == null ? undefined : obj(result.Ok, "MCP Result.Ok");
130
- if (ok === undefined && typeof result.Err !== "string") throw new Error("Invalid Codex MCP Result: expected Ok or Err");
131
- facts.set(callKey(record, str(p.call_id, "MCP call_id")), { error: result.Err != null || ok?.isError === true, text: JSON.stringify(result) });
132
- }
133
- }
134
- for (const record of records) {
135
- branchSeqs.add(record.seq);
136
- if (record.windowId) addWindow(record.windowId, record.type === "session_meta" || record.type === "compacted" ? record.timestamp : undefined);
137
- const p = record.payload;
138
- let item: DecodedHistoryItem | undefined;
139
- switch (record.type) {
140
- case "session_meta":
141
- if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
142
- break;
143
- case "response_item": {
144
- item = response(record, facts);
145
- if (p.id != null) responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
146
- if (item.role === "tool_call" && item.toolCallId) {
147
- if (callsSeen.has(item.toolCallId)) throw new Error(`Unavailable Codex history: duplicate native call ID ${item.toolCallId}`);
148
- callsSeen.add(item.toolCallId);
149
- }
150
- break;
151
- }
152
- case "compacted": item = context(record, `Codex compaction boundary\n${JSON.stringify({ message: p.message, window_number: p.window_number, first_window_id: p.first_window_id, previous_window_id: p.previous_window_id, window_id: p.window_id, replacement_history_items: Array.isArray(p.replacement_history) ? p.replacement_history.length : null })}\nreplacement_history is an inference checkpoint, not new conversation events.`); break;
153
- case "event_msg": {
154
- const type = str(p.type, "event_msg.type");
155
- if (DISPLAY_COPIES.has(type)) break;
156
- // A rollback changes the native selected window retrospectively. Until its
157
- // turn semantics are decoded, don't return stale-but-plausible boot facts.
158
- if (type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
159
- if (type === "patch_apply_end" && callsSeen.has(callKey(record, str(p.call_id, "patch call_id")))) break;
160
- if (type === "mcp_tool_call_end") {
161
- const call = callKey(record, str(p.call_id, "MCP call_id"));
162
- if (!callsSeen.has(call)) item = host(record, "MCP completion without a recorded raw call", p);
163
- break;
164
- }
165
- if (type === "item_completed") {
166
- const display = obj(p.item, "ItemCompleted.item"), kind = str(display.type, "TurnItem.type");
167
- if (ITEM_COPIES.has(kind)) break;
168
- if (toolDisplay(display) && callsSeen.has(callKey(record, str(display.id, "TurnItem.id")))) break;
169
- if (kind === "CommandExecution" || kind === "McpToolCall") {
170
- item = standaloneTool(record, display);
171
- } else if (kind === "FunctionCallOutput") {
172
- // hook_runtime.rs record_pending_input persists raw output FIRST,
173
- // then emits this presentation copy with the SAME response-item ID.
174
- if (!responseIdsSeen.has(callKey(record, str(display.id, "FunctionCallOutput.id")))) item = host(record, "FunctionCallOutput display without raw output", display);
175
- } else if (HOST_ITEMS.has(kind) || kind === "DynamicToolCall") item = host(record, kind, display);
176
- else throw new Error(`Unsupported Codex TurnItem: ${kind}`);
177
- } else if (HOST_EVENTS.has(type)) {
178
- // Lifecycle's repeated final answer isn't a second assistant message.
179
- const { last_agent_message: _displayCopy, ...facts } = p;
180
- item = host(record, type, facts);
181
- }
182
- else throw new Error(`Unsupported Codex persisted event: ${type}`);
183
- break;
184
- }
185
- case "turn_context": case "token_usage_record": case "security_risk_score": case "inter_agent_communication_metadata": break;
186
- case "world_state": item = context(record, "Codex world_state snapshot/patch omitted from the text projection; not a newly spoken message."); break;
187
- case "inter_agent_communication": item = host(record, "inter-agent communication", { author: p.author, recipient: p.recipient, content: p.encrypted_content == null ? p.content : "[encrypted content unavailable]", trigger_turn: p.trigger_turn }); break;
188
- case "retained_context": case "realtime_item": item = context(record, `Codex ${record.type} omitted from text projection; native structured/retained context is not newly spoken dialogue.`); break;
189
- }
190
- if (item) addWindow(record.windowId!).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
191
- }
192
- return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
193
- }
1
+ /** Codex's SDK-facing entry; the local corpus uses the same persisted wire decoder. */
2
+ export { readCodexHistory } from "../../../src/history/codex.js";
3
+ export type { CodexHistoryState, CodexTranscriptSource } from "../../../src/history/codex.js";
@@ -35,7 +35,7 @@ export function bootWithinCap(boot: string): string | undefined {
35
35
  const bytes = Buffer.byteLength(boot, "utf8");
36
36
  return bytes <= MAX_BOOT_BYTES
37
37
  ? undefined
38
- : `notesoup: this window's boot is ${bytes} bytes, over the ${MAX_BOOT_BYTES}-byte cap. No truncated or spilled boot was injected; slim the home MAPs and restart/resume the thread.`;
38
+ : `notesoup: this window's boot is ${bytes} bytes, over the ${MAX_BOOT_BYTES}-byte cap. No truncated or spilled boot was injected; slim the notebook MAPs and restart/resume the thread.`;
39
39
  }
40
40
 
41
41
  export async function readHookInput(stream: NodeJS.ReadableStream): Promise<string> {
@@ -42,7 +42,7 @@ export function safeThreadId(value: unknown, field = "threadId"): string {
42
42
  export function pluginDataRoot(env: NodeJS.ProcessEnv = process.env): string {
43
43
  const value = env.PLUGIN_DATA;
44
44
  if (typeof value !== "string" || value.trim() === "" || !isAbsolute(value)) {
45
- throw new CodexIdentityError("missing_plugin_data", "PLUGIN_DATA is unavailable. Install notesoup as a Codex plugin (or set PLUGIN_DATA for a standalone test) so hook bindings have one mutable home.");
45
+ throw new CodexIdentityError("missing_plugin_data", "PLUGIN_DATA is unavailable. Install notesoup as a Codex plugin (or set PLUGIN_DATA for a standalone test) so hook bindings have one mutable data directory.");
46
46
  }
47
47
  return resolve(value);
48
48
  }
@@ -52,7 +52,7 @@ export function notesHome(env: NodeJS.ProcessEnv = process.env): string {
52
52
  return value !== undefined && value.trim() !== "" ? resolve(value) : join(homedir(), ".agents", "notes");
53
53
  }
54
54
 
55
- /** Native ids arrive provider-prefixed; @model is the last segment, slugged like every other home. */
55
+ /** Native ids arrive provider-prefixed; @model is the last segment, slugged like every other notebook. */
56
56
  export function modelSlug(value: unknown): string | undefined {
57
57
  if (typeof value !== "string") return undefined;
58
58
  const id = value.trim();
@@ -138,7 +138,7 @@ export function turnModel(meta: Record<string, unknown>): string {
138
138
  }
139
139
  const model = typeof value === "object" && value !== null ? (value as Record<string, unknown>).model : undefined;
140
140
  const slug = modelSlug(model);
141
- if (slug === undefined) throw new CodexIdentityError("missing_model", "Codex did not supply this turn's model in MCP metadata, so notesoup cannot choose an @model home. Update Codex, or call notes from a model turn.");
141
+ if (slug === undefined) throw new CodexIdentityError("missing_model", "Codex did not supply this turn's model in MCP metadata, so notesoup cannot choose an @model notebook. Update Codex, or call notes from a model turn.");
142
142
  return slug;
143
143
  }
144
144
 
@@ -5,11 +5,13 @@ import { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, typ
5
5
  import { Check, Errors } from "typebox/value";
6
6
  import type { TSchema } from "typebox";
7
7
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
8
- import { historyList, historyRead, historyWindows } from "../../../src/tools/history.js";
8
+ import { historyList, historyRead } from "../../../src/tools/history.js";
9
9
  import { wireResult, type Operation, type Outcome } from "../../../src/tools/result.js";
10
10
  import { CodexIdentityError, notesIdentityFor, pluginDataRoot, readBinding, rootSessionIdOf, safeThreadId, turnModel, type ThreadBinding } from "./identity.js";
11
11
  import { readCodexHistory } from "./history.js";
12
+ import { localHistoryCorpus } from "../../../src/history/local.js";
12
13
  import { readStartState } from "./state.js";
14
+ import { notesToolContext } from "../../../src/tools/notes-context.js";
13
15
 
14
16
  type Bound = {
15
17
  readonly operation: Operation<TSchema, unknown, readonly unknown[]>;
@@ -24,7 +26,6 @@ const OPERATIONS: Record<string, Bound> = {
24
26
  notes_search: { operation: notesSearch as unknown as Bound["operation"], history: false },
25
27
  history_list: { operation: historyList as unknown as Bound["operation"], history: true },
26
28
  history_read: { operation: historyRead as unknown as Bound["operation"], history: true },
27
- history_windows: { operation: historyWindows as unknown as Bound["operation"], history: true },
28
29
  };
29
30
 
30
31
  function shellFree(reason: unknown): string {
@@ -128,15 +129,15 @@ export async function callTool(name: string, args: unknown, meta: Record<string,
128
129
  if (!Check(bound.operation.parameters, params)) return failure("invalid_params", `invalid ${name} parameters: ${paramProblem(bound.operation.parameters, params)}`);
129
130
  try {
130
131
  const { binding, rootSessionId, model } = await identityFor(meta, env);
131
- const native = await readNative(binding, rootSessionId, bound.history, meta, env);
132
+ const targetedHistory = bound.history && (params as { session?: string }).session !== undefined;
133
+ const native = await readNative(binding, rootSessionId, bound.history && !targetedHistory, meta, env);
132
134
  if (!bound.history) {
133
- const outcome = await bound.operation.execute(params, notesIdentityFor(binding, model)) as Outcome<unknown>;
135
+ const outcome = await bound.operation.execute(params, notesToolContext(notesIdentityFor(binding, model), binding.cwd)) as Outcome<unknown>;
134
136
  return successFor(bound, outcome);
135
137
  }
136
- const projection = (native as Awaited<ReturnType<typeof readCodexHistory>>).projection;
137
- const outcome = name === "history_windows"
138
- ? await (bound.operation.execute as unknown as (p: unknown, projection: unknown, sessionId: string) => Promise<Outcome<unknown>>)(params, projection, binding.threadId)
139
- : await (bound.operation.execute as unknown as (p: unknown, projection: unknown) => Promise<Outcome<unknown>>)(params, projection);
138
+ const current = async () => (await readNative(binding, rootSessionId, true, meta, env) as Awaited<ReturnType<typeof readCodexHistory>>).projection;
139
+ const context = targetedHistory ? { current, corpus: localHistoryCorpus({ env, current: { harness: "codex", id: binding.threadId, load: async () => ({ projection: await current() }) } }) } : (native as Awaited<ReturnType<typeof readCodexHistory>>).projection;
140
+ const outcome = await bound.operation.execute(params, context) as Outcome<unknown>;
140
141
  return successFor(bound, outcome);
141
142
  } catch (error) {
142
143
  if (error instanceof CodexIdentityError) return failure(error.code, error.message);
@@ -25,7 +25,7 @@ export function missingNativeFacts(reason: string): string {
25
25
  return `notesoup: no boot injected because Codex's native window facts could not be read (${reason}). ${CODEX_SETUP_HINT} notesoup supports Codex 0.160.1 transcripts.`;
26
26
  }
27
27
 
28
- /** A boot can still identify itself when the note store itself refused; it must not pretend homes are empty. */
28
+ /** A boot can still identify itself when the note store itself refused; it must not pretend notebooks are empty. */
29
29
  export function notesFailureBoot(reason: string): string {
30
- return `notesoup: your notes did not load this time (${reason}). Try the notes_list tool; if it fails too, tell the human. Do not assume a home is empty from this failure.`;
30
+ return `notesoup: your notes did not load this time (${reason}). Try the notes_list tool; if it fails too, tell the human. Do not assume a notebook is empty from this failure.`;
31
31
  }
@@ -1,275 +1,3 @@
1
- /** Read-only local rollout decoder for official Codex 0.160.1 (d27764b82f71).
2
- * Wire owners: history/src/{lib,rollout_payload}.rs, rollout/src/ordinal.rs,
3
- * thread-store/src/local/rollout_lineage.rs. Not an app-server history client.
4
- * Native .jsonl.zst reads require Node >=22.15 (node:zlib zstdDecompressSync).
5
- */
6
- import { readFile, readdir, realpath, stat } from "node:fs/promises";
7
- import { basename, dirname, join, relative, sep } from "node:path";
8
- import { zstdDecompressSync } from "node:zlib";
9
-
10
- export type CodexTranscriptSource = { transcriptPath: string; threadId: string };
11
- export type CodexTranscriptState = {
12
- threadId: string;
13
- rootSessionId: string;
14
- cliVersion: string;
15
- cwd: string;
16
- model?: string;
17
- /** Native, UNPREFIXED identities, also used by MCP _meta.windowId. */
18
- currentWindowId?: string;
19
- currentWindowNumber?: number;
20
- firstWindowId?: string;
21
- previousWindowId?: string;
22
- };
23
- export type NativeObject = Record<string, unknown>;
24
- export type CodexRecord = {
25
- type: string;
26
- payload: NativeObject;
27
- metadata?: NativeObject;
28
- timestamp: string;
29
- /** One record owns one seq, including records omitted from presentation. */
30
- seq: number;
31
- /** Metadata belongs to its physical segment, not the root-scoped session_id. */
32
- owner: string;
33
- /** Native window at this point, absent only when the producer did not persist it. */
34
- windowId?: string;
35
- };
36
- type Position = { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number };
37
- type Segment = { meta: NativeObject; records: CodexRecord[] };
38
- const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
39
- const UUID_RE = new RegExp(`^${UUID}$`);
40
- const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
41
- const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
42
- const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
43
- // Explicit resource limits, not guessed sequence offsets or partial successful history.
44
- const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
45
- export function nativeObject(value: unknown, field: string): NativeObject {
46
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an object`);
47
- return value as NativeObject;
48
- }
49
- export function nativeString(value: unknown, field: string): string {
50
- if (typeof value !== "string") throw new Error(`Invalid Codex ${field}: expected a string`);
51
- return value;
52
- }
53
- function responseShape(value: unknown): void {
54
- const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
55
- if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
56
- }
57
- function id(value: unknown, field: string): string {
58
- const result = nativeString(value, field);
59
- if (!UUID_RE.test(result)) throw new Error(`Invalid Codex ${field}: expected a canonical UUID`);
60
- return result;
61
- }
62
- function integer(value: unknown, field: string): number {
63
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER) throw new Error(`Invalid Codex ${field}: unsafe or negative integer`);
64
- return value;
65
- }
66
- function position(value: unknown): Position | undefined {
67
- if (value == null) return undefined;
68
- const p = nativeObject(value, "history_base");
69
- return { thread_id: id(p.thread_id, "history_base.thread_id (rollout ID)"), end_ordinal_exclusive: integer(p.end_ordinal_exclusive, "history_base ordinal"), end_byte_offset: integer(p.end_byte_offset, "history_base byte offset") };
70
- }
71
- function initialWindow(meta: NativeObject): string | undefined {
72
- return meta.context_window == null ? undefined : id(nativeObject(meta.context_window, "context_window").window_id, "context_window.window_id");
73
- }
74
- function checkMeta(meta: NativeObject): void {
75
- id(meta.id, "session_meta.id");
76
- if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
77
- if (meta.cli_version !== "0.160.1") throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
78
- nativeString(meta.cwd, "session_meta.cwd");
79
- if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
80
- for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
81
- for (const field of ["forked_from_ordinal_exclusive", "subagent_history_start_ordinal"]) if (meta[field] != null) integer(meta[field], field);
82
- initialWindow(meta);
83
- }
84
-
85
- /** Only newline-committed records count. A valid JSON value without its newline is still an append tail. */
86
- function segmentFromBytes(bytes: Buffer, cutoff?: Position): Segment {
87
- const limit = cutoff?.end_byte_offset ?? bytes.length;
88
- if (limit > bytes.length || (cutoff && (limit === 0 || bytes[limit - 1] !== 10))) throw new Error("Unavailable Codex lineage: cutoff is not a complete decoded JSONL boundary");
89
- const records: CodexRecord[] = [];
90
- let meta: NativeObject | undefined, previous = -1, lineNumber = 0;
91
- for (let offset = 0; offset < limit;) {
92
- const newline = bytes.indexOf(10, offset);
93
- if (newline < 0 || newline >= limit) break;
94
- lineNumber++;
95
- let row: NativeObject;
96
- try {
97
- const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, newline));
98
- row = nativeObject(JSON.parse(text), "record");
99
- } catch { throw new Error(`Malformed committed Codex JSONL record at line ${lineNumber}`); }
100
- offset = newline + 1;
101
- const type = nativeString(row.type, "record.type");
102
- if (!RECORD_TYPES.has(type)) throw new Error(`Unsupported Codex rollout record: ${type}`);
103
- const payload = nativeObject(row.payload, `${type}.payload`);
104
- if (!meta) {
105
- if (type !== "session_meta") throw new Error("Invalid Codex transcript: first record must be session_meta");
106
- meta = payload;
107
- checkMeta(meta);
108
- } else if (type === "session_meta") {
109
- // Legacy copied forks can contain replayed metadata with no provable original
110
- // coordinates. Do not relabel a copied tree as independently spoken events.
111
- throw new Error("Unavailable Codex history: copied session_meta ancestry has no proved source addresses");
112
- }
113
- const paginated = meta.history_mode === "paginated";
114
- const ordinal = paginated ? integer(row.ordinal, "paginated record ordinal") : lineNumber - 1;
115
- if (!paginated && row.ordinal != null) throw new Error("Invalid Codex legacy transcript: unexpected ordinal");
116
- if (ordinal <= previous) throw new Error("Invalid Codex transcript: non-increasing record ordinals");
117
- if (records.length === 0 && ordinal !== (position(meta.history_base)?.end_ordinal_exclusive ?? 0)) throw new Error("Invalid Codex transcript: metadata ordinal does not match history_base");
118
- previous = ordinal;
119
- if (cutoff && ordinal >= cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
120
- if (type === "event_msg" && payload.type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
121
- if (type === "response_item") responseShape(payload);
122
- records.push({ type, payload, timestamp: nativeString(row.timestamp, "record.timestamp"), seq: ordinal + 1, owner: meta.id as string, ...(row.metadata == null ? {} : { metadata: nativeObject(row.metadata, "response metadata") }) });
123
- }
124
- if (!meta) throw new Error("Unavailable Codex transcript: no committed session_meta yet");
125
- const base = position(meta.history_base);
126
- if (base && meta.history_mode !== "paginated") throw new Error("Invalid Codex history_base on a non-paginated transcript");
127
- if (cutoff && meta.history_mode !== "paginated") throw new Error("Unavailable Codex lineage: referenced source is not paginated");
128
- // A cutoff is a native coordinate pair, not permission to approximate an ordinal
129
- // inside a gap. Usually the included prefix already proves its exclusive end.
130
- if (cutoff && previous + 1 !== cutoff.end_ordinal_exclusive) {
131
- const nextNewline = bytes.indexOf(10, limit);
132
- if (nextNewline < 0) throw new Error("Unavailable Codex lineage: ordinal cutoff is beyond the proved prefix");
133
- let next: NativeObject;
134
- try { next = nativeObject(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(limit, nextNewline))), "cutoff successor"); }
135
- catch { throw new Error("Unavailable Codex lineage: cannot prove ordinal cutoff successor"); }
136
- if (integer(next.ordinal, "cutoff successor ordinal") !== cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
137
- }
138
- const start = meta.subagent_history_start_ordinal;
139
- if (start != null && (meta.history_mode !== "paginated" || previous < integer(start, "subagent history start") - 1)) throw new Error("Unavailable Codex history: incomplete inherited subagent prefix");
140
- return { meta, records };
141
- }
142
-
143
- function within(root: string, path: string): boolean {
144
- const rel = relative(root, path);
145
- return rel !== ".." && !rel.startsWith(`..${sep}`);
146
- }
147
- /** Infer storage roots only from the supplied native path, never $HOME or a private DB. */
148
- function storageHome(path: string): string {
149
- for (let cursor = dirname(path); dirname(cursor) !== cursor; cursor = dirname(cursor)) {
150
- if (basename(cursor) === "sessions" || basename(cursor) === "archived_sessions") return dirname(cursor);
151
- }
152
- throw new Error("Unavailable Codex lineage: transcript must be under native sessions/ or archived_sessions/ to resolve history_base");
153
- }
154
- async function referencedPath(home: string, rolloutId: string): Promise<string> {
155
- const matches: string[] = [], directories = [join(home, "sessions"), join(home, "archived_sessions")];
156
- let entriesSeen = 0;
157
- while (directories.length) {
158
- const directory = directories.pop()!;
159
- let entries;
160
- try { entries = await readdir(directory, { withFileTypes: true }); }
161
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
162
- for (const entry of entries) {
163
- if (++entriesSeen > MAX_DIRECTORY_ENTRIES) throw new Error("Unavailable Codex lineage: native directory discovery limit exceeded");
164
- const path = join(directory, entry.name);
165
- if (entry.isDirectory()) directories.push(path);
166
- else if (entry.isFile()) {
167
- const name = FILE_RE.exec(entry.name);
168
- if (name && (name[2] ?? name[1]) === rolloutId) matches.push(path);
169
- }
170
- }
171
- }
172
- if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
173
- return matches[0]!;
174
- }
175
- async function decodedBytes(path: string, remaining: number): Promise<Buffer> {
176
- const info = await stat(path);
177
- if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
178
- const bytes = await readFile(path);
179
- // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
180
- const decoded = path.endsWith(".jsonl.zst") ? zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
181
- if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
182
- return decoded;
183
- }
184
-
185
- /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
186
- export async function readCodexTranscript(source: CodexTranscriptSource): Promise<{ state: CodexTranscriptState; records: CodexRecord[]; highestSeq: number }> {
187
- if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
188
- id(source.threadId, "requested threadId");
189
- try {
190
- let path = await realpath(source.transcriptPath), cutoff: Position | undefined, home: string | undefined;
191
- let remaining = MAX_BYTES;
192
- const segments: Segment[] = [], seen = new Set<string>();
193
- while (true) {
194
- if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
195
- seen.add(path);
196
- const bytes = await decodedBytes(path, remaining);
197
- remaining -= bytes.length;
198
- const segment = segmentFromBytes(bytes, cutoff);
199
- if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
200
- if (cutoff) {
201
- const name = FILE_RE.exec(basename(path));
202
- if (!name || (name[2] ?? name[1]) !== cutoff.thread_id || name[1] !== segment.meta.id) throw new Error("Unavailable Codex lineage: native filename/rollout/metadata identity mismatch");
203
- }
204
- segments.unshift(segment);
205
- const base = position(segment.meta.history_base);
206
- if (!base) break;
207
- if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
208
- home ??= storageHome(path);
209
- path = await realpath(await referencedPath(home, base.thread_id));
210
- if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
211
- cutoff = base;
212
- }
213
- // history_base is physical; forked_from_ordinal_exclusive is the logical
214
- // parent boundary (protocol.rs HistoryPosition, revert_thread.rs). A revert
215
- // may retain this thread's own later delta, but cannot grow inherited history.
216
- for (let index = 0; index < segments.length; index++) {
217
- const meta = segments[index]!.meta, end = meta.forked_from_ordinal_exclusive;
218
- if (end != null && meta.forked_from_id != null) {
219
- for (const ancestor of segments.slice(0, index)) {
220
- if (ancestor.meta.id !== meta.id && ancestor.records.some((record) => record.seq - 1 >= (end as number))) throw new Error("Unavailable Codex lineage: physical ancestry exceeds the logical fork cutoff");
221
- }
222
- }
223
- }
224
- const selected = segments.at(-1)!.meta;
225
- const state: CodexTranscriptState = { threadId: source.threadId, rootSessionId: (selected.session_id ?? selected.id) as string, cliVersion: selected.cli_version as string, cwd: selected.cwd as string };
226
- const records: CodexRecord[] = [];
227
- let window: string | undefined, first: string | undefined, previousWindow: string | undefined, number: number | undefined, sawCompacted = false, lastSeq = 0;
228
- let contextModel: string | undefined, settingsModel: string | undefined;
229
- for (const segment of segments) {
230
- // Native reconstruction uses the requested header's initial identity unless
231
- // an inherited checkpoint supplies the effective window (rollout_reconstruction.rs).
232
- if (!sawCompacted) { window = initialWindow(segment.meta); first = window; previousWindow = undefined; number = window ? 0 : undefined; }
233
- for (const record of segment.records) {
234
- if (record.seq <= lastSeq) throw new Error("Unavailable Codex lineage: overlapping source coordinates");
235
- lastSeq = record.seq;
236
- if (record.type === "compacted") {
237
- sawCompacted = true;
238
- const p = record.payload;
239
- nativeString(p.message, "compacted.message");
240
- if (p.replacement_history != null && !Array.isArray(p.replacement_history)) throw new Error("Invalid Codex replacement_history");
241
- if (Array.isArray(p.replacement_history)) p.replacement_history.forEach(responseShape);
242
- if (p.replacement_history_metadata != null && (!Array.isArray(p.replacement_history_metadata) || !Array.isArray(p.replacement_history) || p.replacement_history_metadata.length !== p.replacement_history.length)) throw new Error("Invalid Codex replacement_history_metadata alignment");
243
- // Numeric legacy window_id has no usable native identity; don't turn it
244
- // into a UUID, or silently assign subsequent records to the old window.
245
- window = p.window_id == null || typeof p.window_id === "number" ? undefined : id(p.window_id, "compacted.window_id");
246
- number = p.window_number == null ? (typeof p.window_id === "number" ? integer(p.window_id, "legacy window number") : undefined) : integer(p.window_number, "window_number");
247
- first = p.first_window_id == null ? undefined : id(p.first_window_id, "first_window_id");
248
- previousWindow = p.previous_window_id == null ? undefined : id(p.previous_window_id, "previous_window_id");
249
- }
250
- record.windowId = window;
251
- // Explicitly copied subagent inference context isn't child-local history.
252
- // Preserve its coordinates as holes, not invented parent event addresses.
253
- const start = segment.meta.subagent_history_start_ordinal;
254
- if (start != null && record.type !== "session_meta" && record.seq - 1 < (start as number)) continue;
255
- if (record.owner === source.threadId && record.type === "turn_context") contextModel = nativeString(record.payload.model, "turn_context.model");
256
- if (record.type === "event_msg" && record.payload.type === "thread_settings_applied" && record.payload.thread_id === source.threadId) {
257
- settingsModel = nativeString(nativeObject(record.payload.thread_settings, "thread_settings").model, "thread_settings.model");
258
- }
259
- records.push(record);
260
- }
261
- }
262
- Object.assign(state, { currentWindowId: window, currentWindowNumber: number, firstWindowId: first, previousWindowId: previousWindow });
263
- // Native latest model settings win over a frozen companion TurnContext after
264
- // compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
265
- if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
266
- return { state, records, highestSeq: lastSeq };
267
- } catch (error) {
268
- throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
269
- }
270
- }
271
-
272
- /** Same decoder and ownership as history; no independently guessed boot window. */
273
- export async function readCodexTranscriptState(source: CodexTranscriptSource): Promise<CodexTranscriptState> {
274
- return (await readCodexTranscript(source)).state;
275
- }
1
+ /** Codex wire-format entry shared by boot/state and cross-harness history. */
2
+ export { nativeObject, nativeString, readCodexTranscript, readCodexTranscriptState } from "../../../src/history/codex-transcript.js";
3
+ export type { CodexTranscriptSource, CodexTranscriptState, CodexRecord, NativeObject } from "../../../src/history/codex-transcript.js";
@@ -129,8 +129,8 @@ export class NotesoupCompactionEngine extends CompactionEngine {
129
129
  try {
130
130
  const next = await this.windows.mint(agent, previous.window + 1, opened.time);
131
131
  signal?.throwIfAborted();
132
- if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1) throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
133
- // Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
132
+ if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1) throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next page; retry after current work finishes.");
133
+ // Mint BEFORE writing the checkpoint. A rejected append restores the previous page.
134
134
  // One draw per reset artifact: the checkpoint text and the steered copy share it.
135
135
  const continuation = selectContinuation(origin);
136
136
  state.snapshot = next;
@@ -2,6 +2,8 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { SessionId, SessionEvent } from "@deepseek-ai/dsh-session";
3
3
  import type {} from "@deepseek-ai/dsh-session-query";
4
4
  import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "../../src/history/history.js";
5
+ import { localHistoryCorpus } from "../../src/history/local.js";
6
+ import type { HistoryContext } from "../../src/history/corpus.js";
5
7
  import { checkpointSnapshot, recordSnapshot, windowId } from "./window.js";
6
8
 
7
9
  /** Preserve every recorded block; attachments/reasoning have JSON evidence rather than invented text. */
@@ -55,3 +57,18 @@ export async function historyProjection(ctx: Context, sessionId: SessionId): Pro
55
57
  const log = await ctx.sessionQuery.readSession(sessionId);
56
58
  return decodeHistory(sessionId, log.events);
57
59
  }
60
+
61
+ /** DSH contributes its logical live/persisted corpus; foreign files use SDK-free decoders. */
62
+ export function historyContext(ctx: Context, sessionId: SessionId): HistoryContext {
63
+ const current = () => historyProjection(ctx, sessionId);
64
+ return { current, corpus: localHistoryCorpus({
65
+ current: { harness: "dsh", id: sessionId, load: async () => ({ projection: await current() }) },
66
+ dshSessions: async () => Promise.all((await ctx.sessionQuery.listSessions()).map(async ({ header }) => {
67
+ const log = await ctx.sessionQuery.readSession(header.id);
68
+ return {
69
+ harness: "dsh" as const, id: header.id, modifiedAt: log.events.at(-1)?.time ?? header.createdAt,
70
+ load: async () => ({ projection: decodeHistory(header.id, log.events) }),
71
+ };
72
+ })),
73
+ }) };
74
+ }