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,313 +1,2 @@
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
- const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
10
- const UUID_RE = new RegExp(`^${UUID}$`);
11
- const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
12
- 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"]);
13
- 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"]);
14
- // Explicit resource limits, not guessed sequence offsets or partial successful history.
15
- const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
16
- export function nativeObject(value, field) {
17
- if (typeof value !== "object" || value === null || Array.isArray(value))
18
- throw new Error(`Invalid Codex ${field}: expected an object`);
19
- return value;
20
- }
21
- export function nativeString(value, field) {
22
- if (typeof value !== "string")
23
- throw new Error(`Invalid Codex ${field}: expected a string`);
24
- return value;
25
- }
26
- function responseShape(value) {
27
- const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
28
- if (!RESPONSE_TYPES.has(type))
29
- throw new Error(`Unsupported Codex response item: ${type}`);
30
- }
31
- function id(value, field) {
32
- const result = nativeString(value, field);
33
- if (!UUID_RE.test(result))
34
- throw new Error(`Invalid Codex ${field}: expected a canonical UUID`);
35
- return result;
36
- }
37
- function integer(value, field) {
38
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER)
39
- throw new Error(`Invalid Codex ${field}: unsafe or negative integer`);
40
- return value;
41
- }
42
- function position(value) {
43
- if (value == null)
44
- return undefined;
45
- const p = nativeObject(value, "history_base");
46
- 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") };
47
- }
48
- function initialWindow(meta) {
49
- return meta.context_window == null ? undefined : id(nativeObject(meta.context_window, "context_window").window_id, "context_window.window_id");
50
- }
51
- function checkMeta(meta) {
52
- id(meta.id, "session_meta.id");
53
- if (meta.session_id != null)
54
- id(meta.session_id, "session_meta.session_id");
55
- if (meta.cli_version !== "0.160.1")
56
- throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
57
- nativeString(meta.cwd, "session_meta.cwd");
58
- if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated")
59
- throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
60
- for (const field of ["forked_from_id", "parent_thread_id"])
61
- if (meta[field] != null)
62
- id(meta[field], field);
63
- for (const field of ["forked_from_ordinal_exclusive", "subagent_history_start_ordinal"])
64
- if (meta[field] != null)
65
- integer(meta[field], field);
66
- initialWindow(meta);
67
- }
68
- /** Only newline-committed records count. A valid JSON value without its newline is still an append tail. */
69
- function segmentFromBytes(bytes, cutoff) {
70
- const limit = cutoff?.end_byte_offset ?? bytes.length;
71
- if (limit > bytes.length || (cutoff && (limit === 0 || bytes[limit - 1] !== 10)))
72
- throw new Error("Unavailable Codex lineage: cutoff is not a complete decoded JSONL boundary");
73
- const records = [];
74
- let meta, previous = -1, lineNumber = 0;
75
- for (let offset = 0; offset < limit;) {
76
- const newline = bytes.indexOf(10, offset);
77
- if (newline < 0 || newline >= limit)
78
- break;
79
- lineNumber++;
80
- let row;
81
- try {
82
- const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, newline));
83
- row = nativeObject(JSON.parse(text), "record");
84
- }
85
- catch {
86
- throw new Error(`Malformed committed Codex JSONL record at line ${lineNumber}`);
87
- }
88
- offset = newline + 1;
89
- const type = nativeString(row.type, "record.type");
90
- if (!RECORD_TYPES.has(type))
91
- throw new Error(`Unsupported Codex rollout record: ${type}`);
92
- const payload = nativeObject(row.payload, `${type}.payload`);
93
- if (!meta) {
94
- if (type !== "session_meta")
95
- throw new Error("Invalid Codex transcript: first record must be session_meta");
96
- meta = payload;
97
- checkMeta(meta);
98
- }
99
- else if (type === "session_meta") {
100
- // Legacy copied forks can contain replayed metadata with no provable original
101
- // coordinates. Do not relabel a copied tree as independently spoken events.
102
- throw new Error("Unavailable Codex history: copied session_meta ancestry has no proved source addresses");
103
- }
104
- const paginated = meta.history_mode === "paginated";
105
- const ordinal = paginated ? integer(row.ordinal, "paginated record ordinal") : lineNumber - 1;
106
- if (!paginated && row.ordinal != null)
107
- throw new Error("Invalid Codex legacy transcript: unexpected ordinal");
108
- if (ordinal <= previous)
109
- throw new Error("Invalid Codex transcript: non-increasing record ordinals");
110
- if (records.length === 0 && ordinal !== (position(meta.history_base)?.end_ordinal_exclusive ?? 0))
111
- throw new Error("Invalid Codex transcript: metadata ordinal does not match history_base");
112
- previous = ordinal;
113
- if (cutoff && ordinal >= cutoff.end_ordinal_exclusive)
114
- throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
115
- if (type === "event_msg" && payload.type === "thread_rolled_back")
116
- throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
117
- if (type === "response_item")
118
- responseShape(payload);
119
- records.push({ type, payload, timestamp: nativeString(row.timestamp, "record.timestamp"), seq: ordinal + 1, owner: meta.id, ...(row.metadata == null ? {} : { metadata: nativeObject(row.metadata, "response metadata") }) });
120
- }
121
- if (!meta)
122
- throw new Error("Unavailable Codex transcript: no committed session_meta yet");
123
- const base = position(meta.history_base);
124
- if (base && meta.history_mode !== "paginated")
125
- throw new Error("Invalid Codex history_base on a non-paginated transcript");
126
- if (cutoff && meta.history_mode !== "paginated")
127
- 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)
133
- throw new Error("Unavailable Codex lineage: ordinal cutoff is beyond the proved prefix");
134
- let next;
135
- try {
136
- next = nativeObject(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(limit, nextNewline))), "cutoff successor");
137
- }
138
- catch {
139
- throw new Error("Unavailable Codex lineage: cannot prove ordinal cutoff successor");
140
- }
141
- if (integer(next.ordinal, "cutoff successor ordinal") !== cutoff.end_ordinal_exclusive)
142
- throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
143
- }
144
- const start = meta.subagent_history_start_ordinal;
145
- if (start != null && (meta.history_mode !== "paginated" || previous < integer(start, "subagent history start") - 1))
146
- throw new Error("Unavailable Codex history: incomplete inherited subagent prefix");
147
- return { meta, records };
148
- }
149
- function within(root, path) {
150
- const rel = relative(root, path);
151
- return rel !== ".." && !rel.startsWith(`..${sep}`);
152
- }
153
- /** Infer storage roots only from the supplied native path, never $HOME or a private DB. */
154
- function storageHome(path) {
155
- for (let cursor = dirname(path); dirname(cursor) !== cursor; cursor = dirname(cursor)) {
156
- if (basename(cursor) === "sessions" || basename(cursor) === "archived_sessions")
157
- return dirname(cursor);
158
- }
159
- throw new Error("Unavailable Codex lineage: transcript must be under native sessions/ or archived_sessions/ to resolve history_base");
160
- }
161
- async function referencedPath(home, rolloutId) {
162
- const matches = [], directories = [join(home, "sessions"), join(home, "archived_sessions")];
163
- let entriesSeen = 0;
164
- while (directories.length) {
165
- const directory = directories.pop();
166
- let entries;
167
- try {
168
- entries = await readdir(directory, { withFileTypes: true });
169
- }
170
- catch (error) {
171
- if (error.code === "ENOENT")
172
- continue;
173
- throw error;
174
- }
175
- for (const entry of entries) {
176
- if (++entriesSeen > MAX_DIRECTORY_ENTRIES)
177
- throw new Error("Unavailable Codex lineage: native directory discovery limit exceeded");
178
- const path = join(directory, entry.name);
179
- if (entry.isDirectory())
180
- directories.push(path);
181
- else if (entry.isFile()) {
182
- const name = FILE_RE.exec(entry.name);
183
- if (name && (name[2] ?? name[1]) === rolloutId)
184
- matches.push(path);
185
- }
186
- }
187
- }
188
- if (matches.length !== 1)
189
- throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
190
- return matches[0];
191
- }
192
- async function decodedBytes(path, remaining) {
193
- const info = await stat(path);
194
- if (!info.isFile() || info.size > remaining)
195
- throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
196
- const bytes = await readFile(path);
197
- // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
198
- const decoded = path.endsWith(".jsonl.zst") ? zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
199
- if (decoded.length > remaining)
200
- throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
201
- return decoded;
202
- }
203
- /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
204
- export async function readCodexTranscript(source) {
205
- if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath)
206
- throw new Error("Codex transcript_path is unavailable");
207
- id(source.threadId, "requested threadId");
208
- try {
209
- let path = await realpath(source.transcriptPath), cutoff, home;
210
- let remaining = MAX_BYTES;
211
- const segments = [], seen = new Set();
212
- while (true) {
213
- if (segments.length >= MAX_SEGMENTS || seen.has(path))
214
- throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
215
- seen.add(path);
216
- const bytes = await decodedBytes(path, remaining);
217
- remaining -= bytes.length;
218
- const segment = segmentFromBytes(bytes, cutoff);
219
- if (segments.length === 0 && segment.meta.id !== source.threadId)
220
- throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
221
- if (cutoff) {
222
- const name = FILE_RE.exec(basename(path));
223
- if (!name || (name[2] ?? name[1]) !== cutoff.thread_id || name[1] !== segment.meta.id)
224
- throw new Error("Unavailable Codex lineage: native filename/rollout/metadata identity mismatch");
225
- }
226
- segments.unshift(segment);
227
- const base = position(segment.meta.history_base);
228
- if (!base)
229
- break;
230
- if (base.end_ordinal_exclusive === 0)
231
- throw new Error("Invalid Codex lineage: history_base must include source metadata");
232
- home ??= storageHome(path);
233
- path = await realpath(await referencedPath(home, base.thread_id));
234
- if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path)))
235
- throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
236
- cutoff = base;
237
- }
238
- // history_base is physical; forked_from_ordinal_exclusive is the logical
239
- // parent boundary (protocol.rs HistoryPosition, revert_thread.rs). A revert
240
- // may retain this thread's own later delta, but cannot grow inherited history.
241
- for (let index = 0; index < segments.length; index++) {
242
- const meta = segments[index].meta, end = meta.forked_from_ordinal_exclusive;
243
- if (end != null && meta.forked_from_id != null) {
244
- for (const ancestor of segments.slice(0, index)) {
245
- if (ancestor.meta.id !== meta.id && ancestor.records.some((record) => record.seq - 1 >= end))
246
- throw new Error("Unavailable Codex lineage: physical ancestry exceeds the logical fork cutoff");
247
- }
248
- }
249
- }
250
- const selected = segments.at(-1).meta;
251
- const state = { threadId: source.threadId, rootSessionId: (selected.session_id ?? selected.id), cliVersion: selected.cli_version, cwd: selected.cwd };
252
- const records = [];
253
- let window, first, previousWindow, number, sawCompacted = false, lastSeq = 0;
254
- let contextModel, settingsModel;
255
- for (const segment of segments) {
256
- // Native reconstruction uses the requested header's initial identity unless
257
- // an inherited checkpoint supplies the effective window (rollout_reconstruction.rs).
258
- if (!sawCompacted) {
259
- window = initialWindow(segment.meta);
260
- first = window;
261
- previousWindow = undefined;
262
- number = window ? 0 : undefined;
263
- }
264
- for (const record of segment.records) {
265
- if (record.seq <= lastSeq)
266
- throw new Error("Unavailable Codex lineage: overlapping source coordinates");
267
- lastSeq = record.seq;
268
- if (record.type === "compacted") {
269
- sawCompacted = true;
270
- const p = record.payload;
271
- nativeString(p.message, "compacted.message");
272
- if (p.replacement_history != null && !Array.isArray(p.replacement_history))
273
- throw new Error("Invalid Codex replacement_history");
274
- if (Array.isArray(p.replacement_history))
275
- p.replacement_history.forEach(responseShape);
276
- 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))
277
- throw new Error("Invalid Codex replacement_history_metadata alignment");
278
- // Numeric legacy window_id has no usable native identity; don't turn it
279
- // into a UUID, or silently assign subsequent records to the old window.
280
- window = p.window_id == null || typeof p.window_id === "number" ? undefined : id(p.window_id, "compacted.window_id");
281
- number = p.window_number == null ? (typeof p.window_id === "number" ? integer(p.window_id, "legacy window number") : undefined) : integer(p.window_number, "window_number");
282
- first = p.first_window_id == null ? undefined : id(p.first_window_id, "first_window_id");
283
- previousWindow = p.previous_window_id == null ? undefined : id(p.previous_window_id, "previous_window_id");
284
- }
285
- record.windowId = window;
286
- // Explicitly copied subagent inference context isn't child-local history.
287
- // Preserve its coordinates as holes, not invented parent event addresses.
288
- const start = segment.meta.subagent_history_start_ordinal;
289
- if (start != null && record.type !== "session_meta" && record.seq - 1 < start)
290
- continue;
291
- if (record.owner === source.threadId && record.type === "turn_context")
292
- contextModel = nativeString(record.payload.model, "turn_context.model");
293
- if (record.type === "event_msg" && record.payload.type === "thread_settings_applied" && record.payload.thread_id === source.threadId) {
294
- settingsModel = nativeString(nativeObject(record.payload.thread_settings, "thread_settings").model, "thread_settings.model");
295
- }
296
- records.push(record);
297
- }
298
- }
299
- Object.assign(state, { currentWindowId: window, currentWindowNumber: number, firstWindowId: first, previousWindowId: previousWindow });
300
- // Native latest model settings win over a frozen companion TurnContext after
301
- // compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
302
- if (settingsModel ?? contextModel)
303
- state.model = settingsModel ?? contextModel;
304
- return { state, records, highestSeq: lastSeq };
305
- }
306
- catch (error) {
307
- throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
308
- }
309
- }
310
- /** Same decoder and ownership as history; no independently guessed boot window. */
311
- export async function readCodexTranscriptState(source) {
312
- return (await readCodexTranscript(source)).state;
313
- }
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";
@@ -142,8 +142,8 @@ export class NotesoupCompactionEngine extends CompactionEngine {
142
142
  const next = await this.windows.mint(agent, previous.window + 1, opened.time);
143
143
  signal?.throwIfAborted();
144
144
  if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1)
