notesoup 0.47.1 → 0.48.0

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 (78) hide show
  1. package/README.md +1 -1
  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 +59 -11
  6. package/dist/src/budget/text.d.ts +29 -9
  7. package/dist/src/budget/text.js +51 -10
  8. package/dist/src/claude/helper.d.ts +2 -3
  9. package/dist/src/claude/helper.js +45 -11
  10. package/dist/src/claude/history.d.ts +9 -0
  11. package/dist/src/claude/history.js +271 -0
  12. package/dist/src/dsh/engine.d.ts +2 -1
  13. package/dist/src/dsh/engine.js +18 -9
  14. package/dist/src/dsh/index.js +9 -4
  15. package/dist/src/dsh/window.d.ts +2 -1
  16. package/dist/src/dsh/window.js +14 -8
  17. package/dist/src/history/query.js +59 -81
  18. package/dist/src/notes/address.d.ts +5 -0
  19. package/dist/src/notes/address.js +20 -21
  20. package/dist/src/notes/store.js +12 -19
  21. package/dist/src/pi/boot.d.ts +1 -1
  22. package/dist/src/pi/boot.js +28 -5
  23. package/dist/src/pi/budget.d.ts +0 -2
  24. package/dist/src/pi/budget.js +13 -53
  25. package/dist/src/pi/entries.d.ts +0 -1
  26. package/dist/src/pi/entries.js +0 -1
  27. package/dist/src/pi/history.d.ts +3 -0
  28. package/dist/src/pi/history.js +4 -0
  29. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  30. package/dist/src/pi/reset/artifacts.js +16 -14
  31. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  32. package/dist/src/pi/reset/lifecycle.js +48 -72
  33. package/dist/src/pi/runtime.js +6 -6
  34. package/dist/src/pi/window.d.ts +12 -6
  35. package/dist/src/pi/window.js +7 -0
  36. package/dist/test/agent-loop.test.js +52 -29
  37. package/dist/test/boot.integration.test.js +114 -11
  38. package/dist/test/budget-settings.integration.test.js +4 -2
  39. package/dist/test/claude-history.test.d.ts +1 -0
  40. package/dist/test/claude-history.test.js +184 -0
  41. package/dist/test/claude-mod.test.js +236 -42
  42. package/dist/test/dsh.test.js +79 -2
  43. package/dist/test/helpers/extension.d.ts +3 -0
  44. package/dist/test/helpers/extension.js +33 -5
  45. package/dist/test/history.integration.test.js +66 -0
  46. package/dist/test/host-neutral.test.js +1 -1
  47. package/dist/test/model-facing-text.test.d.ts +1 -0
  48. package/dist/test/model-facing-text.test.js +181 -0
  49. package/dist/test/notes.integration.test.js +16 -18
  50. package/dist/test/reset-lifecycle.test.js +201 -46
  51. package/docs/architecture.md +3 -3
  52. package/docs/claude-code-mod.md +15 -3
  53. package/docs/dsh.md +1 -1
  54. package/docs/reset-lifecycle.md +32 -20
  55. package/docs/skills.md +1 -1
  56. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  57. package/mods/notesoup/dist/claude/helper.js +836 -92
  58. package/mods/notesoup/hooks/register.ts +140 -38
  59. package/package.json +1 -1
  60. package/src/boot/render.ts +41 -23
  61. package/src/boot/text.ts +68 -11
  62. package/src/budget/text.ts +61 -10
  63. package/src/claude/helper.ts +53 -22
  64. package/src/claude/history.ts +228 -0
  65. package/src/dsh/engine.ts +16 -9
  66. package/src/dsh/index.ts +8 -3
  67. package/src/dsh/window.ts +15 -9
  68. package/src/history/query.ts +57 -82
  69. package/src/notes/address.ts +19 -16
  70. package/src/notes/store.ts +9 -14
  71. package/src/pi/boot.ts +27 -5
  72. package/src/pi/budget.ts +13 -50
  73. package/src/pi/entries.ts +0 -1
  74. package/src/pi/history.ts +7 -2
  75. package/src/pi/reset/artifacts.ts +17 -14
  76. package/src/pi/reset/lifecycle.ts +56 -79
  77. package/src/pi/runtime.ts +6 -6
  78. package/src/pi/window.ts +11 -1
@@ -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
+ }
@@ -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") {
@@ -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
  }