notesoup 0.56.1 → 0.57.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 (60) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/entries.d.ts +0 -1
  3. package/dist/plugins/pi/entries.js +0 -1
  4. package/dist/plugins/pi/reset/lifecycle.d.ts +2 -1
  5. package/dist/plugins/pi/reset/lifecycle.js +19 -36
  6. package/dist/plugins/pi/runtime.js +14 -10
  7. package/dist/plugins/pi/text.d.ts +0 -2
  8. package/dist/plugins/pi/text.js +2 -6
  9. package/dist/src/history/claude.d.ts +2 -0
  10. package/dist/src/history/claude.js +13 -2
  11. package/dist/src/history/codex-transcript.d.ts +15 -3
  12. package/dist/src/history/codex-transcript.js +57 -21
  13. package/dist/src/history/codex.d.ts +4 -2
  14. package/dist/src/history/codex.js +3 -3
  15. package/dist/src/history/corpus.d.ts +8 -1
  16. package/dist/src/history/corpus.js +17 -1
  17. package/dist/src/history/history.d.ts +16 -10
  18. package/dist/src/history/history.js +9 -9
  19. package/dist/src/history/local.d.ts +2 -0
  20. package/dist/src/history/local.js +35 -38
  21. package/dist/src/history/prefilter.d.ts +5 -0
  22. package/dist/src/history/prefilter.js +95 -0
  23. package/dist/src/history/query.d.ts +29 -27
  24. package/dist/src/history/query.js +82 -34
  25. package/dist/src/history/summary-cache.d.ts +10 -0
  26. package/dist/src/history/summary-cache.js +129 -0
  27. package/dist/src/tools/history.js +31 -20
  28. package/dist/test/agent-loop.test.js +143 -110
  29. package/dist/test/codex-history.test.js +90 -4
  30. package/dist/test/codex-plugin.test.js +6 -2
  31. package/dist/test/history-corpus.test.js +221 -33
  32. package/dist/test/history-prefilter.test.d.ts +1 -0
  33. package/dist/test/history-prefilter.test.js +174 -0
  34. package/dist/test/history-summary-cache.test.d.ts +1 -0
  35. package/dist/test/history-summary-cache.test.js +297 -0
  36. package/dist/test/history.integration.test.js +87 -52
  37. package/dist/test/marker.test.js +1 -1
  38. package/dist/test/model-facing-text.test.js +3 -4
  39. package/dist/test/reset-lifecycle.test.js +52 -12
  40. package/docs/history-sessions.md +26 -2
  41. package/docs/reset-lifecycle.md +14 -13
  42. package/docs/tool-results.md +4 -2
  43. package/package.json +1 -1
  44. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  45. package/plugins/claude/dist/claude/helper.js +425 -122
  46. package/plugins/codex/dist/codex/notesoup.js +423 -123
  47. package/plugins/pi/entries.ts +0 -1
  48. package/plugins/pi/reset/lifecycle.ts +19 -35
  49. package/plugins/pi/runtime.ts +14 -10
  50. package/plugins/pi/text.ts +2 -7
  51. package/src/history/claude.ts +16 -2
  52. package/src/history/codex-transcript.ts +52 -17
  53. package/src/history/codex.ts +5 -5
  54. package/src/history/corpus.ts +19 -2
  55. package/src/history/history.ts +11 -11
  56. package/src/history/local.ts +34 -38
  57. package/src/history/prefilter.ts +86 -0
  58. package/src/history/query.ts +77 -33
  59. package/src/history/summary-cache.ts +119 -0
  60. package/src/tools/history.ts +33 -20
