notesoup 0.52.6 → 0.52.7

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.
@@ -7,7 +7,7 @@ import { readClaudeHistory } from "./history.js";
7
7
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
8
8
  import { renderBootBlock } from "../../../src/boot/render.js";
9
9
  import { selectContinuation } from "../../../src/budget/text.js";
10
- import { CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./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
11
  import { resolveClaudeLimits } from "./thresholds.js";
12
12
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
13
13
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -27,15 +27,12 @@ function paramProblem(schema, params) {
27
27
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
28
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
29
  }
30
- /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
30
+ /** Bind shared execution/rendering to a host context; dispatch validates parameters before calling. */
31
31
  function boundOperation(operation) {
32
32
  return {
33
33
  description: operation.description,
34
34
  parameters: operation.parameters,
35
35
  async call(params, ...context) {
36
- // Refuse before the operation can act: a rejected shape never reaches a write.
37
- if (!Check(operation.parameters, params))
38
- throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
39
36
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
40
37
  const outcome = await operation.execute(params, ...context);
41
38
  return { text: operation.render(outcome), ok: outcome.ok };
@@ -85,17 +82,47 @@ export async function dispatch(request) {
85
82
  if (value.op === "tool") {
86
83
  if (typeof value.tool !== "string" || (!Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool)))
87
84
  throw new Error("unknown tool");
85
+ const operation = Object.hasOwn(OPERATIONS, value.tool) ? OPERATIONS[value.tool] : HISTORY_OPERATIONS[value.tool];
86
+ // Refuse before any operation can act: a rejected shape never reaches a write.
87
+ if (!Check(operation.parameters, value.params))
88
+ throw new Error(`invalid ${value.tool} parameters: ${paramProblem(operation.parameters, value.params)}`);
88
89
  const id = identity(value.identity);
89
90
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
91
+ const tool = value.tool;
90
92
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
91
- return HISTORY_OPERATIONS[value.tool].call(value.params, projection, id.sessionId);
93
+ const notice = claudeHistoryGapNotice(projection.missingAncestors);
94
+ 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
+ }
111
+ }
112
+ }
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);
116
+ return { ...result, text: wrapText(result.text) };
92
117
  }
93
118
  return OPERATIONS[value.tool].call(value.params, id);
94
119
  }
95
120
  if (value.op === "history_state") {
96
121
  const id = identity(value.identity);
97
122
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
98
- return { window: projection.windows.length - 1 };
123
+ if (projection.currentWindowOrdinal === undefined)
124
+ throw new Error(CLAUDE_HISTORY_UNKNOWN_WINDOW);
125
+ return { window: projection.currentWindowOrdinal };
99
126
  }