145
- throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
146
- // Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
145
+ throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next page; retry after current work finishes.");
146
+ // Mint BEFORE writing the checkpoint. A rejected append restores the previous page.
147
147
  // One draw per reset artifact: the checkpoint text and the steered copy share it.
148
148
  const continuation = selectContinuation(origin);
149
149
  state.snapshot = next;
@@ -1,6 +1,9 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { SessionId, SessionEvent } from "@deepseek-ai/dsh-session";
3
3
  import { type HistoryProjection } from "../../src/history/history.js";
4
+ import type { HistoryContext } from "../../src/history/corpus.js";
4
5
  /** Native seq zero becomes public seq one. Forks contain only their selected seed prefix. */
5
6
  export declare function decodeHistory(sessionId: string, events: readonly SessionEvent[]): HistoryProjection;
6
7
  export declare function historyProjection(ctx: Context, sessionId: SessionId): Promise<HistoryProjection>;
8
+ /** DSH contributes its logical live/persisted corpus; foreign files use SDK-free decoders. */
9
+ export declare function historyContext(ctx: Context, sessionId: SessionId): HistoryContext;
@@ -1,4 +1,5 @@
1
1
  import { projectHistory } from "../../src/history/history.js";
2
+ import { localHistoryCorpus } from "../../src/history/local.js";
2
3
  import { checkpointSnapshot, recordSnapshot, windowId } from "./window.js";
