notesoup 0.59.1 → 0.59.2

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.
@@ -94,8 +94,8 @@ export async function dispatch(request, historyOptions = {}) {
94
94
  const id = identity(value.identity);
95
95
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
96
96
  const tool = value.tool;
97
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId), { waitForHead: true });
97
98
  if (value.params.session !== undefined) {
98
- const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
99
99
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
100
100
  const projection = await current();
101
101
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
@@ -103,7 +103,7 @@ export async function dispatch(request, historyOptions = {}) {
103
103
  } } });
104
104
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
105
105
  }
106
- const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
106
+ const projection = await current();
107
107
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
108
108
  const wrapText = (text) => notice + text;
109
109
  const params = value.params;
@@ -15,4 +15,6 @@ export declare function claudeHistoryFromJsonl(text: string, source: Omit<Claude
15
15
  export declare function offlineClaudeHead(text: string): string;
16
16
  /** Select an offline head and build its projection from the same decoded records. */
17
17
  export declare function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection;
18
- export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
18
+ export declare function readClaudeHistory(source: ClaudeHistorySource, { waitForHead }?: {
19
+ waitForHead?: boolean | undefined;
20
+ }): Promise<ClaudeHistoryProjection>;
@@ -1,7 +1,11 @@
1
1
  /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { isDeepStrictEqual } from "node:util";
4
5
  import { contentText, projectHistory } from "./history.js";
6
+ class UnpersistedClaudeHead extends Error {
7
+ constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
8
+ }
5
9
  const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
6
10
  const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
7
11
  function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
@@ -199,7 +203,7 @@ function claudeHistoryFromRows(rows, source) {
199
203
  if (!source.headUuid)
200
204
  throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
201
205
  if (!nodes.has(source.headUuid))
202
- throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
206
+ throw new UnpersistedClaudeHead();
203
207
  // The inference tree uses the latest rewritten parents. At a compact boundary the logical
204
208
  // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
205
209
  const selected = new Set(), visited = new Set(), visiting = new Set();
@@ -345,8 +349,40 @@ export function offlineClaudeHistoryFromJsonl(text, sessionId) {
345
349
  const rows = rowsOf(text);
346
350
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
347
351
  }
348
- export async function readClaudeHistory(source) {
352
+ export async function readClaudeHistory(source, { waitForHead = false } = {}) {
349
353
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
350
354
  throw new Error("Claude history transcript_path is unavailable");
351
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
355
+ const snapshot = { ...source };
356
+ const read = async () => claudeHistoryFromJsonl(await readFile(snapshot.transcriptPath, "utf8"), snapshot);
357
+ if (!waitForHead || !snapshot.headUuid)
358
+ return read();
359
+ const revision = async () => {
360
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot.transcriptPath, { bigint: true });
361
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
362
+ };
363
+ let seen = await revision();
364
+ try {
365
+ return await read();
366
+ }
367
+ catch (error) {
368
+ if (!(error instanceof UnpersistedClaudeHead))
369
+ throw error;
370
+ // A kept append can reach the tool before its disk write. Only retry that same
371
+ // head, and only reparse on file changes. Never fall back to an offline leaf.
372
+ for (const delay of [50, 100, 200, 300, 350]) {
373
+ await sleep(delay);
374
+ const current = await revision();
375
+ if (current === seen)
376
+ continue;
377
+ seen = current;
378
+ try {
379
+ return await read();
380
+ }
381
+ catch (retry) {
382
+ if (!(retry instanceof UnpersistedClaudeHead))
383
+ throw retry;
384
+ }
385
+ }
386
+ throw error;
387
+ }
352
388
  }
@@ -1,4 +1,4 @@
1
- export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
1
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean, stopOnHit?: boolean) => Promise<boolean>;
2
2
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
3
3
  export declare function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter;
4
4
  /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
@@ -24,7 +24,7 @@ export function createHistoryPrefilter(queries) {
24
24
  }));
25
25
  // No safe tokens (or generated text alone) cannot prove a miss.