100
127
  if (value.op === "boot") {
101
128
  const id = identity(value.identity);
@@ -4,6 +4,11 @@ export type ClaudeHistorySource = {
4
4
  transcriptPath: string;
5
5
  headUuid?: string;
6
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
+ };
7
12
  /** 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>;
13
+ export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
+ export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
@@ -132,8 +132,8 @@ export function claudeHistoryFromJsonl(text, source) {
132
132
  const nodes = new Map();
133
133
  let nextSeq = 1;
134
134
  for (const row of rowsOf(text)) {
135
- // Ignore non-message records, including future metadata. A skipped UUID that
136
- // the selected branch actually requires still fails ancestry resolution below.
135
+ // Ignore non-message records, including future metadata. If selected ancestry
136
+ // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
137
137
  if (!MESSAGE_TYPES.has(row.type))
138
138
  continue;
139
139
  const uuid = requiredString(row.uuid, "uuid");
@@ -160,32 +160,39 @@ export function claudeHistoryFromJsonl(text, source) {
160
160
  nextSeq += items.length;
161
161
  nodes.set(uuid, { first: version, latest: version, items });
162
162
  }
163
- function ordinalOf(version) {
164
- // Persisted history is not limited to the host's newest 4096 inference rows.
165
- // Resolve long parent chains iteratively, not with the JavaScript call stack.
163
+ const missingAncestors = new Set();
164
+ function positionOf(version) {
165
+ // Resolve long chains iteratively. A gap destroys ordinal evidence, not the
166
+ // confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
166
167
  const chain = [], calculating = new Set();
167
168
  let cursor = version;
168
- while (cursor.ordinal === undefined) {
169
- // A notice can precede its parent on disk; use that parent's first eventual version.
169
+ let before = { ordinal: 0 };
170
+ while (cursor.position === undefined) {
171
+ // Forward references use the parent's first eventual version, not a rewrite.
170
172
  cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
171
173
  if (calculating.has(cursor))
172
174
  throw new Error("cyclic Claude transcript ancestry");
173
- if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined)
174
- throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
175
175
  calculating.add(cursor);
176
176
  chain.push(cursor);
177
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
178
+ missingAncestors.add(cursor.ancestorUuid);
179
+ before = { unknownAncestor: cursor.ancestorUuid };
180
+ break;
181
+ }
177
182
  if (cursor.ancestor === undefined)
178
183
  break;
179
184
  cursor = cursor.ancestor;
180
185
  }
181
- let before = cursor.ordinal ?? 0;
186
+ before = cursor.position ?? before;
182
187
  for (const current of chain.reverse()) {
183
188
  const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
184
189
  const marked = bootOrdinal(current.row, retained);
185
- current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
186
- before = current.ordinal;
190
+ current.position = marked !== undefined
191
+ ? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
192
+ : "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
193
+ before = current.position;
187
194
  }
188
- return version.ordinal;
195
+ return version.position;
189
196
  }
190
197
  if (!source.headUuid)
191
198
  throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
@@ -210,8 +217,10 @@ export function claudeHistoryFromJsonl(text, source) {
210
217
  visiting.add(key);
211
218
  stack.push({ ...step, exit: true });
212
219
  const node = nodes.get(uuid);
213
- if (!node)
214
- throw new Error(`missing Claude transcript ancestor: ${uuid}`);
220
+ if (!node) {
221
+ missingAncestors.add(uuid);
222
+ continue;
223
+ }
215
224
  selected.add(uuid);
216
225
  const row = (historical ? node.first : node.latest).row;
217
226
  const ancestor = parent(row);
@@ -244,22 +253,44 @@ export function claudeHistoryFromJsonl(text, source) {
244
253
  }
245
254
  }
246
255
  }
247
- let maxOrdinal = ordinalOf(nodes.get(source.headUuid).latest);
248
- for (const uuid of selected)
249
- maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid).first));
250
- const windows = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
256
+ const current = positionOf(nodes.get(source.headUuid).latest);
257
+ const windowId = (position) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
258
+ const windowsById = new Map();
251
259
  const branchSeqs = new Set();
260
+ let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
252
261
  for (const [uuid, node] of nodes) {
253
262
  if (!selected.has(uuid))
254
263
  continue;
255
- const window = windows[ordinalOf(node.first)];
264
+ const position = positionOf(node.first);
265
+ if ("ordinal" in position)
266
+ maxOrdinal = Math.max(maxOrdinal, position.ordinal);
267
+ const id = windowId(position);
268
+ let window = windowsById.get(id);
269
+ if (!window) {
270
+ window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
271
+ windowsById.set(id, window);
272
+ }
256
273
  window.createdAt ??= node.items[0]?.createdAt;
257
274
  for (const item of node.items) {
258
275
  branchSeqs.add(item.seq);
259
- window.items.push({ ...item, windowId: window.windowId });
276
+ window.items.push({ ...item, windowId: id });
277
+ }
278
+ }
279
+ // Preserve complete-history empty windows (including copied boot ordinals).
280
+ // With gaps, report only evidenced windows, never invent the missing ordinals.
281
+ if (missingAncestors.size === 0) {
282
+ for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
283
+ const id = windowId({ ordinal });
284
+ if (!windowsById.has(id))
285
+ windowsById.set(id, { windowId: id, ordinal, items: [] });
260
286
  }
261
287
  }
262
- return projectHistory(windows, nextSeq - 1, branchSeqs);
288
+ // Forward references can put a newer numbered window on disk first. Unknown
289
+ // segments are a separate, unordered group, not an inferred place in that timeline.
290
+ const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
291
+ ? b.ordinal === undefined ? 0 : 1
292
+ : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
293
+ return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
263
294
  }
264
295
  export async function readClaudeHistory(source) {
265
296
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
@@ -2,3 +2,8 @@
2
2
  export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
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
+ 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
+ export declare function claudeHistoryUnconfirmedSeq(seq: number): string;
8
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
9
+ export declare function claudeHistoryGapNotice(missing: readonly string[]): string;
@@ -3,3 +3,15 @@ import { warningNotice } from "../../../src/budget/text.js";
3
3
  export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
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
+ 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
+ export function claudeHistoryUnconfirmedSeq(seq) {
9
+ return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
10
+ }
11
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
12
+ export function claudeHistoryGapNotice(missing) {
13
+ if (missing.length === 0)
14
+ return "";
15
+ const evidence = missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.length > 160 ? `${uuid.slice(0, 160)}…` : uuid)).join(", ");
16
+ return `Claude history is incomplete: missing ancestor UUID(s): ${evidence}${missing.length > 5 ? `; ${missing.length - 5} more` : ""}. Only confirmed selected ancestry is returned; disconnected prefixes and unrelated branches are excluded. Window IDs containing :unknown: have unconfirmed ordinal/ownership and may span native compactions; they are listed separately after numbered windows, not placed in a chronological order. A later retained boot can re-anchor window numbering, but cannot fill the history gap.\n\n`;
17
+ }
@@ -75,31 +75,32 @@ function toolEvent(item, result) {
75
75
  }
76
76
  /** Pair results into call events; consumed result seqs are not alternate read addresses. */
77
77
  export function projectHistory(rawWindows, highestSeq, branchSeqs) {
78
- const raw = rawWindows.flatMap((current) => current.items);
78
+ // Pair in durable address order, not window presentation order. Unnumbered
79
+ // segments need not have a provable chronological order relative to each other.
80
+ const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
79
81
  const resultsById = new Map();
80
82
  for (const item of raw) {
81
83
  if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId))
82
84
  resultsById.set(item.toolCallId, item);
83
85
  }
