notesoup 0.56.0 → 0.57.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 (59) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/marker.d.ts +4 -2
  3. package/dist/plugins/pi/marker.js +18 -8
  4. package/dist/plugins/pi/reset/lifecycle.js +6 -0
  5. package/dist/plugins/pi/runtime.js +8 -8
  6. package/dist/plugins/pi/text.js +1 -1
  7. package/dist/src/history/claude.d.ts +2 -0
  8. package/dist/src/history/claude.js +13 -2
  9. package/dist/src/history/codex-transcript.d.ts +15 -3
  10. package/dist/src/history/codex-transcript.js +57 -21
  11. package/dist/src/history/codex.d.ts +4 -2
  12. package/dist/src/history/codex.js +3 -3
  13. package/dist/src/history/corpus.d.ts +8 -1
  14. package/dist/src/history/corpus.js +17 -1
  15. package/dist/src/history/history.d.ts +16 -10
  16. package/dist/src/history/history.js +9 -9
  17. package/dist/src/history/local.d.ts +2 -0
  18. package/dist/src/history/local.js +35 -38
  19. package/dist/src/history/prefilter.d.ts +5 -0
  20. package/dist/src/history/prefilter.js +95 -0
  21. package/dist/src/history/query.d.ts +29 -27
  22. package/dist/src/history/query.js +82 -34
  23. package/dist/src/history/summary-cache.d.ts +10 -0
  24. package/dist/src/history/summary-cache.js +129 -0
  25. package/dist/src/tools/history.js +31 -20
  26. package/dist/test/agent-loop.test.js +62 -27
  27. package/dist/test/codex-history.test.js +90 -4
  28. package/dist/test/codex-plugin.test.js +6 -2
  29. package/dist/test/history-corpus.test.js +221 -33
  30. package/dist/test/history-prefilter.test.d.ts +1 -0
  31. package/dist/test/history-prefilter.test.js +174 -0
  32. package/dist/test/history-summary-cache.test.d.ts +1 -0
  33. package/dist/test/history-summary-cache.test.js +297 -0
  34. package/dist/test/history.integration.test.js +87 -52
  35. package/dist/test/marker.test.js +46 -15
  36. package/dist/test/model-facing-text.test.js +1 -1
  37. package/dist/test/reset-lifecycle.test.js +4 -6
  38. package/docs/architecture.md +1 -1
  39. package/docs/history-sessions.md +26 -2
  40. package/docs/reset-lifecycle.md +4 -4
  41. package/docs/tool-results.md +4 -2
  42. package/package.json +1 -1
  43. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  44. package/plugins/claude/dist/claude/helper.js +425 -122
  45. package/plugins/codex/dist/codex/notesoup.js +423 -123
  46. package/plugins/pi/marker.ts +18 -12
  47. package/plugins/pi/reset/lifecycle.ts +5 -0
  48. package/plugins/pi/runtime.ts +8 -8
  49. package/plugins/pi/text.ts +1 -1
  50. package/src/history/claude.ts +16 -2
  51. package/src/history/codex-transcript.ts +52 -17
  52. package/src/history/codex.ts +5 -5
  53. package/src/history/corpus.ts +19 -2
  54. package/src/history/history.ts +11 -11
  55. package/src/history/local.ts +34 -38
  56. package/src/history/prefilter.ts +86 -0
  57. package/src/history/query.ts +77 -33
  58. package/src/history/summary-cache.ts +119 -0
  59. 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 } from "./prefilter.js";
9
10
  import { sessionIdentity } from "./corpus.js";
11
+ import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
10
12
  function rootsFor(options) {
11
13
  const env = options.env ?? process.env;
12
14
  const home = options.home ?? env.HOME ?? homedir();
@@ -37,34 +39,7 @@ async function filesAt(root, depth) {
37
39
  }
38
40
  return paths;
39
41
  }