@@ -3,10 +3,12 @@ import { readdir, readFile, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { piHistoryFromJsonl } from "./pi.js";
6
- import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
6
+ import { offlineClaudeHistoryFromJsonl } from "./claude.js";
7
7
  import { readCodexHistory } from "./codex.js";
8
- import { readCodexTranscriptBytes } from "./codex-transcript.js";
8
+ import { createCodexTranscriptReader } from "./codex-transcript.js";
9
+ import { createHistoryPrefilter, historyFileMayMatch, type HistoryPrefilter } from "./prefilter.js";
9
10
  import { sessionIdentity, type HistoryCorpus, type HistorySession } from "./corpus.js";
11
+ import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
10
12
 
11
13
  export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
12
14
  export type LocalHistoryOptions = {
@@ -15,6 +17,8 @@ export type LocalHistoryOptions = {
15
17
  roots?: LocalHistoryRoots;
16
18
  home?: string;
17
19
  env?: NodeJS.ProcessEnv;
20
+ /** Internal hermetic-test seam, not a tool parameter or host setting. */
21
+ summaryCacheRoot?: string;
18
22
  /** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
19
23
  dshSessions?: () => Promise<HistorySession[]>;
20
24
  };
@@ -43,36 +47,7 @@ async function filesAt(root: string, depth: number): Promise<string[]> {
43
47
  return paths;
44
48
  }
45
49
 
46
- const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
47
- copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
48
- does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
49
- not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
50
- FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
51
- the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
52
-
53
- function escapeRegExp(value: string): string {
54
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
55
- }
56
-
57
- /** Only prove misses, not hits. Only \\uXXXX can encode a word character; other JSON escapes are control/quote/slash. */
58
- function mayMatch(text: string, queries: readonly string[], codex: boolean): boolean {
59
- if (codex && text.includes('"history_base"')) return true;
60
- const unescaped = text.includes("\\u")
61
- ? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
62
- : text;
63
- return queries.some((query) => {
64
- const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
65
- return tokens === null || tokens.every((token) => {
66
- const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
67
- return parts.every((part) => {
68
- const literal = new RegExp(escapeRegExp(part), "iu");
69
- return literal.test(unescaped) || (unescaped !== text && literal.test(text)) || literal.test(PRESENTATION);
70
- });
71
- });
72
- });
73
- }
74
-
75
- async function localSessions(harness: "pi" | "claude" | "codex", root: string): Promise<HistorySession[]> {
50
+ async function localSessions(harness: "pi" | "claude" | "codex", root: string, cacheRoot: string, prefilters: WeakMap<readonly string[], HistoryPrefilter>): Promise<HistorySession[]> {
76
51
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
77
52
  const sessions: HistorySession[] = [];
78
53
  for (const path of paths) {
@@ -86,13 +61,31 @@ async function localSessions(harness: "pi" | "claude" | "codex", root: string):
86
61
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
87
62
  sessions.push({
88
63
  harness, id, modifiedAt,
64
+ async loadRepresentative() {
65
+ return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
66
+ if (harness === "codex") {
67
+ const readBytes = createCodexTranscriptReader();
68
+ const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
69
+ await track(source);
70
+ return readBytes(source, remaining);
71
+ });
72
+ return { data: { projection: history.projection }, lineageSources: history.lineageSources };
73
+ }
74
+ const data = await this.load();
75
+ if (!data) throw new Error("Session returned no history");
76
+ return { data };
77
+ });
78
+ },
89
79
  async load(queries) {
90
- if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
91
- const text = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile(path, "utf8");
92
- if (queries?.length && !mayMatch(text, queries, harness === "codex")) return undefined;
80
+ if (queries?.length) {
81
+ let prefilter = prefilters.get(queries);
82
+ if (!prefilter) prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
83
+ if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return undefined;
84
+ }
93
85
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
86
+ const text = await readFile(path, "utf8");
94
87
  if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
95
- const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
88
+ const projection = offlineClaudeHistoryFromJsonl(text, id);
96
89
  const missing = projection.missingAncestors;
97
90
  return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
98
91
  },
@@ -107,17 +100,20 @@ export function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus
107
100
  currentHarness: options.current.harness,
108
101
  async sessions(onlyHarness) {
109
102
  const roots = rootsFor(options);
103
+ const env = options.env ?? process.env;
104
+ const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
110
105
  const discovered: HistorySession[] = [];
106
+ const prefilters = new WeakMap<readonly string[], HistoryPrefilter>();
111
107
  for (const harness of ["pi", "claude", "codex"] as const) {
112
108
  if (onlyHarness !== undefined && onlyHarness !== harness) continue;
113
109
  const root = roots[harness];
114
- if (root != null) discovered.push(...await localSessions(harness, root));
110
+ if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
115
111
  }
116
112
  if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
117
113
  discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
118
114
  const unique = new Map<string, HistorySession>();
119
115
  for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
120
- const current = { ...options.current, modifiedAt: Date.now() };
116
+ const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
121
117
  if (onlyHarness === undefined || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
122
118
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
123
119
  },
@@ -0,0 +1,86 @@
1
+ /** Conservative streaming proof-of-miss. A possible hit still needs the normal strict decoder. */
2
+ import { createReadStream } from "node:fs";
3
+ import { stat } from "node:fs/promises";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import * as zlib from "node:zlib";
7
+ import { CODEX_TRANSCRIPT_MAX_BYTES } from "./codex-transcript.js";
8
+
9
+ const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
11
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
12
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
13
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
14
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
15
+ const HISTORY_BASE = '"history_base"';
16
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
17
+
18
+ /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
19
+ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter {
20
+ let overlap = HISTORY_BASE.length;
21
+ const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
22
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
23
+ return parts.map((part) => {
24
+ overlap = Math.max(overlap, part.length);
25
+ return new RegExp(part, "iu");
26
+ }).filter((literal) => !literal.test(PRESENTATION));
27
+ }));
28
+ // No safe tokens (or generated text alone) cannot prove a miss.
29
+ const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
30
+ return async (chunks, codex = false) => {
31
+ const decoder = new StringDecoder("utf8");
32
+ const seen = alternatives.map((tokens) => tokens.map(() => false));
33
+ let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
34
+ // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
35
+ const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
36
+ const scan = (chunk: string, final = false) => {
37
+ const raw = rawTail + chunk, source = pending + chunk;
38
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
39
+ pending = "";
40
+ const decoded = needsNormalization ? source.replace(escapes, (match, hex: string | undefined, offset: number) => {
41
+ if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
42
+ // Tokens cannot include backslashes: an unresolved run needs only one separator,
43
+ // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
44
+ const literal = hex === undefined ? "\\" : `\\u${hex}`;
45
+ if (!final && offset + match.length === source.length) { pending = literal; return ""; }
46
+ return literal;
47
+ }) : chunk;
48
+ const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
49
+ if (codex && raw.includes(HISTORY_BASE)) possible = true;
50
+ else possible = alternatives.some((tokens, index) => {
51
+ const bits = seen[index]!;
52
+ for (let token = 0; token < tokens.length; token++) bits[token] ||= tokens[token]!.test(raw) || (normalized !== raw && tokens[token]!.test(normalized));
53
+ return bits.every(Boolean);
54
+ });
55
+ rawTail = raw.slice(-overlap);
56
+ normalizedTail = normalized.slice(-overlap);
57
+ };
58
+ for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
59
+ if (!possible) scan(decoder.end(), true);
60
+ return possible;
61
+ };
62
+ }
63
+
64
+ /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
65
+ export async function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity): Promise<boolean> {
66
+ if (codex) {
67
+ const info = await stat(path);
68
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
69
+ }
70
+ // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
71
+ const compressed = codex && path.endsWith(".jsonl.zst");
72
+ if (compressed && typeof zlib.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
73
+ const input = createReadStream(path);
74
+ const consume = async (chunks: AsyncIterable<Buffer>) => {
75
+ let size = 0;
76
+ async function* bounded() {
77
+ for await (const chunk of chunks) {
78
+ size += chunk.length;
79
+ if (size > maxBytes) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
80
+ yield chunk;
81
+ }
82
+ }
83
+ return prefilter(bounded(), codex);
84
+ };
85
+ return compressed ? pipeline(input, zlib.createZstdDecompress(), consume) : pipeline(input, consume);
86
+ }
@@ -7,7 +7,13 @@ import { InvalidQueryError, searchQueries } from "../tools/schema.js";
7
7
  import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
8
8
 
9
9
  type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
- type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean };
10
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean; discarded?: boolean; from?: HistoryOrder };
11
+ const multiPages = new WeakSet<HistoryPage>();
12
+ export function isMultiPage(page: HistoryPage): boolean { return multiPages.has(page); }
13
+ export function markMultiPage(page: HistoryPage): HistoryPage {
14
+ multiPages.add(page);
15
+ return page;
16
+ }
11
17
 