26
26
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
27
- return async (chunks, codex = false) => {
27
+ return async (chunks, codex = false, stopOnHit = false) => {
28
28
  const decoder = new StringDecoder("utf8");
29
29
  const seen = alternatives.map((tokens) => tokens.map(() => false));
30
30
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -59,9 +59,12 @@ export function createHistoryPrefilter(queries) {
59
59
  rawTail = raw.slice(-overlap);
60
60
  normalizedTail = normalized.slice(-overlap);
61
61
  };
62
- for await (const chunk of chunks)
62
+ for await (const chunk of chunks) {
63
63
  if (!possible)
64
64
  scan(decoder.write(chunk));
65
+ if (possible && stopOnHit)
66
+ return true;
67
+ }
65
68
  if (!possible)
66
69
  scan(decoder.end(), true);
67
70
  return possible;
@@ -69,13 +72,15 @@ export function createHistoryPrefilter(queries) {
69
72
  }
70
73
  /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
71
74
  export async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
72
- if (codex) {
73
- const info = await stat(path);
74
- if (!info.isFile() || info.size > maxBytes)
75
- throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
76
- }
77
- // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
78
- const compressed = codex && path.endsWith(".jsonl.zst");
75
+ // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
76
+ // hit. Don't drain a potentially huge file just to read it from the beginning again.
77
+ if (!codex)
78
+ return prefilter(createReadStream(path), false, true);
79
+ const info = await stat(path);
80
+ if (!info.isFile() || info.size > maxBytes)
81
+ throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
82
+ // Native Codex compression is zstd; scan through EOF to enforce the decoded size limit.
83
+ const compressed = path.endsWith(".jsonl.zst");
79
84
  if (compressed && typeof zlib.createZstdDecompress !== "function")
80
85
  throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
81
86
  const input = createReadStream(path);
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import test from "node:test";
@@ -50,6 +51,27 @@ test("Claude helper resolves foreign history without requiring a current append
50
51
  assert.equal(invalid.ok, false);
51
52
  assert.match(invalid.text, /invalid_session/);
52
53
  });
54
+ test("Claude history tools wait for the confirmed append, never substitute a persisted sibling", async (t) => {
55
+ const home = mkdtempSync(join(tmpdir(), "claude-history-lag-"));
56
+ t.after(() => rmSync(home, { recursive: true, force: true }));
57
+ const transcriptPath = join(home, "transcript.jsonl");
58
+ const rows = [user("root", null, "start"), assistant("sibling", "root", "sibling-only text")];
59
+ writeFileSync(transcriptPath, jsonl(rows));
60
+ const identity = { home, sessionId, cwd: home, agent: "claude", model: "claude" };
61
+ const history = { sessionId, transcriptPath, headUuid: "active" };
62
+ const options = { roots: { pi: null, claude: null, codex: null }, env: {} };
63
+ const invoke = (tool, params) => dispatch({ op: "tool", tool, params, identity, history }, options);
64
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /active head is not persisted/);
65
+ const delayedWrite = sleep(120).then(() => writeFileSync(transcriptPath, jsonl([...rows, assistant("active", "root", "confirmed active text")])));
66
+ const [list, read] = await Promise.all([invoke("history_list", {}), invoke("history_read", { session: `claude:${sessionId}`, seq: 3 }), delayedWrite]);
67
+ for (const outcome of [list, read]) {
68
+ assert.ok(outcome.ok, outcome.text);
69
+ assert.match(outcome.text, /confirmed active text/);
70
+ assert.doesNotMatch(outcome.text, /sibling-only text/);
71
+ }
72
+ history.headUuid = "never-written";
73
+ await assert.rejects(invoke("history_list", {}), /active head is not persisted/);
74
+ });
53
75
  test("Claude append and result arrival preserve call addresses and use the shared paired read", async () => {
54
76
  const rows = [user("u", null, "run tools"), assistant("a", "u", [{ type: "thinking", thinking: "private thought" }, { type: "text", text: "working" }, call("one"), call("two")])];
55
77
  const pending = project(rows, "a");
@@ -71,7 +71,7 @@ async function loadHookModule(t) {
71
71
  if (typeof matcherOrHandler === "function")
72
72
  on(event, matcherOrHandler);
73
73
  else
74
- on(event, ($, e, next) => Object.entries(matcherOrHandler).every(([key, value]) => e[key] === value) ? handler($, e, next) : next(e));
74
+ on(event, ($, e, next) => Object.entries(matcherOrHandler).every(([key, value]) => Array.isArray(value) ? value.includes(e[key]) : e[key] === value) ? handler($, e, next) : next(e));
75
75
  }) };
