notesoup 0.55.0 → 0.55.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.
@@ -133,9 +133,7 @@ export function registerContext(pi, settingsManager) {
133
133
  const windowId = reset?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
134
134
  try {
135
135
  if (reset) {
136
- if (!event.messages.some((message) => isWindowBoot(message, windowId)))
137
- throw new Error(`Missing boot for context window ${windowId}`);
138
- return { messages: isCheckpointBackedReset(ctx, reset) ? event.messages : projectWindow(event.messages, windowId) };
136
+ return { messages: projectWindow(event.messages, windowId) };
139
137
  }
140
138
  return { messages: projectRootWindow(event.messages, windowId) };
141
139
  }
@@ -18,7 +18,7 @@ function piOperationResult(render, outcome, details) {
18
18
  }
19
19
  export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
20
20
  export const DREAM_NAMESPACE = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
21
- export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
21
+ export const HISTORY_NAMESPACE = { name: "history", description: "Session history (this or other local sessions): history_list to browse/search, history_read to read one event." };
22
22
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
23
23
  export function registerOperation(pi, operation, run, namespace, renderers, exposure) {
24
24
  pi.registerTool(defineTool({
@@ -11,6 +11,6 @@ export type ClaudeHistoryProjection = HistoryProjection & {
11
11
  };
12
12
  /** All addresses are allocated on the full first-occurrence log, before branch selection. */
13
13
  export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
- /** Offline files have no live append binding. A unique graph leaf proves one ancestry; never pick among siblings by file order. */
14
+ /** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
15
15
  export declare function offlineClaudeHead(text: string): string;
16
16
  export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
@@ -291,12 +291,15 @@ export function claudeHistoryFromJsonl(text, source) {
291
291
  : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
292
292
  return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
293
293
  }
294
- /** Offline files have no live append binding. A unique graph leaf proves one ancestry; never pick among siblings by file order. */
294
+ /** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
295
295
  export function offlineClaudeHead(text) {
296
296
  const latest = new Map();
297
297
  for (const row of rowsOf(text)) {
298
- if (MESSAGE_TYPES.has(row.type))
299
- latest.set(requiredString(row.uuid, "uuid"), row);
298
+ if (!MESSAGE_TYPES.has(row.type))
299
+ continue;
300
+ const uuid = requiredString(row.uuid, "uuid");
301
+ latest.delete(uuid);
302
+ latest.set(uuid, row);
300
303
  }
301
304
  const ancestors = new Set();
302
305
  for (const row of latest.values()) {
@@ -325,9 +328,11 @@ export function offlineClaudeHead(text) {
325
328
  }
326
329
  }
327
330
  const leaves = [...latest.keys()].filter((uuid) => !ancestors.has(uuid));
328
- if (leaves.length !== 1)
329
- throw new Error(`Offline Claude transcript has ${leaves.length} possible heads; no confirmed unique leaf (refusing to guess a selected branch)`);
330
- return leaves[0];
331
+ if (leaves.length === 0)
332
+ throw new Error("Offline Claude transcript has 0 possible heads");
333
+ const nonAttachments = leaves.filter((uuid) => latest.get(uuid).type !== "attachment");
334
+ const candidates = nonAttachments.length ? nonAttachments : leaves;
335
+ return candidates.at(-1);
331
336
  }
332
337
  export async function readClaudeHistory(source) {
333
338
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
@@ -29,6 +29,8 @@ export type CodexRecord = {
29
29
  };
30
30
  export declare function nativeObject(value: unknown, field: string): NativeObject;
31
31
  export declare function nativeString(value: unknown, field: string): string;
32
+ /** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
33
+ export declare function readCodexTranscriptBytes(path: string, remaining?: number): Promise<Buffer>;
32
34
  /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
33
35
  export declare function readCodexTranscript(source: CodexTranscriptSource): Promise<{
34
36
  state: CodexTranscriptState;
@@ -189,7 +189,8 @@ async function referencedPath(home, rolloutId) {
189
189
  throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
190
190
  return matches[0];
191
191
  }
192
- async function decodedBytes(path, remaining) {
192
+ /** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
193
+ export async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
193
194
  const info = await stat(path);
194
195
  if (!info.isFile() || info.size > remaining)
195
196
  throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
@@ -215,7 +216,7 @@ export async function readCodexTranscript(source) {
215
216
  if (segments.length >= MAX_SEGMENTS || seen.has(path))
216
217
  throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
217
218
  seen.add(path);
218
- const bytes = await decodedBytes(path, remaining);
219
+ const bytes = await readCodexTranscriptBytes(path, remaining);
219
220
  remaining -= bytes.length;
220
221
  const segment = segmentFromBytes(bytes, cutoff);
221
222
  if (segments.length === 0 && segment.meta.id !== source.threadId)
@@ -10,7 +10,7 @@ export type HistorySession = {
10
10
  harness: HistoryHarness;
11
11
  id: string;
12
12
  modifiedAt: number;
13
- load(): Promise<HistorySessionData>;
13
+ load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
14
14
  };
15
15
  export type HistoryCorpus = {
16
16
  currentHarness: HistoryHarness;
@@ -32,4 +32,5 @@ export declare function parseSessionSelector(value: string): Outcome<SessionSele
32
32
  export declare function matchesSession(session: HistorySession, selector: SessionSelector): boolean;
33
33
  export declare function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>>;
34
34
  export declare function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
35
+ export declare function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
35
36
  export declare function currentHistory(context: HistoryContext): HistoryProjection | Promise<HistoryProjection>;
@@ -41,9 +41,12 @@ export async function resolveSession(corpus, selector) {
41
41
  return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
42
42
  return success(matches[0]);
43
43
  }
44
- export async function loadHistorySession(session) {
44
+ export async function loadHistorySession(session, queries) {
45
45
  try {
46
- return success(await session.load());
46
+ const data = await session.load(queries);
47
+ if (data === undefined && !queries?.length)
48
+ throw new Error("Session returned no history");
49
+ return success(data);
47
50
  }
48
51
  catch (error) {
49
52
  return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
@@ -1,11 +1,7 @@
1
- import { type HistoryCorpus, type HistoryHarness, type HistorySession, type HistorySessionData } from "./corpus.js";
1
+ import { type HistoryCorpus, type HistorySession } from "./corpus.js";
2
2
  export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
3
3
  export type LocalHistoryOptions = {
4
- current: {
5
- harness: HistoryHarness;
6
- id: string;
7
- load(): Promise<HistorySessionData>;
8
- };
4
+ current: Pick<HistorySession, "harness" | "id" | "load">;
9
5
  /** Undefined uses the harness default; null disables that harness's filesystem discovery. */
10
6
  roots?: LocalHistoryRoots;
11
7
  home?: string;
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  import { piHistoryFromJsonl } from "./pi.js";
6
6
  import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
7
7
  import { readCodexHistory } from "./codex.js";
8
+ import { readCodexTranscriptBytes } from "./codex-transcript.js";
8
9
  import { sessionIdentity } from "./corpus.js";
9
10
  function rootsFor(options) {
10
11
  const env = options.env ?? process.env;
@@ -36,6 +37,33 @@ async function filesAt(root, depth) {
36
37
  }
37
38
  return paths;
38
39
  }
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
+ }
39
67
  async function localSessions(harness, root) {
40
68
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
41
69
  const sessions = [];
@@ -57,10 +85,14 @@ async function localSessions(harness, root) {
57
85
  }
58
86
  sessions.push({
59
87
  harness, id, modifiedAt,
60
- async load() {
88
+ 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;
61
94
  if (harness === "codex")
62
95
  return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
63
- const text = await readFile(path, "utf8");
64
96
  if (harness === "pi")
65
97
  return { projection: piHistoryFromJsonl(text, id) };
66
98
  const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
@@ -1,7 +1,7 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type, type Static } from "typebox";
3
3
  import { type Outcome } from "../tools/result.js";
4
- import { type HistoryFilter, type HistoryProjection } from "./history.js";
4
+ import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
5
5
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
6
6
  export type HistoryOrder = "newest" | "oldest";
7
7
  /**
@@ -66,7 +66,9 @@ export type HistoryPage = Static<typeof HistoryPageSchema>;
66
66
  export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
67
67
  /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
68
68
  export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
69
- /** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
69
+ /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
70
+ export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
71
+ /** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
70
72
  export declare function selectCorpusPage(sessions: {
71
73
  session: string;
72
74
  projection: HistoryProjection;
@@ -144,18 +144,27 @@ export function selectPage(projection, params, fits, maxChars) {
144
144
  }
145
145
  /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
146
146
  export function corpusSelection(params) {
147
- const scoped = resolveSelection(params);
148
- if (!scoped.ok)
149
- return scoped;
150
- if (scoped.data.query === undefined)
151
- return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
152
147
  if (params.before_seq !== undefined || params.after_seq !== undefined)
153
148
  return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
154
- return scoped;
149
+ return resolveSelection(params);
155
150
  }
156
- /** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
151
+ /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
152
+ export function sessionRepresentative(projection, scoped) {
153
+ const events = filteredItems(projection, scoped, false).filter((event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
154
+ if (scoped.roles)
155
+ return events.at(-1);
156
+ return events.find((event) => event.role === "user")
157
+ ?? events.filter((event) => event.role === "assistant").at(-1)
158
+ ?? events.at(-1);
159
+ }
160
+ /** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
157
161
  export function selectCorpusPage(sessions, scoped, fits, maxChars) {
158
- const candidates = sessions.flatMap(({ session, projection }) => prepareSelection(projection, { ...scoped, session }).candidates);
162
+ const candidates = sessions.flatMap(({ session, projection }) => {
163
+ if (scoped.query !== undefined)
164
+ return prepareSelection(projection, { ...scoped, session }).candidates;
165
+ const event = sessionRepresentative(projection, scoped);
166
+ return event === undefined ? [] : [{ session, event }];
167
+ });
159
168
  const time = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
160
169
  candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq));
161
170
  return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
@@ -3,7 +3,7 @@ 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 } from "../history/query.js";
6
+ import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage, sessionRepresentative } from "../history/query.js";
7
7
  import { currentHistory, 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. */
@@ -65,7 +65,7 @@ function renderRead(data) {
65
65
  }
66
66
  const plainText = (text) => text;
67
67
  /* ------------------------------------------------------------------ history_list */
68
- const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions (query required); history_read needs one session." }));
68
+ const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
69
69
  export const historyListParameters = Type.Object({
70
70
  session: sessionParameter,
71
71
  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.")),
@@ -81,7 +81,7 @@ export const historyListParameters = Type.Object({
81
81
  export const historyList = {
82
82
  name: "history_list",
83
83
  label: "History list items",
84
- description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * with query to search across local harnesses. Read one in full with `history_read`.",
84
+ description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * to browse recent sessions across local harnesses (add query to search). Read one in full with `history_read`.",
85
85
  parameters: historyListParameters,
86
86
  outputSchema: resultSchema(HistoryPageSchema),
87
87
  async execute(params, context, wrapText = plainText) {
@@ -101,15 +101,22 @@ export const historyList = {
101
101
  if (corpus === undefined)
102
102
  return failure("unknown_session", "This host supplied no cross-session history corpus.");
103
103
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
104
+ const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
105
+ if (!queries)
106
+ sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
104
107
  const loaded = [];
105
108
  const notices = [];
106
109
  for (const session of sessions) {
107
- const result = await loadHistorySession(session);
108
- if (!result.ok)
109
- return result;
110
+ const result = await loadHistorySession(session, queries);
111
+ if (!result.ok || !result.data)
112
+ continue;
113
+ if (!queries && !sessionRepresentative(result.data.projection, scoped.data))
114
+ continue;
110
115
  loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
111
116
  if (result.data.notice)
112
117
  notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
118
+ if (!queries && loaded.length >= Math.max(1, params.limit ?? 20))
119
+ break;
113
120
  }
114
121
  const notice = notices.length ? { notice: notices.join("") } : {};
115
122
  const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
@@ -51,6 +51,30 @@ test("custom reset marker removes old provider context while history remains sea
51
51
  assert.equal(found.items.length, 1);
52
52
  assert.equal(found.items[0]?.seq, oldSeq);
53
53
  });
54
+ test("a checkpoint-backed reset projects from its boot and drops the empty compaction wrapper", async () => {
55
+ const sessionManager = manager();
56
+ const captured = makeExtension(sessionManager);
57
+ const ctx = context(sessionManager);
58
+ appendText(sessionManager, "user", "before the reset");
59
+ await call(captured, "empty_brain", {}, ctx);
60
+ assert.equal((await commitTurnEndBoundary(captured, sessionManager, ctx)).continue, true);
61
+ // Pi projects the empty retain-none checkpoint into a compactionSummary that precedes the boot.
62
+ const sessionMessages = sessionManager.buildSessionProjection().messages;
63
+ const wrapperIndex = sessionMessages.findIndex((message) => message.role === "compactionSummary");
64
+ const bootIndex = sessionMessages.findIndex((message) => message.role === "custom" && message.customType === BOOT_TYPE);
65
+ assert.ok(wrapperIndex >= 0 && wrapperIndex < bootIndex, "the empty wrapper sits before the boot");
66
+ const projected = await runContextWithSystemHook(captured, ctx, [
67
+ { role: "system", content: "SYSTEM HEAD", timestamp: 0 },
68
+ ...sessionMessages,
69
+ ]);
70
+ const messages = (projected?.messages ?? []);
71
+ assert.equal(messages[0]?.role, "system", "the leading system message survives");
72
+ assert.equal(messages[0]?.role === "system" ? messages[0].content : undefined, "SYSTEM HEAD");
73
+ const first = messages[1];
74
+ assert.ok(first?.role === "custom", "the window starts at its boot");
75
+ assert.equal(first.customType, BOOT_TYPE);
76
+ assert.equal(messages.some((message) => message.role === "compactionSummary"), false, "the empty checkpoint wrapper never reaches the provider");
77
+ });
54
78
  test("the root boot and reset boot carry durable window identity", async () => {
55
79
  const sessionManager = manager();
56
80
  const captured = makeExtension(sessionManager);