3
4
  /** Preserve every recorded block; attachments/reasoning have JSON evidence rather than invented text. */
4
5
  function blockText(content, omitCalls = false) {
@@ -71,3 +72,17 @@ export async function historyProjection(ctx, sessionId) {
71
72
  const log = await ctx.sessionQuery.readSession(sessionId);
72
73
  return decodeHistory(sessionId, log.events);
73
74
  }
75
+ /** DSH contributes its logical live/persisted corpus; foreign files use SDK-free decoders. */
76
+ export function historyContext(ctx, sessionId) {
77
+ const current = () => historyProjection(ctx, sessionId);
78
+ return { current, corpus: localHistoryCorpus({
79
+ current: { harness: "dsh", id: sessionId, load: async () => ({ projection: await current() }) },
80
+ dshSessions: async () => Promise.all((await ctx.sessionQuery.listSessions()).map(async ({ header }) => {
81
+ const log = await ctx.sessionQuery.readSession(header.id);
82
+ return {
83
+ harness: "dsh", id: header.id, modifiedAt: log.events.at(-1)?.time ?? header.createdAt,
84
+ load: async () => ({ projection: decodeHistory(header.id, log.events) }),
85
+ };
86
+ })),
87
+ }) };
88
+ }
@@ -2,10 +2,11 @@ import { HarnessError } from "@deepseek-ai/dsh-llm";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import { Check, Errors } from "typebox/value";
4
4
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../src/tools/notes.js";
5
- import { historyList, historyRead, historyWindows } from "../../src/tools/history.js";
5
+ import { historyList, historyRead } from "../../src/tools/history.js";
6
6
  import { success } from "../../src/tools/result.js";
7
- import { historyProjection } from "./history.js";
8
- import { notesIdentity } from "./window.js";
7
+ import { historyContext } from "./history.js";
8
+ import { notesCwd, notesIdentity } from "./window.js";
9
+ import { notesToolContext } from "../../src/tools/notes-context.js";
9
10
  import { measureBudget } from "./budget.js";
10
11
  import { preflight } from "./engine.js";
11
12
  /** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
@@ -75,15 +76,14 @@ export function registerTools(ctx, engine) {
75
76
  if (!exec.parent && nestedResets.get(exec.agent)?.delete(exec.rootCallId) && !result.isError)
76
77
  state.pendingReset = true;
77
78
  });
78
- const identity = (agent) => notesIdentity(agent, engine.config);
79
- register(ctx, notesWrite, (agent) => [identity(agent)]);
80
- register(ctx, notesUpdate, (agent) => [identity(agent)]);
81
- register(ctx, notesRead, (agent) => [identity(agent)]);
82
- register(ctx, notesList, (agent) => [identity(agent)]);
83
- register(ctx, notesSearch, (agent) => [identity(agent)]);
84
- register(ctx, historyList, async (agent) => [await historyProjection(ctx, agent.session.id)]);
85
- register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)]);
86
- register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id]);
79
+ const toolContext = (agent) => notesToolContext(notesIdentity(agent, engine.config), notesCwd(agent));
80
+ register(ctx, notesWrite, (agent) => [toolContext(agent)]);
81
+ register(ctx, notesUpdate, (agent) => [toolContext(agent)]);
82
+ register(ctx, notesRead, (agent) => [toolContext(agent)]);
83
+ register(ctx, notesList, (agent) => [toolContext(agent)]);
84
+ register(ctx, notesSearch, (agent) => [toolContext(agent)]);
85
+ register(ctx, historyList, (agent) => [historyContext(ctx, agent.session.id)]);
86
+ register(ctx, historyRead, (agent) => [historyContext(ctx, agent.session.id)]);
87
87
  ctx.tools.register(defineTool({
88
88
  name: "empty_brain",
89
89
  description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
@@ -34,6 +34,7 @@ export declare function recordSnapshot(event: SessionEvent): WindowSnapshot | un
34
34
  /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
35
35
  export declare function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined;
36
36
  export declare function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined;
37
+ export declare function notesCwd(agent: Pick<Agent, "session" | "options">): string;
37
38
  /** Identity is extracted here, never in the filesystem domain. */
38
39
  export declare function notesIdentity(agent: Pick<Agent, "session" | "options">, config: NotesConfig): NotesIdentity;
39
40
  /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
@@ -79,13 +79,16 @@ export function recoverSnapshot(events) {
79
79
  }
80
80
  return latest;
81
81
  }
