opencode-vcc-compaction 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Same-session recall core, ported from dsh-compaction-vcc@0.7.4
3
+ * `src/recall.js` (MIT: Copyright (c) 2026 TsFreddie,
4
+ * Copyright (c) 2026 Tingfeng) — the lossless counterpart of the compiler:
5
+ * checkpoint `(seq N)` pointers expand back into exact original content
6
+ * from the append-only log.
7
+ *
8
+ * Faithful port with two documented deviations:
9
+ * - Upstream imports are split across the sibling stages: compiler
10
+ * helpers from `./compile.mjs` (`isCheckpointSource`,
11
+ * `projectToolResultText`), budget primitives from `./tokenize.mjs`
12
+ * (`estimateEntryTokens`, `sanitize`, `truncateTokens`), session access
13
+ * from `./session-compat.mjs` (`sessionEventAt`, `sessionEvents`) —
14
+ * nothing re-defined here.
15
+ * - DSH session-shape vocabulary (`eventAt`/`snapshotEvents`/`events`,
16
+ * `deriveEventMessage`, `tool/result` event types) is carried verbatim;
17
+ * the OpenCode adapter supplies the session-shaped value later
18
+ * (per `archive/plans/vcc-compiler.md` handoff).
19
+ *
20
+ * Upstream semicolons kept verbatim, per the repo `.mjs` convention
21
+ * (see `compiler/compile.mjs` header).
22
+ *
23
+ * Everything below is deterministic and offline: same session + reference
24
+ * always yields the same recalled text, with no model call.
25
+ */
26
+ import { isCheckpointSource, projectToolResultText } from "./compile.mjs";
27
+ import {
28
+ estimateEntryTokens,
29
+ sanitize,
30
+ truncateTokens,
31
+ } from "./tokenize.mjs";
32
+ import { sessionEventAt, sessionEvents } from "./session-compat.mjs";
33
+
34
+ /** Default total budget for one recall operation, in density-aware tokens. */
35
+ export const DEFAULT_MAX_RECALL_TOKENS = 16000;
36
+ /** Widest single range accepted from one selection, bounding expansion work. */
37
+ export const MAX_RECALL_SPAN = 1000;
38
+
39
+ /**
40
+ * Parse one seq selection string into ordered inclusive ranges.
41
+ *
42
+ * Accepted forms per comma-separated part: `12`, `3-7`, `seq 12`,
43
+ * `seqs 3-7`, with optional surrounding parentheses — so a model or human
44
+ * can paste a checkpoint marker verbatim.
45
+ * @param input - raw selection text.
46
+ * @returns `{ selections, errors }`; errors are stable human-readable strings.
47
+ */
48
+ export function parseSeqSpec(input) {
49
+ const selections = [];
50
+ const errors = [];
51
+ const raw = String(input ?? "").trim();
52
+ if (raw.length === 0) return { selections, errors: ["missing seq selection"] };
53
+ for (const part of raw.split(",")) {
54
+ let token = part.trim();
55
+ if (token.length === 0) continue;
56
+ token = token.replace(/^\((.*)\)$/u, "$1").trim();
57
+ const match = /^(?:seqs?\s+)?(\d+)(?:\s*-\s*(\d+))?$/iu.exec(token);
58
+ if (match === null) {
59
+ errors.push(`invalid seq selection "${part}"`);
60
+ continue;
61
+ }
62
+ const start = Number(match[1]);
63
+ const end = match[2] === undefined ? start : Number(match[2]);
64
+ // ⚠️ 2026-11-07 — reject anything outside the safe-integer range BEFORE any
65
+ // arithmetic. A seq at or above 2^53 makes `seq += 1` a no-op in IEEE-754
66
+ // (start + 1 === start), so `expandSelections`'s `for (seq = start; seq <=
67
+ // end; seq += 1)` never terminates and freezes the host synchronously —
68
+ // the tool call never returns and no timer can fire. Both bounds are
69
+ // checked because an out-of-range `end` only needs the loop guard to be
70
+ // true; the pathological case is start === end === 2^53.
71
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {
72
+ errors.push(`seq selection "${part}" is outside the safe integer range`);
73
+ continue;
74
+ }
75
+ if (start < 1) {
76
+ errors.push(`invalid seq selection "${part}" (seq starts at 1)`);
77
+ continue;
78
+ }
79
+ if (end < start) {
80
+ errors.push(`invalid seq range "${part}" (end before start)`);
81
+ continue;
82
+ }
83
+ if (end - start + 1 > MAX_RECALL_SPAN) {
84
+ errors.push(`seq range "${part}" is wider than the ${MAX_RECALL_SPAN}-seq limit`);
85
+ continue;
86
+ }
87
+ selections.push({ start, end });
88
+ }
89
+ return { selections, errors };
90
+ }
91
+
92
+ /**
93
+ * Project one derived message into plain text, keeping everything: text,
94
+ * reasoning, raw tool-call arguments, and nested tool-result content.
95
+ * Recall is the lossless layer, so nothing is elided here except media,
96
+ * which renders as labels (their bytes live in the attachment service).
97
+ * @param message - derived message (`Session.deriveEventMessage` output).
98
+ * @returns full plain-text projection.
99
+ */
100
+ export function projectMessageText(message) {
101
+ const parts = [];
102
+ for (const block of message.content) {
103
+ switch (block.type) {
104
+ case "text":
105
+ if (block.text !== undefined && block.text.length > 0) parts.push(sanitize(block.text));
106
+ break;
107
+ case "reasoning":
108
+ if (block.text !== undefined && block.text.length > 0) parts.push(`[reasoning]\n${sanitize(block.text)}`);
109
+ break;
110
+ case "tool-call":
111
+ parts.push(`[tool-call ${block.name ?? "unknown"}]\n${sanitize(block.arguments ?? "")}`);
112
+ break;
113
+ case "tool-result":
114
+ parts.push(`[tool-result]\n${projectToolResultText(block.content ?? [])}`);
115
+ break;
116
+ case "image":
117
+ parts.push("[image]");
118
+ break;
119
+ case "document":
120
+ parts.push("[document]");
121
+ break;
122
+ default:
123
+ parts.push(`[${String(block.type)}]`);
124
+ }
125
+ }
126
+ return parts.join("\n");
127
+ }
128
+
129
+ /**
130
+ * Expand ordered selections into a deduplicated ordered seq list.
131
+ * @param selections - parsed inclusive ranges.
132
+ * @returns unique seqs in first-appearance order.
133
+ */
134
+ export function expandSelections(selections) {
135
+ const seqs = [];
136
+ const seen = new Set();
137
+ for (const { start, end } of selections) {
138
+ // ⚠️ 2026-11-07 — defensive guard. `parseSeqSpec` already rejects unsafe
139
+ // integers, but this function is exported and reachable with a hand-built
140
+ // selection array. Without the guard, `seq += 1` at 2^53 is a no-op and the
141
+ // loop below never terminates (synchronous host freeze, unrecoverable
142
+ // without a restart). Skipping the range is the only safe failure mode.
143
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) continue;
144
+ for (let seq = start; seq <= end; seq += 1) {
145
+ if (seen.has(seq)) continue;
146
+ seen.add(seq);
147
+ seqs.push(seq);
148
+ }
149
+ }
150
+ return seqs;
151
+ }
152
+
153
+ /**
154
+ * Collect the durable seqs of every landed compaction checkpoint node in one
155
+ * session, oldest first. Each compaction replaces its span with exactly one
156
+ * checkpoint node, so the ordinal (`1` = oldest) counts compactions.
157
+ * @param session - session-shaped value with `eventAt()`/`snapshotEvents()` (or the legacy `events` array).
158
+ * @returns checkpoint node seqs in chronological order.
159
+ */
160
+ export function findCheckpointSeqs(session) {
161
+ const seqs = [];
162
+ for (const event of sessionEvents(session)) {
163
+ if (event.type === "user/message" && isCheckpointSource(event.data?.source)) seqs.push(event.seq);
164
+ }
165
+ return seqs;
166
+ }
167
+
168
+ /**
169
+ * Resolve one typed recall reference into inclusive seq ranges.
170
+ *
171
+ * - `type: "seq"` — `id` is a seq selection: numbers/ranges with the
172
+ * checkpoint marker forms (`12`, `3-7,15`, `seq 12`, `seqs 3-7`).
173
+ * - `type: "result"` — `id` names a tool result: the `result N` pointer
174
+ * from a tool-call one-liner (`result 3`, `seq 3`, or bare `3`); the
175
+ * resolved seq must be a `tool/result` event.
176
+ * - `type: "checkpoint"` — `id` is a checkpoint ordinal (`1` = oldest,
177
+ * as in the `[checkpoint N]` elision marker) or a `seq N` pointer to a
178
+ * checkpoint node.
179
+ *
180
+ * @param session - session-shaped value with `events` and `deriveEventMessage`.
181
+ * @param type - reference type: `seq`, `result`, or `checkpoint`.
182
+ * @param id - type-dependent reference text.
183
+ * @returns `{ selections, errors }`; errors are stable human-readable strings.
184
+ */
185
+ export function resolveRecallReference(session, type, id) {
186
+ const raw = String(id ?? "").trim();
187
+ if (type === "seq") return parseSeqSpec(raw);
188
+ if (type === "result") {
189
+ const token = raw.replace(/^\((.*)\)$/u, "$1").trim().replace(/^result\s+/iu, "");
190
+ const match = /^(\d+)$/u.exec(token);
191
+ if (match === null) return { selections: [], errors: [`invalid result reference "${id}" (expected a seq like "3" or "result 3")`] };
192
+ const seq = Number(match[1]);
193
+ const event = sessionEventAt(session, seq);
194
+ if (event === undefined || event.seq !== seq) return { selections: [], errors: [`result seq ${seq} not found in this session`] };
195
+ if (event.type !== "tool/result") return { selections: [], errors: [`seq ${seq} is not a tool result (it is ${event.type})`] };
196
+ return { selections: [{ start: seq, end: seq }], errors: [] };
197
+ }
198
+ if (type === "checkpoint") {
199
+ const token = raw.replace(/^\((.*)\)$/u, "$1").trim();
200
+ const bySeq = /^seqs?\s+(\d+)$/iu.exec(token);
201
+ if (bySeq !== null) {
202
+ const seq = Number(bySeq[1]);
203
+ const event = sessionEventAt(session, seq);
204
+ if (event === undefined || event.seq !== seq) return { selections: [], errors: [`checkpoint seq ${seq} not found in this session`] };
205
+ if (!isCheckpointSource(event.data?.source)) return { selections: [], errors: [`seq ${seq} is not a checkpoint node`] };
206
+ return { selections: [{ start: seq, end: seq }], errors: [] };
207
+ }
208
+ const ordinal = token.replace(/^checkpoint\s+/iu, "");
209
+ const match = /^(\d+)$/u.exec(ordinal);
210
+ if (match === null) return { selections: [], errors: [`invalid checkpoint reference "${id}" (expected an ordinal like "1" or "checkpoint 1", or a "seq N" pointer)`] };
211
+ const index = Number(match[1]);
212
+ if (!Number.isSafeInteger(index) || index < 1) return { selections: [], errors: [`invalid checkpoint ordinal "${id}"`] };
213
+ const checkpointSeqs = findCheckpointSeqs(session);
214
+ const seq = checkpointSeqs[index - 1];
215
+ if (seq === undefined) return { selections: [], errors: [`checkpoint ${index} not found (this session has ${checkpointSeqs.length} checkpoint(s))`] };
216
+ return { selections: [{ start: seq, end: seq }], errors: [] };
217
+ }
218
+ return { selections: [], errors: [`invalid recall type "${String(type)}" (expected "seq", "result", or "checkpoint")`] };
219
+ }
220
+
221
+ /**
222
+ * Recall the full original content of the requested seqs from one session's
223
+ * durable log. Message events project through `deriveEventMessage`; log-only
224
+ * events render as a labeled data dump. The total output is bounded by
225
+ * `config.maxRecallTokens`; a cut appends a provenance marker and remaining
226
+ * requested seqs are accounted in `skipped`.
227
+ * @param session - session-shaped value with `events` and `deriveEventMessage`.
228
+ * @param selections - parsed inclusive ranges.
229
+ * @param config - `{ maxRecallTokens }`.
230
+ * @returns `{ text, entries, seqs, recalled, missing, skipped, truncated, tokens }`.
231
+ */
232
+ export function recallSession(session, selections, config) {
233
+ const maxRecallTokens = config.maxRecallTokens;
234
+ const requested = expandSelections(selections);
235
+ const entries = [];
236
+ const seqs = [];
237
+ let budget = maxRecallTokens;
238
+ let truncated = false;
239
+ let missing = 0;
240
+ let skipped = 0;
241
+ for (let index = 0; index < requested.length; index += 1) {
242
+ const seq = requested[index];
243
+ if (budget <= 0) {
244
+ skipped = requested.length - index;
245
+ truncated = true;
246
+ break;
247
+ }
248
+ const event = sessionEventAt(session, seq);
249
+ if (event === undefined || event.seq !== seq) {
250
+ missing += 1;
251
+ entries.push({ seq, text: `[seq ${seq}: not found in this session]` });
252
+ continue;
253
+ }
254
+ const message = typeof session.deriveEventMessage === "function" ? session.deriveEventMessage(event) : null;
255
+ const body = message !== null
256
+ ? `[seq ${seq}: ${message.role}]\n${projectMessageText(message)}`
257
+ : `[seq ${seq}: ${event.type}]\n${JSON.stringify(event.data).slice(0, maxRecallTokens * 4)}`;
258
+ const kept = truncateTokens(body, budget, "recall budget");
259
+ budget -= estimateEntryTokens(kept.text);
260
+ if (kept.truncated) truncated = true;
261
+ entries.push({ seq, text: kept.text, truncated: kept.truncated });
262
+ seqs.push(seq);
263
+ }
264
+ if (skipped > 0) {
265
+ entries.push({ seq: requested[requested.length - skipped], text: `[recall budget exhausted: ${skipped} further requested seq(s) not included]` });
266
+ }
267
+ return {
268
+ text: entries.map((entry) => entry.text).join("\n\n"),
269
+ entries,
270
+ seqs,
271
+ recalled: seqs.length,
272
+ missing,
273
+ skipped,
274
+ truncated,
275
+ tokens: entries.reduce((total, entry) => total + estimateEntryTokens(entry.text), 0)
276
+ };
277
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Keyword/regex search over the durable session log, ported from
3
+ * dsh-compaction-vcc@0.7.4 `src/search.js` (MIT: Copyright (c) 2026
4
+ * TsFreddie, Copyright (c) 2026 Tingfeng) — the retrieval counterpart of
5
+ * the compiler: scans every event's projected content, returns matching
6
+ * events with `(seq N)` pointers that `recall` restores in full.
7
+ *
8
+ * Faithful port with two documented deviations:
9
+ * - Upstream imports are split across the sibling stages: budget
10
+ * primitives from `./tokenize.mjs` (`estimateEntryTokens`, `sanitize`,
11
+ * `truncateTokens`), message projection from `./recall.mjs`
12
+ * (`projectMessageText`), session access from `./session-compat.mjs`
13
+ * (`sessionEventAt`, `sessionEvents`) — nothing re-defined here.
14
+ * (`sessionEventAt` is imported but unused, exactly as upstream.)
15
+ * - Known upstream quirk carried verbatim: the scan is positional
16
+ * (`events[seq]` with `event.seq === seq`, so a 1-based log in a
17
+ * 0-based array matches nothing). The future adapter's event list must
18
+ * satisfy this; not papered over here.
19
+ *
20
+ * Upstream semicolons kept verbatim, per the repo `.mjs` convention
21
+ * (see `compiler/compile.mjs` header).
22
+ *
23
+ * Everything below is deterministic and offline: same session + pattern
24
+ * always yields the same hits, with no model call.
25
+ */
26
+ import { estimateEntryTokens, sanitize, truncateTokens } from "./tokenize.mjs";
27
+ import { projectMessageText } from "./recall.mjs";
28
+ import { sessionEventAt, sessionEvents } from "./session-compat.mjs";
29
+
30
+ /** Default cap on the number of matching events shown in one result. */
31
+ export const DEFAULT_MAX_SEARCH_HITS = 50;
32
+ /** Default cap on shown matching lines per hit event. */
33
+ export const MAX_LINES_PER_HIT = 10;
34
+
35
+ /** A search pattern that cannot be compiled into a regular expression. */
36
+ export class InvalidSearchPatternError extends Error {
37
+ /**
38
+ * @param source - the raw pattern the user supplied.
39
+ * @param reason - the regex compiler's message.
40
+ */
41
+ constructor(source, reason) {
42
+ super(`invalid search pattern ${JSON.stringify(String(source))}: ${reason}`);
43
+ this.source = String(source);
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Compile one search pattern: case-insensitive, Unicode-aware, treated as a
49
+ * regular expression (VCC `--grep` semantics) so keywords work as-is and
50
+ * regexes work when escaped.
51
+ * @param source - raw pattern text.
52
+ * @returns the compiled pattern.
53
+ * @throws InvalidSearchPatternError when empty or not compilable.
54
+ */
55
+ export function compileSearchPattern(source) {
56
+ const trimmed = String(source ?? "").trim();
57
+ if (trimmed.length === 0) throw new InvalidSearchPatternError(source, "pattern is empty");
58
+ try {
59
+ return new RegExp(trimmed, "iu");
60
+ } catch (error) {
61
+ throw new InvalidSearchPatternError(source, error instanceof Error ? error.message : String(error));
62
+ }
63
+ }
64
+
65
+ /** One search hit: the durable seq, its kind, and the rendered matched lines. */
66
+ export function searchSession(session, patternSource, config) {
67
+ const pattern = compileSearchPattern(patternSource);
68
+ const maxHits = config.maxSearchHits;
69
+ const maxTokens = config.maxRecallTokens;
70
+ const events = sessionEvents(session);
71
+ const hits = [];
72
+ let totalMatches = 0;
73
+ let budget = maxTokens;
74
+ let truncated = false;
75
+ for (let seq = 0; seq < events.length; seq += 1) {
76
+ const event = events[seq];
77
+ if (event === undefined || event.seq !== seq) continue;
78
+ const message = typeof session.deriveEventMessage === "function" ? session.deriveEventMessage(event) : null;
79
+ const body = message !== null
80
+ ? projectMessageText(message)
81
+ : `[${event.type}]\n${JSON.stringify(event.data ?? null)}`;
82
+ const lines = body.split("\n");
83
+ const matched = [];
84
+ for (let index = 0; index < lines.length; index += 1) {
85
+ if (pattern.test(lines[index])) matched.push({ line: index + 1, text: sanitize(lines[index]) });
86
+ }
87
+ if (matched.length === 0) continue;
88
+ totalMatches += 1;
89
+ if (hits.length >= maxHits || budget <= 0) {
90
+ truncated = true;
91
+ continue;
92
+ }
93
+ const header = `[seq ${seq}: ${message !== null ? message.role : event.type}]`;
94
+ const shown = matched.slice(0, MAX_LINES_PER_HIT);
95
+ const more = matched.length - shown.length;
96
+ const block = [
97
+ header,
98
+ ...shown.map((match) => ` ${match.line}: ${match.text}`),
99
+ ...(more > 0 ? [` ...(${more} more matching lines in this event)`] : [])
100
+ ].join("\n");
101
+ const kept = truncateTokens(block, budget, "search budget");
102
+ budget -= estimateEntryTokens(kept.text);
103
+ if (kept.truncated) truncated = true;
104
+ hits.push({ seq, kind: message !== null ? message.role : event.type, text: kept.text });
105
+ }
106
+ const omitted = totalMatches - hits.length;
107
+ const lines = [
108
+ `[search "${pattern.source}": ${totalMatches} matching event(s)]`,
109
+ ...hits.map((hit) => hit.text),
110
+ ...(omitted > 0 ? [`[${omitted} more matching event(s) omitted — narrow the pattern or use recall]`] : []),
111
+ ...(truncated ? ["[search budget exhausted; some hits were cut]"] : [])
112
+ ];
113
+ if (hits.length > 0) lines.push("[use recall with a (seq N) pointer to restore any hit's full original content]");
114
+ const text = lines.join("\n\n");
115
+ return {
116
+ pattern: pattern.source,
117
+ totalMatches,
118
+ hits,
119
+ omitted,
120
+ truncated,
121
+ tokens: hits.reduce((total, hit) => total + estimateEntryTokens(hit.text), 0),
122
+ text
123
+ };
124
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Cross-version session-log access, ported from
3
+ * dsh-compaction-vcc@0.7.4 `src/session-compat.js` (MIT:
4
+ * Copyright (c) 2026 TsFreddie, Copyright (c) 2026 Tingfeng).
5
+ *
6
+ * Implied dependency of the recall/search stages: `recall.mjs` imports
7
+ * `sessionEventAt` / `sessionEvents` from here, exactly as upstream
8
+ * `recall.js` imports them from `./session-compat.js`. Carried as its own
9
+ * file (see the `archive/plans/vcc-compiler.md` module map) rather than
10
+ * inlined, so the recall port stays line-for-line verbatim. Duck-typed accessors
11
+ * (`eventAt`/`snapshotEvents`) with legacy `events`-array fallback — no
12
+ * DSH imports, so the OpenCode adapter can supply any session-shaped value.
13
+ *
14
+ * Upstream semicolons kept verbatim, per the repo `.mjs` convention
15
+ * (see `compiler/compile.mjs` header).
16
+ *
17
+ * Everything below is deterministic and offline.
18
+ */
19
+ /** @type {Set<string>} Capability gaps already reported, so the log stays readable. */
20
+ const warned = new Set();
21
+
22
+ /**
23
+ * Report a missing session capability exactly once per documented key.
24
+ * @param message - human-readable warning body.
25
+ */
26
+ function warnOnce(message) {
27
+ if (warned.has(message)) return;
28
+ warned.add(message);
29
+ try {
30
+ console.warn(`[dsh-compaction-vcc] ${message}`);
31
+ } catch {
32
+ /* stderr may be unavailable in embedded contexts */
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Report whether a session-shaped value exposes any readable event log.
38
+ *
39
+ * Exported so an engine can probe once at construction instead of discovering
40
+ * the gap in the middle of a compaction.
41
+ * @param session - session-shaped value to inspect.
42
+ * @returns true when `snapshotEvents`, `eventAt` or the legacy `events` exists.
43
+ */
44
+ export function hasSessionEventAccess(session) {
45
+ if (session === null || session === undefined) return false;
46
+ if (typeof session.snapshotEvents === "function") return true;
47
+ if (typeof session.eventAt === "function") return true;
48
+ return session.events !== null && session.events !== undefined;
49
+ }
50
+
51
+ /**
52
+ * Return a frozen snapshot of every event in the durable log.
53
+ * @param session - session-shaped value with `snapshotEvents()` or legacy `events`.
54
+ * @returns the frozen event array; empty only when the session genuinely has
55
+ * no log access, which is reported once through `console.warn`.
56
+ */
57
+ export function sessionEvents(session) {
58
+ if (session === null || session === undefined) return [];
59
+ if (typeof session.snapshotEvents === "function") {
60
+ const events = session.snapshotEvents();
61
+ if (events === null || events === undefined) {
62
+ warnOnce("snapshotEvents() returned no array; treating the log as empty");
63
+ return [];
64
+ }
65
+ return events;
66
+ }
67
+ if (session.events !== null && session.events !== undefined) return session.events;
68
+ warnOnce("session exposes neither snapshotEvents() nor events; the durable log is unreadable on this host — compaction will not run");
69
+ return [];
70
+ }
71
+
72
+ /**
73
+ * Return the immutable event stored at one exact sequence number.
74
+ * @param session - session-shaped value with `eventAt()` or legacy `events`.
75
+ * @param seq - event sequence number.
76
+ * @returns the accepted event, or undefined when the log does not contain it.
77
+ */
78
+ export function sessionEventAt(session, seq) {
79
+ if (session === null || session === undefined) return undefined;
80
+ if (typeof session.eventAt === "function") {
81
+ const event = session.eventAt(seq);
82
+ return event === null ? undefined : event;
83
+ }
84
+ const events = session.events;
85
+ if (events === null || events === undefined) return undefined;
86
+ // ⚠️ The legacy array is indexed by POSITION, not by seq: the durable log
87
+ // numbers events from 1 while array indices start at 0, so `events[seq]` is
88
+ // off by one. Every call site re-checks `event.seq === seq` and treats a
89
+ // mismatch as "not found", so this is a safe failure rather than wrong data —
90
+ // but it means the legacy path only works for a 0-based array. Prefer the
91
+ // accessor pair; this branch exists for old unit fixtures.
92
+ const positional = events[seq];
93
+ if (positional !== undefined && positional?.seq === seq) return positional;
94
+ for (const event of events) {
95
+ if (event?.seq === seq) return event;
96
+ }
97
+ return positional;
98
+ }