notesoup 0.47.1 → 0.48.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 (88) hide show
  1. package/README.md +2 -2
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +60 -13
  6. package/dist/src/budget/constants.d.ts +2 -4
  7. package/dist/src/budget/constants.js +2 -4
  8. package/dist/src/budget/policy.d.ts +2 -2
  9. package/dist/src/budget/policy.js +3 -3
  10. package/dist/src/budget/text.d.ts +29 -9
  11. package/dist/src/budget/text.js +51 -10
  12. package/dist/src/claude/helper.d.ts +2 -3
  13. package/dist/src/claude/helper.js +45 -11
  14. package/dist/src/claude/history.d.ts +9 -0
  15. package/dist/src/claude/history.js +271 -0
  16. package/dist/src/dsh/budget.js +1 -1
  17. package/dist/src/dsh/engine.d.ts +2 -1
  18. package/dist/src/dsh/engine.js +18 -9
  19. package/dist/src/dsh/index.js +9 -4
  20. package/dist/src/dsh/tools.js +1 -1
  21. package/dist/src/dsh/window.d.ts +2 -1
  22. package/dist/src/dsh/window.js +14 -8
  23. package/dist/src/history/query.js +59 -81
  24. package/dist/src/notes/address.d.ts +5 -0
  25. package/dist/src/notes/address.js +20 -21
  26. package/dist/src/notes/store.js +12 -19
  27. package/dist/src/pi/boot.d.ts +1 -1
  28. package/dist/src/pi/boot.js +28 -5
  29. package/dist/src/pi/budget.d.ts +1 -3
  30. package/dist/src/pi/budget.js +20 -61
  31. package/dist/src/pi/entries.d.ts +0 -1
  32. package/dist/src/pi/entries.js +0 -1
  33. package/dist/src/pi/history.d.ts +3 -0
  34. package/dist/src/pi/history.js +4 -0
  35. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  36. package/dist/src/pi/reset/artifacts.js +16 -14
  37. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  38. package/dist/src/pi/reset/lifecycle.js +48 -72
  39. package/dist/src/pi/runtime.js +9 -8
  40. package/dist/src/pi/window.d.ts +12 -6
  41. package/dist/src/pi/window.js +7 -0
  42. package/dist/test/agent-loop.test.js +53 -30
  43. package/dist/test/boot.integration.test.js +123 -12
  44. package/dist/test/budget-settings.integration.test.js +10 -6
  45. package/dist/test/claude-history.test.d.ts +1 -0
  46. package/dist/test/claude-history.test.js +184 -0
  47. package/dist/test/claude-mod.test.js +236 -42
  48. package/dist/test/dsh.test.js +80 -3
  49. package/dist/test/helpers/extension.d.ts +3 -0
  50. package/dist/test/helpers/extension.js +33 -5
  51. package/dist/test/history.integration.test.js +66 -0
  52. package/dist/test/host-neutral.test.js +1 -1
  53. package/dist/test/model-facing-text.test.d.ts +1 -0
  54. package/dist/test/model-facing-text.test.js +181 -0
  55. package/dist/test/notes.integration.test.js +16 -18
  56. package/dist/test/reset-lifecycle.test.js +201 -46
  57. package/docs/architecture.md +3 -3
  58. package/docs/claude-code-mod.md +15 -3
  59. package/docs/dsh.md +2 -2
  60. package/docs/reset-lifecycle.md +32 -20
  61. package/docs/skills.md +1 -1
  62. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  63. package/mods/notesoup/dist/claude/helper.js +836 -92
  64. package/mods/notesoup/hooks/register.ts +140 -38
  65. package/package.json +1 -1
  66. package/src/boot/render.ts +41 -23
  67. package/src/boot/text.ts +69 -13
  68. package/src/budget/constants.ts +2 -4
  69. package/src/budget/policy.ts +3 -3
  70. package/src/budget/text.ts +61 -10
  71. package/src/claude/helper.ts +53 -22
  72. package/src/claude/history.ts +228 -0
  73. package/src/dsh/budget.ts +1 -1
  74. package/src/dsh/engine.ts +16 -9
  75. package/src/dsh/index.ts +8 -3
  76. package/src/dsh/tools.ts +1 -1
  77. package/src/dsh/window.ts +15 -9
  78. package/src/history/query.ts +57 -82
  79. package/src/notes/address.ts +19 -16
  80. package/src/notes/store.ts +9 -14
  81. package/src/pi/boot.ts +27 -5
  82. package/src/pi/budget.ts +20 -58
  83. package/src/pi/entries.ts +0 -1
  84. package/src/pi/history.ts +7 -2
  85. package/src/pi/reset/artifacts.ts +17 -14
  86. package/src/pi/reset/lifecycle.ts +56 -79
  87. package/src/pi/runtime.ts +9 -8
  88. package/src/pi/window.ts +11 -1