12
18
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
13
19
  export type HistoryOrder = "newest" | "oldest";
@@ -50,21 +56,12 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
50
56
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
51
57
  }
52
58
 
53
- export const HistoryOlderSchema = Type.Object({
54
- session: Type.Optional(Type.String()),
55
- before_seq: Type.Integer({ minimum: 1 }),
56
- }, { additionalProperties: false });
57
- export const HistoryNewerSchema = Type.Object({
58
- session: Type.Optional(Type.String()),
59
- after_seq: Type.Integer({ minimum: 1 }),
60
- from: Type.Literal("oldest"),
61
- }, { additionalProperties: false });
62
-
63
59
  export const HistoryPageSchema = Type.Object({
64
60
  notice: Type.Optional(Type.String()),
65
- items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
66
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Args to merge into `history_list` for older events." }),
67
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Args to merge into `history_list` for newer events." }),
61
+ items: Type.Array(HistoryPageItemSchema),
62
+ folded_after: Type.Optional(HistoryFoldedRowSchema),
63
+ has_older: Type.Boolean(),
64
+ has_newer: Type.Boolean(),
68
65
  }, { additionalProperties: false });
69
66
 
70
67
  /** One whole page payload, before it becomes an outcome. */
@@ -97,7 +94,7 @@ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow |
97
94
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
98
95
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
99
96
  const tools = Object.fromEntries(entries);