76
76
  }
77
77
  /** An engine that answers the hook by running the real helper against a throwaway notes home. */
@@ -1824,6 +1824,13 @@ test("Claude history keeps classic transcript_path across startup, confirms appe
1824
1824
  const handlers = new Map();
1825
1825
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1826
1826
  const invoke = (name, event = {}, result = {}) => handlers.get(name)(host, event, async () => result);
1827
+ const budgets = new Map();
1828
+ const run = host.process.run;
1829
+ host.process.run = (argv, init) => {
1830
+ const request = JSON.parse(init.stdin);
1831
+ budgets.set(request.tool ?? request.op, init?.timeoutMs);
1832
+ return run(argv, init);
1833
+ };
1827
1834
  const transcriptPath = join(home, "transcript.jsonl");
1828
1835
  const root = { type: "user", uuid: "root", parentUuid: null, sessionId: "hook-session", message: { role: "user", content: "old request" } };
1829
1836
  const attachment = { type: "attachment", uuid: "startup", parentUuid: "root", sessionId: "hook-session", rendered: [{ content: [{ type: "text", text: "startup injection" }] }] };
@@ -1858,6 +1865,11 @@ test("Claude history keeps classic transcript_path across startup, confirms appe
1858
1865
  const switched = await call("history_list");
1859
1866
  assert.match(switched.result, /another branch/);
1860
1867
  assert.doesNotMatch(switched.result, /startup injection/);
1868
+ await call("notes_list");
1869
+ assert.equal(budgets.get("history_list"), 120_000);
1870
+ assert.equal(budgets.get("history_read"), 120_000);
1871
+ assert.equal(budgets.get("notes_list"), 10_000);
1872
+ assert.equal(budgets.get("history_state"), 10_000);
1861
1873
  });