40
- const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
41
- copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
42
- does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
43
- not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
44
- FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
45
- the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
46
- function escapeRegExp(value) {
47
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
- }
49
- /** Only prove misses, not hits. Only \\uXXXX can encode a word character; other JSON escapes are control/quote/slash. */
50
- function mayMatch(text, queries, codex) {
51
- if (codex && text.includes('"history_base"'))
52
- return true;
53
- const unescaped = text.includes("\\u")
54
- ? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)))
55
- : text;
56
- return queries.some((query) => {
57
- const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
58
- return tokens === null || tokens.every((token) => {
59
- const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
60
- return parts.every((part) => {
61
- const literal = new RegExp(escapeRegExp(part), "iu");
62
- return literal.test(unescaped) || (unescaped !== text && literal.test(text)) || literal.test(PRESENTATION);
63
- });
64
- });
65
- });
66
- }
67
- async function localSessions(harness, root) {
42
+ async function localSessions(harness, root, cacheRoot, prefilters) {
68
43
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
69
44
  const sessions = [];
70
45
  for (const path of paths) {
@@ -85,17 +60,36 @@ async function localSessions(harness, root) {
85
60
  }
86
61
  sessions.push({
87
62
  harness, id, modifiedAt,
63
+ async loadRepresentative() {
64
+ return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
65
+ if (harness === "codex") {
66
+ const readBytes = createCodexTranscriptReader();
67
+ const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
68
+ await track(source);
69
+ return readBytes(source, remaining);
70
+ });
71
+ return { data: { projection: history.projection }, lineageSources: history.lineageSources };
72
+ }
73
+ const data = await this.load();
74
+ if (!data)
75
+ throw new Error("Session returned no history");
76
+ return { data };
77
+ });
78
+ },
88
79
  async load(queries) {
89
- if (harness === "codex" && !queries?.length)
90
- 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"))
93
- return undefined;
80
+ if (queries?.length) {
81
+ let prefilter = prefilters.get(queries);
82
+ if (!prefilter)
83
+ prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
84
+ if (!await historyFileMayMatch(path, prefilter, harness === "codex"))
85
+ return undefined;
86
+ }
94
87
  if (harness === "codex")
95
88
  return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
89
+ const text = await readFile(path, "utf8");
96
90
  if (harness === "pi")
97
91
  return { projection: piHistoryFromJsonl(text, id) };
98
- const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
92
+ const projection = offlineClaudeHistoryFromJsonl(text, id);
99
93
  const missing = projection.missingAncestors;
100
94
  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` }) };
101
95
  },
@@ -109,13 +103,16 @@ export function localHistoryCorpus(options) {
109
103
  currentHarness: options.current.harness,
110
104
  async sessions(onlyHarness) {
111
105
  const roots = rootsFor(options);
106
+ const env = options.env ?? process.env;
107
+ const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
112
108
  const discovered = [];
109
+ const prefilters = new WeakMap();
113
110
  for (const harness of ["pi", "claude", "codex"]) {
114
111
  if (onlyHarness !== undefined && onlyHarness !== harness)
115
112
  continue;
116
113
  const root = roots[harness];
117
114
  if (root != null)
118
- discovered.push(...await localSessions(harness, root));
115
+ discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
119
116
  }
120
117
  if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
121
118
  discovered.push(...await options.dshSessions());
@@ -124,7 +121,7 @@ export function localHistoryCorpus(options) {
124
121
  for (const session of discovered)
125
122
  if (!unique.has(sessionIdentity(session)))
126
123
  unique.set(sessionIdentity(session), session);
127
- const current = { ...options.current, modifiedAt: Date.now() };
124
+ const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
128
125
  if (onlyHarness === undefined || onlyHarness === current.harness)
129
126
  unique.set(sessionIdentity(current), current);
130
127
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
@@ -0,0 +1,5 @@
1
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
2
+ /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
3
+ export declare function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter;
4
+ /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
5
+ export declare function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex?: boolean, maxBytes?: number): Promise<boolean>;
@@ -0,0 +1,95 @@
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
+ const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
9
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
10
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
11
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
12
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
13
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
14
+ const HISTORY_BASE = '"history_base"';
15
+ /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
16
+ export function createHistoryPrefilter(queries) {
17
+ let overlap = HISTORY_BASE.length;
18
+ const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
19
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
20
+ return parts.map((part) => {
21
+ overlap = Math.max(overlap, part.length);
22
+ return new RegExp(part, "iu");
23
+ }).filter((literal) => !literal.test(PRESENTATION));
24
+ }));
25
+ // No safe tokens (or generated text alone) cannot prove a miss.
26
+ const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
27
+ return async (chunks, codex = false) => {
28
+ const decoder = new StringDecoder("utf8");
29
+ const seen = alternatives.map((tokens) => tokens.map(() => false));
30
+ let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
31
+ // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
32
+ const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
33
+ const scan = (chunk, final = false) => {
34
+ const raw = rawTail + chunk, source = pending + chunk;
35
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
36
+ pending = "";
37
+ const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
38
+ if (hex?.length === 4)
39
+ return String.fromCharCode(Number.parseInt(hex, 16));
40
+ // Tokens cannot include backslashes: an unresolved run needs only one separator,
41
+ // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
42
+ const literal = hex === undefined ? "\\" : `\\u${hex}`;
43
+ if (!final && offset + match.length === source.length) {
44
+ pending = literal;
45
+ return "";
46
+ }
47
+ return literal;
48
+ }) : chunk;
49
+ const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
50
+ if (codex && raw.includes(HISTORY_BASE))
51
+ possible = true;
52
+ else
53
+ possible = alternatives.some((tokens, index) => {
54
+ const bits = seen[index];
55
+ for (let token = 0; token < tokens.length; token++)
56
+ bits[token] ||= tokens[token].test(raw) || (normalized !== raw && tokens[token].test(normalized));
57
+ return bits.every(Boolean);
58
+ });
59
+ rawTail = raw.slice(-overlap);
60
+ normalizedTail = normalized.slice(-overlap);
61
+ };
62
+ for await (const chunk of chunks)
63
+ if (!possible)
64
+ scan(decoder.write(chunk));
65
+ if (!possible)
66
+ scan(decoder.end(), true);
67
+ return possible;
68
+ };
69
+ }
70
+ /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
71
+ export async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
72
+ if (codex) {
73
+ const info = await stat(path);
74
+ if (!info.isFile() || info.size > maxBytes)
75
+ throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
76
+ }
77
+ // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
78
+ const compressed = codex && path.endsWith(".jsonl.zst");
79
+ if (compressed && typeof zlib.createZstdDecompress !== "function")
80
+ throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
81
+ const input = createReadStream(path);
82
+ const consume = async (chunks) => {
83
+ let size = 0;
84
+ async function* bounded() {
85
+ for await (const chunk of chunks) {
86
+ size += chunk.length;
87
+ if (size > maxBytes)
88
+ throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
89
+ yield chunk;
90
+ }
91
+ }
92
+ return prefilter(bounded(), codex);
93
+ };
94
+ return compressed ? pipeline(input, zlib.createZstdDecompress(), consume) : pipeline(input, consume);
95
+ }
@@ -2,6 +2,8 @@
2
2
  import { Type, type Static } from "typebox";
3
3
  import { type Outcome } from "../tools/result.js";
4
4
  import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
5
+ export declare function isMultiPage(page: HistoryPage): boolean;
6
+ export declare function markMultiPage(page: HistoryPage): HistoryPage;
5
7
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
6
8
  export type HistoryOrder = "newest" | "oldest";
7
9
  /**
@@ -18,18 +20,9 @@ export type HistorySelection = HistoryFilter & {
18
20
  until?: string;
19
21
  max_chars_per_item?: number;
20
22
  };
21
- export declare const HistoryOlderSchema: Type.TObject<{
22
- session: Type.TOptional<Type.TString>;
23
- before_seq: Type.TInteger;
24
- }>;
25
- export declare const HistoryNewerSchema: Type.TObject<{
26
- session: Type.TOptional<Type.TString>;
27
- after_seq: Type.TInteger;
28
- from: Type.TLiteral<"oldest">;
29
- }>;
30
23
  export declare const HistoryPageSchema: Type.TObject<{
31
24
  notice: Type.TOptional<Type.TString>;
32
- items: Type.TArray<Type.TUnion<[Type.TObject<{
25
+ items: Type.TArray<Type.TObject<{
33
26
  content: Type.TString;
34
27
  truncated: Type.TBoolean;
35
28
  offset_chars: Type.TOptional<Type.TInteger>;
@@ -38,26 +31,26 @@ export declare const HistoryPageSchema: Type.TObject<{
38
31
  output_truncated: Type.TOptional<Type.TLiteral<true>>;
39
32
  full_output_path: Type.TOptional<Type.TString>;
40
33
  session: Type.TOptional<Type.TString>;
34
+ folded_before: Type.TOptional<Type.TObject<{
35
+ session: Type.TOptional<Type.TString>;
36
+ first_seq: Type.TInteger;
37
+ last_seq: Type.TInteger;
38
+ count: Type.TInteger;
39
+ tools: Type.TRecord<"^.*$", Type.TInteger>;
40
+ }>>;
41
41
  seq: Type.TInteger;
42
42
  role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
43
43
  created_at: Type.TUnion<[Type.TString, Type.TNull]>;
44
- }>, Type.TObject<{
44
+ }>>;
45
+ folded_after: Type.TOptional<Type.TObject<{
45
46
  session: Type.TOptional<Type.TString>;
46
- folded: Type.TLiteral<true>;
47
47
  first_seq: Type.TInteger;
48
48
  last_seq: Type.TInteger;
49
49
  count: Type.TInteger;
50
50
  tools: Type.TRecord<"^.*$", Type.TInteger>;
51
- }>]>>;
52
- page_older: Type.TUnion<[Type.TObject<{
53
- session: Type.TOptional<Type.TString>;
54
- before_seq: Type.TInteger;
55
- }>, Type.TNull]>;
56
- page_newer: Type.TUnion<[Type.TObject<{
57
- session: Type.TOptional<Type.TString>;
58
- after_seq: Type.TInteger;
59
- from: Type.TLiteral<"oldest">;
60
- }>, Type.TNull]>;
51
+ }>>;
52
+ has_older: Type.TBoolean;
53
+ has_newer: Type.TBoolean;
61
54
  }>;
62
55
  /** One whole page payload, before it becomes an outcome. */
63
56
  export type HistoryPage = Static<typeof HistoryPageSchema>;
@@ -66,8 +59,17 @@ export declare function selectPage(projection: HistoryProjection, params: Histor
66
59
  export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
67
60
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
68
61
  export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
69
- /** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
70
- export declare function selectCorpusPage(sessions: {
71
- session: string;
72
- projection: HistoryProjection;
73
- }[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
62
+ /** Keep only the requested end of the globally ordered selection while sessions are released. */
63
+ export declare class CorpusCollector {
64
+ private readonly scoped;
65
+ private readonly candidates;
66
+ private readonly limit;
67
+ private discarded;
68
+ constructor(scoped: HistorySelection);
69
+ private admit;
70
+ /** Admit an already selected strict overview event without selecting it a second time. */
71
+ addRepresentative(session: string, event: HistoryEvent | undefined): boolean;
72
+ /** Returns whether this session contributes an overview representative. */
73
+ add(session: string, projection: HistoryProjection): boolean;
74
+ page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean): Outcome<HistoryPage>;
75
+ }
@@ -5,6 +5,12 @@ import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
5
  import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
7
7
  import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
8
+ const multiPages = new WeakSet();
9
+ export function isMultiPage(page) { return multiPages.has(page); }
10
+ export function markMultiPage(page) {
11
+ multiPages.add(page);
12
+ return page;
13
+ }
8
14
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
9
15
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
10
16
  /** Epoch ms for one optional time param, or a refusal naming it. */
@@ -28,20 +34,12 @@ function resolveTimeBounds(params) {
28
34
  }
29
35
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
30
36
  }
31
- export const HistoryOlderSchema = Type.Object({
32
- session: Type.Optional(Type.String()),
33
- before_seq: Type.Integer({ minimum: 1 }),
34
- }, { additionalProperties: false });
35
- export const HistoryNewerSchema = Type.Object({
36
- session: Type.Optional(Type.String()),
37
- after_seq: Type.Integer({ minimum: 1 }),
38
- from: Type.Literal("oldest"),
39
- }, { additionalProperties: false });
40
37
  export const HistoryPageSchema = Type.Object({
41
38
  notice: Type.Optional(Type.String()),
42
- items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
43
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Args to merge into `history_list` for older events." }),
44
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Args to merge into `history_list` for newer events." }),
39
+ items: Type.Array(HistoryPageItemSchema),
40
+ folded_after: Type.Optional(HistoryFoldedRowSchema),
41
+ has_older: Type.Boolean(),
42
+ has_newer: Type.Boolean(),
45
43
  }, { additionalProperties: false });
46
44
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
47
45
  function truncateHistoryItem(item, fits) {
@@ -74,7 +72,7 @@ function foldedRun(events, session) {
74
72
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
75
73
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
76
74
  const tools = Object.fromEntries(entries);
77
- return { ...(session === undefined ? {} : { session }), folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
75
+ return { ...(session === undefined ? {} : { session }), first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
78
76
  }
79
77
  /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
80
78
  function prepareSelection(projection, params) {
@@ -100,21 +98,19 @@ function prepareSelection(projection, params) {
100
98
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
101
99
  function pageData(prepared, start, end, maxChars, preview) {
102
100
  const { candidates, tail } = prepared;
103
- const identity = prepared.session === undefined ? {} : { session: prepared.session };
104
101
  const items = [];
105
102
  for (let index = start; index < end; index++) {
106
103
  const candidate = candidates[index];
107
- if (candidate.before && (index > start || start === 0))
108
- items.push(candidate.before);
109
- items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
104
+ const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
105
+ items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
110
106
  }
111
- if (end === candidates.length && tail)
112
- items.push(tail);
113
- return {
107
+ const page = {
114
108
  items,
115
- page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start].event.seq } : null,
116
- page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1].event.seq, from: "oldest" } : null,
109
+ ...(end === candidates.length && tail ? { folded_after: tail } : {}),
110
+ has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
111
+ has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
117
112
  };
113
+ return prepared.multi ? markMultiPage(page) : page;
118
114
  }
119
115
  /**
120
116
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
@@ -155,22 +151,74 @@ export function sessionRepresentative(projection, scoped) {
155
151
  ?? events.filter((event) => event.role === "assistant").at(-1)
156
152
  ?? events.at(-1);
157
153
  }
158
- /** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
159
- export function selectCorpusPage(sessions, scoped, fits, maxChars) {
160
- const candidates = sessions.flatMap(({ session, projection }) => {
161
- if (scoped.query !== undefined)
162
- return prepareSelection(projection, { ...scoped, session }).candidates;
163
- const event = sessionRepresentative(projection, scoped);
164
- return event === undefined ? [] : [{ session, event }];
165
- });
166
- const time = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
167
- candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq));
168
- return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
154
+ const eventTime = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
155
+ const compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
156
+ /** Keep only the requested end of the globally ordered selection while sessions are released. */
157
+ export class CorpusCollector {
158
+ scoped;
159
+ candidates = [];
160
+ limit;
161
+ discarded = false;
162
+ constructor(scoped) {
163
+ this.scoped = scoped;
164
+ this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
165
+ }
166
+ admit(candidate) {
167
+ // Upper bound preserves the stable ordering of equal candidates.
168
+ let low = 0, high = this.candidates.length;
169
+ while (low < high) {
170
+ const mid = (low + high) >>> 1;
171
+ if (compareCorpus(this.candidates[mid], candidate) <= 0)
172
+ low = mid + 1;
173
+ else
174
+ high = mid;
175
+ }
176
+ if (this.candidates.length === this.limit) {
177
+ this.discarded = true;
178
+ if (this.scoped.from === "oldest") {
179
+ if (low === this.limit)
180
+ return;
181
+ this.candidates.pop();
182
+ }
183
+ else {
184
+ if (low === 0)
185
+ return;
186
+ this.candidates.shift();
187
+ low--;
188
+ }
189
+ }
190
+ this.candidates.splice(low, 0, candidate);
191
+ }
192
+ /** Admit an already selected strict overview event without selecting it a second time. */
193
+ addRepresentative(session, event) {
194
+ if (!event)
195
+ return false;
196
+ this.admit({ session, event });
197
+ return true;
198
+ }
199
+ /** Returns whether this session contributes an overview representative. */
200
+ add(session, projection) {
201
+ if (this.scoped.query === undefined)
202
+ return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
203
+ for (const event of filteredItems(projection, this.scoped, false)) {
204
+ const document = eventDocument(event);
205
+ if ((event.role === "user" || event.role === "assistant") && document === "")
206
+ continue;
207
+ const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
208
+ if (matchOffset >= 0)
209
+ this.admit({ session, event, matchOffset });
210
+ }
211
+ return true;
212
+ }
213
+ page(fits, maxChars, unvisited = false) {
214
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
215
+ }
169
216
  }
170
217
  function selectPrepared(prepared, scoped, fits, maxChars) {
171
218
  const { candidates } = prepared;
172
219
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
173
- const newest = scoped.from !== "oldest";
220
+ const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
221
+ const newest = from === "newest";
174
222
  let start = newest ? candidates.length : 0;
175
223
  let end = start;
176
224
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -0,0 +1,10 @@
1
+ import { type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
2
+ import { type CodexLineageSource } from "./codex-transcript.js";
3
+ /** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
4
+ export declare function historySummaryCacheRoot(home?: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
5
+ export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{
6
+ data: HistorySessionData;
7
+ lineageSources?: CodexLineageSource[];
8
+ }>;
9
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
10
+ export declare function cachedSessionRepresentative(session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad): Promise<HistorySessionRepresentative>;
@@ -0,0 +1,129 @@
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 } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { sessionIdentity } from "./corpus.js";
9
+ import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
10
+ import { sessionRepresentative } from "./query.js";
11
+ import { validateCodexLineageSources } from "./codex-transcript.js";
12
+ // Bump whenever strict decoding, representative selection, or cached event presentation changes.
13
+ const VERSION = "strict-representative-v1";
14
+ const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
15
+ const FingerprintSchema = Type.Object({
16
+ path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
17
+ }, { additionalProperties: false });
18
+ const EventSchema = Type.Object({
19
+ seq: Type.Integer({ minimum: 1 }), windowId: Type.String(), role: HistoryRoleSchema,
20
+ createdAt: Type.Optional(Type.String()), text: Type.String(),
21
+ execution: Type.Optional(Type.Object({
22
+ name: Type.String(), status: ToolCallStatusSchema,
23
+ arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
24
+ outputTruncated: Type.Optional(Type.Boolean()), fullOutputPath: Type.Optional(Type.String()),
25
+ nestedCalls: Type.Optional(Type.Object({ complete: Type.Boolean(), calls: Type.Array(Type.Object({
26
+ id: Type.String(), name: Type.String(), status: ToolCallStatusSchema,
27
+ arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())), argumentsBytes: Type.Optional(Type.Number()),
28
+ durationMs: Type.Optional(Type.Number()), error: Type.Optional(Type.String()),
29
+ }, { additionalProperties: false })) }, { additionalProperties: false })),
30
+ }, { additionalProperties: false })),
31
+ }, { additionalProperties: false });
32
+ const EntrySchema = Type.Object({
33
+ version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
34
+ event: Type.Union([EventSchema, Type.Null()]), notice: Type.Optional(Type.String()),
35
+ fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
36
+ lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
37
+ }, { additionalProperties: false });
38
+ /** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
39
+ export function historySummaryCacheRoot(home = homedir(), env = process.env, platform = process.platform) {
40
+ return platform === "darwin" ? join(home, "Library/Caches/notesoup/history") : join(env.XDG_CACHE_HOME || join(home, ".cache"), "notesoup/history");
41
+ }
42
+ async function fingerprint(path) {
43
+ const info = await stat(path, { bigint: true });
44
+ if (!info.isFile())
45
+ throw new Error("Not a regular transcript file");
46
+ return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
47
+ }
48
+ async function unchanged(sources) {
49
+ for (const source of sources)
50
+ if (JSON.stringify(await fingerprint(source.path)) !== JSON.stringify(source))
51
+ return false;
52
+ return true;
53
+ }
54
+ /** One fingerprint per actual decoder read, in root-to-ancestor order; no untracked witnesses. */
55
+ function completeDependencies(path, harness, sources, lineage) {
56
+ if (harness !== "codex" && lineage.length !== 0)
57
+ return false;
58
+ const expected = [path, ...lineage.map((source) => source.path)];
59
+ return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
60
+ }
61
+ async function readEntry(path) {
62
+ const file = await open(path, "r");
63
+ try {
64
+ const info = await file.stat();
65
+ if (!info.isFile() || info.size > MAX_ENTRY_BYTES)
66
+ return undefined;
67
+ const buffer = Buffer.alloc(info.size + 1);
68
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
69
+ if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES)
70
+ return undefined;
71
+ return JSON.parse(buffer.toString("utf8", 0, bytesRead));
72
+ }
73
+ finally {
74
+ await file.close();
75
+ }
76
+ }
77
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
78
+ export async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
79
+ let canonical, cachePath;
80
+ const identity = sessionIdentity(session);
81
+ try {
82
+ canonical = await realpath(transcriptPath);
83
+ cachePath = join(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
84
+ const entry = await readEntry(cachePath);
85
+ if (Check(EntrySchema, entry) && entry.path === canonical && entry.session === identity
86
+ && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
87
+ && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
88
+ && await realpath(transcriptPath) === canonical) {
89
+ return { event: entry.event === null ? undefined : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
90
+ }
91
+ }
92
+ catch { /* Absent/corrupt/unwritable cache or changed source: strict load below. */ }
93
+ const fingerprints = new Map();
94
+ let stable = canonical !== undefined;
95
+ const track = async (path) => {
96
+ try {
97
+ if (!fingerprints.has(path))
98
+ fingerprints.set(path, await fingerprint(path));
99
+ }
100
+ catch {
101
+ stable = false;
102
+ }
103
+ };
104
+ if (canonical)
105
+ await track(canonical);
106
+ const { data, lineageSources = [] } = await load(track);
107
+ const event = sessionRepresentative(data.projection, {});
108
+ const result = { event, notice: data.notice };
109
+ try {
110
+ const sources = [...fingerprints.values()];
111
+ if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
112
+ || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical)
113
+ return result;
114
+ const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
115
+ if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES)
116
+ return result;
117
+ await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
118
+ const temporary = `${cachePath}.${randomUUID()}.tmp`;
119
+ try {
120
+ await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
121
+ await rename(temporary, cachePath);
122
+ }
123
+ finally {
124
+ await unlink(temporary).catch(() => { });
125
+ }
126
+ }
127
+ catch { /* The cache cannot turn readable history into a refusal. */ }
128
+ return result;
129
+ }