100
- return { ...(session === undefined ? {} : { session }), folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
97
+ return { ...(session === undefined ? {} : { session }), first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
101
98
  }
102
99
 
103
100
  /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
@@ -123,19 +120,19 @@ function prepareSelection(projection: HistoryProjection, params: HistorySelectio
123
120
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
124
121
  function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
125
122
  const { candidates, tail } = prepared;
126
- const identity = prepared.session === undefined ? {} : { session: prepared.session };
127
123
  const items: HistoryPage["items"] = [];
128
124
  for (let index = start; index < end; index++) {
129
125
  const candidate = candidates[index]!;
130
- if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
131
- items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
126
+ const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
127
+ items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
132
128
  }
133
- if (end === candidates.length && tail) items.push(tail);
134
- return {
129
+ const page = {
135
130
  items,
136
- page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start]!.event.seq } : null,
137
- page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
131
+ ...(end === candidates.length && tail ? { folded_after: tail } : {}),
132
+ has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
133
+ has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
138
134
  };
135
+ return prepared.multi ? markMultiPage(page) : page;
139
136
  }
140
137
 
141
138
  /**
@@ -176,22 +173,69 @@ export function sessionRepresentative(projection: HistoryProjection, scoped: His
176
173
  ?? events.at(-1);
177
174
  }
178
175
 
179
- /** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
180
- export function selectCorpusPage(sessions: { session: string; projection: HistoryProjection }[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
181
- const candidates = sessions.flatMap(({ session, projection }): Candidate[] => {
182
- if (scoped.query !== undefined) return prepareSelection(projection, { ...scoped, session }).candidates;
183
- const event = sessionRepresentative(projection, scoped);
184
- return event === undefined ? [] : [{ session, event }];
185
- });
186
- const time = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
187
- candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq));
188
- return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
176
+ const eventTime = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
177
+ const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event) - eventTime(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
178
+
179
+ /** Keep only the requested end of the globally ordered selection while sessions are released. */
180
+ export class CorpusCollector {
181
+ private readonly candidates: Candidate[] = [];
182
+ private readonly limit: number;
183
+ private discarded = false;
184
+ constructor(private readonly scoped: HistorySelection) {
185
+ this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
186
+ }
187
+
188
+ private admit(candidate: Candidate): void {
189
+ // Upper bound preserves the stable ordering of equal candidates.
190
+ let low = 0, high = this.candidates.length;
191
+ while (low < high) {
192
+ const mid = (low + high) >>> 1;
193
+ if (compareCorpus(this.candidates[mid]!, candidate) <= 0) low = mid + 1;
194
+ else high = mid;
195
+ }
196
+ if (this.candidates.length === this.limit) {
197
+ this.discarded = true;
198
+ if (this.scoped.from === "oldest") {
199
+ if (low === this.limit) return;
200
+ this.candidates.pop();
201
+ } else {
202
+ if (low === 0) return;
203
+ this.candidates.shift();
204
+ low--;
205
+ }
206
+ }
207
+ this.candidates.splice(low, 0, candidate);
208
+ }
209
+
210
+ /** Admit an already selected strict overview event without selecting it a second time. */
211
+ addRepresentative(session: string, event: HistoryEvent | undefined): boolean {
212
+ if (!event) return false;
213
+ this.admit({ session, event });
214
+ return true;
215
+ }
216
+
217
+ /** Returns whether this session contributes an overview representative. */
218
+ add(session: string, projection: HistoryProjection): boolean {
219
+ if (this.scoped.query === undefined) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
220
+ for (const event of filteredItems(projection, this.scoped, false)) {
221
+ const document = eventDocument(event);
222
+ if ((event.role === "user" || event.role === "assistant") && document === "") continue;
223
+ const matchOffset = earliestMatchOffsetChars(document, this.scoped.query as string[]);
224
+ if (matchOffset >= 0) this.admit({ session, event, matchOffset });
225
+ }
226
+ return true;
227
+ }
228
+
229
+ page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited = false): Outcome<HistoryPage> {
230
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
231
+ }
189
232
  }
