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
package/README.md CHANGED
@@ -11,7 +11,7 @@ The old name is retired: `@astrosheep/pi-context` is deprecated, and the package
11
11
  ## Why not just compaction?
12
12
 
13
13
  - **Reset ≠ summary.** Compaction is lossy compression you sit and wait for — and the next one summarizes the summary of the summary. A notesoup reset summarizes *nothing*: the window closes in O(1), because whatever mattered was already written to notes beforehand. Fast because there's nothing to compute; safe because the raw history never leaves disk.
14
- - **Notes are files you can open.** Plain Markdown in `~/.agents/notes`, in named homes (`@project`, `@human`, `@self`, `@model`, plus per-session). Readable, editable, greppable, git-able. Not an encrypted blob — and not a secret the model is instructed to keep from you. (Yes, that was a real instruction. No, we didn't port it.)
14
+ - **Notes are files you can open.** Plain Markdown in `~/.agents/notes`, in named notebooks (`@project`, `@human`, `@self`, `@model`, plus per-session). Readable, editable, greppable, git-able. Not an encrypted blob — and not a secret the model is instructed to keep from you. (Yes, that was a real instruction. No, we didn't port it.)
15
15
  - **History never forgets.** Every closed window — messages, tool calls, tool output — stays fully searchable through the `history_*` tools. Notes are the agent's lossy index; history is the lossless record underneath. This is the half the original experiment never shipped.
16
16
 
17
17
  ## Install
@@ -31,11 +31,10 @@ pi -e npm:notesoup
31
31
  - **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops; `/fresh-window Continue reviewing the implementation` clears and continues. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
32
32
  - **A boot block at every window head.** Static once-per-window content (cache-stable) with the window identity, the recent-notes index, and a short protocol teaching the model how to recover: notes for its own bookkeeping, history tools for everything before the reset.
33
33
  - **`get_context_remaining`** — how much room the brain has left before the hard-reserve wipe, including the warning runway.
34
- - **Eight history/notes tools**, flattened from the original Codex actions:
34
+ - **Seven history/notes tools**, flattened from the original Codex actions:
35
35
 
36
36
  | Codex action | Pi tool |
37
37
  | --- | --- |
38
- | `history.list_windows` | `history_windows` |
39
38
  | `history.list_items` | `history_list` |
40
39
  | `history.read_item` | `history_read` |
41
40
  | `history.search_contents` | `history_list` (`query`) |
@@ -47,6 +46,7 @@ pi -e npm:notesoup
47
46
  | `notes.search` | `notes_search` |
48
47
 
49
48
  - **Migration**: `history_search` is gone; pass `query` to `history_list`.
49
+ - **Cross-session history**: both history tools accept `session: "<id-or-prefix>"` or `"<harness>:<id>"` (`pi`, `claude`, `codex`, `dsh`). `history_list({ session: "*", query: "phrase" })` searches local transcripts across harnesses; hits carry the session to copy into `history_read`. Omit `session` for unchanged current-session behavior. See [cross-session history](docs/history-sessions.md) for discovery roots, refusals and offline limits.
50
50
  - **Migration (0.40.0)**: parameters renamed: `order` → `from`, `before`/`after` → `before_seq`/`after_seq`, `limit_chars` → `max_chars`, `wastebasket` → `crumpled`, `pattern` → `glob` (the standalone library's options included), and `notes_update`'s `change_kind` value `file` → `moved`. Old names are refused.
51
51
 
52
52
  - **Runtime toggle** — `/notesoup off` stops new automatic resets; `/notesoup on` re-enables them; bare `/notesoup` reports the state.
@@ -82,11 +82,13 @@ Environment variables:
82
82
  - `NOTESOUP_KEEP_MEMORY` — Claude only: keep Claude Code's auto-memory guidance, which notesoup omits by default (its summarization guidance is always omitted). Enabled by any non-empty value except `0`, `false`, `no`, or `off` (case-insensitive); read at session startup.
83
83
  - `NOTESOUP_HOME` — overrides the notes root (default `~/.agents/notes`).
84
84
  - `NOTESOUP_AGENT` — overrides the root agent name on Pi and Codex (default `anonymous`; Codex children use `agent_type`).
85
+ - `NOTESOUP_HISTORY_PI_ROOT`, `NOTESOUP_HISTORY_CLAUDE_ROOT`, `NOTESOUP_HISTORY_CODEX_ROOT` — override local transcript discovery directories, independently of the notes root; see [cross-session history](docs/history-sessions.md).
85
86
 
86
87
  ## Documentation
87
88
 
88
89
  - [Architecture](docs/architecture.md) and [reset lifecycle](docs/reset-lifecycle.md) — how windows, checkpoints, markers and branches actually work
89
90
  - [Tool results](docs/tool-results.md) — receipts, paging, and error shapes
91
+ - [Cross-session history](docs/history-sessions.md) — one-session lookup, wildcard search, local discovery and harness limits
90
92
  - [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
91
93
  - [DeepSeek Harness](docs/dsh.md) — adapter and profile patch for dsh 0.2.1-alpha.2
92
94
  - [Claude Code Mod](docs/claude-code-mod.md) — early-access notes and persisted-session history tools for Claude Code
@@ -100,7 +102,7 @@ npm test # build from a clean dist, then run the suite
100
102
  npm run typecheck
101
103
  git diff --check
102
104
  node scripts/check-notes-package.mjs # optional built /notes CRUD smoke; no install
103
- npx tsx scripts/boot-smoke.mts [cwd] # optional live boot render against the real notes homes
105
+ npx tsx scripts/boot-smoke.mts [cwd] # optional live boot render against the real notes notebooks
104
106
  ```
105
107
 
106
108
  The repository splits host-neutral code from host plugins:
@@ -1,3 +1,4 @@
1
+ import { type LocalHistoryOptions } from "../../../src/history/local.js";
1
2
  export type ClaudeIdentityInput = Readonly<{
2
3
  home: string;
3
4
  sessionId: string;
@@ -10,5 +11,5 @@ export type ClaudeToolResult = {
10
11
  text: string;
11
12
  ok: boolean;
12
13
  };
13
- export declare function dispatch(request: unknown): Promise<unknown>;
14
+ export declare function dispatch(request: unknown, historyOptions?: Pick<LocalHistoryOptions, "roots" | "home" | "env">): Promise<unknown>;
14
15
  export declare function handleLine(line: string): Promise<string>;
@@ -2,14 +2,16 @@ import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
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
+ import { localHistoryCorpus } from "../../../src/history/local.js";
6
7
  import { readClaudeHistory } from "./history.js";
7
8
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
8
9
  import { renderBootBlock } from "../../../src/boot/render.js";
9
10
  import { selectContinuation } from "../../../src/budget/text.js";
10
- import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_PREVIOUS, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
11
+ import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
11
12
  import { resolveClaudeLimits } from "./thresholds.js";
12
13
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
14
+ import { notesToolContext } from "../../../src/tools/notes-context.js";
13
15
  const MAX_REQUEST_BYTES = 512 * 1024;
14
16
  const MAX_RESPONSE_BYTES = 1024 * 1024;
15
17
  function identity(input) {
@@ -49,7 +51,6 @@ const OPERATIONS = {
49
51
  const HISTORY_OPERATIONS = {
50
52
  history_list: boundOperation(historyList),
51
53
  history_read: boundOperation(historyRead),
52
- history_windows: boundOperation(historyWindows),
53
54
  };
54
55
  function historySource(value, sessionId) {
55
56
  if (!value || typeof value !== "object")
@@ -59,7 +60,7 @@ function historySource(value, sessionId) {
59
60
  throw new Error("Claude history binding belongs to a different session");
60
61
  return source;
61
62
  }
62
- export async function dispatch(request) {
63
+ export async function dispatch(request, historyOptions = {}) {
63
64
  if (!request || typeof request !== "object" || Array.isArray(request))
64
65
  throw new Error("malformed request");
65
66
  const value = request;
@@ -89,33 +90,29 @@ export async function dispatch(request) {
89
90
  const id = identity(value.identity);
90
91
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
91
92
  const tool = value.tool;
93
+ if (value.params.session !== undefined) {
94
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
95
+ const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
96
+ const projection = await current();
97
+ const notice = claudeHistoryGapNotice(projection.missingAncestors);
98
+ return { projection, ...(notice ? { notice } : {}) };
99
+ } } });
100
+ return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
101
+ }
92
102
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
93
103
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
94
104
  const wrapText = (text) => notice + text;
95
- let params = value.params;
96
- if (projection.missingAncestors.length > 0) {
97
- // An unknown segment is not evidence for the window before the current
98
- // one. Resolve the exact ordinal, never array adjacency across a gap.
99
- if (params.window_id === "@previous") {
100
- const previous = projection.currentWindowOrdinal === undefined ? undefined : `claude:${id.sessionId}:${projection.currentWindowOrdinal - 1}`;
101
- if (!projection.windows.some((window) => window.windowId === previous)) {
102
- return { ok: false, text: wrapText(CLAUDE_HISTORY_UNKNOWN_PREVIOUS) };
103
- }
104
- params = { ...params, window_id: previous };
105
- }
106
- if (value.tool === "history_read") {
107
- const { seq } = params;
108
- if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
109
- return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
110
- }
105
+ const params = value.params;
106
+ if (projection.missingAncestors.length > 0 && tool === "history_read") {
107
+ const { seq } = params;
108
+ if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
109
+ return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
111
110
  }
112
111
  }
113
- const result = tool === "history_windows"
114
- ? await HISTORY_OPERATIONS[tool].call(params, projection, id.sessionId, wrapText)
115
- : await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
112
+ const result = await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
116
113
  return { ...result, text: wrapText(result.text) };
117
114
  }
118
- return OPERATIONS[value.tool].call(value.params, id);
115
+ return OPERATIONS[value.tool].call(value.params, notesToolContext(id, value.identity.cwd));
119
116
  }
120
117
  if (value.op === "history_state") {
121
118
  const id = identity(value.identity);
@@ -1,14 +1,3 @@
1
- import { type HistoryProjection } from "../../../src/history/history.js";
2
- export type ClaudeHistorySource = {
3
- sessionId: string;
4
- transcriptPath: string;
5
- headUuid?: string;
6
- };
7
- /** Claude graph evidence stays in the adapter; shared queries only see addressed windows. */
8
- export type ClaudeHistoryProjection = HistoryProjection & {
9
- missingAncestors: string[];
10
- currentWindowOrdinal: number | undefined;
11
- };
12
- /** All addresses are allocated on the full first-occurrence log, before branch selection. */
13
- export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
- export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
1
+ /** Claude's SDK-facing entry; the persisted wire decoder is shared with the local corpus. */
2
+ export { claudeHistoryFromJsonl, readClaudeHistory } from "../../../src/history/claude.js";
3
+ export type { ClaudeHistorySource, ClaudeHistoryProjection } from "../../../src/history/claude.js";
@@ -1,298 +1,2 @@
1
- /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
- import { readFile } from "node:fs/promises";
3
- import { isDeepStrictEqual } from "node:util";
4
- import { contentText, projectHistory } from "../../../src/history/history.js";
5
- const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
6
- const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
7
- function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
8
- function requiredString(value, field) {
9
- if (typeof value !== "string" || value.length === 0)
10
- throw new Error(`invalid Claude transcript ${field}`);
11
- return value;
12
- }
13
- function parent(row) {
14
- if (row.parentUuid === null)
15
- return undefined;
16
- return requiredString(row.parentUuid, "parentUuid");
17
- }
18
- function boundary(row) { return row.type === "system" && row.subtype === "compact_boundary"; }
19
- /** A trailing incomplete write is not a committed line. Valid unterminated JSON is still readable. */
20
- function rowsOf(text) {
21
- const lines = text.split("\n"), rows = [];
22
- for (let index = 0; index < lines.length; index++) {
23
- const line = lines[index];
24
- if (line.trim() === "")
25
- continue;
26
- let value;
27
- try {
28
- value = JSON.parse(line);
29
- }
30
- catch {
31
- if (index === lines.length - 1 && !text.endsWith("\n"))
32
- break;
33
- throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
34
- }
35
- if (!object(value) || typeof value.type !== "string")
36
- throw new Error(`invalid Claude transcript record at line ${index + 1}`);
37
- rows.push(value);
38
- }
39
- return rows;
40
- }
41
- /** Only recorded visible text; never stringify unknown blocks or attachment internals (thinking included). */
42
- function blocksOf(value) {
43
- if (typeof value === "string")
44
- return [{ type: "text", text: value }];
45
- if (!Array.isArray(value))
46
- throw new Error("invalid Claude transcript message content");
47
- return value.map((block) => {
48
- if (!object(block) || typeof block.type !== "string")
49
- throw new Error("invalid Claude transcript content block");
50
- if (block.type === "text") {
51
- if (typeof block.text !== "string")
52
- throw new Error("invalid Claude transcript text block");
53
- }
54
- else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
55
- throw new Error(`unsupported Claude transcript content block: ${block.type}`);
56
- }
57
- return block;
58
- });
59
- }
60
- function decode(row, seq) {
61
- // A system record without a body is graph metadata, not a message.
62
- if (row.type === "system" && row.content == null)
63
- return [];
64
- const common = { windowId: "", ...(typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {}) };
65
- let blocks, role;
66
- if (row.type === "user" || row.type === "assistant") {
67
- if (!object(row.message) || row.message.role !== row.type)
68
- throw new Error("invalid Claude transcript message role");
69
- blocks = blocksOf(row.message.content);
70
- role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
71
- }
72
- else if (row.type === "system") {
73
- blocks = blocksOf(row.content);
74
- role = "system";
75
- }
76
- else {
77
- // Old/new attachments are graph nodes even when they put no bytes in the request.
78
- // `rendered` is a list of native rendered messages, not raw attachment payloads.
79
- if (row.rendered === undefined)
80
- blocks = [];
81
- else if (Array.isArray(row.rendered))
82
- blocks = row.rendered.flatMap((message) => {
83
- if (!object(message))
84
- throw new Error("invalid Claude transcript rendered attachment");
85
- return blocksOf(message.content);
86
- });
87
- else
88
- throw new Error("invalid Claude transcript rendered attachment");
89
- role = "system";
90
- }
91
- const items = [{ ...common, seq, role, text: contentText(blocks) }];
92
- for (const block of blocks) {
93
- if (block.type === "tool_use") {
94
- if (!object(block.input))
95
- throw new Error("invalid Claude transcript tool arguments");
96
- items.push({ ...common, seq: seq + items.length, role: "tool_call", text: "", toolName: requiredString(block.name, "tool name"), toolCallId: requiredString(block.id, "tool id"), arguments: block.input });
97
- }
98
- else if (block.type === "tool_result") {
99
- if (block.is_error !== undefined && typeof block.is_error !== "boolean")
100
- throw new Error("invalid Claude transcript tool error flag");
101
- const output = block.content === undefined ? "" : contentText(blocksOf(block.content));
102
- items.push({ ...common, seq: seq + items.length, role: "tool", text: output, toolCallId: requiredString(block.tool_use_id, "tool result id"), toolError: block.is_error === true });
103
- }
104
- }
105
- return items;
106
- }
107
- /**
108
- * The protocol tags a complete boot carries; `context_window` is the pre-rename spelling that
109
- * sessions and Claude transcripts already on disk still use, so both stay readable.
110
- */
111
- const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
112
- const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
113
- const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
114
- /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
115
- function bootOrdinal(row, retained) {
116
- if (!retained || row.type !== "user" || !object(row.message))
117
- return undefined;
118
- const text = contentText(row.message.content);
119
- if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text))
120
- return undefined;
121
- // A fork copies the retained boot verbatim. Its ordinal survives, while
122
- // public window ids below always belong to the current transcript session.
123
- const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
124
- if (suffix === undefined)
125
- return undefined;
126
- const ordinal = Number(suffix);
127
- return Number.isSafeInteger(ordinal) ? ordinal : undefined;
128
- }
129
- /** All addresses are allocated on the full first-occurrence log, before branch selection. */
130
- export function claudeHistoryFromJsonl(text, source) {
131
- const nodes = new Map();
132
- let nextSeq = 1;
133
- for (const row of rowsOf(text)) {
134
- // Ignore non-message records, including future metadata. If selected ancestry
135
- // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
136
- if (!MESSAGE_TYPES.has(row.type))
137
- continue;
138
- const uuid = requiredString(row.uuid, "uuid");
139
- parent(row);
140
- if (row.sessionId !== source.sessionId)
141
- throw new Error("Claude transcript belongs to a different session");
142
- if (row.isSidechain === true || row.agentId !== undefined)
143
- throw new Error("Claude history supports only the main session transcript");
144
- // Resolve the window in the graph as it existed at this append, not the final
145
- // rewritten tree. A preserved old row stays in its original window; a NEW child
146
- // of its rewritten version belongs to the new window.
147
- const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
148
- const version = { row, ancestorUuid: ancestor, ancestor: ancestor === undefined ? undefined : nodes.get(ancestor)?.latest };
149
- const previous = nodes.get(uuid);
150
- if (previous) {
151
- // Native resume/compaction rewrites provenance and parent links, not logical identities.
152
- if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
153
- throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
154
- }
155
- previous.latest = version;
156
- continue;
157
- }
158
- const items = decode(row, nextSeq);
159
- nextSeq += items.length;
160
- nodes.set(uuid, { first: version, latest: version, items });
161
- }
162
- const missingAncestors = new Set();
163
- function positionOf(version) {
164
- // Resolve long chains iteratively. A gap destroys ordinal evidence, not the
165
- // confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
166
- const chain = [], calculating = new Set();
167
- let cursor = version;
168
- let before = { ordinal: 0 };
169
- while (cursor.position === undefined) {
170
- // Forward references use the parent's first eventual version, not a rewrite.
171
- cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
172
- if (calculating.has(cursor))
173
- throw new Error("cyclic Claude transcript ancestry");
174
- calculating.add(cursor);
175
- chain.push(cursor);
176
- if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
177
- missingAncestors.add(cursor.ancestorUuid);
178
- before = { unknownAncestor: cursor.ancestorUuid };
179
- break;
180
- }
181
- if (cursor.ancestor === undefined)
182
- break;
183
- cursor = cursor.ancestor;
184
- }
185
- before = cursor.position ?? before;
186
- for (const current of chain.reverse()) {
187
- const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
188
- const marked = bootOrdinal(current.row, retained);
189
- current.position = marked !== undefined
190
- ? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
191
- : "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
192
- before = current.position;
193
- }
194
- return version.position;
195
- }
196
- if (!source.headUuid)
197
- throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
198
- if (!nodes.has(source.headUuid))
199
- throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
200
- // The inference tree uses the latest rewritten parents. At a compact boundary the logical
201
- // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
202
- const selected = new Set(), visited = new Set(), visiting = new Set();
203
- const stack = [{ uuid: source.headUuid, historical: false }];
204
- while (stack.length > 0) {
205
- const step = stack.pop(), { uuid, historical } = step;
206
- const key = `${historical ? "old" : "live"}:${uuid}`;
207
- if (step.exit) {
208
- visiting.delete(key);
209
- visited.add(key);
210
- continue;
211
- }
212
- if (visited.has(key))
213
- continue;
214
- if (visiting.has(key))
215
- throw new Error("cyclic Claude transcript ancestry");
216
- visiting.add(key);
217
- stack.push({ ...step, exit: true });
218
- const node = nodes.get(uuid);
219
- if (!node) {
220
- missingAncestors.add(uuid);
221
- continue;
222
- }
223
- selected.add(uuid);
224
- const row = (historical ? node.first : node.latest).row;
225
- const ancestor = parent(row);
226
- if (ancestor !== undefined)
227
- stack.push({ uuid: ancestor, historical });
228
- if (!boundary(row))
229
- continue;
230
- if (row.logicalParentUuid != null)
231
- stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
232
- const meta = row.compactMetadata;
233
- if (!object(meta))
234
- continue;
235
- if (object(meta.preservedSegment)) {
236
- for (const field of ["headUuid", "tailUuid"])
237
- if (meta.preservedSegment[field] !== undefined)
238
- stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
239
- }
240
- if (object(meta.preservedMessages)) {
241
- const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
242
- if (uuids === undefined)
243
- continue;
244
- if (!Array.isArray(uuids))
245
- throw new Error("invalid Claude preserved messages");
246
- for (const id of uuids) {
247
- const uuid = requiredString(id, "preserved UUID");
248
- // allUuids also names virtual/non-persisted attachments. It is auxiliary
249
- // evidence, not a reason to pretend the stored parent chain is missing.
250
- if (nodes.has(uuid))
251
- stack.push({ uuid, historical: true });
252
- }
253
- }
254
- }
255
- const current = positionOf(nodes.get(source.headUuid).latest);
256
- const windowId = (position) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
257
- const windowsById = new Map();
258
- const branchSeqs = new Set();
259
- let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
260
- for (const [uuid, node] of nodes) {
261
- if (!selected.has(uuid))
262
- continue;
263
- const position = positionOf(node.first);
264
- if ("ordinal" in position)
265
- maxOrdinal = Math.max(maxOrdinal, position.ordinal);
266
- const id = windowId(position);
267
- let window = windowsById.get(id);
268
- if (!window) {
269
- window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
270
- windowsById.set(id, window);
271
- }
272
- window.createdAt ??= node.items[0]?.createdAt;
273
- for (const item of node.items) {
274
- branchSeqs.add(item.seq);
275
- window.items.push({ ...item, windowId: id });
276
- }
277
- }
278
- // Preserve complete-history empty windows (including copied boot ordinals).
279
- // With gaps, report only evidenced windows, never invent the missing ordinals.
280
- if (missingAncestors.size === 0) {
281
- for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
282
- const id = windowId({ ordinal });
283
- if (!windowsById.has(id))
284
- windowsById.set(id, { windowId: id, ordinal, items: [] });
285
- }
286
- }
287
- // Forward references can put a newer numbered window on disk first. Unknown
288
- // segments are a separate, unordered group, not an inferred place in that timeline.
289
- const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
290
- ? b.ordinal === undefined ? 0 : 1
291
- : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
292
- return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
293
- }
294
- export async function readClaudeHistory(source) {
295
- if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
296
- throw new Error("Claude history transcript_path is unavailable");
297
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
298
- }
1
+ /** Claude's SDK-facing entry; the persisted wire decoder is shared with the local corpus. */
2
+ export { claudeHistoryFromJsonl, readClaudeHistory } from "../../../src/history/claude.js";
@@ -3,7 +3,6 @@ export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't availa
3
3
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
4
4
  export declare const CLAUDE_WARNING_PROMPT: string;
5
5
  export declare const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
6
- export declare const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = "Cannot resolve \"@previous\": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.";
7
6
  export declare function claudeHistoryUnconfirmedSeq(seq: number): string;
8
7
  /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
9
8
  export declare function claudeHistoryGapNotice(missing: readonly string[]): string;
@@ -4,7 +4,6 @@ export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in t
4
4
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
5
5
  export const CLAUDE_WARNING_PROMPT = warningNotice();
6
6
  export const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
7
- export const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = 'Cannot resolve "@previous": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.';
8
7
  export function claudeHistoryUnconfirmedSeq(seq) {
9
8
  return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
10
9
  }
@@ -1,8 +1,3 @@
1
- /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
- import { type HistoryProjection } from "../../../src/history/history.js";
3
- import { type CodexTranscriptSource, type CodexTranscriptState } from "./transcript.js";
4
- export type { CodexTranscriptSource } from "./transcript.js";
5
- export type CodexHistoryState = CodexTranscriptState & {
6
- projection: HistoryProjection;
7
- };
8
- export declare function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState>;
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";