ltms-reader 0.0.0-stage → 0.1.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.
package/src/helper.mjs ADDED
@@ -0,0 +1,127 @@
1
+ // src/helper.mjs — the extension's reading process. It reads one transcript at a time with ltms's parser and answers the
2
+ // extension over stdin and stdout: one JSON request per line in, one JSON reply per line out. The extension starts it with
3
+ // the editor's own binary as Node (ELECTRON_RUN_AS_NODE=1), so a large transcript is parsed outside the editor's process,
4
+ // and its memory is given back when this process exits: when stdin closes, or after LTMS_GUI_IDLE_MS without a request.
5
+ //
6
+ // The extension checks every path before it sends one; this process still reads only regular files (never through a
7
+ // symbolic link at the last step), and keeps the parses of the most recent files, up to LTMS_GUI_CACHE_BYTES of source.
8
+ import { createHash } from 'node:crypto';
9
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, realpathSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
+ import { dirname } from 'node:path';
12
+ import { getHeapStatistics } from 'node:v8';
13
+ import { parseTranscript } from '#ltms';
14
+ import { fieldWindow, recordIndexAt, recordView, sessionView, turnItems } from './view.mjs';
15
+ import { onLines } from './lines.mjs';
16
+
17
+ const IDLE_MS = Number(process.env.LTMS_GUI_IDLE_MS) > 0 ? Number(process.env.LTMS_GUI_IDLE_MS) : 600_000;
18
+ const CACHE_BYTES = Number(process.env.LTMS_GUI_CACHE_BYTES) > 0 ? Number(process.env.LTMS_GUI_CACHE_BYTES) : 128 * 1024 * 1024;
19
+ // ltms's own rule (its cli.js): a file over a tenth of the runtime's heap limit is skipped, so the session view and the
20
+ // lists ltms makes agree on which files can be read; and never past about 480 MB, under JavaScript's string limit.
21
+ const MAX_FILE = Math.min(480 * 1024 * 1024, Math.floor(getHeapStatistics().heap_size_limit / 10));
22
+
23
+ class Refusal extends Error { constructor(kind, message) { super(message); this.kind = kind; } }
24
+
25
+ const cache = new Map(); // key → { t, bytes }, the most recently used last
26
+ /** Open one transcript as load() does, and return its descriptor and its stat; the caller closes it. */
27
+ function openChecked(file, dir) {
28
+ let fd;
29
+ // the folder is checked before the open as well as after; O_NONBLOCK, so a FIFO put at the name cannot block the open
30
+ if (typeof dir === 'string') { let real; try { real = realpathSync(dirname(file)); } catch { real = null; } if (real !== dir) throw new Refusal('not-file', `${file} is no longer in the folder that was checked (a folder on its path was replaced)`); }
31
+ try { fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); }
32
+ catch (e) {
33
+ if (e.code === 'ELOOP' || e.code === 'EMLINK') throw new Refusal('not-file', `${file} is a symbolic link; transcripts are read only as regular files`);
34
+ let st; try { st = lstatSync(file); } catch { throw new Refusal('missing', `no file at ${file} (${e.code ?? 'unreadable'}): it may have been moved, or removed by Claude Code's cleanup`); }
35
+ if (st.isSymbolicLink()) throw new Refusal('not-file', `${file} is a symbolic link; transcripts are read only as regular files`);
36
+ throw new Refusal('unreadable', `${file} could not be opened (${e.code ?? 'unreadable'})`);
37
+ }
38
+ try {
39
+ const st = fstatSync(fd);
40
+ if (!st.isFile()) throw new Refusal('not-file', `${file} is not a regular file`);
41
+ if (typeof dir === 'string' && realpathSync(dirname(file)) !== dir) throw new Refusal('not-file', `${file} is no longer in the folder that was checked (a folder on its path was replaced)`);
42
+ // A9: a folder on the path flipped to a link and back around the open would pass both checks above; the descriptor
43
+ // must be the very file the name stands for now
44
+ let now; try { now = lstatSync(file); } catch { now = null; }
45
+ if (!now || now.dev !== st.dev || now.ino !== st.ino) throw new Refusal('not-file', `${file} is not the file that was opened (a folder on its path was replaced while it was opened)`);
46
+ return { fd, st };
47
+ } catch (e) { closeSync(fd); throw e; }
48
+ }
49
+
50
+ /** The sha256 of a transcript's bytes, read 1 MiB at a time from the descriptor checked (so two copies can be told
51
+ * identical without holding either whole). */
52
+ function digest(file, dir) {
53
+ const { fd, st } = openChecked(file, dir);
54
+ try {
55
+ const h = createHash('sha256'), buf = Buffer.allocUnsafe(1 << 20);
56
+ let size = 0;
57
+ for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) { h.update(buf.subarray(0, n)); size += n; }
58
+ return { sha256: h.digest('hex'), size, mtimeMs: st.mtimeMs, ino: String(st.ino), dev: String(st.dev) };
59
+ } finally { closeSync(fd); }
60
+ }
61
+
62
+ /** Read one transcript: opened without following a link at the last step (O_NOFOLLOW), checked to be a regular file
63
+ * in the folder the extension checked (`dir`, so a folder swapped for a link since is refused), and read from the
64
+ * descriptor it checked. */
65
+ function load(file, dir) {
66
+ const { fd, st } = openChecked(file, dir);
67
+ try {
68
+ if (st.size > MAX_FILE) throw new Refusal('too-large', `${file} is ${Math.round(st.size / 1048576)} MB; like ltms, the reader skips a transcript over a tenth of its memory limit (${Math.round(MAX_FILE / 1048576)} MB here)`);
69
+ const key = `${file}\0${st.size}\0${st.mtimeMs}\0${st.ino}`;
70
+ const hit = cache.get(key);
71
+ if (hit) { cache.delete(key); cache.set(key, hit); return hit.t; }
72
+ for (const k of [...cache.keys()]) if (k.startsWith(`${file}\0`)) cache.delete(k); // an older reading of the same file
73
+ const t = parseTranscript(readFileSync(fd, 'utf8'));
74
+ cache.set(key, { t, bytes: st.size });
75
+ let total = 0;
76
+ for (const v of cache.values()) total += v.bytes;
77
+ for (const [k, v] of cache) { if (total <= CACHE_BYTES || cache.size <= 1) break; cache.delete(k); total -= v.bytes; }
78
+ return t;
79
+ } finally { closeSync(fd); }
80
+ }
81
+
82
+ const name = (q) => { if (typeof q.name !== 'string' || !/^[^/\\\0]+\.jsonl$/.test(q.name)) throw new Refusal('bad-request', 'a request names its file by its name, ending in .jsonl'); return q.name; };
83
+ const file = (q) => { if (typeof q.file !== 'string' || q.file === '' || q.file.includes('\0')) throw new Refusal('bad-request', 'a request names its file by its full path'); return q.file; };
84
+ const line = (q) => { if (!Number.isSafeInteger(q.line) || q.line < 1) throw new Refusal('bad-request', `a line is a whole number from 1; given ${JSON.stringify(q.line)}`); return q.line; };
85
+
86
+ const ops = {
87
+ digest: (q) => digest(file(q), q.dir),
88
+ hello: () => ({ pid: process.pid, node: process.versions.node, maxFile: MAX_FILE, ltms: JSON.parse(readFileSync(createRequire(import.meta.url).resolve('#ltms/package.json'), 'utf8')).version }),
89
+ session: (q) => sessionView(load(file(q), q.dir), { name: name(q) }),
90
+ turn: (q) => {
91
+ if (typeof q.ta !== 'string' || q.ta.length > 40) throw new Refusal('bad-request', 'a turn is named by its id, as <prefix>:T<n>');
92
+ const r = turnItems(load(file(q), q.dir), { name: name(q), ta: q.ta });
93
+ if (!r) throw new Refusal('no-turn', `${q.ta} is not a turn of ${q.name}`);
94
+ return { ta: q.ta, ...r };
95
+ },
96
+ record: (q) => {
97
+ const v = recordView(load(file(q), q.dir), line(q), { name: name(q), whole: q.whole === true });
98
+ if (!v) throw new Refusal('no-record', `no record was parsed on line ${q.line} of ${q.name}: the line is blank, not a JSON object, or past the end of the file`);
99
+ return v;
100
+ },
101
+ window: (q) => {
102
+ const t = load(file(q), q.dir), i = recordIndexAt(t, line(q));
103
+ if (i === undefined) throw new Refusal('no-record', `no record was parsed on line ${q.line} of ${name(q)}`);
104
+ if (!Number.isSafeInteger(q.at) || q.at < 0 || !Array.isArray(q.field) || q.field.length > 64 || !q.field.every((k) => typeof k === 'string' || Number.isSafeInteger(k))) throw new Refusal('bad-request', 'a match is named by its field (a key path) and its offset');
105
+ return fieldWindow(t.records[i], q.field, q.at, 600);
106
+ },
107
+ };
108
+
109
+ let idle;
110
+ const touch = () => { clearTimeout(idle); idle = setTimeout(() => process.exit(0), IDLE_MS); idle.unref?.(); };
111
+ const reply = (o) => process.stdout.write(`${JSON.stringify(o)}\n`);
112
+ touch();
113
+ onLines(process.stdin, (l) => {
114
+ if (l === '') return;
115
+ touch();
116
+ let q;
117
+ try { q = JSON.parse(l); } catch { reply({ id: null, ok: false, error: { kind: 'bad-request', message: 'a request is one JSON object on one line' } }); return; }
118
+ const id = Number.isSafeInteger(q?.id) ? q.id : null;
119
+ const op = Object.hasOwn(ops, q?.op) ? ops[q.op] : null;
120
+ if (!op) { reply({ id, ok: false, error: { kind: 'bad-request', message: `no operation ${JSON.stringify(q?.op)}; known: ${Object.keys(ops).join(', ')}` } }); return; }
121
+ try { reply({ id, ok: true, result: op(q) }); }
122
+ catch (e) {
123
+ // ltms's rule: an internal error is reported by its kind, never by its message, which could quote the transcript
124
+ if (e instanceof Refusal) reply({ id, ok: false, error: { kind: e.kind, message: e.message } });
125
+ else reply({ id, ok: false, error: { kind: 'internal', message: `${e?.name ?? 'Error'} while answering ${q.op}` } });
126
+ }
127
+ }, () => process.exit(0));
package/src/layout.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // src/layout.mjs — where a project's transcripts are, by ltms's own rules (ltms 0.2.0, dist/cli.js walkPaths), with no
2
+ // editor in it. A transcript is any regular .jsonl file at any depth under the project's folder, reached without
3
+ // following a symbolic link: what `ltms search <folder>` reads, as near as this code can tell (ltms also skips a file
4
+ // larger than a tenth of its runtime's memory, and this walk stops at MAX_DEPTH folders and MAX_FILES files, saying so).
5
+ // `ltms index <folder>` reads the same files except those in a session's own folder, the set-aside copies and the
6
+ // folders holding PINS.log, and lists a session wherever it finds one (a copy kept under another folder of the project
7
+ // is listed too). The GUI names each transcript by its path in the project, '/'-separated; the page names nothing else.
8
+ //
9
+ // A session's own folder (ltms's rule): beside <name>.jsonl, the folder <name>/, or a folder named by a UUID. Claude Code
10
+ // keeps a session's agents there: subagents/agent-<id>.jsonl, and a workflow's under subagents/workflows/<run>/. ltms index
11
+ // counts every agent-*.jsonl at any depth of that folder; a symbolic link met there, a folder there that cannot be
12
+ // listed, or the own folder itself a symbolic link, makes the count unknown (null).
13
+ import { lstatSync, readdirSync } from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ export const AGENT_NAME = /^agent-.*\.jsonl$/;
17
+ export const UUID_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ /** ltms's set-aside copies: Claude Code's <session>.orphaned-<time>-<suffix>.jsonl, pin's <stem>.superseded-<12 hex>.jsonl. */
19
+ export const SET_ASIDE = /^(.+?)\.(?:orphaned-[^/]*|superseded-[0-9a-f]{12})\.jsonl$/;
20
+ // a backslash is an ordinary character in a name on Linux and macOS (ltms reads such files); on Windows it separates
21
+ const PLAIN = process.platform === 'win32' ? /^[^/\\\0]+$/ : /^[^/\0]+$/;
22
+ const LOSSY = String.fromCodePoint(0xfffd); // what Node writes for bytes of a name that are not UTF-8
23
+ /** One component of a path the page sends: a plain name, never '.' or '..'. */
24
+ export const isName = (s) => typeof s === 'string' && s !== '.' && s !== '..' && PLAIN.test(s) && s.length <= 255;
25
+ export const MAX_DEPTH = 64;
26
+ export const MAX_FILES = 200_000;
27
+
28
+ const kind = (p) => { try { const s = lstatSync(p); return s.isSymbolicLink() ? 'link' : s.isDirectory() ? 'dir' : s.isFile() ? 'file' : 'other'; } catch { return 'none'; } };
29
+
30
+ /** The path the page sends, checked: plain names joined by '/', at most MAX_DEPTH of them; null if it is not one. */
31
+ export function relParts(rel, { jsonl = true } = {}) {
32
+ if (typeof rel !== 'string' || rel.length > 4096) return null;
33
+ const parts = rel.split('/');
34
+ if (!parts.length || parts.length > MAX_DEPTH || !parts.every(isName)) return null;
35
+ if (jsonl && !parts[parts.length - 1].endsWith('.jsonl')) return null;
36
+ return parts;
37
+ }
38
+
39
+ /**
40
+ * Every regular .jsonl file under `dir`, at any depth: { files: [{ rel, size, mtimeMs, dev, ino }], links, linkRels,
41
+ * lossy, pinStores, unreadable, cut }. Symbolic links are counted (linkRels: their paths) and not followed, also when a
42
+ * folder became one after its parent was listed; a folder is entered once (by device and inode); a folder that cannot be
43
+ * listed, or an entry that vanished or cannot be stat'ed, is counted in `unreadable`. `lossy`: the .jsonl files whose
44
+ * names are not UTF-8 (ltms counts them and cannot read them either). `pinStores`: the folders holding PINS.log. `cut`:
45
+ * more than maxFiles were found (the rest are not listed), or a folder lay deeper than MAX_DEPTH.
46
+ */
47
+ export function walk(dir, { maxFiles = MAX_FILES, under = '' } = {}) {
48
+ const files = [], linkRels = [], lossy = [], pinStores = [];
49
+ let unreadable = 0, cut = false;
50
+ const entered = new Set();
51
+ const stack = [{ abs: dir, rel: under, depth: 0 }];
52
+ while (stack.length) {
53
+ const { abs, rel, depth } = stack.pop();
54
+ let st;
55
+ try { st = lstatSync(abs, { bigint: true }); } catch { unreadable++; continue; }
56
+ // listed as a folder by its parent, it may have been replaced by a link since: never listed through one
57
+ if (!st.isDirectory()) { if (st.isSymbolicLink()) linkRels.push(rel); else unreadable++; continue; }
58
+ const id = `${st.dev}:${st.ino}`;
59
+ if (entered.has(id)) continue;
60
+ entered.add(id);
61
+ let entries;
62
+ try { entries = readdirSync(abs, { withFileTypes: true }); } catch { unreadable++; continue; }
63
+ if (rel && entries.some((e) => e.name === 'PINS.log' && e.isFile())) pinStores.push(rel);
64
+ for (const e of entries) {
65
+ const childAbs = path.join(abs, e.name), childRel = rel ? `${rel}/${e.name}` : e.name;
66
+ if (e.isSymbolicLink()) { linkRels.push(childRel); continue; }
67
+ if (e.name.includes(LOSSY)) { if (e.isFile() && e.name.endsWith('.jsonl')) lossy.push(childRel); else if (e.isDirectory()) unreadable++; continue; }
68
+ if (e.isDirectory()) {
69
+ if (!isName(e.name)) { unreadable++; continue; }
70
+ if (depth + 1 >= MAX_DEPTH) { cut = true; continue; }
71
+ stack.push({ abs: childAbs, rel: childRel, depth: depth + 1 });
72
+ } else if (e.isFile() && e.name.endsWith('.jsonl')) {
73
+ if (!isName(e.name)) { unreadable++; continue; }
74
+ if (files.length >= maxFiles) { cut = true; continue; }
75
+ try { const s = lstatSync(childAbs); if (!s.isFile()) continue; files.push({ rel: childRel, size: s.size, mtimeMs: s.mtimeMs, dev: s.dev, ino: s.ino }); }
76
+ catch { unreadable++; }
77
+ }
78
+ }
79
+ }
80
+ files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
81
+ return { files, links: linkRels.length, linkRels, lossy, pinStores, unreadable, cut };
82
+ }
83
+
84
+ /**
85
+ * Each file of a walk, by what `ltms index` does with it (its classify): 'read' (it reads it), 'part' (in a session's own
86
+ * folder: counted, not read), 'aside' (a set-aside copy: counted, not read), 'pinned' (under a folder holding PINS.log:
87
+ * not entered). A session's own folder is any folder below the one walked named by a UUID, or with <its name>.jsonl
88
+ * beside it.
89
+ */
90
+ export function classify(w) {
91
+ const names = new Set(w.files.map((f) => f.rel));
92
+ const pins = w.pinStores.map((p) => `${p}/`);
93
+ const out = new Map();
94
+ for (const f of w.files) {
95
+ if (pins.some((p) => f.rel.startsWith(p))) { out.set(f.rel, 'pinned'); continue; }
96
+ const parts = f.rel.split('/');
97
+ let part = false;
98
+ for (let i = 0; i < parts.length - 1 && !part; i++) {
99
+ const folder = parts.slice(0, i + 1).join('/');
100
+ if (UUID_NAME.test(parts[i]) || names.has(`${folder}.jsonl`)) part = true;
101
+ }
102
+ out.set(f.rel, part ? 'part' : SET_ASIDE.test(parts[parts.length - 1]) ? 'aside' : 'read');
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** A transcript of the project at `rel`: every folder on its way a real folder (never a link), the file a regular file.
108
+ * Returns { abs, name } or { refused: kind, why }. */
109
+ export function transcriptAt(projectDir, rel) {
110
+ const parts = relParts(rel);
111
+ if (!parts) return { refused: 'bad-name', why: `${JSON.stringify(rel)} is not the path of a transcript in a project (plain names joined by /, ending in .jsonl)` };
112
+ let at = projectDir;
113
+ for (let i = 0; i < parts.length - 1; i++) {
114
+ at = path.join(at, parts[i]);
115
+ const k = kind(at);
116
+ if (k !== 'dir') return { refused: 'no-session', why: `${parts.slice(0, i + 1).join('/')} is not a folder${k === 'link' ? ' (a symbolic link is not followed)' : ''}` };
117
+ }
118
+ const abs = path.join(at, parts[parts.length - 1]), k = kind(abs);
119
+ if (k !== 'file') return { refused: 'no-session', why: k === 'none' ? `no file ${rel}: it may have been removed by Claude Code's cleanup` : `${rel} is not a regular file${k === 'link' ? ' (a symbolic link is not followed)' : ''}` };
120
+ return { abs, name: parts[parts.length - 1] };
121
+ }
122
+
123
+ /** The session a transcript's name stands for: its name without .jsonl, or, for a set-aside copy, the session's. */
124
+ export const sessionStem = (name) => SET_ASIDE.exec(name)?.[1] ?? name.slice(0, -'.jsonl'.length);
125
+
126
+ /** A session's own folder, by ltms's rule: <folder of the file>/<its session's name>. { folder (its path in the project,
127
+ * or null), kind: 'dir' | 'link' | 'none' }. */
128
+ export function ownFolder(projectDir, rel) {
129
+ const parts = relParts(rel);
130
+ if (!parts) return { folder: null, kind: 'none' };
131
+ const stem = sessionStem(parts[parts.length - 1]);
132
+ if (!isName(stem)) return { folder: null, kind: 'none' };
133
+ const own = [...parts.slice(0, -1), stem].join('/');
134
+ const k = kind(path.join(projectDir, ...own.split('/')));
135
+ return { folder: k === 'dir' ? own : null, kind: k === 'dir' || k === 'link' ? k : 'none' };
136
+ }
137
+
138
+ /**
139
+ * The agent transcripts of the session at `rel`: every agent-*.jsonl at any depth of its own folder, oldest first (ltms
140
+ * index counts the same files). Each: { file (its path in the project), name, group (its folder under the session's own,
141
+ * such as subagents or subagents/workflows/<run>), bytes, mtime, openable }. `known` is false where ltms index gives the
142
+ * count as null: the own folder is itself a symbolic link, or one was met in it, or a folder in it could not be listed.
143
+ * A name that is not UTF-8 is counted, as ltms counts it, and cannot be opened.
144
+ */
145
+ export function agentsOf(projectDir, rel) {
146
+ const own = ownFolder(projectDir, rel);
147
+ if (own.kind === 'link') return { agents: [], known: false, folder: null };
148
+ if (own.folder === null) return { agents: [], known: true, folder: null };
149
+ const w = walk(path.join(projectDir, ...own.folder.split('/')), { under: own.folder });
150
+ const of = (file, extra) => ({ file, name: file.slice(file.lastIndexOf('/') + 1), group: file.slice(own.folder.length + 1, file.lastIndexOf('/')), ...extra });
151
+ const agents = [
152
+ ...w.files.filter((f) => AGENT_NAME.test(f.rel.slice(f.rel.lastIndexOf('/') + 1))).map((f) => of(f.rel, { bytes: f.size, mtime: f.mtimeMs, openable: true })),
153
+ ...w.lossy.filter((r) => AGENT_NAME.test(r.slice(r.lastIndexOf('/') + 1))).map((r) => of(r, { bytes: null, mtime: null, openable: false })),
154
+ ].sort((a, b) => (a.mtime ?? Infinity) - (b.mtime ?? Infinity) || (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
155
+ return { agents, known: w.links === 0 && w.unreadable === 0, folder: own.folder };
156
+ }
157
+
158
+ /** The session whose own folder holds the transcript at `rel` (an agent's): the nearest folder on its path with
159
+ * <folder>.jsonl beside it, or a set-aside copy of it (<folder>.orphaned-….jsonl, <folder>.superseded-….jsonl). Its
160
+ * path in the project, or null. */
161
+ export function parentOf(projectDir, rel) {
162
+ const parts = relParts(rel);
163
+ if (!parts) return null;
164
+ for (let i = parts.length - 2; i >= 0; i--) {
165
+ const at = parts.slice(0, i), name = parts[i];
166
+ if (kind(path.join(projectDir, ...at, `${name}.jsonl`)) === 'file') return [...at, `${name}.jsonl`].join('/');
167
+ let beside = [];
168
+ try { beside = readdirSync(path.join(projectDir, ...at), { withFileTypes: true }); } catch {}
169
+ const aside = beside.filter((e) => e.isFile() && SET_ASIDE.exec(e.name)?.[1] === name).map((e) => e.name).sort();
170
+ if (aside.length) return [...at, aside[0]].join('/');
171
+ }
172
+ return null;
173
+ }
174
+
175
+ /** A name that stands for one transcript: a session's (a UUID) or an agent's (agent-<id>). Only such names are grouped
176
+ * as copies; a workflow's journal.jsonl, say, has the same name in every run. */
177
+ export const identifies = (name) => UUID_NAME.test(name.slice(0, -'.jsonl'.length)) || AGENT_NAME.test(name);
178
+
179
+ /** The order in which copies are chosen: the fewest folders first (Claude Code keeps a session at its project's top, an
180
+ * agent in its session's folder), then by path. */
181
+ export const byPlace = (a, b) => a.split('/').length - b.split('/').length || (a < b ? -1 : a > b ? 1 : 0);
package/src/lines.mjs ADDED
@@ -0,0 +1,18 @@
1
+ // src/lines.mjs — the lines of a stream, split at "\n" only.
2
+ //
3
+ // Every process this extension talks to (the reading process, the ltms command) writes one JSON value per line.
4
+ // JSON.stringify leaves U+2028 and U+2029 unescaped inside strings, and Node's readline ends a line at both, so a
5
+ // transcript that holds either would cut a JSON line in two, and the request it answers would wait forever (measured:
6
+ // three JSON lines through readline came out as five, four of them not JSON). So this splits at "\n" alone.
7
+ export function onLines(stream, onLine, onEnd) {
8
+ // each chunk is searched once: the unfinished line's chunks wait in a list, joined only when its "\n" arrives (a long
9
+ // line is not scanned again for every chunk that brings it)
10
+ let parts = [];
11
+ stream.setEncoding('utf8');
12
+ stream.on('data', (chunk) => {
13
+ let start = 0, i;
14
+ while ((i = chunk.indexOf('\n', start)) >= 0) { parts.push(chunk.slice(start, i)); onLine(parts.join('')); parts = []; start = i + 1; }
15
+ if (start < chunk.length) parts.push(chunk.slice(start));
16
+ });
17
+ stream.on('end', () => { if (parts.length) onLine(parts.join('')); parts = []; onEnd?.(); });
18
+ }
package/src/main.mjs ADDED
@@ -0,0 +1,133 @@
1
+ // src/main.mjs — the command: its arguments, the refusals made before anything is read, then the screen until a way
2
+ // out, and the terminal restored on each: q (exit 0), Ctrl-C (130), SIGINT (130), SIGHUP (129), SIGTERM (143), the
3
+ // command's process gone (N5; R3: then this process ends by SIGKILL, no one waiting for its code), and an uncaught error
4
+ // (1), which is printed after the restore. An error is printed by its kind and where it happened in this package, not by
5
+ // its message, which could quote a transcript (ltms's own rule); a refusal of this package's own (a file too large, a
6
+ // name refused) is printed whole: it holds paths and sizes, never a transcript's text.
7
+ import { spawnSync } from 'node:child_process';
8
+ import { readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { App } from './app.mjs';
13
+ import { openScreen, colourFrom } from './screen.mjs';
14
+ import { FileSource, RootSource } from './sources.mjs';
15
+ import { USAGE, againOf, notTerminal, parseArgs, startOf } from './start.mjs';
16
+ import { rtlModeOf, visible } from './text.mjs';
17
+
18
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
19
+ export const version = () => JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
20
+
21
+ /** What is printed of an error after the terminal is restored: its kind, and the lines of its stack that are in this
22
+ * package or in Node; its message only when it is a refusal of this package's own (it has a kind). `where`: the
23
+ * process it happened in, when it is not the screen's (src/guard.mjs: "the command's process"). */
24
+ export function errorReport(e, where = null) {
25
+ const kind = typeof e?.name === 'string' ? e.name : typeof e;
26
+ const own = e instanceof Error && typeof e.kind === 'string';
27
+ const frames = String(e?.stack ?? '').split('\n').filter((l) => /^\s+at /.test(l) && (l.includes(ROOT) || /\(node:|at node:/.test(l))).slice(0, 12);
28
+ return visible(`ltms-reader: ${own ? e.message : `an internal error (${kind})${where ? ` in ${where}` : ''} ended it`}; the terminal was restored.\n${frames.length ? `${frames.join('\n')}\n` : ''}${own ? '' : 'Its message is not printed: it could quote a transcript.\n'}`);
29
+ }
30
+
31
+ /**
32
+ * What the command does before its screen opens: the help, the version, a usage error, and the refusals (stdin or
33
+ * stdout not a terminal, LTMS_READER_BIDI set to a mode there is not, a path that is none of the three ways in), each
34
+ * written, and its exit code returned; or, when the screen is to open, { a: the arguments, start: what to open, rtl: the
35
+ * right-to-left mode }. Only isTTY is read of stdin and stdout.
36
+ */
37
+ export function before(argv, { stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, env = process.env } = {}) {
38
+ const a = parseArgs(argv);
39
+ if (a.help) { stdout.write(USAGE); return 0; }
40
+ if (a.version) { stdout.write(`ltms-reader ${version()}\n`); return 0; }
41
+ if (a.usage) { stderr.write(`${visible(`ltms-reader: ${a.usage}\n`)}${USAGE}`); return 2; }
42
+ const tty = notTerminal(stdin, stdout);
43
+ if (tty) { stderr.write(tty); return 2; }
44
+ const rtl = rtlModeOf(env);
45
+ if (rtl.refused) { stderr.write(visible(`ltms-reader: ${rtl.refused}; nothing was read\n`)); return 2; }
46
+ const start = startOf(a.path, { env, home: homedir() });
47
+ if (start.refused) { stderr.write(visible(`ltms-reader: ${start.refused}\n`)); return 2; }
48
+ return { a, start, rtl: rtl.mode };
49
+ }
50
+
51
+ /** Who has the terminal now, by /proc/self/stat (Linux): { ours: whether this process's group is the terminal's
52
+ * foreground group, group: the foreground group }; null where that cannot be read (another system, no terminal). */
53
+ export function terminalOwner(stat = () => readFileSync('/proc/self/stat', 'utf8')) {
54
+ try {
55
+ const s = stat(), f = s.slice(s.lastIndexOf(')') + 2).split(' ');
56
+ const pgrp = Number(f[2]), tpgid = Number(f[5]);
57
+ if (!(pgrp > 0) || !(tpgid > 0)) return null;
58
+ return { ours: tpgid === pgrp, group: tpgid };
59
+ } catch { return null; }
60
+ }
61
+
62
+ /** The terminal's modes as `stty -g` gives them, read on this process's stdin; null when stty cannot say. */
63
+ export function terminalModes() {
64
+ try {
65
+ const r = spawnSync('stty', ['-g'], { stdio: [0, 'pipe', 'ignore'], encoding: 'utf8', timeout: 2000 });
66
+ return r.status === 0 ? r.stdout.trim() : null;
67
+ } catch { return null; }
68
+ }
69
+
70
+ /**
71
+ * Run the command. Returns the exit code when it ends before the screen (usage, a refusal); once the screen is open,
72
+ * it returns { app, finish } and the process exits from the screen, through finish(). The streams and the process are
73
+ * parameters so that the tests can run it whole on streams of their own. bin/ltms-reader.mjs runs this in a process of
74
+ * its own (src/screen-process.mjs), and restores the terminal if that process ends without doing so (src/guard.mjs).
75
+ */
76
+ export function main(argv, { stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, env = process.env, proc = process, owner = terminalOwner, modes = terminalModes } = {}) {
77
+ const b = before(argv, { stdin, stdout, stderr, env });
78
+ if (typeof b === 'number') return b;
79
+ const { a, start, rtl } = b;
80
+
81
+ // a refusal of a transcript too large names the command that was run, with what it was given
82
+ const again = againOf(a.path);
83
+ const source = start.kind === 'file' ? new FileSource({ file: start.file, again }) : new RootSource({ root: start.root, only: start.project ?? null, again });
84
+ let screen = null, app = null, finished = false;
85
+ const finish = (code, err = null) => {
86
+ if (finished) return;
87
+ finished = true;
88
+ try { app?.dispose(); } catch {}
89
+ try { screen?.restore(); } catch {}
90
+ try { source.dispose(); } catch {}
91
+ if (err !== null) { try { stderr.write(errorReport(err)); } catch {} }
92
+ proc.exit(code);
93
+ };
94
+ proc.on('SIGTERM', () => finish(143));
95
+ proc.on('SIGHUP', () => finish(129));
96
+ proc.on('SIGINT', () => finish(130));
97
+ proc.on('uncaughtException', (e) => finish(1, e));
98
+ proc.on('unhandledRejection', (e) => finish(1, e));
99
+ proc.on('exit', () => { try { screen?.restore(); } catch {} });
100
+ // run by the command (src/guard.mjs), this process has an IPC channel to it, which closes when the command's process
101
+ // is gone, by SIGKILL too, which nothing there can answer (N5): the terminal is restored here, and this process ends.
102
+ // The channel is unref'd, so that it keeps nothing running.
103
+ //
104
+ // R3: a shell with job control that waited for the command takes the terminal back as soon as the command is gone
105
+ // (measured: bash, zsh and fish wrote their prompt 4 to 6 ms after its SIGKILL, this process 4 to 5 ms after), and
106
+ // sets its own modes (bash and fish set theirs; zsh builds its line editor's on the modes it finds). This process's
107
+ // group is then a background one, orphaned, so that the kernel refuses it the terminal's modes (EIO), but where SIGTTOU
108
+ // is blocked, as Node's own exit blocks it to put back the modes this process started with: that put them back over
109
+ // the shell's (the terminal echoed what was typed twice). So the leave sequence is written at once (the screen), and
110
+ // when the terminal is no longer this process group's, the modes are left to the shell, but if they are still the
111
+ // screen's raw ones (`stty -g`, read when the screen opened): a shell that sets none (as dash's job control sets none)
112
+ // gets them back by Node's own exit; otherwise this process ends by SIGKILL, without that exit.
113
+ const commandGone = () => {
114
+ if (finished) return;
115
+ finished = true;
116
+ try { app?.dispose(); } catch {}
117
+ const who = owner(), back = who !== null && !who.ours;
118
+ try { screen?.restore({ modes: !back }); } catch {}
119
+ try { source.dispose(); } catch {}
120
+ if (back && (rawModes === null || modes() === rawModes)) { proc.exit(129); return; }
121
+ proc.kill(proc.pid, 'SIGKILL');
122
+ };
123
+ if (proc.channel) { proc.on('disconnect', commandGone); try { proc.channel.unref(); } catch {} }
124
+
125
+ const draw = () => { if (screen && app) { const { cols, rows } = screen.size(); app.state.cols = cols; app.state.rows = rows; screen.draw(app.lines(), cols, rows); } };
126
+ screen = openScreen({ input: stdin, output: stdout, colour: colourFrom(env), rtl, onKey: (str, k) => app?.key(str, k ?? {}), onResize: () => draw() });
127
+ // the screen's raw modes, by stty, to tell after the command's end whether a shell has set its own since (R3)
128
+ const rawModes = proc.channel ? modes() : null;
129
+ const { cols, rows } = screen.size();
130
+ app = new App({ source, cols, rows, onChange: draw, onExit: (code) => finish(code) });
131
+ app.start({ project: start.project ?? null });
132
+ return { app, finish };
133
+ }
@@ -0,0 +1,165 @@
1
+ // src/reading.mjs — one transcript read in the reader's own process, with ltms's parser, and the session view of it
2
+ // (src/view.mjs). A terminal app has no editor to protect, so it needs no separate reading process (DESIGN.md, "One view
3
+ // layer, two faces").
4
+ //
5
+ // The file is opened without following a symbolic link at its last step (O_NOFOLLOW), and without blocking on a FIFO put
6
+ // at its name (O_NONBLOCK); it must be a regular file, and it is read from the descriptor checked. A transcript too
7
+ // large to parse in this process's memory is refused before it is read, with its size and the NODE_OPTIONS that would
8
+ // let it be read: the rule is ltms's own (a file over a tenth of the runtime's memory limit is skipped, so the reader
9
+ // and ltms's lists agree on which files can be read; parsing takes 5 to 8 times a file's size), the memory limit read
10
+ // as memoryLimit reads it, and a file over 480 MB cannot be read at all, by JavaScript's limit on a string's length.
11
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';
12
+ import { totalmem } from 'node:os';
13
+ import path from 'node:path';
14
+ import { getHeapStatistics } from 'node:v8';
15
+ import { parseTranscript } from '#ltms';
16
+ import { prefixOf, sessionView } from './view.mjs';
17
+
18
+ export const MB = 1024 * 1024;
19
+ /** No memory setting reads a file over this: its text would pass JavaScript's limit on a string's length. */
20
+ export const STRING_MAX = 480 * MB;
21
+
22
+ export class Refusal extends Error { constructor(kind, message) { super(message); this.kind = kind; } }
23
+
24
+ /** NODE_OPTIONS's words, as Node reads them (its ParseNodeOptionsEnvVar): apart at spaces, a double-quoted stretch part
25
+ * of a word with its spaces, a backslash in one taking the character after it as it is. */
26
+ function nodeOptionWords(s) {
27
+ const out = [];
28
+ let word = null, quoted = false;
29
+ for (let i = 0; i < s.length; i++) {
30
+ let c = s[i];
31
+ if (c === '\\' && quoted && i + 1 < s.length) c = s[++i];
32
+ else if (c === '"') { quoted = !quoted; continue; }
33
+ else if (c === ' ' && !quoted) { if (word !== null) out.push(word); word = null; continue; }
34
+ word = (word ?? '') + c;
35
+ }
36
+ if (word !== null) out.push(word);
37
+ return out;
38
+ }
39
+
40
+ /** The memory Node reads for --max-old-space-size-percentage: the process's constraint (a cgroup's limit), where there
41
+ * is one, else the machine's. */
42
+ function memoryOfNode() {
43
+ const c = typeof process.constrainedMemory === 'function' ? process.constrainedMemory() : 0;
44
+ return c > 0 && Number.isSafeInteger(c) ? c : totalmem();
45
+ }
46
+
47
+ /**
48
+ * The memory limit the size rules read: Node's heap limit (V8's heap_size_limit, ltms's measure), but no
49
+ * more than the old space's where Node's flags set it. A heap limit is the old space and the young generation's reserve,
50
+ * and the reserve is sized from the machine's memory, not from the old space set: with --max-old-space-size=16, measured,
51
+ * the heap limit is 64 MB on Node 20.20.2 and 22.23.3, 208 MB on 24.22.3 and 112 MB on 26.13.1 (with
52
+ * --max-semi-space-size=1 too, 19 MB). A transcript's text and what its parse makes of it live in the old space: by a
53
+ * tenth of the heap limit, under an old space of 16 MB, Node 24 read a transcript of 8 to 20 MB and its parse ran the old
54
+ * space out (R.F14 on Box B's Node 24.18.0), and Node 26 one of 10 or 11 MB (measured on 2026-11-17). The flags, as
55
+ * Node and V8 take them (measured on Node 22.23.3 and 24.22.3): --max-old-space-size=N (or --max_old_space_size), in
56
+ * NODE_OPTIONS or on node's command line, the command line's over NODE_OPTIONS', the last given, 0 setting none; and
57
+ * --max-old-space-size-percentage=P (Node 22 and later), the old space at P per cent of the memory Node reads (in MB,
58
+ * rounded down), over --max-old-space-size wherever each is given. Where no flag sets the old space, V8 sizes the old
59
+ * space and the young generation together, from the memory it finds, and the heap limit is the measure. Not read: a
60
+ * limit set by --max-heap-size (the heap limit is then about it) or by an embedder. `heap`, `execArgv`, `nodeOptions` and
61
+ * `memory` are this process's when not given.
62
+ */
63
+ export function memoryLimit({ heap = getHeapStatistics().heap_size_limit, execArgv = process.execArgv, nodeOptions = process.env.NODE_OPTIONS, memory = memoryOfNode() } = {}) {
64
+ let size = 0, percent = 0;
65
+ for (const word of [...(typeof nodeOptions === 'string' ? nodeOptionWords(nodeOptions) : []), ...execArgv]) {
66
+ const m = /^--max[-_]old[-_]space[-_]size(?:[-_](percentage))?=(.*)$/.exec(word);
67
+ if (!m) continue;
68
+ const v = Number(m[2]);
69
+ if (m[1]) { if (v > 0 && v <= 100) percent = v; } else if (Number.isInteger(v) && v >= 0) size = v;
70
+ }
71
+ const old = percent > 0 ? Math.floor((Math.floor(memory / MB) * percent) / 100) * MB : size > 0 ? size * MB : null;
72
+ return old === null ? heap : Math.min(heap, old);
73
+ }
74
+
75
+ /** The largest transcript this process reads, by ltms's rule, for a memory limit of `heapLimit` bytes. */
76
+ export const sizeLimit = (heapLimit) => Math.min(STRING_MAX, Math.floor(heapLimit / 10));
77
+
78
+ /** n bytes as a refusal says them: in KB under a megabyte, else in MB, rounded by `round`: a size up (Math.ceil), so that
79
+ * it is never said smaller than it is, and a limit down (Math.floor), never said larger. Rounding both up, a
80
+ * transcript's refusal said "it is 2 MB, and this process reads a transcript of up to 2 MB". */
81
+ const sized = (n, round) => (n < MB ? `${round(n / 1024).toLocaleString('en-US')} KB` : `${round(n / MB).toLocaleString('en-US')} MB`);
82
+
83
+ /** Why a file of `size` bytes is not read here (with the NODE_OPTIONS that would let it be, before `again`, the command
84
+ * that was run: src/start.mjs's againOf), or null when it is read. `heapLimit`: the memory limit (memoryLimit). */
85
+ export function tooLarge(size, heapLimit = memoryLimit(), again = 'npx ltms-reader') {
86
+ const limit = sizeLimit(heapLimit);
87
+ if (size <= limit) return null;
88
+ if (size > STRING_MAX) return `it is ${sized(size, Math.ceil)}: no memory setting lets it be read, since its text would pass JavaScript's limit on a string's length (about ${sized(STRING_MAX, Math.floor)} here); ltms skips it too`;
89
+ // ltms's rule reads a file of up to a tenth of the heap's limit; the old space alone, set to ten times the size, is enough
90
+ const need = Math.ceil((size * 10) / MB / 256) * 256;
91
+ return `it is ${sized(size, Math.ceil)}, and this process reads a transcript of up to ${sized(limit, Math.floor)} (a tenth of its memory limit, as ltms reads; parsing takes 5 to 8 times a file's size). To read it, give Node more memory: NODE_OPTIONS=--max-old-space-size=${need} ${again}`;
92
+ }
93
+
94
+ /** What a transcript's parse takes, at most, for each byte of the file (ltms's figure: 5 to 8 times a file's size). */
95
+ export const PARSE_PER_BYTE = 8;
96
+ /** What a record's view takes, at most, for each byte of the record's line in the file. Measured (R.F1's probe, one
97
+ * record of each kind): its strings (the record as JSON, and the parts it re-writes as JSON) and the marks of its lines
98
+ * took up to 5.5 bytes a byte, for an array of numbers (re-written with indents, some 6 characters a byte); a JSON
99
+ * that holds one character outside Latin-1 takes two bytes a character, so up to 12; this is that with a margin. */
100
+ export const RECORD_VIEW_PER_BYTE = 16;
101
+
102
+ /** What writing a record's JSON takes in the old space, for each byte of that JSON (`built`, view.mjs recordViewBytes),
103
+ * the JSON itself included. Measured on 2026-11-17 (the least --max-old-space-size at
104
+ * which the reader, run as the tests run it, opened a record and laid out its JSON, with the size rules set aside), less
105
+ * what the reader needs for a record of no size (BUILT_MARGIN's measure), over the JSON: for lists nested 200 to 990 deep
106
+ * of 10,000 to 1,000,000 numbers, Latin or Hebrew strings, in files of up to 2.4 MB, up to 1.04 times on Node 22.23.3,
107
+ * 24.22.3 and 26.13.1 (13 records each), and up to 1.41 on Node 20.20.2 (19 records; a list nested 600 deep of 60,000
108
+ * Hebrew strings, 212 MB of JSON, opened from an old space of 306 MB there, from 222 to 224 on the others). */
109
+ export const BUILT_PER_BYTE = 1.5;
110
+ /** What a record's view needs beside what writing its JSON takes and the transcript's parse, in the old space: the
111
+ * reader's own, measured as the least old space at which it opened the smallest record (R.F1's shape, a
112
+ * line of 11 KB) and laid out its JSON: 7 MB on Node 20.20.2 and 22.23.3, 8 on 26.13.1, 9 on 24.22.3. With these, the
113
+ * rule refuses at every old space at which a measured record's view ran out (130 records over the four lines: text of
114
+ * 11 KB to 16 MB, lists nested deep, a list of a million numbers, objects of 100,000 and 200,000 keys), and shows the
115
+ * smallest from an old space of 14 MB. An earlier rule had 96 MB here, measured against Node's heap limit, which holds
116
+ * the young generation's reserve beside the old space; once the rule read the old space set, with 96 MB it refused
117
+ * every record under an old space below about 107 MB (found on 2026-11-17: records of 11 KB and 513 KB at 32 and
118
+ * 64 MB, on Node 20, 24 and 26). */
119
+ export const BUILT_MARGIN = 12 * MB;
120
+
121
+ /**
122
+ * Why the record written on a line of `bytes` bytes, in a transcript of `fileSize` bytes, is not shown here (with the
123
+ * NODE_OPTIONS that would let it be, before `again`, the command that was run), or null when it is shown: its view, at
124
+ * RECORD_VIEW_PER_BYTE times its size, must fit beside the transcript's parse, at PARSE_PER_BYTE times the file's size,
125
+ * in nine tenths of the memory limit (R.F1: a record a transcript's size allowed ran Node's heap out, and the abort left
126
+ * the terminal raw); and so must what writing the JSON the view writes of it takes, BUILT_PER_BYTE times its `built`
127
+ * bytes (view.mjs recordViewBytes), and BUILT_MARGIN (N3: a record nested deep, its line small, wrote JSON hundreds of
128
+ * times its size, and ran the heap out).
129
+ */
130
+ export function recordTooLarge(bytes, fileSize, heapLimit = memoryLimit(), again = 'npx ltms-reader', built = 0) {
131
+ const room = 0.9 * heapLimit - PARSE_PER_BYTE * fileSize;
132
+ const limit = Math.max(0, Math.floor(room / RECORD_VIEW_PER_BYTE));
133
+ // the setting at which both fit: its old space alone (Node's limit is that and more), and a tenth of it for the transcript
134
+ const need = (view) => Math.ceil(Math.max(10 * fileSize, (PARSE_PER_BYTE * fileSize + view) / 0.9) / MB / 256) * 256;
135
+ const writing = built > 0 ? BUILT_PER_BYTE * built + BUILT_MARGIN : 0;
136
+ const view = Math.max(RECORD_VIEW_PER_BYTE * bytes, writing);
137
+ if (bytes > limit) return `it is ${sized(bytes, Math.ceil)}, and in a transcript of ${sized(fileSize, Math.ceil)} this process shows a record of up to ${sized(limit, Math.floor)} (its view takes up to ${RECORD_VIEW_PER_BYTE} times a record's size, the transcript's parse up to ${PARSE_PER_BYTE} times the file's, both within nine tenths of the memory limit). To show it, give Node more memory: NODE_OPTIONS=--max-old-space-size=${need(view)} ${again}`;
138
+ if (built > 0 && writing > room) return `it is ${sized(bytes, Math.ceil)}, and its view would write ${sized(built, Math.ceil)} of JSON (indented, as JSON is, once more at each level a value is nested in), which takes up to ${BUILT_PER_BYTE} times that to write, and with what the view needs beside it (${sized(BUILT_MARGIN, Math.ceil)}) does not fit beside the transcript's parse in nine tenths of the memory limit. To show it, give Node more memory: NODE_OPTIONS=--max-old-space-size=${need(view)} ${again}`;
139
+ return null;
140
+ }
141
+
142
+ /**
143
+ * Read and parse one transcript; `abs` is its full path (already checked by the caller to be a regular file reached
144
+ * through no symbolic link). Returns { abs, name, prefix, size, t, view }: `view` is the session view, uncapped (a
145
+ * terminal draws only the rows on screen), whose turns, calls and compactions are those `ltms skeleton` prints.
146
+ * heapLimit: the limit the size rule reads by (the runtime's when not given); again: the command a refusal names.
147
+ */
148
+ export function readTranscript(abs, { heapLimit, again } = {}) {
149
+ let fd;
150
+ try { fd = openSync(abs, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); }
151
+ catch (e) {
152
+ if (e.code === 'ELOOP' || e.code === 'EMLINK') throw new Refusal('not-file', `${abs} is a symbolic link; a transcript is read only as a regular file`);
153
+ if (e.code === 'ENOENT') throw new Refusal('missing', `no file at ${abs}: it may have been moved, or removed by Claude Code's cleanup`);
154
+ throw new Refusal('unreadable', `${abs} could not be opened (${e.code ?? 'unreadable'})`);
155
+ }
156
+ try {
157
+ const st = fstatSync(fd);
158
+ if (!st.isFile()) throw new Refusal('not-file', `${abs} is not a regular file`);
159
+ const why = tooLarge(st.size, heapLimit, again);
160
+ if (why) throw new Refusal('too-large', `${abs} is not read: ${why}`);
161
+ const t = parseTranscript(readFileSync(fd, 'utf8'));
162
+ const name = path.basename(abs);
163
+ return { abs, name, prefix: prefixOf(name), size: st.size, mtimeMs: st.mtimeMs, t, view: sessionView(t, { name, caps: false }) };
164
+ } finally { closeSync(fd); }
165
+ }
@@ -0,0 +1,6 @@
1
+ // src/screen-process.mjs — the reader's screen in a process of its own: bin/ltms-reader.mjs starts it (src/guard.mjs)
2
+ // on its own terminal, with its own arguments, and restores the terminal when this process ends without doing so.
3
+ import { main } from './main.mjs';
4
+
5
+ const code = main(process.argv.slice(2));
6
+ if (typeof code === 'number') process.exitCode = code;