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
@@ -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, selectCorpusPage, selectPage, sessionRepresentative } from "../history/query.js";
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, from: "oldest", roles: ["tool", "context"] })}`;
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.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
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.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
56
- page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
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 afterSeq = data.seq - 10;
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: 1, description: "(optional) Only events with seq above this." })),
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, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
78
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
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 loaded = [];
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
- for (const session of sessions) {
110
- const result = await loadHistorySession(session, queries);
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
- if (!queries && !sessionRepresentative(result.data.projection, scoped.data))
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
- loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
124
+ qualifying++;
116
125
  if (result.data.notice)
117
126
  notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
118
- if (!queries && loaded.length >= Math.max(1, params.limit ?? 20))
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 = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
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)