@@ -2,15 +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 "../tools/notes.js";
5
+ import { historyList, historyRead, historyWindows } from "../tools/history.js";
6
+ import { readClaudeHistory } from "./history.js";
5
7
  import { loadNotesSnapshot } from "../boot/snapshot.js";
6
8
  import { renderBootBlock } from "../boot/render.js";
7
- import { CLAUDE_WIPE_SENTENCE } from "../boot/text.js";
8
- import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
9
+ import { CLAUDE_WIPE_SENTENCE, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE } from "../boot/text.js";
10
+ import { CLAUDE_WARNING_PROMPT, selectContinuation } from "../budget/text.js";
9
11
  import { resolveClaudeLimits } from "./thresholds.js";
10
12
  import { projectKey, snapshotNotesIdentity } from "../notes/index.js";
11
13
  const MAX_REQUEST_BYTES = 512 * 1024;
12
14
  const MAX_RESPONSE_BYTES = 1024 * 1024;
13
- const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"];
14
15
  function identity(input) {
15
16
  if (!input || typeof input !== "object" || typeof input.cwd !== "string")
16
17
  throw new Error("invalid identity");
@@ -27,17 +28,17 @@ function paramProblem(schema, params) {
27
28
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
28
29
  }
29
30
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
30
- function boundOperation(operation, ...rest) {
31
+ function boundOperation(operation) {
31
32
  return {
32
33
  description: operation.description,
33
34
  parameters: operation.parameters,
34
- async call(params, id) {
35
+ async call(params, ...context) {
35
36
  // Refuse before the operation can act: a rejected shape never reaches a write.
36
37
  if (!Check(operation.parameters, params))
37
38
  throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
38
39
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
39
- const outcome = await operation.execute(params, id, ...rest);
40
- return { text: operation.render(outcome), outcome };
40
+ const outcome = await operation.execute(params, ...context);
41
+ return { text: operation.render(outcome), ok: outcome.ok };
41
42
  },
42
43
  };
43
44
  }
@@ -48,26 +49,55 @@ const OPERATIONS = {
48
49
  notes_list: boundOperation(notesList),
49
50
  notes_search: boundOperation(notesSearch),
50
51
  };
52
+ const HISTORY_OPERATIONS = {
53
+ history_list: boundOperation(historyList),
54
+ history_read: boundOperation(historyRead),
55
+ history_windows: boundOperation(historyWindows),
56
+ };
57
+ function historySource(value, sessionId) {
58
+ if (!value || typeof value !== "object")
59
+ throw new Error("Claude history transcript_path is unavailable");
60
+ const source = value;
61
+ if (source.sessionId !== sessionId)
62
+ throw new Error("Claude history binding belongs to a different session");
63
+ return source;
64
+ }
51
65
  export async function dispatch(request) {
52
66
  if (!request || typeof request !== "object" || Array.isArray(request))
53
67
  throw new Error("malformed request");
54
68
  const value = request;
55
69
  if (value.op === "schemas")
56
- return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
70
+ return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
57
71
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
58
72
  // cannot drift apart. The hooks module caches one copy per session.
59
73
  if (value.op === "texts")
60
- return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
74
+ return { warning: CLAUDE_WARNING_PROMPT, wipeSentence: CLAUDE_WIPE_SENTENCE, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
75
+ // Claude has no model-facing reset tool, so every reset it creates is system-triggered. The
76
+ // caller draws once per artifact and caches the answer; text reads never draw.
77
+ if (value.op === "continuation") {
78
+ if (value.origin !== "normal" && value.origin !== "forced")
79
+ throw new Error("invalid reset origin");
80
+ return { text: selectContinuation(value.origin) };
81
+ }
61
82
  // Threshold derivation crosses the boundary as raw facts: everything the engine could
62
83
  // read, unvalidated. resolveClaudeLimits guards every field and never throws.
63
84
  if (value.op === "limits")
64
85
  return resolveClaudeLimits(value.facts);
65
86
  if (value.op === "tool") {
66
- if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool))
87
+ if (typeof value.tool !== "string" || (!Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool)))
67
88
  throw new Error("unknown tool");
68
89
  const id = identity(value.identity);
90
+ if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
91
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
92
+ return HISTORY_OPERATIONS[value.tool].call(value.params, projection, id.sessionId);
93
+ }
69
94
  return OPERATIONS[value.tool].call(value.params, id);
70
95
  }
96
+ if (value.op === "history_state") {
97
+ const id = identity(value.identity);
98
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
99
+ return { window: projection.windows.length - 1 };
100
+ }
71
101
  if (value.op === "boot") {
72
102
  const id = identity(value.identity);
73
103
  if (!value.tools || typeof value.tools !== "object")
@@ -77,7 +107,11 @@ export async function dispatch(request) {
77
107
  throw new Error("invalid context window");
78
108
  const snapshot = await loadNotesSnapshot(id, typeof value.openedAt === "number" ? value.openedAt : Date.now());
79
109
  const windowId = (index) => `claude:${id.sessionId}:${index}`;
80
- return renderBootBlock({ agentName: id.agent, modelName: id.model, firstWindowId: windowId(0), currentWindowId: windowId(window), ...(window > 0 ? { previousWindowId: windowId(window - 1) } : {}), notes: snapshot, tools: value.tools });
110
+ const trunk = `claude:${id.sessionId}`;
111
+ const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
112
+ const rendered = renderBootBlock({ agentName: id.agent, modelName: id.model, tree, notes: snapshot, tools: value.tools });
113
+ // Retained Claude boots are restored by their full current/previous ids.
114
+ return `${rendered}\nCurrent context window id: ${windowId(window)}${window > 0 ? `\nPrevious context window id: ${windowId(window - 1)}` : ""}`;
81
115
  }
82
116
  throw new Error("unknown operation");
83
117
  }
@@ -0,0 +1,9 @@
1
+ import { type HistoryProjection } from "../history/history.js";
2
+ export type ClaudeHistorySource = {
3
+ sessionId: string;
4
+ transcriptPath: string;
5
+ headUuid?: string;
6
+ };
7
+ /** All addresses are allocated on the full first-occurrence log, before branch selection. */
8
+ export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): HistoryProjection;
9
+ export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<HistoryProjection>;
@@ -0,0 +1,271 @@
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 "../history/history.js";
5
+ const METADATA = new Set([
6
+ "queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
7
+ "summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
8
+ ]);
9
+ const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
10
+ const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
11
+ function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
12
+ function requiredString(value, field) {
13
+ if (typeof value !== "string" || value.length === 0)
14
+ throw new Error(`invalid Claude transcript ${field}`);
15
+ return value;
16
+ }
17
+ function parent(row) {
18
+ if (row.parentUuid === null)
19
+ return undefined;
20
+ return requiredString(row.parentUuid, "parentUuid");
21
+ }
22
+ function boundary(row) { return row.type === "system" && row.subtype === "compact_boundary"; }
23
+ /** A trailing incomplete write is not a committed line. Valid unterminated JSON is still readable. */
24
+ function rowsOf(text) {
25
+ const lines = text.split("\n"), rows = [];
26
+ for (let index = 0; index < lines.length; index++) {
27
+ const line = lines[index];
28
+ if (line.trim() === "")
29
+ continue;
30
+ let value;
31
+ try {
32
+ value = JSON.parse(line);
33
+ }
34
+ catch {
35
+ if (index === lines.length - 1 && !text.endsWith("\n"))
36
+ break;
37
+ throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
38
+ }
39
+ if (!object(value) || typeof value.type !== "string")
40
+ throw new Error(`invalid Claude transcript record at line ${index + 1}`);
41
+ rows.push(value);
42
+ }
43
+ return rows;
44
+ }
45
+ /** Only recorded visible text; never stringify unknown blocks or attachment internals (thinking included). */
46
+ function blocksOf(value) {
47
+ if (typeof value === "string")
48
+ return [{ type: "text", text: value }];
49
+ if (!Array.isArray(value))
50
+ throw new Error("invalid Claude transcript message content");
51
+ return value.map((block) => {
52
+ if (!object(block) || typeof block.type !== "string")
53
+ throw new Error("invalid Claude transcript content block");
54
+ if (block.type === "text") {
55
+ if (typeof block.text !== "string")
56
+ throw new Error("invalid Claude transcript text block");
57
+ }
58
+ else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
59
+ throw new Error(`unsupported Claude transcript content block: ${block.type}`);
60
+ }
61
+ return block;
62
+ });
63
+ }
64
+ function decode(row, seq) {
65
+ // Native duration bookkeeping has a UUID/parent but no message body. Keep its
66
+ // graph edge, not a fabricated empty message or serialized timing payload.
67
+ if (row.type === "system" && row.subtype === "turn_duration")
68
+ return [];
69
+ const common = { windowId: "", ...(typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {}) };
70
+ let blocks, role;
71
+ if (row.type === "user" || row.type === "assistant") {
72
+ if (!object(row.message) || row.message.role !== row.type)
73
+ throw new Error("invalid Claude transcript message role");
74
+ blocks = blocksOf(row.message.content);
75
+ role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
76
+ }
77
+ else if (row.type === "system") {
78
+ blocks = blocksOf(row.content);
79
+ role = "system";
80
+ }
81
+ else {
82
+ // Old/new attachments are graph nodes even when they put no bytes in the request.
83
+ // `rendered` is a list of native rendered messages, not raw attachment payloads.
84
+ if (row.rendered === undefined)
85
+ blocks = [];
86
+ else if (Array.isArray(row.rendered))
87
+ blocks = row.rendered.flatMap((message) => {
88
+ if (!object(message))
89
+ throw new Error("invalid Claude transcript rendered attachment");
90
+ return blocksOf(message.content);
91
+ });
92
+ else
93
+ throw new Error("invalid Claude transcript rendered attachment");
94
+ role = "system";
95
+ }
96
+ const items = [{ ...common, seq, role, text: contentText(blocks) }];
97
+ for (const block of blocks) {
98
+ if (block.type === "tool_use") {
99
+ if (!object(block.input))
100
+ throw new Error("invalid Claude transcript tool arguments");
101
+ 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 });
102
+ }
103
+ else if (block.type === "tool_result") {
104
+ if (block.is_error !== undefined && typeof block.is_error !== "boolean")
105
+ throw new Error("invalid Claude transcript tool error flag");
106
+ const output = block.content === undefined ? "" : contentText(blocksOf(block.content));
107
+ 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 });
108
+ }
109
+ }
110
+ return items;
111
+ }
112
+ /**
113
+ * The protocol tags a complete boot carries; `context_window` is the pre-rename spelling that
114
+ * sessions and Claude transcripts already on disk still use, so both stay readable.
115
+ */
116
+ const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
117
+ const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
118
+ const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
119
+ /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
120
+ function bootOrdinal(row, sessionId, retained) {
121
+ if (!retained || row.type !== "user" || !object(row.message))
122
+ return undefined;
123
+ const text = contentText(row.message.content);
124
+ if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text))
125
+ return undefined;
126
+ const prefix = `Current context window id: claude:${sessionId}:`;
127
+ const suffix = text.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
128
+ if (suffix === undefined || !/^\d+$/.test(suffix))
129
+ return undefined;
130
+ const ordinal = Number(suffix);
131
+ return Number.isSafeInteger(ordinal) ? ordinal : undefined;
132
+ }
133
+ /** All addresses are allocated on the full first-occurrence log, before branch selection. */
134
+ export function claudeHistoryFromJsonl(text, source) {
135
+ const nodes = new Map();
136
+ let nextSeq = 1;
137
+ for (const row of rowsOf(text)) {
138
+ if (METADATA.has(row.type))
139
+ continue;
140
+ if (!MESSAGE_TYPES.has(row.type))
141
+ throw new Error(`unsupported Claude transcript record type: ${row.type}`);
142
+ const uuid = requiredString(row.uuid, "uuid");
143
+ parent(row);
144
+ if (row.sessionId !== source.sessionId)
145
+ throw new Error("Claude transcript belongs to a different session");
146
+ if (row.isSidechain === true || row.agentId !== undefined)
147
+ throw new Error("Claude history supports only the main session transcript");
148
+ // Resolve the window in the graph as it existed at this append, not the final
149
+ // rewritten tree. A preserved old row stays in its original window; a NEW child
150
+ // of its rewritten version belongs to the new window.
151
+ const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
152
+ const version = { row, ancestorUuid: ancestor, ancestor: ancestor === undefined ? undefined : nodes.get(ancestor)?.latest };
153
+ const previous = nodes.get(uuid);
154
+ if (previous) {
155
+ // Native resume/compaction rewrites provenance and parent links, not logical identities.
156
+ if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
157
+ throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
158
+ }
159
+ previous.latest = version;
160
+ continue;
161
+ }
162
+ const items = decode(row, nextSeq);
163
+ nextSeq += items.length;
164
+ nodes.set(uuid, { first: version, latest: version, items });
165
+ }
166
+ function ordinalOf(version) {
167
+ // Persisted history is not limited to the host's newest 4096 inference rows.
168
+ // Resolve long parent chains iteratively, not with the JavaScript call stack.
169
+ const chain = [], calculating = new Set();
170
+ let cursor = version;
171
+ while (cursor.ordinal === undefined) {
172
+ // A notice can precede its parent on disk; use that parent's first eventual version.
173
+ cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
174
+ if (calculating.has(cursor))
175
+ throw new Error("cyclic Claude transcript ancestry");
176
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined)
177
+ throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
178
+ calculating.add(cursor);
179
+ chain.push(cursor);
180
+ if (cursor.ancestor === undefined)
181
+ break;
182
+ cursor = cursor.ancestor;
183
+ }
184
+ let before = cursor.ordinal ?? 0;
185
+ for (const current of chain.reverse()) {
186
+ const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
187
+ const marked = bootOrdinal(current.row, source.sessionId, retained);
188
+ current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
189
+ before = current.ordinal;
190
+ }
191
+ return version.ordinal;
192
+ }
193
+ if (!source.headUuid)
194
+ throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
195
+ if (!nodes.has(source.headUuid))
196
+ throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
197
+ // The inference tree uses the latest rewritten parents. At a compact boundary the logical
198
+ // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
199
+ const selected = new Set(), visited = new Set(), visiting = new Set();
200
+ const stack = [{ uuid: source.headUuid, historical: false }];
201
+ while (stack.length > 0) {
202
+ const step = stack.pop(), { uuid, historical } = step;
203
+ const key = `${historical ? "old" : "live"}:${uuid}`;
204
+ if (step.exit) {
205
+ visiting.delete(key);
206
+ visited.add(key);
207
+ continue;
208
+ }
209
+ if (visited.has(key))
210
+ continue;
211
+ if (visiting.has(key))
212
+ throw new Error("cyclic Claude transcript ancestry");
213
+ visiting.add(key);
214
+ stack.push({ ...step, exit: true });
215
+ const node = nodes.get(uuid);
216
+ if (!node)
217
+ throw new Error(`missing Claude transcript ancestor: ${uuid}`);
218
+ selected.add(uuid);
219
+ const row = (historical ? node.first : node.latest).row;
220
+ const ancestor = parent(row);
221
+ if (ancestor !== undefined)
222
+ stack.push({ uuid: ancestor, historical });
223
+ if (!boundary(row))
224
+ continue;
225
+ if (row.logicalParentUuid != null)
226
+ stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
227
+ const meta = row.compactMetadata;
228
+ if (!object(meta))
229
+ continue;
230
+ if (object(meta.preservedSegment)) {
231
+ for (const field of ["headUuid", "tailUuid"])
232
+ if (meta.preservedSegment[field] !== undefined)
233
+ stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
234
+ }
235
+ if (object(meta.preservedMessages)) {
236
+ const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
237
+ if (uuids === undefined)
238
+ continue;
239
+ if (!Array.isArray(uuids))
240
+ throw new Error("invalid Claude preserved messages");
241
+ for (const id of uuids) {
242
+ const uuid = requiredString(id, "preserved UUID");
243
+ // allUuids also names virtual/non-persisted attachments. It is auxiliary
244
+ // evidence, not a reason to pretend the stored parent chain is missing.
245
+ if (nodes.has(uuid))
246
+ stack.push({ uuid, historical: true });
247
+ }
248
+ }
249
+ }
250
+ let maxOrdinal = ordinalOf(nodes.get(source.headUuid).latest);
251
+ for (const uuid of selected)
252
+ maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid).first));
253
+ const windows = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
254
+ const branchSeqs = new Set();
255
+ for (const [uuid, node] of nodes) {
256
+ if (!selected.has(uuid))
257
+ continue;
258
+ const window = windows[ordinalOf(node.first)];
259
+ window.createdAt ??= node.items[0]?.createdAt;
260
+ for (const item of node.items) {
261
+ branchSeqs.add(item.seq);
262
+ window.items.push({ ...item, windowId: window.windowId });
263
+ }
264
+ }
265
+ return projectHistory(windows, nextSeq - 1, branchSeqs);
266
+ }
267
+ export async function readClaudeHistory(source) {
268
+ if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
269
+ throw new Error("Claude history transcript_path is unavailable");
270
+ return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
271
+ }
@@ -30,5 +30,5 @@ export async function measureBudget(ctx, agent, config, signal) {
30
30
  }