190
233
 
191
234
  function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
192
235
  const { candidates } = prepared;
193
236
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
194
- const newest = scoped.from !== "oldest";
237
+ const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
238
+ const newest = from === "newest";
195
239
  let start = newest ? candidates.length : 0;
196
240
  let end = start;
197
241
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -0,0 +1,119 @@
1
+ /** Strict offline overview summaries, never projections or search indexes. Cache failures are misses. */
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { mkdir, open, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { Type, type Static } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
9
+ import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
10
+ import { sessionRepresentative } from "./query.js";
11
+ import { validateCodexLineageSources, type CodexLineageSource } from "./codex-transcript.js";
12
+
13
+ // Bump whenever strict decoding, representative selection, or cached event presentation changes.
14
+ const VERSION = "strict-representative-v1";
15
+ const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
16
+ const FingerprintSchema = Type.Object({
17
+ path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
18
+ }, { additionalProperties: false });
19
+ type Fingerprint = Static<typeof FingerprintSchema>;
20
+ const EventSchema = Type.Object({
21
+ seq: Type.Integer({ minimum: 1 }), windowId: Type.String(), role: HistoryRoleSchema,
22
+ createdAt: Type.Optional(Type.String()), text: Type.String(),
23
+ execution: Type.Optional(Type.Object({
24
+ name: Type.String(), status: ToolCallStatusSchema,
25
+ arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
26
+ outputTruncated: Type.Optional(Type.Boolean()), fullOutputPath: Type.Optional(Type.String()),
27
+ nestedCalls: Type.Optional(Type.Object({ complete: Type.Boolean(), calls: Type.Array(Type.Object({
28
+ id: Type.String(), name: Type.String(), status: ToolCallStatusSchema,
29
+ arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())), argumentsBytes: Type.Optional(Type.Number()),
30
+ durationMs: Type.Optional(Type.Number()), error: Type.Optional(Type.String()),
31
+ }, { additionalProperties: false })) }, { additionalProperties: false })),
32
+ }, { additionalProperties: false })),
33
+ }, { additionalProperties: false });
34
+ const EntrySchema = Type.Object({
35
+ version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
36
+ event: Type.Union([EventSchema, Type.Null()]), notice: Type.Optional(Type.String()),
37
+ fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
38
+ lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
39
+ }, { additionalProperties: false });
40
+
41
+ /** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
42
+ export function historySummaryCacheRoot(home = homedir(), env = process.env, platform = process.platform): string {
43
+ return platform === "darwin" ? join(home, "Library/Caches/notesoup/history") : join(env.XDG_CACHE_HOME || join(home, ".cache"), "notesoup/history");
44
+ }
45
+
46
+ async function fingerprint(path: string): Promise<Fingerprint> {
47
+ const info = await stat(path, { bigint: true });
48
+ if (!info.isFile()) throw new Error("Not a regular transcript file");
49
+ return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
50
+ }
51
+ async function unchanged(sources: Fingerprint[]): Promise<boolean> {
52
+ for (const source of sources) if (JSON.stringify(await fingerprint(source.path)) !== JSON.stringify(source)) return false;
53
+ return true;
54
+ }
55
+
56
+ /** One fingerprint per actual decoder read, in root-to-ancestor order; no untracked witnesses. */
57
+ function completeDependencies(path: string, harness: HistorySession["harness"], sources: Fingerprint[], lineage: CodexLineageSource[]): boolean {
58
+ if (harness !== "codex" && lineage.length !== 0) return false;
59
+ const expected = [path, ...lineage.map((source) => source.path)];
60
+ return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
61
+ }
62
+
63
+ async function readEntry(path: string): Promise<unknown> {
64
+ const file = await open(path, "r");
65
+ try {
66
+ const info = await file.stat();
67
+ if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return undefined;
68
+ const buffer = Buffer.alloc(info.size + 1);
69
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
70
+ if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return undefined;
71
+ return JSON.parse(buffer.toString("utf8", 0, bytesRead));
72
+ } finally { await file.close(); }
73
+ }
74
+
75
+ export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{ data: HistorySessionData; lineageSources?: CodexLineageSource[] }>;
76
+
77
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
78
+ export async function cachedSessionRepresentative(
79
+ session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
80
+ ): Promise<HistorySessionRepresentative> {
81
+ let canonical: string | undefined, cachePath: string | undefined;
82
+ const identity = sessionIdentity(session);
83
+ try {
84
+ canonical = await realpath(transcriptPath);
85
+ cachePath = join(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
86
+ const entry = await readEntry(cachePath);
87
+ if (Check(EntrySchema, entry) && entry.path === canonical && entry.session === identity
88
+ && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
89
+ && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
90
+ && await realpath(transcriptPath) === canonical) {
91
+ return { event: entry.event === null ? undefined : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
92
+ }
93
+ } catch { /* Absent/corrupt/unwritable cache or changed source: strict load below. */ }
94
+
95
+ const fingerprints = new Map<string, Fingerprint>();
96
+ let stable = canonical !== undefined;
97
+ const track = async (path: string) => {
98
+ try { if (!fingerprints.has(path)) fingerprints.set(path, await fingerprint(path)); }
99
+ catch { stable = false; }
100
+ };
101
+ if (canonical) await track(canonical);
102
+ const { data, lineageSources = [] } = await load(track);
103
+ const event = sessionRepresentative(data.projection, {});
104
+ const result = { event, notice: data.notice };
105
+ try {
106
+ const sources = [...fingerprints.values()];
107
+ if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
108
+ || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical) return result;
109
+ const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
110
+ if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
111
+ await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
112
+ const temporary = `${cachePath}.${randomUUID()}.tmp`;
113
+ try {
114
+ await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
115
+ await rename(temporary, cachePath);
116
+ } finally { await unlink(temporary).catch(() => {}); }
117
+ } catch { /* The cache cannot turn readable history into a refusal. */ }
118
+ return result;
119
+ }
@@ -3,8 +3,8 @@ import { Type, type Static } from "typebox";
3
3
  import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
- import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage, sessionRepresentative, type HistoryPage } from "../history/query.js";
7
- import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
6
+ import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage, type HistoryPage } from "../history/query.js";
7
+ import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
8
8
  import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