1862
1874
  test("Claude history without a documented path refuses honestly and keeps notes usable", async (t) => {
1863
1875
  const home = mkdtempSync(join(tmpdir(), "claude-no-history-path-"));
@@ -35,6 +35,11 @@ test("only EOF proves a miss, while errors after tokens or a fallback still prop
35
35
  }
36
36
  assert.equal(await createHistoryPrefilter(["needle"])(late()), true);
37
37
  assert.equal(finished, true);
38
+ finished = false;
39
+ assert.equal(await createHistoryPrefilter(["needle"])(late(), false, true), true);
40
+ assert.equal(finished, false, "a plain-file hit leaves the rest to the strict decoder");
41
+ assert.equal(await createHistoryPrefilter(["absentword"])(late(), false, true), false);
42
+ assert.equal(finished, true, "even the early-hit path must read to EOF to prove a miss");
38
43
  async function* broken() { yield Buffer.from("needle"); throw new Error("read failed"); }
39
44
  for (const queries of [["absentword"], ["needle"], ["😀"]])
40
45
  await assert.rejects(createHistoryPrefilter(queries)(broken()), /read failed/);
@@ -34,7 +34,9 @@ The notes tools also serve subagent calls, using the same session identity and s
34
34
 
35
35
  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`.
36
36
 
37
- 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.
37
+ 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. History tools wait briefly (up to one second of polling) for the exact confirmed UUID, retrying the read only when the file changes. If it still isn't on disk they refuse rather than switch branches. The internal `history_state` check for reset bookkeeping does not wait. Session end clears the binding; a new classic start rebinds it.
38
+
39
+ History tools have a two-minute helper deadline so a cold search can scan large archives. Notes, boot and reset helper calls keep the ten-second deadline.
38
40
 
39
41
  Seqs are allocated over first-occurrence persisted append order, before active-branch filtering: one address per logical message/attachment/notice and additional addresses for each tool use/result. Repeated UUID records do not allocate again. List pages skip empty user/assistant envelopes even with explicit roles, so tool-only and thinking-only rows do not crowd out dialogue; direct reads preserve those addresses and explicitly say when no visible text was recorded. Results pair by `tool_use_id`; pending calls remain unfinished, and a paired result's seq redirects to its call. Only text blocks and recorded attachment renderings become visible text; thinking and raw, unrendered attachment payloads are never exposed. Record types other than user, assistant, system and attachment are ignored, including future metadata, without allocating addresses or exposing payloads. If the selected branch requires a skipped record as an ancestor, that UUID is an ancestry gap, not a visible metadata event. Invalid supported message/block schemas, conflicting duplicates, session/sidechain mismatches, cycles and malformed committed JSONL lines still refuse explicitly. An incomplete final unterminated write is tolerated. Valid forward parent references are resolved after reading the snapshot, without reallocating addresses.
40
42
 
@@ -27,7 +27,7 @@ history_list({ session: "*", query: ["deployment", "rollback"], limit: 20 })
27
27
  history_list({ session: "codex:*", query: "migration", roles: ["tool"], since: "2026-10-01" })
28
28
  ```
29
29
 
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.
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. A possible hit in a Pi or Claude file stops the prefilter early: the strict decoder will read and validate the file next.
31
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.
32
32
  - `before_seq` and `after_seq` refuse with `invalid_bounds`: seqs from different sessions cannot define a common range.
33
33
  - `history_read` refuses wildcard selectors with `invalid_session`; take a specific `session` and `seq` from a search hit instead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.59.1",
3
+ "version": "0.59.2",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -9955,7 +9955,7 @@ var historyRead = {
9955
9955
  };
9956
9956
 
9957
9957
  // src/history/local.ts
9958
- import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
9958
+ import { readdir as readdir4, readFile as readFile4, stat as stat5 } from "node:fs/promises";
9959
9959
  import { homedir as homedir2 } from "node:os";
9960
9960
  import { join as join6 } from "node:path";
9961
9961
 
@@ -10124,8 +10124,14 @@ function piHistoryFromJsonl(text, sessionId) {
10124
10124
  }
10125
10125
 
10126
10126
  // src/history/claude.ts
10127
- import { readFile as readFile2 } from "node:fs/promises";
10127
+ import { readFile as readFile2, stat } from "node:fs/promises";
10128
+ import { setTimeout as sleep } from "node:timers/promises";
10128
10129
  import { isDeepStrictEqual } from "node:util";
10130
+ var UnpersistedClaudeHead = class extends Error {
10131
+ constructor() {
10132
+ super("Claude history active head is not persisted yet; retry after the transcript write");
10133
+ }
10134
+ };
10129
10135
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
10130
10136
  var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
10131
10137
  function object(value) {
@@ -10271,7 +10277,7 @@ function claudeHistoryFromRows(rows, source) {
10271
10277
  return version.position;
10272
10278
  }
10273
10279
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
10274
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
10280
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
10275
10281
  const selected = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), visiting = /* @__PURE__ */ new Set();
10276
10282
  const stack = [{ uuid: source.headUuid, historical: false }];
10277
10283
  while (stack.length > 0) {
@@ -10380,13 +10386,37 @@ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10380
10386
  const rows = rowsOf(text);
10381
10387
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10382
10388
  }
10383
- async function readClaudeHistory(source) {
10389
+ async function readClaudeHistory(source, { waitForHead = false } = {}) {
10384
10390
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10385
- return claudeHistoryFromJsonl(await readFile2(source.transcriptPath, "utf8"), source);
10391
+ const snapshot2 = { ...source };
10392
+ const read = async () => claudeHistoryFromJsonl(await readFile2(snapshot2.transcriptPath, "utf8"), snapshot2);
10393
+ if (!waitForHead || !snapshot2.headUuid) return read();
10394
+ const revision = async () => {
10395
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot2.transcriptPath, { bigint: true });
10396
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
10397
+ };
10398
+ let seen = await revision();
10399
+ try {
10400
+ return await read();
10401
+ } catch (error) {
10402
+ if (!(error instanceof UnpersistedClaudeHead)) throw error;
10403
+ for (const delay of [50, 100, 200, 300, 350]) {
10404
+ await sleep(delay);
10405
+ const current = await revision();
10406
+ if (current === seen) continue;
10407
+ seen = current;
10408
+ try {
10409
+ return await read();
10410
+ } catch (retry) {
10411
+ if (!(retry instanceof UnpersistedClaudeHead)) throw retry;
10412
+ }
10413
+ }
10414
+ throw error;
10415
+ }
10386
10416
  }
10387
10417
 
10388
10418
  // src/history/codex-transcript.ts
10389
- import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "node:fs/promises";
10419
+ import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
10390
10420
  import { basename as basename2, dirname as dirname3, join as join4, relative, sep as sep2 } from "node:path";
10391
10421
  import * as zlib from "node:zlib";
10392
10422
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -10548,7 +10578,7 @@ function createCodexTranscriptReader() {
10548
10578
  let pending = cache.get(canonical);
10549
10579
  if (!pending) {
10550
10580
  pending = (async () => {
10551
- const info = await stat(canonical);
10581
+ const info = await stat2(canonical);
10552
10582
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10553
10583
  const stored = await readFile3(canonical);
10554
10584
  if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
@@ -10852,7 +10882,7 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10852
10882
 
10853
10883
  // src/history/prefilter.ts
10854
10884
  import { createReadStream } from "node:fs";
10855
- import { stat as stat2 } from "node:fs/promises";
10885
+ import { stat as stat3 } from "node:fs/promises";
10856
10886
  import { pipeline } from "node:stream/promises";
10857
10887
  import { StringDecoder } from "node:string_decoder";
10858
10888
  import * as zlib2 from "node:zlib";
@@ -10873,7 +10903,7 @@ function createHistoryPrefilter(queries) {
10873
10903
  }).filter((literal) => !literal.test(PRESENTATION));
10874
10904
  }));
10875
10905
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10876
- return async (chunks, codex = false) => {
10906
+ return async (chunks, codex = false, stopOnHit = false) => {
10877
10907
  const decoder = new StringDecoder("utf8");
10878
10908
  const seen = alternatives.map((tokens) => tokens.map(() => false));
10879
10909
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -10901,17 +10931,19 @@ function createHistoryPrefilter(queries) {
10901
10931
  rawTail = raw.slice(-overlap);
10902
10932
  normalizedTail = normalized.slice(-overlap);
10903
10933
  };
10904
- for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
10934
+ for await (const chunk of chunks) {
10935
+ if (!possible) scan(decoder.write(chunk));
10936
+ if (possible && stopOnHit) return true;
10937
+ }
10905
10938
  if (!possible) scan(decoder.end(), true);
10906
10939
  return possible;
10907
10940
  };
10908
10941
  }
10909
10942
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10910
- if (codex) {
10911
- const info = await stat2(path);
10912
- if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10913
- }
10914
- const compressed = codex && path.endsWith(".jsonl.zst");
10943
+ if (!codex) return prefilter(createReadStream(path), false, true);
10944
+ const info = await stat3(path);
10945
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10946
+ const compressed = path.endsWith(".jsonl.zst");
10915
10947
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10916
10948
  const input = createReadStream(path);
10917
10949
  const consume = async (chunks) => {
@@ -10930,7 +10962,7 @@ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = co
10930
10962
 
10931
10963
  // src/history/summary-cache.ts
10932
10964
  import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10933
- import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10965
+ import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10934
10966
  import { homedir } from "node:os";
10935
10967
  import { join as join5 } from "node:path";
10936
10968
  var VERSION = "strict-representative-v1";
@@ -10979,7 +11011,7 @@ function historySummaryCacheRoot(home = homedir(), env = process.env, platform =
10979
11011
  return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
10980
11012
  }
10981
11013
  async function fingerprint(path) {
10982
- const info = await stat3(path, { bigint: true });
11014
+ const info = await stat4(path, { bigint: true });
10983
11015
  if (!info.isFile()) throw new Error("Not a regular transcript file");
10984
11016
  return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
10985
11017
  }
@@ -11084,7 +11116,7 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11084
11116
  if (!id2) continue;
11085
11117
  let modifiedAt;
11086
11118
  try {
11087
- modifiedAt = (await stat4(path)).mtimeMs;
11119
+ modifiedAt = (await stat5(path)).mtimeMs;
11088
11120
  } catch (error) {
11089
11121
  if (error.code === "ENOENT") continue;
11090
11122
  throw error;
@@ -11589,8 +11621,8 @@ async function dispatch(request, historyOptions = {}) {
11589
11621
  const id2 = identity(value.identity);
11590
11622
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
11591
11623
  const tool = value.tool;
11624
+ const current = () => readClaudeHistory(historySource(value.history, id2.sessionId), { waitForHead: true });
11592
11625
  if (value.params.session !== void 0) {
11593
- const current = () => readClaudeHistory(historySource(value.history, id2.sessionId));
11594
11626
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id2.sessionId, async load() {
11595
11627
  const projection2 = await current();
11596
11628
  const notice2 = claudeHistoryGapNotice(projection2.missingAncestors);
@@ -11598,7 +11630,7 @@ async function dispatch(request, historyOptions = {}) {
11598
11630
  } } });
11599
11631
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
11600
11632
  }
11601
- const projection = await readClaudeHistory(historySource(value.history, id2.sessionId));
11633
+ const projection = await current();
11602
11634
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
11603
11635
  const wrapText = (text) => notice + text;
11604
11636
  const params = value.params;
@@ -3,6 +3,8 @@ import type { EngineInterface, On, ProcessRunResult, ToolCallInput, ToolCallResu
3
3
  const PREFIX = "mcp__notesoup__"
4
4
  const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
5
5
  const TIMEOUT_MS = 10_000
6
+ // A cold history query can scan gigabytes of transcripts; notes and reset plumbing should fail fast.
7
+ const HISTORY_TIMEOUT_MS = 120_000
6
8
  const OUTPUT_LIMIT = 1024 * 1024
7
9
 
8
10
  type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
@@ -322,10 +324,10 @@ function decode(result: ProcessRunResult): { ok: true; result: unknown } | { ok:
322
324
  return { ok: false, error: typeof value.error === "string" ? value.error : "helper returned an invalid error" }
323
325
  } catch { return { ok: false, error: "helper returned invalid JSON" } }
324
326
  }
325
- async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown) {
327
+ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown, timeoutMs = TIMEOUT_MS) {
326
328
  // A session may still name a removed worktree. Project identity travels in stdin;
327
329
  // launch from the plugin directory so removing that worktree cannot prevent spawn.
328
- try { return decode(await $.process.run(["node", HELPER], { cwd: import.meta.dir, stdin: `${JSON.stringify(request)}\n`, timeoutMs: TIMEOUT_MS })) }
330
+ try { return decode(await $.process.run(["node", HELPER], { cwd: import.meta.dir, stdin: `${JSON.stringify(request)}\n`, timeoutMs })) }
329
331
  // The host's rejection is the only diagnosis there is: it carries the spawn failure's own
330
332
  // reason (`timed out after …`), which a bare phrase would throw away.
331
333
  catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
@@ -523,10 +525,9 @@ export function register(on: On) {
523
525
  }
524
526
  return result
525
527
  })
526
- on("command.run", async ($, e, next) => {
528
+ on("command.run", { command: ["notesoup", "empty", "fresh-window"] }, async ($, e, next) => {
527
529
  if (state.disabled) return next(e)
528
530
  if (e.command === "notesoup") return capCommand($, state, e.args)
529
- if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
530
531
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
531
532
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
532
533
  const first = state.flow.requestReset()
@@ -619,8 +620,9 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
619
620
  if (state.flow.requestReset({ lastWord, terminate: terminate === true })) state.continuation = undefined
620
621
  return { result: `Brain reset requested. This tool batch will finish, then the turn stops before its next model request unless it has new user input to handle. Your notes and sticky note survive the reset.${state.flow.request!.resume ? " You will continue in a fresh window after the reset." : " No automatic continuation will be submitted."}` }
621
622
  }
622
- if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
623
- const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
623
+ const history = name === "history_list" || name === "history_read"
624
+ if (history && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
625
+ const result = await run($, { op: "tool", tool: name, params, identity, history: state.history }, history ? HISTORY_TIMEOUT_MS : TIMEOUT_MS)
624
626
  if (!result.ok) return errorResult(result.error)
625
627
  const outcome = toolResultOf(result.result)
626
628
  if (!outcome) return errorResult("helper returned an invalid tool result")
@@ -101,8 +101,8 @@ export async function dispatch(request: unknown, historyOptions: Pick<LocalHisto
101
101
  const id = identity(value.identity as ClaudeIdentityInput);
102
102
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
103
103
  const tool = value.tool as keyof typeof HISTORY_OPERATIONS;
104
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId), { waitForHead: true });
104
105
  if ((value.params as { session?: string }).session !== undefined) {
105
- const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
106
106
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
107
107
  const projection = await current();
108
108
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
@@ -110,7 +110,7 @@ export async function dispatch(request: unknown, historyOptions: Pick<LocalHisto
110
110
  } } });
111
111
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
112
112
  }
113
- const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
113
+ const projection = await current();
114
114
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
115
115
  const wrapText: HistoryTextWrapper = (text) => notice + text;
116
116
  const params = value.params;
@@ -27684,6 +27684,11 @@ function piHistoryFromJsonl(text2, sessionId) {
27684
27684
 
27685
27685
  // src/history/claude.ts
27686
27686
  import { isDeepStrictEqual } from "node:util";
27687
+ var UnpersistedClaudeHead = class extends Error {
27688
+ constructor() {
27689
+ super("Claude history active head is not persisted yet; retry after the transcript write");
27690
+ }
27691
+ };
27687
27692
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
27688
27693
  var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
27689
27694
  function object3(value) {
@@ -27826,7 +27831,7 @@ function claudeHistoryFromRows(rows, source) {
27826
27831
  return version2.position;
27827
27832
  }
27828
27833
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
27829
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
27834
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
27830
27835
  const selected = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), visiting = /* @__PURE__ */ new Set();
27831
27836
  const stack = [{ uuid: source.headUuid, historical: false }];
27832
27837
  while (stack.length > 0) {
@@ -27959,7 +27964,7 @@ function createHistoryPrefilter(queries) {
27959
27964
  }).filter((literal2) => !literal2.test(PRESENTATION));
27960
27965
  }));