31
31
  }
32
32
  const remaining = Math.max(0, contextWindow - used);
33
- return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, thresholds.warning), warning: thresholds.warning, reminder: thresholds.reminder };
33
+ return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, reserve), warning: thresholds.warning, reminder: thresholds.reminder };
34
34
  }
@@ -3,6 +3,7 @@ import type { CommandId } from "@deepseek-ai/dsh-commands/brand";
3
3
  import { CompactionEngine, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from "@deepseek-ai/dsh-compaction";
4
4
  import { type SessionSeq } from "@deepseek-ai/dsh-session";
5
5
  import { type BudgetConfig } from "./budget.js";
6
+ import { type ResetOrigin } from "../budget/text.js";
6
7
  import { Windows, type NotesConfig } from "./window.js";
7
8
  export type EngineConfig = NotesConfig & Partial<BudgetConfig>;
8
9
  export type ResolvedConfig = NotesConfig & BudgetConfig;
@@ -14,7 +15,7 @@ export declare class NotesoupCompactionEngine extends CompactionEngine {
14
15
  constructor(ctx: Context, config?: EngineConfig);
15
16
  get automaticListenerPresent(): boolean;
16
17
  compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null>;
17
- compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal): Promise<CompactionResult>;
18
+ compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal, origin?: ResetOrigin): Promise<CompactionResult>;
18
19
  compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null>;