82
+ export function notesCwd(agent) {
83
+ return agent.session.header.cwd ?? process.cwd();
84
+ }
82
85
  /** Identity is extracted here, never in the filesystem domain. */
83
86
  export function notesIdentity(agent, config) {
84
87
  const home = config.notesHome ?? join(homedir(), ".agents", "notes");
85
88
  return snapshotNotesIdentity({
86
89
  home,
87
90
  sessionId: agent.session.id,
88
- projectKey: projectKey(agent.session.header.cwd ?? process.cwd(), home),
91
+ projectKey: projectKey(notesCwd(agent), home),
89
92
  agent: slugify(config.agentName ?? "dsh"),
90
93
  model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
91
94
  });
@@ -108,9 +111,10 @@ export class Windows {
108
111
  if (existing)
109
112
  return existing;
110
113
  const restored = recoverSnapshot(agent.session.snapshotEvents());
111
- const snapshot = restored ?? await this.mint(agent, 0, agent.session.header.createdAt);
114
+ const sameSession = restored !== undefined && restored.windowId === windowId(agent.session.id, restored.window);
115
+ const snapshot = sameSession ? restored : await this.mint(agent, restored?.window ?? 0, agent.session.header.createdAt);
112
116
  signal?.throwIfAborted();
113
- if (!restored)
117
+ if (!sameSession)
114
118
  appendPluginRecord(agent.session, WINDOW_RECORD, snapshot);
115
119
  const state = { snapshot, pendingReset: false, warned: false, reminded: false };
116
120
  restoreWarnings(state, agent.session.snapshotEvents());
@@ -1,3 +1,3 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- /** Register the three shared history operations; the adapter allocates addresses and supplies them. */
2
+ /** Register the two deferred history operations; the adapter allocates addresses and supplies them. */
3
3
  export declare function registerHistoryTools(pi: ExtensionAPI): void;
@@ -1,9 +1,13 @@
1
- import { historyWindows, historyList, historyRead } from "../../src/tools/history.js";
1
+ import { historyList, historyRead } from "../../src/tools/history.js";
2
2
  import { historyFromSession } from "./history.js";
3
+ import { localHistoryCorpus } from "../../src/history/local.js";
3
4
  import { HISTORY_NAMESPACE, registerOperation } from "./tool-result.js";
4
- /** Register the three shared history operations; the adapter allocates addresses and supplies them. */
5
+ function historyContext(ctx) {
6
+ const current = () => historyFromSession(ctx);
7
+ return { current, corpus: localHistoryCorpus({ current: { harness: "pi", id: ctx.sessionManager.getSessionId(), load: async () => ({ projection: current() }) } }) };
8
+ }
9
+ /** Register the two deferred history operations; the adapter allocates addresses and supplies them. */
5
10
  export function registerHistoryTools(pi) {
6
- registerOperation(pi, historyWindows, (params, ctx) => historyWindows.execute(params, historyFromSession(ctx), ctx.sessionManager.getSessionId()), HISTORY_NAMESPACE);
7
- registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
8
- registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
11
+ registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyContext(ctx)), HISTORY_NAMESPACE, undefined, "deferred");
12
+ registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyContext(ctx)), HISTORY_NAMESPACE, undefined, "deferred");
9
13
  }