84
86
  const pairedResults = new Map();
85
- const consumed = new Set();
87
+ for (const item of raw) {
88
+ const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
89
+ if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
90
+ pairedResults.set(result.seq, item.seq);
91
+ }
92
+ }
86
93
  const windows = rawWindows.map((current) => ({
87
94
  windowId: current.windowId,
88
95
  ...(current.createdAt ? { createdAt: current.createdAt } : {}),
89
96
  items: current.items.flatMap((item) => {
90
- if (consumed.has(item.seq))
97
+ if (pairedResults.has(item.seq))
91
98
  return [];
92
- if (item.role === "tool_call") {
99
+ if (item.role === "tool_call" || item.role === "tool") {
93
100
  const result = item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
94
- const paired = result && result.seq > item.seq && !consumed.has(result.seq) ? result : undefined;
95
- if (paired) {
96
- consumed.add(paired.seq);
97
- pairedResults.set(paired.seq, item.seq);
98
- }
101
+ const paired = result && pairedResults.get(result.seq) === item.seq ? result : undefined;
99
102
  return [toolEvent(item, paired)];
100
103
  }
101
- if (item.role === "tool")
102
- return [toolEvent(item)];
103
104
  return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
104
105
  }),
105
106
  }));
@@ -33,9 +33,11 @@ declare const HistoryWindowsDataSchema: Type.TObject<{
33
33
  more: Type.TInteger;
34
34
  }>;
35
35
  type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
36
+ /** Pure host decoration, measured during selection and applied unchanged by the caller at delivery. */
37
+ export type HistoryTextWrapper = (text: string) => string;
36
38
  export declare const PREVIOUS_WINDOW = "@previous";
37
39
  export declare const historyWindowsParameters: Type.TObject<{}>;
38
- export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]>;
40
+ export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string, HistoryTextWrapper?]>;
39
41
  export declare const historyListParameters: Type.TObject<{
40
42
  query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
41
43
  roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
@@ -48,11 +50,11 @@ export declare const historyListParameters: Type.TObject<{
48
50
  limit: Type.TOptional<Type.TInteger>;
49
51
  max_chars_per_item: Type.TOptional<Type.TInteger>;
50
52
  }>;
51
- export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]>;
53
+ export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection, HistoryTextWrapper?]>;
52
54
  export declare const historyReadParameters: Type.TObject<{
53
55
  offset_chars: Type.TOptional<Type.TInteger>;
54
56
  max_chars: Type.TOptional<Type.TInteger>;
55
57
  seq: Type.TInteger;
56
58
  }>;