19
20
  /** No model call, no shrink requirement: even a one-message window can be cleared. */
20
21
  private transaction;
@@ -3,6 +3,7 @@ import { CompactionEngine, CompactionId, ManualCompactionError, compactCheckpoin
3
3
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
4
  import { appendPluginRecord } from "@deepseek-ai/dsh-session";
5
5
  import { measureBudget } from "./budget.js";
6
+ import { selectContinuation } from "../budget/text.js";
6
7
  import { checkpointText, Windows, WINDOW_RECORD } from "./window.js";
7
8
  function resolveConfig(config) {
8
9
  const resolved = { ...config, auto: config.auto ?? true, thresholdRatio: config.thresholdRatio ?? 0.8, headroomTokens: config.headroomTokens ?? 65536 };
@@ -70,8 +71,10 @@ export class NotesoupCompactionEngine extends CompactionEngine {
70
71
  async compactIfNeeded(agent, trigger, signal) {
71
72
  signal.throwIfAborted();
72
73
  const state = this.windows.get(agent.session);
73
- const forced = state.pendingReset;
74
- if (!forced) {
74
+ // `pendingReset` is the model's own `empty_brain` call. A budget cutoff happens without one,
75
+ // and that difference is the reset's actual origin.
76
+ const modelRequested = state.pendingReset;
77
+ if (!modelRequested) {
75
78
  if (!this.config.auto)
76
79
  return null;
77
80
  // Context overflow is deliberately left to the host. This adapter owns reserve resets.
@@ -84,12 +87,12 @@ export class NotesoupCompactionEngine extends CompactionEngine {
84
87
  const selected = range(agent.session);
85
88
  if (!selected)
86
89
  return null;
87
- return this.compactRegion(selected.start, selected.end, agent, signal);
90
+ return this.compactRegion(selected.start, selected.end, agent, signal, modelRequested ? "normal" : "forced");
88
91
  }
89
- async compactRegion(start, end, agent, signal) {
92
+ async compactRegion(start, end, agent, signal, origin = "forced") {
90
93
  if (entryState(agent.session).turn === null)
91
94
  throw new ManualCompactionError("busy", "notesoup: compactRegion needs an open turn; use compactNow while idle.");
92
- return this.transaction(start, end, agent, signal);
95
+ return this.transaction(start, end, agent, signal, origin);
93
96
  }
94
97
  compactNow(agent, signal, sourceCommandId) {
95
98
  signal.throwIfAborted();
@@ -102,7 +105,7 @@ export class NotesoupCompactionEngine extends CompactionEngine {
102
105
  const selected = range(agent.session);
103
106
  if (!selected)
104
107
  return null;
105
- return this.transaction(selected.start, selected.end, agent, combined, sourceCommandId, true);
108
+ return this.transaction(selected.start, selected.end, agent, combined, "forced", sourceCommandId, true);
106
109
  });
107
110
  }
108
111
  catch (error) {
@@ -110,7 +113,7 @@ export class NotesoupCompactionEngine extends CompactionEngine {
110
113
  }
111
114
  }
112
115
  /** No model call, no shrink requirement: even a one-message window can be cleared. */
113
- async transaction(start, end, agent, signal, sourceCommandId, flush = false) {
116
+ async transaction(start, end, agent, signal, origin, sourceCommandId, flush = false) {
114
117
  const session = agent.session;
115
118
  signal?.throwIfAborted();
116
119
  const selected = range(session);
@@ -121,6 +124,7 @@ export class NotesoupCompactionEngine extends CompactionEngine {
121
124
  throw new ManualCompactionError("busy", "notesoup: a compaction/start has no matching end; reload this session before retrying.");
122
125
  const state = this.windows.get(session);
123
126
  const previous = state.snapshot;
127
+ const previousContinuation = state.continuation;
124
128
  const shadowedSeqs = [...session.surface.nodes.slice(1)];
125
129
  const generation = session.surface.contentGeneration;
126
130
  const measured = this.ctx.tokenMeter.measure(session);
@@ -140,8 +144,11 @@ export class NotesoupCompactionEngine extends CompactionEngine {
140
144
  if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1)
141
145
  throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
142
146
  // Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
147
+ // One draw per reset artifact: the checkpoint text and the steered copy share it.
148
+ const continuation = selectContinuation(origin);
143
149
  state.snapshot = next;
144
- const summary = [{ type: "text", text: checkpointText(next) }];
150
+ state.continuation = continuation;
151
+ const summary = [{ type: "text", text: checkpointText(next, continuation) }];
145
152
  const summarized = session.append("compaction/summary", { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount, provider: "notesoup", model: "notes" });
146
153
  session.append("user/message", createUserMessage({ content: summary, source: compactCheckpointSource(compactionId, sourceCommandId) }), { surfaceOp: { op: "replace", startSeq: start, endSeq: end }, sourceEventSeqs: [opened.seq, summarized.seq, ...shadowedSeqs] });
147
154
  landed = true;
@@ -160,8 +167,10 @@ export class NotesoupCompactionEngine extends CompactionEngine {
160
167
  }
161
168
  }
162
169
  catch (error) {
163
- if (!landed)
170
+ if (!landed) {
164
171
  state.snapshot = previous;
172
+ state.continuation = previousContinuation;
173
+ }
165
174
  failure = error;
166
175
  if (!closing) {
167
176
  try {
@@ -1,5 +1,5 @@
1
1
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
- import { CONTINUATION, WARNING_PROMPT, tokenBudgetGuidance } from "../budget/text.js";
2
+ import { COUNTDOWN_LINE, warningPrompt, tokenBudgetGuidance } from "../budget/text.js";
3
3
  import { measureBudget } from "./budget.js";
4
4
  import { BOOT_SECTION, restoreWarnings } from "./window.js";
5
5
  import { preflight } from "./engine.js";
@@ -33,7 +33,7 @@ export function apply(ctx) {
33
33
  const state = engine.windows.get(agent.session);
34
34
  const phase = budget.remaining <= budget.warning ? "warning" : budget.remaining <= budget.reminder ? "reminder" : undefined;
35
35
  if (phase && !(phase === "warning" ? state.warned : state.reminded || state.warned)) {
36
- const text = phase === "warning" ? WARNING_PROMPT : tokenBudgetGuidance(budget.countdown, "empty_brain");
36
+ const text = phase === "warning" ? `${warningPrompt()}\n${COUNTDOWN_LINE}` : tokenBudgetGuidance(budget.countdown, "empty_brain");
37
37
  agent.steer(createUserMessage({ content: [{ type: "text", text }], source: { kind: "notesoup-budget", windowId: state.snapshot.windowId, phase } }));
38
38
  if (phase === "warning")
39
39
  state.warned = true;
@@ -48,8 +48,13 @@ export function apply(ctx) {
48
48
  if (signal.aborted)
49
49
  return;
50
50
  const result = await engine.compactIfNeeded(agent, "pressure", signal);
51
- if (result)
52
- agent.steer(createUserMessage({ content: [{ type: "text", text: CONTINUATION }], source: { kind: "notesoup-continuation" } }));
51
+ if (result) {
52
+ // The checkpoint already carries this exact paragraph; the steer is the same artifact's
53
+ // second representation, never a second draw.
54
+ const { continuation } = engine.windows.get(agent.session);
55
+ if (continuation !== undefined)
56
+ agent.steer(createUserMessage({ content: [{ type: "text", text: continuation }], source: { kind: "notesoup-continuation" } }));
57
+ }
53
58
  });
54
59
  ctx.on("session/event", (session, event) => {
55
60
  if (event.type === "turn/end" && event.data.reason.kind !== "completed") {
@@ -98,7 +98,7 @@ export function registerTools(ctx, engine) {
98
98
  }));
99
99
  ctx.tools.register(defineTool({
100
100
  name: "get_context_remaining",
101
- description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
101
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
102
102
  parameters: {},
103
103
  output: { schema: { type: "object", properties: { remaining_tokens: { oneOf: [{ type: "integer" }, { type: "null" }], required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
104
104
  async execute(_args, exec) {
@@ -16,6 +16,7 @@ export type WindowState = {
16
16
  pendingReset: boolean;
17
17
  warned: boolean;
18
18
  reminded: boolean;
19
+ continuation?: string;
19
20
  };
20
21
  export type NotesConfig = {
21
22
  notesHome?: string;
@@ -28,7 +29,7 @@ declare module "@deepseek-ai/dsh-session/types" {
28
29
  }
29
30
  }
30
31
  export declare function windowId(sessionId: string, window: number): string;
31
- export declare function checkpointText(snapshot: WindowSnapshot): string;
32
+ export declare function checkpointText(snapshot: WindowSnapshot, continuation: string): string;
32
33
  export declare function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined;
33
34
  /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
34
35
  export declare function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined;
@@ -6,7 +6,6 @@ import { createHash } from "node:crypto";
6
6
  import { loadNotesSnapshot } from "../boot/snapshot.js";
7
7
  import { renderBootBlock } from "../boot/render.js";
8
8
  import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
9
- import { CONTINUATION } from "../budget/text.js";
10
9
  import { contentText } from "../history/history.js";
11
10
  import { projectKey, slugify, snapshotNotesIdentity } from "../notes/index.js";
12
11
  export const WINDOW_RECORD = "plugin:notesoup/window";
@@ -28,7 +27,7 @@ export function restoreWarnings(state, events) {
28
27
  }
29
28
  export function windowId(sessionId, window) { return `dsh:${sessionId}:${window}`; }
30
29
  function digest(boot) { return createHash("sha256").update(boot).digest("hex"); }
31
- export function checkpointText(snapshot) { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
30
+ export function checkpointText(snapshot, continuation) { return snapshot.boot + CHECKPOINT_END + continuation + "\n</notesoup-continuation>"; }
32
31
  export function recordSnapshot(event) {
33
32
  const record = pluginRecordOf(event);
34
33
  if (record?.type !== WINDOW_RECORD || typeof record.data !== "object" || record.data === null)
@@ -58,11 +57,18 @@ function systemSnapshot(event) {
58
57
  return undefined;
59
58
  return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
60
59
  }
60
+ /**
61
+ * Read the window identity out of a persisted boot. The `context_window` spelling is what boots
62
+ * written before the rename carry, so both spellings still yield their ordinal and window id.
63
+ */
61
64
  function snapshotFromBoot(boot, openedAt) {
62
- const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
63
- if (!id || !Number.isSafeInteger(Number(id[2])))
65
+ const identity = /<(?:context_window|notesoup:window_identity)>\n[\s\S]*?\n(dsh:[^\n]+)\n[\s\S]*?└─ (\d+)(?: +[^\n]*)?\n<\/(?:context_window|notesoup:window_identity)>/.exec(boot);
66
+ const legacy = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
67
+ const shortName = identity?.[2] ?? legacy?.[2];
68
+ const id = identity ? `${identity[1]}:${shortName}` : legacy?.[1];
69
+ if (!id || shortName === undefined || !Number.isSafeInteger(Number(shortName)))
64
70
  return undefined;
65
- return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1], openedAt, boot, notesDigest: digest(boot) });
71
+ return Object.freeze({ version: 1, window: Number(shortName), windowId: id, openedAt, boot, notesDigest: digest(boot) });
66
72
  }
67
73
  export function recoverSnapshot(events) {
68
74
  let latest;
@@ -114,9 +120,9 @@ export class Windows {
114
120
  async mint(agent, window, openedAt) {
115
121
  const identity = notesIdentity(agent, this.config);
116
122
  const notes = await loadNotesSnapshot(identity, openedAt);
117
- const previous = this.states.get(agent.session)?.snapshot;
118
- const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
119
- const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
123
+ const trunk = `dsh:${agent.session.id}`;
124
+ const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
125
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, tree, notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
120
126
  return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
121
127
  }
122
128
  }