27961
27966
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
27962
- return async (chunks, codex = false) => {
27967
+ return async (chunks, codex = false, stopOnHit = false) => {
27963
27968
  const decoder = new StringDecoder("utf8");
27964
27969
  const seen = alternatives.map((tokens) => tokens.map(() => false));
27965
27970
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -27987,17 +27992,19 @@ function createHistoryPrefilter(queries) {
27987
27992
  rawTail = raw.slice(-overlap);
27988
27993
  normalizedTail = normalized.slice(-overlap);
27989
27994
  };
27990
- for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
27995
+ for await (const chunk of chunks) {
27996
+ if (!possible) scan(decoder.write(chunk));
27997
+ if (possible && stopOnHit) return true;
27998
+ }
27991
27999
  if (!possible) scan(decoder.end(), true);
27992
28000
  return possible;
27993
28001
  };
27994
28002
  }
27995
28003
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
27996
- if (codex) {
27997
- const info = await stat2(path);
27998
- if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
27999
- }
28000
- const compressed = codex && path.endsWith(".jsonl.zst");
28004
+ if (!codex) return prefilter(createReadStream(path), false, true);
28005
+ const info = await stat2(path);
28006
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
28007
+ const compressed = path.endsWith(".jsonl.zst");
28001
28008
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
28002
28009
  const input = createReadStream(path);