@@ -1,7 +1,6 @@
1
+ /** Pi's native reader and pending-boundary addressing use the shared Pi wire decoder. */
1
2
  import type { SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
3
  import type { SessionReader } from "./session-reader.js";
3
- import { type HistoryProjection } from "../../src/history/history.js";
4
- /** Pending boundary drafts use the same slots as persisted entries. */
4
+ import type { HistoryProjection } from "../../src/history/history.js";
5
5
  export declare function nextHistorySeq(ctx: SessionReader, pending?: readonly SessionBoundaryDraft[]): number;
6
- /** Build stable internal addresses, then project the active branch into public events. */
7
6
  export declare function historyFromSession(ctx: SessionReader): HistoryProjection;
@@ -1,151 +1,8 @@
1
- import { isWindowMarker, rootWindowId } from "./window.js";
2
- import { contentText, projectHistory } from "../../src/history/history.js";
3
- function mapRole(role) {
4
- if (role === "user" || role === "assistant")
5
- return role;
6
- if (role === "toolResult" || role === "bashExecution")
7
- return "tool";
8
- if (role === "custom")
9
- return "developer";
10
- if (role === "compactionSummary" || role === "branchSummary")
11
- return "system";
12
- return undefined;
13
- }
14
- function isToolCall(part) {
15
- return typeof part === "object" && part !== null && part.type === "toolCall";
16
- }
17
- /** Seq allocation depends on entry kind and role, never on visible content. */
18
- function sequenceCount(entry) {
19
- if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message")
20
- return 1;
21
- if (entry.type !== "message" || mapRole(entry.message.role) === undefined)
22
- return 0;
23
- if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content))
24
- return 1;
25
- return 1 + entry.message.content.filter(isToolCall).length;
26
- }
27
- /** Pending boundary drafts use the same slots as persisted entries. */
1
+ import { piHistoryFromEntries, piSequenceCount } from "../../src/history/pi.js";
28
2
  export function nextHistorySeq(ctx, pending = []) {
29
- return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + sequenceCount(entry), 0);
30
- }
31
- function messageContent(message) {
32
- switch (message.role) {
33
- case "bashExecution":
34
- return message.output;
35
- case "branchSummary":
36
- case "compactionSummary":
37
- return message.summary;
38
- default:
39
- return contentText(message.content);
40
- }
41
- }
42
- /**
43
- * Pass the host's nested-call record through as recorded. It is evidence about calls this run made,
44
- * not a second transcript: the host stores no nested results, and this lane invents none.
45
- */
46
- function nestedCallsOf(message) {
47
- if (message.role !== "toolResult" || message.nestedCalls === undefined)
48
- return undefined;
49
- return { calls: message.nestedCalls.calls, complete: message.nestedCalls.complete };
50
- }
51
- function toolInfo(message) {
52
- if (message.role === "bashExecution") {
53
- // A standalone bash run records its own outcome, so its status is read here rather than
54
- // inferred from a result message that will never arrive: a cancelled or nonzero run is an
55
- // error, and a run with no recorded exit code stays unknown instead of being called ok.
56
- const status = message.cancelled === true ? "error" : typeof message.exitCode === "number" ? (message.exitCode === 0 ? "ok" : "error") : "unfinished";
57
- // A truncated run is only half the record without the on-disk path: surface both.
58
- return { toolName: "bash", arguments: { command: message.command }, recordedStatus: status, outputTruncated: message.truncated || undefined, fullOutputPath: message.truncated ? message.fullOutputPath : undefined };
59
- }
60
- if (message.role !== "toolResult")
61
- return {};
62
- const nestedCalls = nestedCallsOf(message);
63
- return {
64
- toolName: message.toolName,
65
- toolCallId: message.toolCallId,
66
- toolError: message.isError === true ? true : undefined,
67
- ...(nestedCalls ? { nestedCalls } : {}),
68
- };
69
- }
70
- function toolCallItems(windowId, entry, message, entrySeq) {
71
- if (message.role !== "assistant" || !Array.isArray(message.content))
72
- return [];
73
- const items = [];
74
- let callIndex = 0;
75
- for (const part of message.content) {
76
- if (!isToolCall(part))
77
- continue;
78
- items.push({
79
- seq: entrySeq + callIndex + 1,
80
- windowId,
81
- role: "tool_call",
82
- text: "",
83
- createdAt: entry.timestamp,
84
- toolName: part.name,
85
- toolCallId: part.id,
86
- arguments: part.arguments,
87
- });
88
- callIndex += 1;
89
- }
90
- return items;
3
+ return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + piSequenceCount(entry), 0);
91
4
  }