9
9
 
10
10
  /** One read: identity, tool summary and a flat document slice. */
@@ -47,25 +47,31 @@ function renderPageItem(item: HistoryPageItem): string {
47
47
  function renderFoldedRow(row: HistoryFoldedRow): string {
48
48
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
49
49
  const identity = row.session === undefined ? {} : { session: row.session };
50
- const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
50
+ const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
51
51
  return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
52
52
  }
53
53
 
54
54
  function renderPage(page: HistoryPage): string {
55
55
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
56
- if (page.items.length === 0) return `${page.notice ?? ""}No events match these filters.`;
57
- const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
56
+ if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
57
+ const body = [...page.items.flatMap((item) => [...(item.folded_before ? [renderFoldedRow(item.folded_before)] : []), renderPageItem(item)]), ...(page.folded_after ? [renderFoldedRow(page.folded_after)] : [])].join("\n\n");
58
+ if (isMultiPage(page)) {
59
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
60
+ return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
61
+ }
62
+ const first = page.items[0]!;
63
+ const last = page.items.at(-1)!;
64
+
58
65
  const cursors = [
59
- page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
60
- page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
66
+ page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
67
+ page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
61
68
  ].filter((line) => line !== "");
62
69
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
63
70
  }
64
71
 
65
72
  function renderRead(data: HistoryReadData): string {
66
73
  const tool = toolHeader(data);
67
- const afterSeq = data.seq - 10;
68
- const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
74
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after_seq: Math.max(0, data.seq - 10), before_seq: data.seq + 10 })})`;
69
75
  return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
70
76
  }
71
77
 
@@ -84,11 +90,11 @@ export const historyListParameters = Type.Object({
84
90
  query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
85
91
  roles: historyRoles(),
86
92
  before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
87
- after_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
93
+ after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
88
94
  since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
89
95
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
90
- from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
91
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
96
+ from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
97
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
92
98
  max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
93
99
  }, { additionalProperties: false });
94
100
 
@@ -113,19 +119,26 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
113
119
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
114
120
  const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
115
121
  if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
116
- const loaded = [];
122
+ const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
123
+ const collector = new CorpusCollector(scoped.data);
124
+ let qualifying = 0;
117
125
  const notices: string[] = [];
118
- for (const session of sessions) {
119
- const result = await loadHistorySession(session, queries);
126
+ let unvisited = false;
127
+ for (const [index, session] of sessions.entries()) {
128
+ const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
120
129
  if (!result.ok || !result.data) continue;
121
- if (!queries && !sessionRepresentative(result.data.projection, scoped.data)) continue;
122
- loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
130
+ const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
131
+ if (!added) continue;
132
+ qualifying++;
123
133
  if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
124
- if (!queries && loaded.length >= Math.max(1, params.limit ?? 20)) break;
134
+ if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
135
+ unvisited = index + 1 < sessions.length;
136
+ break;
137
+ }
125
138
  }
126
139
  const notice = notices.length ? { notice: notices.join("") } : {};
127
- const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
128
- return result.ok ? success({ ...result.data, ...notice }) : result;
140
+ const result = collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited);
141
+ return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
129
142
  }
130
143
  const target = await resolveSession(corpus, selector.data);
131
144
  if (!target.ok) return target;