28003
28010
  const consume = async (chunks) => {
@@ -10,3 +10,19 @@ npm test
10
10
  ```
11
11
 
12
12
  Install this directory with `paseo plugin install /absolute/path/to/plugins/paseo`. Source changes require `paseo plugin reload notesoup`; no daemon restart is needed.
13
+
14
+ ## Markdown maintenance
15
+
16
+ `client/markdown-core.tsx` and `test/markdown-core.test.ts` are manually mirrored,
17
+ byte-for-byte, between the Square and pi-context (notesoup) repositories at
18
+ `plugins/paseo/`. No shared package or cross-repository runtime import is needed.
19
+ When changing rendering behavior, copy both files to the other plugin and run
20
+ `npm test && npm run typecheck` in both plugin directories. Compare the files
21
+ with `diff -u` before delivery. Each `client/markdown.tsx` owns its palette and
22
+ wrapper; do not copy those adapters.
23
+
24
+ The core handles inline nesting, block structure, selectable text, safe `http(s)`/`mailto`
25
+ link presses, and horizontal code/table scrolling. Images render as alt text or `[image]`;
26
+ this is not the full Paseo assistant renderer. Tests inspect React elements with RN host
27
+ primitives, not native layout. Verify wrapping, selection and scrolling on iOS
28
+ before claiming visual or gesture correctness.
@@ -3,6 +3,7 @@ import { Modal } from "@getpaseo/plugin/client/react-native";
3
3
  import { useState } from "react";
4
4
  import { Pressable, Text, View } from "react-native";
5
5
  import type { BrainEmpty } from "../shared/brain-empty.ts";
6
+ import { typography } from "./typography.ts";
6
7
 
7
8
  function label(data: BrainEmpty): string {
8
9
  if (data.status === "running") return "✂ emptying brain …";
@@ -27,6 +28,7 @@ function CutLine({ color }: { color: string }) {
27
28
  export function BrainEmptyDivider({ item, theme }: PluginTimelineItemProps<BrainEmpty>) {
28
29
  const [lastWordOpen, setLastWordOpen] = useState(false);
29
30
  const data = item.data;
31
+ const type = typography(theme);
30
32
  const refused = data.error !== undefined || data.status === "failed";
31
33
  const color = refused ? theme.colors.statusDanger : theme.colors.foregroundMuted;
32
34
  const hasLastWord = data.outcome === "rollover_requested" && data.lastWord !== undefined;
@@ -41,17 +43,17 @@ export function BrainEmptyDivider({ item, theme }: PluginTimelineItemProps<Brain
41
43
  >
42
44
  <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
43
45
  <CutLine color={color} />
44
- <Text style={{ color, fontSize: 11.5, letterSpacing: 0.3 }}>{label(data)}</Text>
46
+ <Text style={{ ...type.sm, color, letterSpacing: 0.3 }}>{label(data)}</Text>
45
47
  <CutLine color={color} />
46
48
  </View>
47
49
  {data.error !== undefined && (
48
- <Text selectable style={{ color: theme.colors.statusDanger, fontSize: 12, textAlign: "center" }}>{data.error}</Text>
50
+ <Text selectable style={{ ...type.sm, color: theme.colors.statusDanger, textAlign: "center" }}>{data.error}</Text>
49
51
  )}
50
52
  </Pressable>
51
53
  {hasLastWord && (
52
54
  <Modal title="Last word" open={lastWordOpen} onOpenChange={setLastWordOpen}>
53
55
  <Modal.Content style={{ backgroundColor: theme.colors.surface2 }}>
54
- <Text selectable style={{ color: theme.colors.foreground, fontSize: 14, lineHeight: 21 }}>{data.lastWord}</Text>
56
+ <Text selectable style={{ ...type.body, color: theme.colors.foreground }}>{data.lastWord}</Text>
55
57
  </Modal.Content>
56
58
  </Modal>
57
59
  )}