notesoup 0.56.1 → 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.
- package/README.md +1 -1
- package/dist/plugins/pi/runtime.js +8 -8
- package/dist/plugins/pi/text.js +1 -1
- package/dist/src/history/claude.d.ts +2 -0
- package/dist/src/history/claude.js +13 -2
- package/dist/src/history/codex-transcript.d.ts +15 -3
- package/dist/src/history/codex-transcript.js +57 -21
- package/dist/src/history/codex.d.ts +4 -2
- package/dist/src/history/codex.js +3 -3
- package/dist/src/history/corpus.d.ts +8 -1
- package/dist/src/history/corpus.js +17 -1
- package/dist/src/history/history.d.ts +16 -10
- package/dist/src/history/history.js +9 -9
- package/dist/src/history/local.d.ts +2 -0
- package/dist/src/history/local.js +35 -38
- package/dist/src/history/prefilter.d.ts +5 -0
- package/dist/src/history/prefilter.js +95 -0
- package/dist/src/history/query.d.ts +29 -27
- package/dist/src/history/query.js +82 -34
- package/dist/src/history/summary-cache.d.ts +10 -0
- package/dist/src/history/summary-cache.js +129 -0
- package/dist/src/tools/history.js +31 -20
- package/dist/test/agent-loop.test.js +18 -26
- package/dist/test/codex-history.test.js +90 -4
- package/dist/test/codex-plugin.test.js +6 -2
- package/dist/test/history-corpus.test.js +221 -33
- package/dist/test/history-prefilter.test.d.ts +1 -0
- package/dist/test/history-prefilter.test.js +174 -0
- package/dist/test/history-summary-cache.test.d.ts +1 -0
- package/dist/test/history-summary-cache.test.js +297 -0
- package/dist/test/history.integration.test.js +87 -52
- package/dist/test/model-facing-text.test.js +1 -1
- package/dist/test/reset-lifecycle.test.js +4 -6
- package/docs/history-sessions.md +26 -2
- package/docs/reset-lifecycle.md +4 -4
- package/docs/tool-results.md +4 -2
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +425 -122
- package/plugins/codex/dist/codex/notesoup.js +423 -123
- package/plugins/pi/runtime.ts +8 -8
- package/plugins/pi/text.ts +1 -1
- package/src/history/claude.ts +16 -2
- package/src/history/codex-transcript.ts +52 -17
- package/src/history/codex.ts +5 -5
- package/src/history/corpus.ts +19 -2
- package/src/history/history.ts +11 -11
- package/src/history/local.ts +34 -38
- package/src/history/prefilter.ts +86 -0
- package/src/history/query.ts +77 -33
- package/src/history/summary-cache.ts +119 -0
- package/src/tools/history.ts +33 -20
|
@@ -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.
|
|
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
|
-
}
|
|
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
|
-
|
|
53
|
-
|
|
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
|
-
/**
|
|
70
|
-
export declare
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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(
|
|
43
|
-
|
|
44
|
-
|
|
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 }),
|
|
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
|
-
|
|
108
|
-
|
|
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
|
-
|
|
112
|
-
items.push(tail);
|
|
113
|
-
return {
|
|
107
|
+
const page = {
|
|
114
108
|
items,
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
|
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
|
+
}
|
|
@@ -3,8 +3,8 @@ import { Type } 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 } from "./result.js";
|
|
5
5
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
|
-
import { HistoryPageSchema, corpusSelection,
|
|
7
|
-
import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
|
|
6
|
+
import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage } from "../history/query.js";
|
|
7
|
+
import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
|
|
8
8
|
import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema } from "../history/history.js";
|
|
9
9
|
/** One read: identity, tool summary and a flat document slice. */
|
|
10
10
|
const HistoryReadDataSchema = Type.Object({
|
|
@@ -43,24 +43,29 @@ function renderPageItem(item) {
|
|
|
43
43
|
function renderFoldedRow(row) {
|
|
44
44
|
const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
|
|
45
45
|
const identity = row.session === undefined ? {} : { session: row.session };
|
|
46
|
-
const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1,
|
|
46
|
+
const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
|
|
47
47
|
return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
|
|
48
48
|
}
|
|
49
49
|
function renderPage(page) {
|
|
50
50
|
// An empty selection has no anchors either, so it would otherwise render as nothing at all.
|
|
51
|
-
if (page.items.length === 0)
|
|
51
|
+
if (page.items.length === 0 && !page.folded_after)
|
|
52
52
|
return `${page.notice ?? ""}No events match these filters.`;
|
|
53
|
-
const body = page.items.
|
|
53
|
+
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");
|
|
54
|
+
if (isMultiPage(page)) {
|
|
55
|
+
const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
|
|
56
|
+
return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
|
|
57
|
+
}
|
|
58
|
+
const first = page.items[0];
|
|
59
|
+
const last = page.items.at(-1);
|
|
54
60
|
const cursors = [
|
|
55
|
-
page.
|
|
56
|
-
page.
|
|
61
|
+
page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
|
|
62
|
+
page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
|
|
57
63
|
].filter((line) => line !== "");
|
|
58
64
|
return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
|
|
59
65
|
}
|
|
60
66
|
function renderRead(data) {
|
|
61
67
|
const tool = toolHeader(data);
|
|
62
|
-
const
|
|
63
|
-
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
|
|
68
|
+
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 })})`;
|
|
64
69
|
return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
65
70
|
}
|
|
66
71
|
const plainText = (text) => text;
|
|
@@ -71,11 +76,11 @@ export const historyListParameters = Type.Object({
|
|
|
71
76
|
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.")),
|
|
72
77
|
roles: historyRoles(),
|
|
73
78
|
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
|
|
74
|
-
after_seq: Type.Optional(Type.Integer({ minimum:
|
|
79
|
+
after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
|
|
75
80
|
since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
|
|
76
81
|
until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
|
|
77
|
-
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional
|
|
78
|
-
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded
|
|
82
|
+
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." })),
|
|
83
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
|
|
79
84
|
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.` })),
|
|
80
85
|
}, { additionalProperties: false });
|
|
81
86
|
export const historyList = {
|
|
@@ -104,23 +109,29 @@ export const historyList = {
|
|
|
104
109
|
const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
|
|
105
110
|
if (!queries)
|
|
106
111
|
sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
107
|
-
const
|
|
112
|
+
const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
|
|
113
|
+
const collector = new CorpusCollector(scoped.data);
|
|
114
|
+
let qualifying = 0;
|
|
108
115
|
const notices = [];
|
|
109
|
-
|
|
110
|
-
|
|
116
|
+
let unvisited = false;
|
|
117
|
+
for (const [index, session] of sessions.entries()) {
|
|
118
|
+
const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
|
|
111
119
|
if (!result.ok || !result.data)
|
|
112
120
|
continue;
|
|
113
|
-
|
|
121
|
+
const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
|
|
122
|
+
if (!added)
|
|
114
123
|
continue;
|
|
115
|
-
|
|
124
|
+
qualifying++;
|
|
116
125
|
if (result.data.notice)
|
|
117
126
|
notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
|
|
118
|
-
if (!queries &&
|
|
127
|
+
if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
|
|
128
|
+
unvisited = index + 1 < sessions.length;
|
|
119
129
|
break;
|
|
130
|
+
}
|
|
120
131
|
}
|
|
121
132
|
const notice = notices.length ? { notice: notices.join("") } : {};
|
|
122
|
-
const result =
|
|
123
|
-
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
133
|
+
const result = collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited);
|
|
134
|
+
return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
|
|
124
135
|
}
|
|
125
136
|
const target = await resolveSession(corpus, selector.data);
|
|
126
137
|
if (!target.ok)
|