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.
@@ -8,7 +8,7 @@ import { Check } from "typebox/value";
8
8
  import { localHistoryCorpus } from "../src/history/local.js";
9
9
  import { parseSessionSelector } from "../src/history/corpus.js";
10
10
  import { allItems, projectHistory } from "../src/history/history.js";
11
- import { offlineClaudeHead } from "../src/history/claude.js";
11
+ import { claudeHistoryFromJsonl, offlineClaudeHead } from "../src/history/claude.js";
12
12
  import { piHistoryFromJsonl } from "../src/history/pi.js";
13
13
  import { historyList, historyRead } from "../src/tools/history.js";
14
14
  import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
@@ -131,11 +131,12 @@ test("all single-session recipes preserve the resolved identity, including folde
131
131
  });
132
132
  test("wildcard refusals precede discovery, and read accepts no wildcard selector", async () => {
133
133
  const ctx = { current: () => { throw new Error("must not load current"); }, corpus: { currentHarness: "pi", sessions: async () => { throw new Error("must not discover"); } } };
134
- for (const query of [undefined, "", [], ["", ""]]) {
135
- refusal(await historyList.execute({ session: "*", query }, ctx), "missing_query");
136
- }
137
- for (const bounds of [{ before_seq: 10 }, { after_seq: 1 }, { before_seq: 10, after_seq: 1 }]) {
138
- refusal(await historyList.execute({ session: "*", query: "needle", ...bounds }, ctx), "invalid_bounds");
134
+ for (const session of ["*", "pi:*", "pre*fix"]) {
135
+ for (const query of [undefined, "", [], ["", ""], "needle"]) {
136
+ for (const bounds of [{ before_seq: 10 }, { after_seq: 1 }, { before_seq: 10, after_seq: 1 }]) {
137
+ refusal(await historyList.execute({ session, query, ...bounds }, ctx), "invalid_bounds");
138
+ }
139
+ }
139
140
  }
140
141
  for (const session of ["*", "pi:*", "cl*", "dsh:pre*suffix"]) {
141
142
  refusal(await historyRead.execute({ session, seq: 1 }, ctx), "invalid_session");
@@ -185,6 +186,103 @@ test("wildcard query merges every role chronologically, limits from either end,
185
186
  assert.ok(Check(historyList.outputSchema, page));
186
187
  assert.match(historyList.render(result), /session pi:pi-one \| seq 1 \| user/);
187
188
  });
189
+ test("query-less wildcards browse recent sessions, normalize empty queries, and keep canonical IDs", async (t) => {
190
+ const { ctx } = await fixture(t);
191
+ for (const query of [undefined, "", [], ["", ""]]) {
192
+ const result = await historyList.execute({ session: "*", query }, ctx);
193
+ const page = data(result);
194
+ assert.deepEqual(page.items.map((item) => "seq" in item ? [item.session, item.seq, item.role] : null), [
195
+ ["pi:pi-one", 1, "user"], ["claude:claude-one", 1, "user"], ["pi:current", 1, "user"], [`codex:${CODEX}`, 2, "assistant"],
196
+ ]);
197
+ assert.equal(page.page_older, null);
198
+ assert.equal(page.page_newer, null);
199
+ assert.ok(Check(historyList.outputSchema, page));
200
+ }
201
+ const harness = data(await historyList.execute({ session: "claude:*" }, ctx));
202
+ assert.deepEqual(harness.items.map((item) => item.session), ["claude:claude-one"]);
203
+ assert.equal(data(await historyList.execute({ session: "pi:absent*" }, ctx)).items.length, 0);
204
+ });
205
+ test("session overviews order discovery by mtime, stop at the session limit, then sort representatives by event time", async () => {
206
+ const loaded = [];
207
+ const sessions = Array.from({ length: 25 }, (_, index) => {
208
+ const createdAt = new Date(Date.parse(AT) + (25 - index) * 1000).toISOString();
209
+ return {
210
+ harness: "pi", id: `s-${index}`, modifiedAt: index,
211
+ async load(queries) {
212
+ assert.equal(queries, undefined);
213
+ loaded.push(index);
214
+ return { projection: projectHistory([{ windowId: "w", items: [{ seq: 1, windowId: "w", role: "user", text: `topic ${index}`, createdAt }] }], 1, new Set([1])) };
215
+ },
216
+ };
217
+ });
218
+ const ctx = context(sessions);
219
+ const recent = data(await historyList.execute({ session: "*" }, ctx));
220
+ assert.deepEqual(loaded, Array.from({ length: 20 }, (_, index) => 24 - index));
221
+ assert.deepEqual(recent.items.map((item) => item.session), loaded.map((index) => `pi:s-${index}`));
222
+ loaded.length = 0;
223
+ const oldest = data(await historyList.execute({ session: "*", from: "oldest", limit: 2 }, ctx));
224
+ assert.deepEqual(loaded, [0, 1]);
225
+ assert.deepEqual(oldest.items.map((item) => item.session), ["pi:s-1", "pi:s-0"]);
226
+ loaded.length = 0;
227
+ const pattern = data(await historyList.execute({ session: "pi:s-2*", limit: 2 }, ctx));
228
+ assert.deepEqual(loaded, [24, 23]);
229
+ assert.deepEqual(pattern.items.map((item) => item.session), ["pi:s-24", "pi:s-23"]);
230
+ });
231
+ test("session representatives respect visibility, role/time filters, opening users and dialogue/any fallbacks", async () => {
232
+ const at = (seconds) => new Date(Date.parse(AT) + seconds * 1000).toISOString();
233
+ const messages = [
234
+ ["system", "early context", 0], ["user", "", 0], ["user", "opening topic", 1],
235
+ ["assistant", "visible reply", 2], ["user", "later topic", 3], ["tool", "tool output", 4],
236
+ ["assistant", "", 5], ["system", "late context", 6],
237
+ ];
238
+ const p = projectHistory([{ windowId: "w", items: messages.map(([role, text, seconds], index) => ({ seq: index + 1, windowId: "w", role, text, createdAt: at(seconds) })) }], 8, new Set([1, 2, 3, 4, 5, 6, 7, 8]));
239
+ const ctx = context([descriptor("claude", "topic", p)]);
240
+ const chosen = async (params) => data(await historyList.execute({ session: "*", ...params }, ctx)).items.map((item) => "seq" in item ? item.seq : "folded");
241
+ assert.deepEqual(await chosen({}), [3]);
242
+ assert.deepEqual(await chosen({ roles: ["user"] }), [5]);
243
+ assert.deepEqual(await chosen({ roles: ["assistant"] }), [4]);
244
+ assert.deepEqual(await chosen({ roles: ["user", "assistant"] }), [5]);
245
+ assert.deepEqual(await chosen({ roles: ["context", "tool"] }), [8]);
246
+ assert.deepEqual(await chosen({ roles: ["tool"] }), [6]);
247
+ assert.deepEqual(await chosen({ roles: [] }), []);
248
+ assert.deepEqual(await chosen({ since: at(2), until: at(3) }), [4]);
249
+ assert.deepEqual(await chosen({ since: at(3) }), [5]);
250
+ assert.deepEqual(await chosen({ until: at(1) }), [1]);
251
+ assert.deepEqual(await chosen({ since: at(4) }), [8]);
252
+ assert.deepEqual(await chosen({ since: at(4), roles: ["user"] }), []);
253
+ assert.deepEqual(await chosen({ since: at(7) }), []);
254
+ const noUsers = { ...p, windows: p.windows.map((window) => ({ ...window, items: window.items.filter((item) => item.role !== "user") })) };
255
+ const fallback = data(await historyList.execute({ session: "*" }, context([descriptor("pi", "assistant-topic", noUsers)])));
256
+ assert.deepEqual(fallback.items.map((item) => "seq" in item ? item.seq : null), [4]);
257
+ });
258
+ test("empty, filtered-out and unavailable sessions do not consume overview slots", async () => {
259
+ const loaded = [];
260
+ const sessions = [
261
+ { ...descriptor("pi", "broken"), modifiedAt: 6, load: async () => { throw new Error("unreadable"); } },
262
+ { ...descriptor("pi", "empty", projectHistory([], 0, new Set())), modifiedAt: 5 },
263
+ { ...descriptor("pi", "filtered", projection("context", "system")), modifiedAt: 4 },
264
+ { ...descriptor("pi", "topic"), modifiedAt: 3 },
265
+ { ...descriptor("pi", "unneeded"), modifiedAt: 2, load: async () => { throw new Error("must not load beyond limit"); } },
266
+ ].map((session) => ({ ...session, async load() { loaded.push(session.id); return session.load(); } }));
267
+ const page = data(await historyList.execute({ session: "*", roles: ["user"], limit: 1 }, context(sessions)));
268
+ assert.deepEqual(page.items.map((item) => item.session), ["pi:topic"]);
269
+ assert.ok(loaded.includes("empty") && loaded.includes("filtered") && !loaded.includes("unneeded"));
270
+ assert.deepEqual(data(await historyList.execute({ session: "*" }, context([]))), { items: [], page_older: null, page_newer: null });
271
+ });
272
+ test("wildcard queries reach lazy loaders and pre-filtered misses are not errors", async () => {
273
+ const seen = [];
274
+ const ctx = context([
275
+ { ...descriptor("pi", "miss"), async load(queries) { seen.push(queries); return undefined; } },
276
+ { ...descriptor("pi", "broken"), async load(queries) { seen.push(queries); throw new Error("unsupported"); } },
277
+ { ...descriptor("claude", "hit"), async load(queries) { seen.push(queries); return { projection: projection("other") }; } },
278
+ ]);
279
+ const page = data(await historyList.execute({ session: "*", query: ["", "needle", "other"] }, ctx));
280
+ assert.equal(page.items.length, 5);
281
+ assert.ok(page.items.every((item) => item.session === "claude:hit"));
282
+ assert.deepEqual(seen, [["needle", "other"], ["needle", "other"], ["needle", "other"]]);
283
+ refusal(await historyList.execute({ session: "pi:miss" }, ctx), "history_unavailable");
284
+ refusal(await historyRead.execute({ session: "pi:broken", seq: 1 }, ctx), "history_unavailable");
285
+ });
188
286
  test("query offsets and text continuation retain cross-session identity and Unicode coordinates", async (t) => {
189
287
  const { ctx } = await fixture(t);
190
288
  const page = data(await historyList.execute({ session: "pi:*", query: "NEEDLE", roles: ["user"], max_chars_per_item: 3 }, ctx));
@@ -248,6 +346,12 @@ test("oversized cross-session reads/searches obey both wire budgets and retain c
248
346
  assert.ok(Buffer.byteLength(historyRead.render(read)) <= TOOL_OUTPUT_MAX_BYTES);
249
347
  assert.equal(data(read).session, "codex:long-id");
250
348
  assert.ok(data(read).next_offset_chars > 0);
349
+ const overview = await historyList.execute({ session: "*", max_chars_per_item: 50_000 }, ctx);
350
+ assert.ok(Buffer.byteLength(JSON.stringify(data(overview))) <= TOOL_OUTPUT_MAX_BYTES);
351
+ assert.ok(Buffer.byteLength(historyList.render(overview)) <= TOOL_OUTPUT_MAX_BYTES);
352
+ assert.equal(data(overview).items.length, 1);
353
+ assert.equal(data(overview).page_older, null);
354
+ assert.equal(data(overview).page_newer, null);
251
355
  });
252
356
  test("qualified lookup and current-harness matches do not inspect unrelated roots", async (t) => {
253
357
  const f = await fixture(t);
@@ -279,12 +383,121 @@ test("cross-session Claude gaps are visible even on an empty page, budgeted, and
279
383
  assert.ok(Buffer.byteLength(JSON.stringify(data(read))) <= TOOL_OUTPUT_MAX_BYTES);
280
384
  assert.ok(Buffer.byteLength(historyRead.render(read)) <= TOOL_OUTPUT_MAX_BYTES);
281
385
  });
282
- test("invalid persisted sessions refuse visibly instead of fabricating a successful partial corpus", async (t) => {
386
+ test("wildcards skip corrupt and unreadable sessions, while single-session lists and reads still refuse", async (t) => {
283
387
  const f = await fixture(t);
284
- await f.put(join(f.roots.pi, "--workspace--", "2026-10-06_broken.jsonl"), "not-json\n");
285
- const message = refusal(await historyList.execute({ session: "pi:*", query: "needle" }, f.ctx), "history_unavailable");
286
- assert.match(message, /pi:broken/);
287
- refusal(await historyRead.execute({ session: "pi:broken", seq: 1 }, f.ctx), "history_unavailable");
388
+ await f.put(join(f.roots.pi, "--workspace--", "2026-10-06_broken.jsonl"), "not-json needle\n", 100);
389
+ const sessions = await f.corpus.sessions();
390
+ await rm(f.claudePath);
391
+ const ctx = { current: () => projection(), corpus: { currentHarness: "pi", sessions: async () => sessions } };
392
+ for (const query of [undefined, "needle"]) {
393
+ const page = data(await historyList.execute({ session: "*", query }, ctx));
394
+ assert.ok(page.items.length > 0);
395
+ assert.ok(page.items.every((item) => item.session !== "pi:broken" && item.session !== "claude:claude-one"));
396
+ }
397
+ for (const session of ["pi:broken", "claude:claude-one"]) {
398
+ assert.ok(refusal(await historyList.execute({ session, query: "absent" }, ctx), "history_unavailable").includes(session));
399
+ refusal(await historyRead.execute({ session, seq: 1 }, ctx), "history_unavailable");
400
+ }
401
+ });
402
+ test("local query misses skip full decoding for Pi, Claude and compressed/uncompressed Codex", async (t) => {
403
+ const f = await fixture(t);
404
+ for (const session of (await f.corpus.sessions()).filter((session) => session.id !== "current")) {
405
+ assert.equal(await session.load(["absentword"]), undefined, session.harness);
406
+ assert.ok(await session.load(["absentword", "NEEDLE"]), session.harness);
407
+ }
408
+ await f.put(f.codexPath.replace(/\.zst$/, ""), f.codexText, 100);
409
+ const uncompressed = (await f.corpus.sessions("codex"))[0];
410
+ assert.equal(await uncompressed.load(["absentword"]), undefined);
411
+ assert.ok(await uncompressed.load(["NEEDLE"]));
412
+ await f.put(f.piPath, "not-json unrelated\n");
413
+ await f.put(f.claudePath, "not-json unrelated\n");
414
+ await f.put(f.codexPath, zstdCompressSync(Buffer.from("not-json unrelated\n")));
415
+ await f.put(f.codexPath.replace(/\.zst$/, ""), "not-json unrelated\n", 100);
416
+ for (const session of (await f.corpus.sessions()).filter((session) => session.id !== "current")) {
417
+ assert.equal(await session.load(["needle"]), undefined, session.harness);
418
+ assert.equal(await session.load(["entirelyabsent phrasewithoutmatch"]), undefined, session.harness);
419
+ await assert.rejects(() => session.load());
420
+ await assert.rejects(() => session.load([]));
421
+ await assert.rejects(() => session.load(["unrelated"]));
422
+ }
423
+ await rm(f.codexPath.replace(/\.zst$/, ""));
424
+ const compressed = (await f.corpus.sessions("codex"))[0];
425
+ assert.equal(await compressed.load(["needle"]), undefined);
426
+ await assert.rejects(() => compressed.load());
427
+ });
428
+ test("raw filtering never loses escaped JSON, Unicode or OR-query matches", async (t) => {
429
+ const f = await fixture(t);
430
+ const content = 'NEEDLE 你好 😀 quote"slash\\ line\nbreak İ LONGſ CASEΣ';
431
+ const escapeText = (text) => text.replaceAll("NEEDLE", "\\u004e\\u0045\\u0045\\u0044\\u004c\\u0045")
432
+ .replaceAll("你好", "\\u4f60\\u597d").replaceAll("😀", "\\ud83d\\ude00").replaceAll("İ", "\\u0130");
433
+ await f.put(f.piPath, escapeText(rows([
434
+ { type: "session", id: "pi-one" },
435
+ { type: "message", id: "u", parentId: null, timestamp: AT, message: { role: "user", content } },
436
+ ])));
437
+ await f.put(f.claudePath, escapeText(rows([
438
+ { type: "user", uuid: "u", parentUuid: null, sessionId: "claude-one", timestamp: AT, message: { role: "user", content } },
439
+ ])));
440
+ const codexText = escapeText(f.codexText.replace("Codex needle", JSON.stringify(content).slice(1, -1)));
441
+ await f.put(f.codexPath, zstdCompressSync(Buffer.from(codexText)));
442
+ for (const query of ["needle", "你好", "😀", 'quote"slash\\', "line\nbreak", "İ", "longs", "caseς", ["absentword", "needle"]]) {
443
+ const page = data(await historyList.execute({ session: "*", query }, f.ctx));
444
+ assert.deepEqual(page.items.map((item) => item.session), ["claude:claude-one", "pi:pi-one", `codex:${CODEX}`], JSON.stringify(query));
445
+ }
446
+ assert.deepEqual(data(await historyList.execute({ session: "*", query: "absentword" }, f.ctx)).items, []);
447
+ });
448
+ test("raw filtering preserves generated tool documents, compact arguments and nested JSON escapes", async (t) => {
449
+ const f = await fixture(t);
450
+ await f.put(f.piPath, rows([
451
+ { type: "session", id: "pi-one" },
452
+ { type: "message", id: "t", parentId: null, timestamp: AT, message: { role: "toolResult", content: [{ type: "text", text: "done" }] } },
453
+ ]));
454
+ for (const query of ["unknown", "arguments", "output"]) {
455
+ const page = data(await historyList.execute({ session: "pi:pi-*", query }, f.ctx));
456
+ assert.equal(page.items.length, 1, query);
457
+ }
458
+ await f.put(f.piPath, rows([
459
+ { type: "session", id: "pi-one" },
460
+ { type: "message", id: "t", parentId: null, timestamp: AT, message: { role: "assistant", content: [{ type: "toolCall", id: "c", name: "read", arguments: { value: "\ud800" } }] } },
461
+ ]));
462
+ assert.equal(data(await historyList.execute({ session: "pi:pi-*", query: "ud" }, f.ctx)).items.length, 1);
463
+ const codexRows = f.codexText.split("\n").filter(Boolean).map((line) => JSON.parse(line));
464
+ codexRows[1].payload = { type: "function_call", call_id: "t", name: "read", arguments: '{ "path" : "\\u006eeedle" }' };
465
+ await f.put(f.codexPath, zstdCompressSync(Buffer.from(rows(codexRows))));
466
+ for (const query of ["needle", '"path":"needle"']) {
467
+ const page = data(await historyList.execute({ session: "codex:*", query }, f.ctx));
468
+ assert.equal(page.items.length, 1, query);
469
+ }
470
+ });
471
+ test("Codex raw pre-filtering preserves query hits inherited through history_base", async (t) => {
472
+ const f = await fixture(t);
473
+ const child = "019a0000-0000-7000-8000-000000000002";
474
+ const parent = rows([
475
+ { type: "session_meta", ordinal: 0, timestamp: AT, payload: { id: CODEX, cwd: "/workspace", cli_version: "0.160.1", history_mode: "paginated", context_window: { window_id: WINDOW } } },
476
+ { type: "response_item", ordinal: 1, timestamp: AT, payload: { type: "message", role: "user", content: [{ type: "input_text", text: "ancestralneedle" }] } },
477
+ ]);
478
+ await f.put(f.codexPath, zstdCompressSync(Buffer.from(parent)));
479
+ await f.put(join(dirname(f.codexPath), `rollout-2026-10-06T01-02-03-${child}.jsonl`), rows([
480
+ { type: "session_meta", ordinal: 2, timestamp: AT, payload: { id: child, cwd: "/workspace", cli_version: "0.160.1", history_mode: "paginated", history_base: { thread_id: CODEX, end_ordinal_exclusive: 2, end_byte_offset: Buffer.byteLength(parent) }, context_window: { window_id: WINDOW } } },
481
+ { type: "response_item", ordinal: 3, timestamp: AT, payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: "local only" }] } },
482
+ ]));
483
+ const page = data(await historyList.execute({ session: `codex:${child}*`, query: "ancestralneedle" }, f.ctx));
484
+ assert.deepEqual(page.items.map((item) => "seq" in item ? [item.session, item.seq] : null), [[`codex:${child}`, 2]]);
485
+ });
486
+ test("offline Claude attachments and retry branches are readable and searchable through session selectors", async (t) => {
487
+ const f = await fixture(t);
488
+ await f.put(f.claudePath, rows([
489
+ { type: "user", uuid: "u", parentUuid: null, sessionId: "claude-one", timestamp: AT, message: { role: "user", content: "topic" } },
490
+ { type: "assistant", uuid: "left", parentUuid: "u", sessionId: "claude-one", timestamp: AT, message: { role: "assistant", content: "leftneedle" } },
491
+ { type: "assistant", uuid: "right", parentUuid: "u", sessionId: "claude-one", timestamp: AT, message: { role: "assistant", content: "rightneedle" } },
492
+ { type: "attachment", uuid: "hook", parentUuid: "u", sessionId: "claude-one", attachment: { type: "hook_success" } },
493
+ ]));
494
+ assert.equal(data(await historyRead.execute({ session: "claude:claude-one", seq: 3 }, f.ctx)).text, "rightneedle");
495
+ refusal(await historyRead.execute({ session: "claude:claude-one", seq: 2 }, f.ctx), "not_on_branch");
496
+ for (const session of ["claude:claude-one", "claude:*"]) {
497
+ const page = data(await historyList.execute({ session, query: "needle" }, f.ctx));
498
+ assert.deepEqual(page.items.map((item) => "seq" in item ? item.seq : null), [3]);
499
+ }
500
+ assert.deepEqual(data(await historyList.execute({ session: "claude:*" }, f.ctx)).items.map((item) => "seq" in item ? item.seq : null), [1]);
288
501
  });
289
502
  test("offline Pi follows persisted parent links, preserves branch seq holes and rejects corrupt ancestry", async () => {
290
503
  const base = { type: "session", version: 3, id: "branch", timestamp: AT };
@@ -297,11 +510,22 @@ test("offline Pi follows persisted parent links, preserves branch seq holes and
297
510
  assert.throws(() => piHistoryFromJsonl(text + "bad\n", "branch"), /malformed Pi/);
298
511
  assert.throws(() => piHistoryFromJsonl(text, "wrong"), /different session/);
299
512
  });
300
- test("offline Claude requires one evidenced leaf, accounts for logical compact links, and never guesses among branches", () => {
513
+ test("offline Claude prefers non-attachment leaves, then transcript order, and keeps compact links", () => {
301
514
  const user = (uuid, parentUuid) => ({ type: "user", uuid, parentUuid, sessionId: "s", message: { role: "user", content: "text" } });
302
515
  assert.equal(offlineClaudeHead(rows([user("u", null), user("a", "u")])), "a");
303
516
  assert.equal(offlineClaudeHead(rows([user("u", null), { type: "system", uuid: "b", parentUuid: null, logicalParentUuid: "u", subtype: "compact_boundary" }, user("a", "b")])), "a");
304
517
  assert.equal(offlineClaudeHead(rows([user("u", null), user("preserved", null), { type: "system", uuid: "b", parentUuid: null, logicalParentUuid: "u", subtype: "compact_boundary", compactMetadata: { preservedSegment: { headUuid: "preserved", tailUuid: "preserved" } } }, user("a", "b")])), "a");
305
- assert.throws(() => offlineClaudeHead(rows([user("u", null), user("left", "u"), user("right", "u")])), /2 possible heads/);
518
+ const attachment = (uuid, parentUuid) => ({ type: "attachment", uuid, parentUuid, sessionId: "s", attachment: { type: "hook_success" } });
519
+ assert.equal(offlineClaudeHead(rows([user("u", null), user("left", "u"), user("right", "u")])), "right");
520
+ assert.equal(offlineClaudeHead(rows([user("u", null), user("right", "u"), user("left", "u")])), "left");
521
+ assert.equal(offlineClaudeHead(rows([user("u", null), user("left", "u"), user("right", "u"), user("left", "u")])), "left");
522
+ assert.equal(offlineClaudeHead(rows([user("u", null), user("answer", "u"), attachment("hook", "u")])), "answer");
523
+ assert.equal(offlineClaudeHead(rows([user("u", null), attachment("hook", "u")])), "hook");
524
+ assert.equal(offlineClaudeHead(rows([attachment("first", null), attachment("last", null)])), "last");
306
525
  assert.throws(() => offlineClaudeHead(""), /0 possible heads/);
526
+ assert.throws(() => offlineClaudeHead(rows([user("a", "b"), user("b", "a")])), /0 possible heads/);
527
+ // Live decoding still requires a host-confirmed head, regardless of offline selection.
528
+ const branch = rows([user("u", null), user("left", "u"), user("right", "u")]);
529
+ assert.throws(() => claudeHistoryFromJsonl(branch, { sessionId: "s" }), /no confirmed active head/);
530
+ assert.deepEqual(allItems(claudeHistoryFromJsonl(branch, { sessionId: "s", headUuid: "left" })).map((item) => item.seq), [1, 2]);
307
531
  });
@@ -22,7 +22,7 @@ The notes tools also serve subagent calls, using the same session identity and s
22
22
 
23
23
  `history_list` and `history_read` use the same schemas, literal search (`history_list.query`), paging, folding, pairing and text rendering as Pi. With `session` omitted they read the current main session's persisted JSONL, via the documented `classic.SessionStart.transcript_path`; no path is guessed and `$.session.messages()` is not treated as full history. The classic binding survives typed `session.start`, which fires later. Without that path, current-session history calls refuse and the boot says history is unavailable. Subagent history calls refuse rather than silently exposing the main transcript.
24
24
 
25
- Explicit `session` selectors use the [local cross-harness corpus](history-sessions.md), including Pi/Claude/Codex files, without needing the current main transcript to have a head yet. Explicitly selecting the current Claude session still uses its strict live binding. Offline Claude targets require a unique graph leaf; multiple possible leaves refuse rather than choosing by file order. The persisted Claude decoder is shared under `src/history/claude.ts`; its plugin entry remains in `plugins/claude/src/history.ts`.
25
+ Explicit `session` selectors use the [local cross-harness corpus](history-sessions.md), including Pi/Claude/Codex files, without needing the current main transcript to have a head yet. Explicitly selecting the current Claude session still uses its strict live binding. Offline Claude targets prefer non-attachment graph leaves when available, then select the last remaining leaf in transcript order; no leaves still refuses. The persisted Claude decoder is shared under `src/history/claude.ts`; its plugin entry remains in `plugins/claude/src/history.ts`.
26
26
 
27
27
  The active head comes from the main loop's successful `session.append` result UUID, including attachments and notices. On startup/resume, before such an append, the public API supplies no authoritative selected leaf: history explicitly refuses instead of assuming the last file row or `last-prompt.leafUuid` is current. The append result means the engine kept a row, but its disk write may lag; a head missing on disk is a retryable refusal, not permission to switch branches. Session end clears the binding; a new classic start rebinds it.
28
28
 
@@ -17,21 +17,23 @@ Within the requested harness an exact ID wins over prefixes. Without a harness,
17
17
 
18
18
  Explicit targeting always returns the canonical `session: "<harness>:<full-id>"`, even when the target happens to be the current session. Headers become `session <harness>:<id> | seq <seq> | <role>`. `page_older`, `page_newer`, folded-row `expand`, and read `neighborhood` recipes carry that same canonical selector. Copy it into subsequent `history_read` calls, including reads continued with `next_offset_chars`.
19
19
 
20
- ## Search across sessions
20
+ ## Browse or search across sessions
21
21
 
22
- Any selector containing `*` is a multi-session search; `*` matches any string and all other characters are literal. `*` covers all available harnesses, `pi:*` restricts to Pi, and `claude:prefix*` narrows by session ID.
22
+ Any selector containing `*` selects multiple sessions; `*` matches any string and all other characters are literal. `*` covers all available harnesses, `pi:*` restricts to Pi, and `claude:prefix*` narrows by session ID.
23
23
 
24
24
  ```js
25
+ history_list({ session: "*" }) // Recent sessions, one opening prompt/topic each
25
26
  history_list({ session: "*", query: ["deployment", "rollback"], limit: 20 })
26
27
  history_list({ session: "codex:*", query: "migration", roles: ["tool"], since: "2026-10-01" })
27
28
  ```
28
29
 
29
- - A non-empty `query` is required (`missing_query`). Empty strings/lists and lists containing only empty entries do not count. Matching is literal, case-insensitive, and ORs a list of texts, as in one-session search.
30
+ - With a non-empty `query`, matching is literal, case-insensitive, and ORs a list of texts, as in one-session search. Local files are conservatively pre-filtered before full decoding: JSON escapes, Unicode case folding, generated event text and inherited Codex history must not lose hits. Uncertain cases use the full decoder.
31
+ - Without `query` (including empty strings/lists or lists containing only empty entries), return a recent-sessions overview. Sessions are considered newest-modified first, or oldest-modified first with `from: "oldest"`; loading stops once `limit` sessions (default 20) produce a representative. Apply `roles`, `since` and `until` before choosing each representative: without roles, prefer the first visible user event, falling back to the latest visible dialogue event or latest event of any role; with roles, choose the latest matching visible event. Sort the chosen representatives by event time, oldest first. There are no folded rows.
30
32
  - `before_seq` and `after_seq` refuse with `invalid_bounds`: seqs from different sessions cannot define a common range.
31
33
  - `history_read` refuses wildcard selectors with `invalid_session`; take a specific `session` and `seq` from a search hit instead.
32
- - Every role is searched, including tool arguments/output and context; `roles` can narrow this. There are no folded rows.
34
+ - With a query, every role is searched, including tool arguments/output and context; `roles` can narrow this. There are no folded rows.
33
35
  - `since` is inclusive and `until` exclusive. Time-bounded searches exclude events with no usable timestamp.
34
- - Files are discovered newest-modified first. Hits are merged by event time, oldest first, with a deterministic session/seq tie-break; untimed events sort before timed events. `limit` counts from the newest end by default, or the oldest with `from: "oldest"`. The complete text and structured result still share the 32 KiB budget, so a large hit can reduce the admitted page.
36
+ - Search hits are merged by event time, oldest first, with a deterministic session/seq tie-break; untimed events sort before timed events. For query searches, `limit` counts from the newest event end by default, or the oldest with `from: "oldest"`. The complete text and structured result still share the 32 KiB budget, so large previews can reduce the admitted page.
35
37
  - Each event carries its canonical `session`. `page_older` and `page_newer` are always null. Narrow by session pattern, query, roles or time rather than trying to page across per-session seqs.
36
38
 
37
39
  ## Local discovery and limits
@@ -39,11 +41,11 @@ history_list({ session: "codex:*", query: "migration", roles: ["tool"], since: "
39
41
  | Harness | Default source | Selection/decoding |
40
42
  | --- | --- | --- |
41
43
  | Pi | `~/.pi/agent/sessions/<workspace>/<timestamp>_<id>.jsonl` | Current session uses the native active branch. Offline current-format files follow persisted parent links from the last tree entry, preserving append seqs and inactive-branch holes. |
42
- | Claude | `~/.claude/projects/<project>/<id>.jsonl` | The current session still requires its live, confirmed append head. Offline files require a unique graph leaf (including logical compact links); multiple possible leaves refuse rather than choosing by append order. Only confirmed ancestors are exposed. |
44
+ | Claude | `~/.claude/projects/<project>/<id>.jsonl` | The current session still requires its live, confirmed append head. Offline files account for logical compact links, prefer non-attachment graph leaves when available, and select the last remaining leaf in transcript order. Only that leaf's confirmed ancestors are exposed; a graph with no leaves still refuses. |
43
45
  | Codex | `~/.codex/sessions/YYYY/MM/DD/rollout-...-<threadId>.jsonl(.zst)` | The same strict 0.160.1 rollout/lineage decoder as current-session history; compressed files need Node >=22.15. Root `session_id` is not a child thread ID. |
44
46
  | DSH | `ctx.sessionQuery.listSessions()` / `readSession(id)` | Available inside DSH only, over its live-preferred local session corpus. Other hosts cannot discover DSH files themselves. |
45
47
 
46
- Filesystem discovery does not follow directory symlinks or recurse into Claude subagent stores. Missing roots are empty. Repeated native files for one qualified ID produce one descriptor (newest modified); the current live binding wins over its on-disk descriptor. Discovery and decoding never mutate transcript bytes or modification times. Unsupported/corrupt or unreadable selected transcripts return `history_unavailable` naming the session; a wildcard search does not silently present partial results as complete. A readable Claude ancestry gap appears as an optional `notice` in cross-session page/read data and in rendered text; it stays outside event text and search/read offsets and counts against the output budget.
48
+ Filesystem discovery does not follow directory symlinks or recurse into Claude subagent stores. Missing roots are empty. Repeated native files for one qualified ID produce one descriptor (newest modified); the current live binding wins over its on-disk descriptor. Discovery and decoding never mutate transcript bytes or modification times. Unsupported/corrupt or unreadable selected transcripts return `history_unavailable` naming the session for single-session list/read calls. Wildcard searches and overviews skip individual sessions that cannot load; an empty wildcard result is not proof that an event never happened. A readable Claude ancestry gap appears as an optional `notice` in cross-session page/read data and in rendered text; it stays outside event text and search/read offsets and counts against the output budget.
47
49
 
48
50
  The default roots respect `PI_CODING_AGENT_DIR` (Pi agent directory), `CLAUDE_CONFIG_DIR` (Claude config directory), and `CODEX_HOME` (Codex home). For direct root overrides use absolute paths in `NOTESOUP_HISTORY_PI_ROOT`, `NOTESOUP_HISTORY_CLAUDE_ROOT`, and `NOTESOUP_HISTORY_CODEX_ROOT`; these name the **sessions**, **projects**, and **sessions** directories respectively, not notes storage. `NOTESOUP_HOME` only changes notes.
49
51
 
package/docs/skills.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Memory skill
4
4
 
5
- The package provides `/skill:memory`, a short self-contained guide to the notes and history tools: note addresses and notebooks, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; current-session history requires the documented main-session transcript path and a confirmed append head, while explicit `session` selectors use the local cross-harness corpus (offline Claude needs a unique graph leaf).
5
+ The package provides `/skill:memory`, a short self-contained guide to the notes and history tools: note addresses and notebooks, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; current-session history requires the documented main-session transcript path and a confirmed append head, while explicit `session` selectors use the local cross-harness corpus (offline Claude prefers non-attachment leaves, then the last leaf in transcript order).
6
6
 
7
7
  ## Dream
8
8
 
@@ -55,7 +55,7 @@ The suffix and presentation header are never part of `text`, search offsets or t
55
55
 
56
56
  The native adapter allocates seqs from session append order, selects the active branch and decodes facts. Shared history pairs calls and results without allocating a second transcript. A paired execution is addressed by its call seq. Its result's raw slot is not a public event address; list/search provide the canonical seq. Unpaired results remain independently addressable. Inactive-branch addresses are not readable.
57
57
 
58
- Seqs address events across the whole session, including earlier windows. With `session` omitted, list and read headers use `seq <seq> | <role>`; the boot window tree supplies per-window seq ranges for narrowing a list with `before_seq` and `after_seq`. With an explicit selector, returned events/read data carry canonical `session`, headers use `session <harness>:<id> | seq <seq> | <role>`, and all paging/expand/neighborhood recipes carry that same identity. Wildcard `history_list` requires `query`, forbids seq bounds, returns only hits across all roles and sets both paging recipes to null. See [cross-session history](history-sessions.md) for resolution, discovery and refusal rules.
58
+ Seqs address events across the whole session, including earlier windows. With `session` omitted, list and read headers use `seq <seq> | <role>`; the boot window tree supplies per-window seq ranges for narrowing a list with `before_seq` and `after_seq`. With an explicit selector, returned events/read data carry canonical `session`, headers use `session <harness>:<id> | seq <seq> | <role>`, and all paging/expand/neighborhood recipes carry that same identity. Wildcard `history_list` forbids seq bounds and sets both paging recipes to null. With `query`, it returns only hits across all roles; without a non-empty query, it returns one representative event per recent session, stopping once `limit` sessions have produced an item. Individual unreadable sessions are skipped only in wildcard calls. See [cross-session history](history-sessions.md) for resolution, discovery and refusal rules.
59
59
 
60
60
  Tool events expose `tool`, `tool_status`, and, when recorded, `output_truncated` and `full_output_path`; a truncated run is named even when the host recorded no path, and the full text path is named only when it exists. `history_read` also reports `nested_calls`; a page row does not. Full arguments and nested-call records live only in the searchable/readable document, avoiding a second structured copy on every read.
61
61
 
@@ -67,7 +67,7 @@ Pi's nested records contain child ID, name, optional arguments, status, timing a
67
67
 
68
68
  One selection determines the structured result and its text. Both complete representations must fit the 32 KiB output budget, including metadata, cursor and rendered notice. A programmatic caller does not receive an unbounded hidden payload beside a truncated textual one. History operations accept an optional pure text wrapper from the host: selection and read-window checks measure that wrapper around the shared rendering, and the caller must apply the same wrapper at delivery. Host prose stays in its plugin; no final clipping or separate query is involved.
69
69
 
70
- History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a call without roles or a non-empty query folds tool/context runs. Omitted queries, empty strings and empty lists all disable search filtering; empty entries in a query list are ignored. Without a query, notes search returns scoped notes with empty `matches`, not every body line. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
70
+ History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a single-session call without roles or a non-empty query folds tool/context runs. Omitted queries, empty strings and empty lists all disable search filtering; empty entries in a query list are ignored. Without a query, notes search returns scoped notes with empty `matches`, not every body line. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
71
71
 
72
72
  A note read reports unrecognized frontmatter under `metadata.extra`; a value too large to carry, or past the verbatim budget, is named in place as `[omitted: too large]` under its key rather than delivered in part, and the value itself stays in the note file. A rename receipt uses `address` for the destination and `rename_from` for the source; it has no duplicate `rename_to` field.
73
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.55.0",
3
+ "version": "0.55.1",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.55.0",
3
+ "version": "0.55.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -9496,14 +9496,20 @@ function selectPage(projection, params, fits, maxChars) {
9496
9496
  return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
9497
9497
  }
9498
9498
  function corpusSelection(params) {
9499
- const scoped = resolveSelection(params);
9500
- if (!scoped.ok) return scoped;
9501
- if (scoped.data.query === void 0) return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
9502
9499
  if (params.before_seq !== void 0 || params.after_seq !== void 0) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
9503
- return scoped;
9500
+ return resolveSelection(params);
9501
+ }
9502
+ function sessionRepresentative(projection, scoped) {
9503
+ const events = filteredItems(projection, scoped, false).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
9504
+ if (scoped.roles) return events.at(-1);
9505
+ return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9504
9506
  }
9505
9507
  function selectCorpusPage(sessions, scoped, fits, maxChars) {
9506
- const candidates = sessions.flatMap(({ session, projection }) => prepareSelection(projection, { ...scoped, session }).candidates);
9508
+ const candidates = sessions.flatMap(({ session, projection }) => {
9509
+ if (scoped.query !== void 0) return prepareSelection(projection, { ...scoped, session }).candidates;
9510
+ const event = sessionRepresentative(projection, scoped);
9511
+ return event === void 0 ? [] : [{ session, event }];
9512
+ });
9507
9513
  const time = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
9508
9514
  candidates.sort((a, b) => time(a.event) - time(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq);
9509
9515
  return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
@@ -9573,9 +9579,11 @@ async function resolveSession(corpus, selector) {
9573
9579
  if (matches.length > 1) 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.`);
9574
9580
  return success(matches[0]);
9575
9581
  }
9576
- async function loadHistorySession(session) {
9582
+ async function loadHistorySession(session, queries) {
9577
9583
  try {
9578
- return success(await session.load());
9584
+ const data = await session.load(queries);
9585
+ if (data === void 0 && !queries?.length) throw new Error("Session returned no history");
9586
+ return success(data);
9579
9587
  } catch (error) {
9580
9588
  return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
9581
9589
  }
@@ -9639,7 +9647,7 @@ function renderRead(data) {
9639
9647
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9640
9648
  }
9641
9649
  var plainText = (text) => text;
9642
- var sessionParameter = typebox_exports.Optional(typebox_exports.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." }));
9650
+ var sessionParameter = typebox_exports.Optional(typebox_exports.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." }));
9643
9651
  var historyListParameters = typebox_exports.Object({
9644
9652
  session: sessionParameter,
9645
9653
  query: typebox_exports.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.")),
@@ -9655,7 +9663,7 @@ var historyListParameters = typebox_exports.Object({
9655
9663
  var historyList = {
9656
9664
  name: "history_list",
9657
9665
  label: "History list items",
9658
- 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`.",
9666
+ 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`.",
9659
9667
  parameters: historyListParameters,
9660
9668
  outputSchema: resultSchema(HistoryPageSchema),
9661
9669
  async execute(params, context2, wrapText = plainText) {
@@ -9670,13 +9678,17 @@ var historyList = {
9670
9678
  if (!scoped.ok) return scoped;
9671
9679
  if (corpus === void 0) return failure("unknown_session", "This host supplied no cross-session history corpus.");
9672
9680
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
9681
+ const queries = Array.isArray(scoped.data.query) ? scoped.data.query : void 0;
9682
+ if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9673
9683
  const loaded2 = [];
9674
9684
  const notices = [];
9675
9685
  for (const session of sessions) {
9676
- const result3 = await loadHistorySession(session);
9677
- if (!result3.ok) return result3;
9686
+ const result3 = await loadHistorySession(session, queries);
9687
+ if (!result3.ok || !result3.data) continue;
9688
+ if (!queries && !sessionRepresentative(result3.data.projection, scoped.data)) continue;
9678
9689
  loaded2.push({ session: sessionIdentity(session), projection: result3.data.projection });
9679
9690
  if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
9691
+ if (!queries && loaded2.length >= Math.max(1, params.limit ?? 20)) break;
9680
9692
  }
9681
9693
  const notice2 = notices.length ? { notice: notices.join("") } : {};
9682
9694
  const result2 = selectCorpusPage(loaded2, scoped.data, (page) => fits({ ...page, ...notice2 }), maxChars);
@@ -10138,7 +10150,10 @@ function claudeHistoryFromJsonl(text, source) {
10138
10150
  function offlineClaudeHead(text) {
10139
10151
  const latest = /* @__PURE__ */ new Map();
10140
10152
  for (const row of rowsOf(text)) {
10141
- if (MESSAGE_TYPES.has(row.type)) latest.set(requiredString(row.uuid, "uuid"), row);
10153
+ if (!MESSAGE_TYPES.has(row.type)) continue;
10154
+ const uuid = requiredString(row.uuid, "uuid");
10155
+ latest.delete(uuid);
10156
+ latest.set(uuid, row);
10142
10157
  }
10143
10158
  const ancestors = /* @__PURE__ */ new Set();
10144
10159
  for (const row of latest.values()) {
@@ -10161,8 +10176,10 @@ function offlineClaudeHead(text) {
10161
10176
  }
10162
10177
  }
10163
10178
  const leaves = [...latest.keys()].filter((uuid) => !ancestors.has(uuid));
10164
- if (leaves.length !== 1) throw new Error(`Offline Claude transcript has ${leaves.length} possible heads; no confirmed unique leaf (refusing to guess a selected branch)`);
10165
- return leaves[0];
10179
+ if (leaves.length === 0) throw new Error("Offline Claude transcript has 0 possible heads");
10180
+ const nonAttachments = leaves.filter((uuid) => latest.get(uuid).type !== "attachment");
10181
+ const candidates = nonAttachments.length ? nonAttachments : leaves;
10182
+ return candidates.at(-1);
10166
10183
  }
10167
10184
  async function readClaudeHistory(source) {
10168
10185
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
@@ -10312,7 +10329,7 @@ async function referencedPath(home, rolloutId) {
10312
10329
  if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
10313
10330
  return matches[0];
10314
10331
  }
10315
- async function decodedBytes(path, remaining) {
10332
+ async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
10316
10333
  const info = await stat(path);
10317
10334
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10318
10335
  const bytes = await readFile3(path);
@@ -10331,7 +10348,7 @@ async function readCodexTranscript(source) {
10331
10348
  while (true) {
10332
10349
  if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
10333
10350
  seen.add(path);
10334
- const bytes = await decodedBytes(path, remaining);
10351
+ const bytes = await readCodexTranscriptBytes(path, remaining);
10335
10352
  remaining -= bytes.length;
10336
10353
  const segment = segmentFromBytes(bytes, cutoff);
10337
10354
  if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
@@ -10632,6 +10649,29 @@ async function filesAt(root, depth) {
10632
10649
  }
10633
10650
  return paths;
10634
10651
  }
10652
+ var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10653
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
10654
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
10655
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
10656
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
10657
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
10658
+ function escapeRegExp(value) {
10659
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10660
+ }
10661
+ function mayMatch(text, queries, codex) {
10662
+ if (codex && text.includes('"history_base"')) return true;
10663
+ const unescaped = text.includes("\\u") ? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))) : text;
10664
+ return queries.some((query) => {
10665
+ const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
10666
+ return tokens === null || tokens.every((token) => {
10667
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
10668
+ return parts.every((part) => {
10669
+ const literal = new RegExp(escapeRegExp(part), "iu");
10670
+ return literal.test(unescaped) || unescaped !== text && literal.test(text) || literal.test(PRESENTATION);
10671
+ });
10672
+ });
10673
+ });
10674
+ }
10635
10675
  async function localSessions(harness, root) {
10636
10676
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
10637
10677
  const sessions = [];
@@ -10650,9 +10690,11 @@ async function localSessions(harness, root) {
10650
10690
  harness,
10651
10691
  id: id2,
10652
10692
  modifiedAt,
10653
- async load() {
10693
+ async load(queries) {
10694
+ if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
10695
+ const text = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile4(path, "utf8");
10696
+ if (queries?.length && !mayMatch(text, queries, harness === "codex")) return void 0;
10654
10697
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
10655
- const text = await readFile4(path, "utf8");
10656
10698
  if (harness === "pi") return { projection: piHistoryFromJsonl(text, id2) };
10657
10699
  const projection = claudeHistoryFromJsonl(text, { sessionId: id2, headUuid: offlineClaudeHead(text) });
10658
10700
  const missing = projection.missingAncestors;
@@ -44,9 +44,11 @@ For list/search, omit `glob` or use the collection alias `@default` for this ses
44
44
  - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
45
45
  - **An earlier window**: use its seq range from the boot window tree with `history_list`'s `before_seq` / `after_seq` bounds, or search for a remembered phrase.
46
46
  - **Another session**: pass `session: "<id-or-prefix>"` or `"pi:<id>"`, `"claude:<id>"`, `"codex:<id>"`, `"dsh:<id>"`. An unqualified selector checks this harness first. If ambiguous, use a longer ID or a harness prefix; never pick a candidate blindly.
47
- - **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard requires a non-empty query; it cannot use `before_seq`/`after_seq` or `history_read`. Results cover every role unless `roles` narrows them, are chronological, and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
47
+ - **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard cannot use `before_seq`/`after_seq` or `history_read`. Query results cover every role unless `roles` narrows them, are chronological, and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
48
48
 
49
- Seqs are stable **within a session**. When a hit carries `session`, copy it together with `seq` into `history_read` and save both in your note. The paging/expand/neighborhood recipes already preserve the resolved session. Omit `session` only when you mean your current host session. An unreadable or unsupported local transcript refuses explicitly; do not treat that as proof the remembered event never happened.
49
+ - **Recent sessions, no remembered phrase**: `history_list({ session: "*" })` returns one representative event per session, preferring its first visible user prompt, up to `limit` (default 20). Sessions are chosen newest-modified first (`from: "oldest"` reverses that), then results are sorted chronologically. Empty queries also browse. Role/time filters apply before choosing representatives; with `roles`, the latest matching event represents each session. No paging cursors.
50
+
51
+ Seqs are stable **within a session**. When a hit carries `session`, copy it together with `seq` into `history_read` and save both in your note. The paging/expand/neighborhood recipes already preserve the resolved session. Omit `session` only when you mean your current host session. A single unreadable or unsupported local transcript refuses explicitly; wildcards skip individual sessions that cannot load. An empty result is not proof the remembered event never happened.
50
52
 
51
53
  ## Saving recovery state
52
54