92
- /** Build stable internal addresses, then project the active branch into public events. */
93
5
  export function historyFromSession(ctx) {
94
- const seqByEntryId = new Map();
95
- let nextSeq = 1;
96
- for (const entry of ctx.sessionManager.getEntries()) {
97
- const count = sequenceCount(entry);
98
- if (count === 0)
99
- continue;
100
- seqByEntryId.set(entry.id, nextSeq);
101
- nextSeq += count;
102
- }
103
- const highestSeq = nextSeq - 1;
104
- const sessionId = ctx.sessionManager.getSessionId();
105
- let window = { windowId: rootWindowId(sessionId), items: [] };
106
- const rawWindows = [window];
107
- const branchSeqs = new Set();
108
- for (const entry of ctx.sessionManager.getBranch()) {
109
- if (isWindowMarker(entry)) {
110
- window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
111
- rawWindows.push(window);
112
- continue;
113
- }
114
- const entrySeq = seqByEntryId.get(entry.id);
115
- if (entrySeq === undefined)
116
- continue;
117
- branchSeqs.add(entrySeq);
118
- if (entry.type === "compaction" || entry.type === "branch_summary") {
119
- window.items.push({ seq: entrySeq, windowId: window.windowId, role: "system", text: entry.summary, createdAt: entry.timestamp });
120
- continue;
121
- }
122
- if (entry.type === "message") {
123
- const role = mapRole(entry.message.role);
124
- if (!role)
125
- continue;
126
- window.items.push({
127
- seq: entrySeq,
128
- windowId: window.windowId,
129
- role,
130
- text: messageContent(entry.message),
131
- createdAt: entry.timestamp,
132
- ...toolInfo(entry.message),
133
- });
134
- const calls = toolCallItems(window.windowId, entry, entry.message, entrySeq);
135
- for (const call of calls)
136
- branchSeqs.add(call.seq);
137
- window.items.push(...calls);
138
- continue;
139
- }
140
- if (entry.type === "custom_message") {
141
- window.items.push({
142
- seq: entrySeq,
143
- windowId: window.windowId,
144
- role: "developer",
145
- text: contentText(entry.content),
146
- createdAt: entry.timestamp,
147
- });
148
- }
149
- }
150
- return projectHistory(rawWindows, highestSeq, branchSeqs);
6
+ const manager = ctx.sessionManager;
7
+ return piHistoryFromEntries(manager.getSessionId(), manager.getEntries(), manager.getBranch());
151
8
  }