57
- export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]>;
59
+ export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection, HistoryTextWrapper?]>;
58
60
  export {};
@@ -70,11 +70,7 @@ function renderRead(data) {
70
70
  const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
71
71
  return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
72
72
  }
73
- /* ------------------------------------------------------------------ shared bounding */
74
- /** Include rendering and cursors in the budget, not just row contents. */
75
- function pageFits(page) {
76
- return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
77
- }
73
+ const plainText = (text) => text;
78
74
  // Sample known ids in the refusal message itself, never as a second listing.
79
75
  const MAX_REPORTED_WINDOWS = 5;
80
76
  /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
@@ -106,9 +102,9 @@ export const historyWindows = {
106
102
  description: "List this session's context windows, oldest first, with seq ranges.",
107
103
  parameters: historyWindowsParameters,
108
104
  outputSchema: resultSchema(HistoryWindowsDataSchema),
109
- async execute(_params, projection, sessionId) {
105
+ async execute(_params, projection, sessionId, wrapText = plainText) {
110
106
  const data = { session_id: sessionId, windows: [], more: projection.windows.length };
111
- const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
107
+ const fits = (candidate) => fitsResult(success(candidate), (result) => wrapText(renderOutcome(result, renderWindows)));
112
108
  for (const window of projection.windows) {
113
109
  let first = null;
114
110
  let last = null;
@@ -151,7 +147,7 @@ export const historyList = {
151
147
  description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
152
148
  parameters: historyListParameters,
153
149
  outputSchema: resultSchema(HistoryPageSchema),
154
- async execute(params, projection) {
150
+ async execute(params, projection, wrapText = plainText) {
155
151
  const resolved = resolveWindowId(projection, params.window_id);
156
152
  if (!resolved.ok)
157
153
  return resolved.outcome;
@@ -159,7 +155,9 @@ export const historyList = {
159
155
  const badWindow = badWindowId(projection, scoped);
160
156
  if (badWindow)
161
157
  return badWindow;
162
- return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
158
+ // Charge wrapped rendering and cursors, not only event previews.
159
+ const fits = (page) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
160
+ return selectPage(projection, scoped, fits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
163
161
  },
164
162
  render: (result) => renderOutcome(result, renderPage),
165
163
  };
@@ -171,7 +169,7 @@ export const historyRead = {
171
169
  description: "Read one event in full: tool arguments, output, and nested calls.",
172
170
  parameters: historyReadParameters,
173
171
  outputSchema: resultSchema(HistoryReadDataSchema),
174
- async execute(params, projection) {
172
+ async execute(params, projection, wrapText = plainText) {
175
173
  const item = allItems(projection).find((event) => event.seq === params.seq);
176
174
  // Address checks run in one order: past the end of the file, off this branch, then
177
175
  // consumed by a pairing. Only the last two can mention what is at the address.
@@ -201,7 +199,7 @@ export const historyRead = {
201
199
  ...toolSummary(item),
202
200
  ...nestedCallSummary(item),
203
201
  ...window,
204
- }), (result) => renderOutcome(result, renderRead));
202
+ }), (result) => wrapText(renderOutcome(result, renderRead)));
205
203
  },
206
204
  render: (result) => renderOutcome(result, renderRead),
207
205
  };
@@ -9,6 +9,7 @@ import { unavailableNotesSnapshot } from "../src/boot/snapshot.js";
9
9
  import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
10
10
  import { allItems, eventDocument } from "../src/history/history.js";
11
11
  import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
12
+ import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
12
13
  import { dispatch } from "../plugins/claude/src/helper.js";
13
14
  const sessionId = "synthetic-session";
14
15
  function row(uuid, parentUuid, type, content, extra = {}) {
@@ -84,11 +85,15 @@ test("Claude file-history deltas do not become events or change history addresse
84
85
  assert.deepEqual(project([delta, rows[0], delta, rows[1], delta], "a"), baseline);
85
86
  assert.equal(baseline.highestSeq, 2);
86
87
  });
87
- test("Claude skips unknown record types unless selected ancestry requires them", () => {
88
+ test("Claude skips unknown record types and treats required skipped UUIDs as gaps, not content", () => {
88
89
  const u = user("u", null, "hello"), a = assistant("a", "u", [{ type: "text", text: "reply" }]);
89
90
  const unknown = { type: "future-record", uuid: "future", parentUuid: "not-on-disk", content: "private metadata" };
90
91
  assert.deepEqual(project([unknown, u, unknown, a, unknown], "a"), project([u, a], "a"));
91
- assert.throws(() => project([u, unknown, { ...a, parentUuid: "future" }], "a"), /missing Claude transcript ancestor: future/);
92
+ const incomplete = project([u, unknown, { ...a, parentUuid: "future" }], "a");
93
+ assert.deepEqual(incomplete.missingAncestors, ["future"]);
94
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
95
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [2]);
96
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /private metadata|hello/);
92
97
  });
93
98
  test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
94
99
  const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
@@ -182,7 +187,7 @@ test("Claude resolves forward persisted ancestry without renumbering or using la
182
187
  assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.windowId, `claude:${sessionId}:0`);
183
188
  assert.equal(allItems(projection).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`);
184
189
  assert.deepEqual(project(rows, "new"), projection);
185
- assert.throws(() => project([notice], "notice"), /missing.*ancestor/);
190
+ assert.deepEqual(project([notice], "notice").missingAncestors, ["attachment"]);
186
191
  assert.equal(project([user("u", null, bootText(9))], "u").windows.length, 1, "ordinary user text is not a trusted retained boot");
187
192
  });
188
193
  test("Claude attachments expose recorded renderings only and keep non-rendered nodes in ancestry", () => {
@@ -203,8 +208,135 @@ test("Claude tolerates only the uncommitted JSONL tail, not malformed committed
203
208
  assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
204
209
  assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
205
210
  assert.throws(() => project([{ ...user("u", null, "first"), isSidechain: true }], "u"), /only the main/);
211
+ assert.throws(() => project([user("u", "a", "cycle"), assistant("a", "u", "cycle")], "a"), /cyclic Claude transcript ancestry/);
212
+ assert.throws(() => project([user("u", "missing", "gap"), assistant("a", "a", "cycle")], "a"), /cyclic Claude transcript ancestry/);
206
213
  assert.throws(() => project([{ ...user("u", null, "first"), sessionId: "another-session" }], "u"), /different session/);
207
214
  });
215
+ test("Claude gaps retain only confirmed suffixes, keep pairing/seqs, and disappear when the ancestor is appended", async () => {
216
+ const rows = [user("prefix", null, "unconfirmed prefix"), assistant("sibling", "prefix", "unrelated sibling"),
217
+ assistant("suffix", "missing", [{ type: "text", text: "searchable suffix" }, call("one")]),
218
+ row("output", "suffix", "user", [result("one", "confirmed output")]),
219
+ assistant("gap-sibling", "missing", "unrelated gap sibling")];
220
+ const incomplete = project(rows, "output");
221
+ assert.deepEqual(incomplete.missingAncestors, ["missing"]);
222
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
223
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [3, 4, 5]);
224
+ assert.equal(incomplete.pairedResults.get(6), 4);
225
+ assert.equal(incomplete.highestSeq, 7);
226
+ assert.match(incomplete.windows[0].windowId, /:unknown:missing$/);
227
+ const suffix = await historyList.execute({ query: "searchable suffix" }, incomplete);
228
+ assert.ok(suffix.ok);
229
+ assert.deepEqual(suffix.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
230
+ const tool = await historyRead.execute({ seq: 4 }, incomplete);
231
+ assert.ok(tool.ok);
232
+ assert.match(tool.data.text, /confirmed output/);
233
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /unconfirmed prefix|unrelated sibling|unrelated gap sibling/);
234
+ // A later first occurrence gets the next append seq, never an inserted seq.
235
+ const recovered = project([...rows, user("missing", "prefix", "recovered ancestor")], "output");
236
+ assert.deepEqual(recovered.missingAncestors, []);
237
+ assert.equal(recovered.currentWindowOrdinal, 0);
238
+ assert.equal(recovered.highestSeq, 8);
239
+ assert.deepEqual(allItems(recovered).map((event) => event.seq), [1, 3, 4, 5, 8]);
240
+ assert.equal(recovered.pairedResults.get(6), 4);
241
+ assert.ok(!recovered.branchSeqs.has(2) && !recovered.branchSeqs.has(7), "recovery never selects either sibling");
242
+ });
243
+ test("Claude helper reports gaps on list/read/windows and re-anchors reset state only with a retained boot", async (t) => {
244
+ const root = mkdtempSync(join(tmpdir(), "claude-history-gap-"));
245
+ t.after(() => rmSync(root, { recursive: true, force: true }));
246
+ const transcriptPath = join(root, "transcript.jsonl");
247
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
248
+ const rows = [user("prefix", null, "do not expose disconnected prefix"),
249
+ { type: "future-record", uuid: "missing", parentUuid: "prefix", content: "do not expose metadata" },
250
+ assistant("suffix", "missing", "confirmed suffix")];
251
+ const history = { sessionId, transcriptPath, headUuid: "suffix" };
252
+ const invoke = (tool, params = {}) => dispatch({ op: "tool", tool, params, identity, history });
253
+ writeFileSync(transcriptPath, jsonl(rows));
254
+ for (const [tool, params] of [["history_list", {}], ["history_read", { seq: 2 }], ["history_windows", {}],
255
+ ["history_list", { query: "no matches" }], ["history_read", { seq: 99 }]]) {
256
+ const response = await invoke(tool, params);
257
+ assert.match(response.text, /history is incomplete: missing ancestor UUID\(s\): "missing"/);
258
+ assert.doesNotMatch(response.text, /do not expose/);
259
+ }
260
+ assert.match((await invoke("history_list")).text, /confirmed suffix/);
261
+ const excluded = await invoke("history_read", { seq: 1 });
262
+ assert.equal(excluded.ok, false);
263
+ assert.match(excluded.text, /outside the confirmed selected history/);
264
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
265
+ await assert.rejects(invoke("history_list", { window_id: "@previous", before_seq: "invalid" }), /invalid history_list parameters: before_seq/);
266
+ await assert.rejects(invoke("history_read", { seq: "2" }), /invalid history_read parameters: seq/);
267
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
268
+ // A native boundary alone cannot count the missing earlier resets. A quoted
269
+ // identity without the full retained protocol is not a new ordinal anchor.
270
+ rows.push(compact("boundary", "suffix"), row("partial", "boundary", "user", "Current context window id: claude:synthetic-session:8"));
271
+ writeFileSync(transcriptPath, jsonl(rows));
272
+ history.headUuid = "partial";
273
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
274
+ rows.push(row("boot", "partial", "user", bootText(8), { isCompactSummary: true }), user("after", "boot", "after anchored reset"));
275
+ writeFileSync(transcriptPath, jsonl(rows));
276
+ history.headUuid = "after";
277
+ const anchored = await readClaudeHistory(history);
278
+ assert.equal(anchored.currentWindowOrdinal, 8);
279
+ assert.deepEqual(anchored.windows.map((window) => window.windowId), [`claude:${sessionId}:8`, `claude:${sessionId}:unknown:missing`], "unknown segments are listed separately, not inserted into the numbered timeline");
280
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 8 }, "never windows.length - 1");
281
+ assert.match((await invoke("history_read", { seq: 6 })).text, /window claude:synthetic-session:8/);
282
+ assert.match((await invoke("history_windows")).text, /history is incomplete/);
283
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
284
+ rows.push(compact("next", "after"), row("next-boot", "next", "user", bootText(9)), user("latest", "next-boot", "latest"));
285
+ writeFileSync(transcriptPath, jsonl(rows));
286
+ history.headUuid = "latest";
287
+ const previous = await invoke("history_list", { window_id: "@previous" });
288
+ assert.ok(previous.ok);
289
+ assert.match(previous.text, /after anchored reset/);
290
+ assert.doesNotMatch(previous.text, /confirmed suffix/);
291
+ // Restore the record as a supported message: warning disappears on the next
292
+ // read, without any in-memory repair state or changed existing addresses.
293
+ rows.push(user("missing", "prefix", "recovered ancestor"));
294
+ writeFileSync(transcriptPath, jsonl(rows));
295
+ assert.doesNotMatch((await invoke("history_windows")).text, /history is incomplete|:unknown:/);
296
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 9 });
297
+ });
298
+ test("Claude gap windows sort by confirmed ordinal despite forward references, without duplicating paired output", async () => {
299
+ const rows = [row("notice", "boot9", "system", "notice"),
300
+ row("boot8", "missing", "user", bootText(8), { isCompactSummary: true }),
301
+ assistant("call", "boot8", [call("t")]), compact("boundary9", "call"),
302
+ row("boot9", "boundary9", "user", bootText(9)), row("result", "notice", "user", [result("t", "output")])];
303
+ const projection = project(rows, "result");
304
+ const windows = await historyWindows.execute({}, projection, sessionId);
305
+ assert.ok(windows.ok);
306
+ assert.deepEqual(windows.data.windows.map((window) => window.window_id), [8, 9].map((ordinal) => `claude:${sessionId}:${ordinal}`));
307
+ assert.equal(projection.currentWindowOrdinal, 9);
308
+ assert.equal(projection.highestSeq, 8);
309
+ assert.deepEqual(allItems(projection).filter((event) => event.role === "tool").map((event) => [event.seq, event.text]), [[4, "output"]]);
310
+ assert.equal(projection.pairedResults.get(8), 4);
311
+ const alias = await historyRead.execute({ seq: 8 }, projection);
312
+ assert.ok(!alias.ok);
313
+ assert.equal(alias.error.code, "not_an_event");
314
+ assert.match(alias.error.message, /read seq 4/);
315
+ });
316
+ test("Claude gap notices participate in list/read budgets without changing read coordinates", async (t) => {
317
+ const root = mkdtempSync(join(tmpdir(), "claude-history-budget-"));
318
+ t.after(() => rmSync(root, { recursive: true, force: true }));
319
+ const transcriptPath = join(root, "transcript.jsonl"), text = "x".repeat(50000);
320
+ writeFileSync(transcriptPath, jsonl([assistant("head", "missing", text)]));
321
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
322
+ const history = { sessionId, transcriptPath, headUuid: "head" };
323
+ const invoke = async (tool, params) => {
324
+ const response = await dispatch({ op: "tool", tool, params, identity, history });
325
+ assert.ok(response.ok);
326
+ assert.match(response.text, /history is incomplete.*"missing"/);
327
+ assert.ok(Buffer.byteLength(response.text, "utf8") <= TOOL_OUTPUT_MAX_BYTES, `${tool}: ${Buffer.byteLength(response.text, "utf8")} bytes`);
328
+ return response.text;
329
+ };
330
+ const first = await invoke("history_read", { seq: 1, max_chars: 50000 });
331
+ const offset = Number(/\[truncated; continue at offset_chars=(\d+)\]$/.exec(first)?.[1]);
332
+ assert.ok(offset > 0 && offset < text.length);
333
+ const firstBody = /\n\n(x+)\n\n\[truncated;/.exec(first)?.[1];
334
+ assert.equal(firstBody, text.slice(0, offset), "the footer addresses the first undelivered character, not the decorated text");
335
+ const rest = await invoke("history_read", { seq: 1, offset_chars: offset, max_chars: 50000 });
336
+ assert.equal(/\n\n(x+)$/.exec(rest)?.[1], text.slice(offset));
337
+ assert.doesNotMatch(rest, /\[truncated;/);
338
+ await invoke("history_list", { max_chars_per_item: 50000 });
339
+ });
208
340
  test("Claude helper history tools reuse shared schemas, outcomes and text rendering from a supplied path", async (t) => {
209
341
  const root = mkdtempSync(join(tmpdir(), "claude-history-"));
210
342
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -93,6 +93,20 @@ test("every history operation declares a result schema its own payload satisfies
93
93
  const refusal = await call(captured, "history_read", { seq: 999 }, ctx);
94
94
  assert.equal(Check(historyRead.outputSchema, refusal.structuredContent), true, "a refusal satisfies the same result schema");
95
95
  });
96
+ test("pairing uses append seq rather than the presentation order of unnumbered segments", async () => {
97
+ const projection = projectHistory([
98
+ { windowId: "unknown-a", items: [
99
+ { seq: 1, windowId: "unknown-a", role: "system", text: "notice" },
100
+ { seq: 3, windowId: "unknown-a", role: "tool", toolCallId: "t", text: "output" },
101
+ ] },
102
+ { windowId: "unknown-b", items: [{ seq: 2, windowId: "unknown-b", role: "tool_call", toolCallId: "t", toolName: "bash", text: "" }] },
103
+ ], 3, new Set([1, 2, 3]));
104
+ assert.deepEqual(projection.windows.map((window) => window.windowId), ["unknown-a", "unknown-b"], "pairing must not invent segment chronology");
105
+ assert.deepEqual(projection.windows.flatMap((window) => window.items).filter((event) => event.role === "tool").map((event) => [event.seq, event.text]), [[2, "output"]]);
106
+ const alias = await historyRead.execute({ seq: 3 }, projection);
107
+ assert.ok(!alias.ok);
108
+ assert.equal(alias.error.code, "not_an_event");
109
+ });
96
110
  test("seq is stable across branch changes, abandoned entries stay unreadable, and a paired result seq is refused precisely", async () => {
97
111
  const session = manager();
98
112
  const captured = makeExtension(session);
@@ -647,7 +661,7 @@ test("history_read paginates one document with an accurate limit and a bounded b
647
661
  assert.equal(past.code, "invalid_offset");
648
662
  assert.match(past.message, new RegExp(`\\b${content.length}\\b`), "the refusal names the real length");
649
663
  });
650
- test("history windows expose stable ranges and session identity", async () => {
664
+ test("history windows expose stable ranges and include host decoration in the complete budget", async () => {
651
665
  const session = manager();
652
666
  const captured = makeExtension(session);
653
667
  const ctx = context(session);
@@ -656,6 +670,17 @@ test("history windows expose stable ranges and session identity", async () => {
656
670
  assert.equal(windows.session_id, session.getSessionId());
657
671
  assert.equal(windows.windows.length, 1);
658
672
  assert.deepEqual(windows.windows[0], { window_id: windows.windows[0].window_id, created_at: null, first_seq: 1, last_seq: 1 });
673
+ const projection = projectHistory([0, 1, 2].map((index) => ({ windowId: `w${index}-${"x".repeat(200)}`, items: [] })), 0, new Set());
674
+ const notice = `${"n".repeat(TOOL_OUTPUT_MAX_BYTES - 400)}\n`;
675
+ const wrapText = (text) => notice + text;
676
+ const bounded = await historyWindows.execute({}, projection, "session-x", wrapText);
677
+ assert.ok(bounded.ok);
678
+ assert.equal(bounded.data.windows.length, 1);
679
+ assert.equal(bounded.data.more, 2);
680
+ const text = wrapText(historyWindows.render(bounded));
681
+ assert.ok(Buffer.byteLength(text, "utf8") <= TOOL_OUTPUT_MAX_BYTES);
682
+ assert.ok(text.startsWith(notice), "decoration is measured, never clipped at delivery");
683
+ assert.match(text, /2 more windows not shown/);
659
684
  });
660
685
  test("historyDocument is one deterministic projection of the facts, with no UI header or continuation suffix", async () => {
661
686
  const windowId = "w1";