@drakulavich/cogload 0.10.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,256 @@
1
+ // The only module that uses bun:sqlite or writes the cache. The transcripts are
2
+ // the system of record: every doubt here resolves to a miss, and no error leaves.
3
+ import { Database } from "bun:sqlite";
4
+ import { createHash } from "node:crypto";
5
+ import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
6
+ import { open } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import type { ScanEntry } from "./scan.io.ts";
9
+ import type { Event, EventKind } from "../types.ts";
10
+
11
+ export type Fresh = { entry: ScanEntry; tail: Uint8Array; fromMs: number; events: Event[] };
12
+ export type TranscriptCache = {
13
+ // null: the cache failed and is off for this run.
14
+ hits(entries: ScanEntry[], cutoffMs: number): Promise<Map<string, Event[]> | null>;
15
+ save(hit: ScanEntry[], fresh: Fresh[], nowMs: number): void;
16
+ close(): void;
17
+ };
18
+
19
+ const USER_VERSION = 1;
20
+ const TAIL_BYTES = 4096;
21
+ const READERS = 16;
22
+ const KEEP_MS = 90 * 86_400_000;
23
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
24
+ const KINDS: Record<EventKind, true> = { prompt: true, report: true, output: true, interrupt: true, reject: true, answer: true, question: true, plan_review: true, mode_change: true, activity: true };
25
+
26
+ export function tailHash(bytes: Uint8Array): Uint8Array {
27
+ return createHash("sha256").update(bytes.subarray(Math.max(0, bytes.length - TAIL_BYTES))).digest();
28
+ }
29
+
30
+ function fingerprint(): Uint8Array {
31
+ const h = createHash("sha256");
32
+ h.update(readFileSync(new URL("./parse.ts", import.meta.url)));
33
+ h.update(readFileSync(new URL("../types.ts", import.meta.url)));
34
+ h.update(String((JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8")) as { version?: unknown }).version));
35
+ return h.digest();
36
+ }
37
+
38
+ function encode(events: Event[]): Uint8Array {
39
+ const sessions: string[] = [];
40
+ const index = new Map<string, number>();
41
+ const rows = events.map((e) => {
42
+ let i = index.get(e.sessionId);
43
+ if (i === undefined) { i = sessions.length; index.set(e.sessionId, i); sessions.push(e.sessionId); }
44
+ return e.tokens === undefined ? [e.ts, e.kind, i] : [e.ts, e.kind, i, e.tokens];
45
+ });
46
+ return new TextEncoder().encode(JSON.stringify({ sessions, events: rows }));
47
+ }
48
+
49
+ function decode(blob: Uint8Array): Event[] | null {
50
+ try {
51
+ const d: unknown = JSON.parse(new TextDecoder().decode(blob));
52
+ if (typeof d !== "object" || d === null) return null;
53
+ const { sessions, events } = d as { sessions?: unknown; events?: unknown };
54
+ if (!Array.isArray(sessions) || !sessions.every((s) => typeof s === "string") || !Array.isArray(events)) return null;
55
+ const out: Event[] = [];
56
+ for (const r of events) {
57
+ if (!Array.isArray(r) || r.length < 3 || r.length > 4) return null;
58
+ const [ts, kind, i, tokens] = r as unknown[];
59
+ if (typeof ts !== "number" || typeof kind !== "string" || !Object.hasOwn(KINDS, kind) || typeof i !== "number" || sessions[i] === undefined) return null;
60
+ const e: Event = { ts, sessionId: sessions[i] as string, kind: kind as EventKind };
61
+ if (r.length === 4) {
62
+ if (kind !== "output" || typeof tokens !== "number") return null;
63
+ e.tokens = tokens;
64
+ }
65
+ out.push(e);
66
+ }
67
+ return out;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ // The bytes just before the stored offset, like a log consumer's check; the
74
+ // size comparison is what notices a file that grew.
75
+ async function readTail(path: string, size: number): Promise<Uint8Array | null> {
76
+ try {
77
+ const fh = await open(path, "r");
78
+ try {
79
+ const n = Math.min(TAIL_BYTES, size);
80
+ const buf = new Uint8Array(n);
81
+ const { bytesRead } = await fh.read(buf, 0, n, size - n);
82
+ return bytesRead === n ? buf : null;
83
+ } finally {
84
+ await fh.close();
85
+ }
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ const equal = (a: Uint8Array, b: Uint8Array): boolean => a.length === b.length && a.every((x, i) => x === b[i]);
92
+
93
+ type Row = { dev: number; ino: number; size: number; mtime_ms: number; tail: Uint8Array; from_ms: number; events: Uint8Array };
94
+
95
+ class Foreign extends Error {}
96
+
97
+ // Only a file that is not ours is replaced; a locked or unopenable one is left alone.
98
+ const replaceable = (e: unknown): boolean =>
99
+ e instanceof Foreign || /^SQLITE_(NOTADB|CORRUPT)/.test(String((e as { code?: unknown } | null)?.code));
100
+
101
+ // Modes are set on what cogload creates; a mode the person set later is theirs.
102
+ function connect(path: string): Database {
103
+ // Made 0600 before SQLite sees it: SQLite would create it 0644 less the
104
+ // umask, and gives -wal and -shm the database file's mode.
105
+ let created = false;
106
+ try {
107
+ closeSync(openSync(path, "wx", 0o600));
108
+ created = true;
109
+ } catch (e) {
110
+ if ((e as { code?: unknown }).code !== "EEXIST") throw e;
111
+ }
112
+ const db = new Database(path, { create: true, strict: true });
113
+ try {
114
+ if (created) chmodSync(path, 0o600);
115
+ db.run("PRAGMA busy_timeout = 2000");
116
+ db.run("PRAGMA journal_mode = WAL");
117
+ db.run("PRAGMA synchronous = NORMAL");
118
+ db.transaction(() => {
119
+ const { user_version } = db.query<{ user_version: number }, []>("PRAGMA user_version").get()!;
120
+ if (user_version === USER_VERSION) return;
121
+ if (user_version !== 0) throw new Foreign();
122
+ db.run(`CREATE TABLE transcript (
123
+ dev INTEGER NOT NULL, ino INTEGER NOT NULL, parser BLOB NOT NULL, size INTEGER NOT NULL, mtime_ms REAL NOT NULL,
124
+ tail BLOB NOT NULL, from_ms REAL NOT NULL, used_at INTEGER NOT NULL, events BLOB NOT NULL, PRIMARY KEY (dev, ino))`);
125
+ db.run(`PRAGMA user_version = ${USER_VERSION}`);
126
+ }).immediate();
127
+ return db;
128
+ } catch (e) {
129
+ try { db.close(); } catch {}
130
+ throw e;
131
+ }
132
+ }
133
+
134
+ export function openCache(env: NodeJS.ProcessEnv): TranscriptCache | null {
135
+ const home = env.HOME;
136
+ if (!home) return null;
137
+ try {
138
+ const parser = fingerprint();
139
+ // No process-wide umask: it would also narrow the card this run writes.
140
+ // Each directory is chmodded the moment it is made, so a restrictive umask
141
+ // cannot leave a parent the next level cannot be made in; `connect`
142
+ // creates the database 0600 itself, and SQLite gives its WAL files the
143
+ // database's mode.
144
+ const dir = join(home, ".claude", "cogload");
145
+ // An existing directory keeps the mode it has.
146
+ for (const d of [join(home, ".claude"), dir]) {
147
+ try {
148
+ mkdirSync(d, { mode: 0o700 });
149
+ chmodSync(d, 0o700);
150
+ } catch (e) {
151
+ if ((e as { code?: unknown }).code !== "EEXIST") throw e;
152
+ }
153
+ }
154
+ const path = join(dir, "cache.db");
155
+ // Taken before the open: a run that failed on the old file must not
156
+ // delete the one another run recreated meanwhile. No file, nothing to delete.
157
+ const seen = fileId(path);
158
+ try {
159
+ return cacheOn(connect(path), parser, path);
160
+ } catch (e) {
161
+ if (!replaceable(e)) return null;
162
+ }
163
+ if (seen !== null && fileId(path) === seen) remove(path);
164
+ return cacheOn(connect(path), parser, path);
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+
170
+ const remove = (path: string): void => { for (const f of [path, `${path}-wal`, `${path}-shm`]) rmSync(f, { force: true }); };
171
+
172
+ const fileId = (path: string): string | null => { try { const s = statSync(path); return `${s.dev}:${s.ino}`; } catch { return null; } };
173
+
174
+ // A file found corrupt only once it is queried (the header was fine) is
175
+ // replaced like one that fails to open, once; this run then misses every file.
176
+ function cacheOn(db: Database, parser: Uint8Array, path: string): TranscriptCache {
177
+ let failed = false;
178
+ const opened = fileId(path);
179
+ // Rows whose events did not decode: the conditional upsert would keep them.
180
+ const broken: { dev: number; ino: number }[] = [];
181
+ return {
182
+ async hits(entries, cutoffMs) {
183
+ const found = new Map<string, Event[]>();
184
+ try {
185
+ const keyed = entries.filter((e) => e.ino !== 0);
186
+ const rows = db.query<Row, [Uint8Array, string]>(
187
+ `SELECT dev, ino, size, mtime_ms, tail, from_ms, events FROM transcript
188
+ WHERE parser = ? AND (dev, ino) IN (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?))`,
189
+ ).all(parser, JSON.stringify(keyed.map((e) => [e.dev, e.ino])));
190
+ const byKey = new Map(rows.map((r) => [`${r.dev}:${r.ino}`, r]));
191
+ const candidates = keyed.flatMap((entry) => {
192
+ const row = byKey.get(`${entry.dev}:${entry.ino}`);
193
+ return row && row.size === entry.size && row.mtime_ms === entry.mtimeMs && row.from_ms <= cutoffMs ? [{ entry, row }] : [];
194
+ });
195
+ let next = 0;
196
+ const reader = async (): Promise<void> => {
197
+ while (next < candidates.length) {
198
+ const { entry, row } = candidates[next++]!;
199
+ const tail = await readTail(entry.path, row.size);
200
+ if (tail === null || !equal(tailHash(tail), row.tail)) continue;
201
+ const events = decode(row.events);
202
+ if (events !== null) found.set(entry.path, events);
203
+ else broken.push({ dev: row.dev, ino: row.ino });
204
+ }
205
+ };
206
+ await Promise.all(Array.from({ length: Math.min(READERS, candidates.length) }, reader));
207
+ } catch (e) {
208
+ found.clear();
209
+ broken.length = 0;
210
+ if (!replaceable(e)) { failed = true; return null; }
211
+ try { db.close(); } catch {}
212
+ try {
213
+ // Only the file this run opened: a different one at the path is
214
+ // another run's fresh cache. Unlinking a file another run still has
215
+ // open is fine for a cache: its descriptors stay valid, its writes are lost.
216
+ if (opened !== null && fileId(path) === opened) remove(path);
217
+ db = connect(path);
218
+ } catch {
219
+ failed = true;
220
+ return null;
221
+ }
222
+ }
223
+ return found;
224
+ },
225
+
226
+ save(hit, fresh, nowMs) {
227
+ if (failed) return;
228
+ try {
229
+ const upsert = db.query(
230
+ `INSERT INTO transcript (dev, ino, parser, size, mtime_ms, tail, from_ms, used_at, events)
231
+ VALUES ($dev, $ino, $parser, $size, $mtime, $tail, $from, $now, $events)
232
+ ON CONFLICT(dev, ino) DO UPDATE SET parser = excluded.parser, size = excluded.size, mtime_ms = excluded.mtime_ms,
233
+ tail = excluded.tail, from_ms = excluded.from_ms, used_at = excluded.used_at, events = excluded.events
234
+ WHERE NOT (transcript.parser = excluded.parser AND transcript.size = excluded.size
235
+ AND transcript.mtime_ms = excluded.mtime_ms AND transcript.tail = excluded.tail
236
+ AND transcript.from_ms <= excluded.from_ms)`,
237
+ );
238
+ const touch = db.query("UPDATE transcript SET used_at = $now WHERE dev = $dev AND ino = $ino");
239
+ const drop = db.query("DELETE FROM transcript WHERE dev = $dev AND ino = $ino");
240
+ db.transaction(() => {
241
+ for (const k of broken) drop.run(k);
242
+ for (const { entry: e, tail, fromMs, events } of fresh) {
243
+ if (e.ino === 0 || !events.every((ev) => UUID.test(ev.sessionId))) continue;
244
+ upsert.run({ dev: e.dev, ino: e.ino, parser, size: e.size, mtime: e.mtimeMs, tail, from: fromMs, now: nowMs, events: encode(events) });
245
+ }
246
+ for (const e of hit) if (e.ino !== 0) touch.run({ now: nowMs, dev: e.dev, ino: e.ino });
247
+ db.run("DELETE FROM transcript WHERE used_at < ?", [nowMs - KEEP_MS]);
248
+ }).immediate();
249
+ } catch {}
250
+ },
251
+
252
+ close() {
253
+ try { db.close(); } catch {}
254
+ },
255
+ };
256
+ }
@@ -0,0 +1,3 @@
1
+ export { parseTranscript } from "./parse.ts";
2
+ export { scan, type ScanEntry, type ScanStats } from "./scan.io.ts";
3
+ export { openCache, tailHash, type Fresh, type TranscriptCache } from "./cache.io.ts";
@@ -0,0 +1,138 @@
1
+ import type { Event } from "../types.ts";
2
+
3
+ // Markers compared against message text. The text itself is never kept.
4
+ const INTERRUPT_PREFIX = "[Request interrupted by user";
5
+ const REJECT_PREFIX = "The user doesn't want to proceed with this tool use";
6
+ const QUESTION_TOOL = "AskUserQuestion";
7
+ const PLAN_TOOL = "ExitPlanMode";
8
+ // Inbound agent messages: read and reacted to, but not typed, so `report`, never
9
+ // `prompt`. An interrupt marker is checked first and wins.
10
+ const AGENT_MARKERS = [
11
+ "Another Claude session sent a message:",
12
+ "<teammate-message",
13
+ "<cross-session-message",
14
+ "<task-notification>",
15
+ "[Cross-session",
16
+ ];
17
+
18
+ type Rec = Record<string, unknown>;
19
+ const isObj = (v: unknown): v is Rec => typeof v === "object" && v !== null;
20
+ const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
21
+
22
+ // A pasted screenshot puts an `image` block before the typed text, so the text
23
+ // block is searched for, not taken from content[0].
24
+ const firstText = (content: unknown): string | null => {
25
+ if (typeof content === "string") return content;
26
+ if (!Array.isArray(content)) return null;
27
+ for (const b of content) if (isObj(b) && b.type === "text") return str(b.text);
28
+ return null;
29
+ };
30
+
31
+ // A record older than the look-back yields only events derive() drops, so it is
32
+ // not parsed at all. Every "timestamp" in the line must be old, since a nested
33
+ // one can differ from the record's own. The skip waits for a first timestamped
34
+ // record, which the mode switches before it attach to; lines naming the two
35
+ // tools whose result the human writes are always parsed, for their ids.
36
+ // One pass over the line: it costs a fifth of JSON.parse.
37
+ const SKIP_SCAN = new RegExp(`"timestamp":"([^"]{20,40})"|${QUESTION_TOOL}|${PLAN_TOOL}`, "g");
38
+ function olderThan(line: string, cutoffMs: number): boolean {
39
+ // Parsing an assistant record can update seenRequestIds even when its events
40
+ // are outside the window. Preserve that deduplication state across the skip.
41
+ if (line.includes('"requestId"')) return false;
42
+ let any = false;
43
+ for (const m of line.matchAll(SKIP_SCAN)) {
44
+ if (m[1] === undefined || !(Date.parse(m[1]) < cutoffMs)) return false;
45
+ any = true;
46
+ }
47
+ return any;
48
+ }
49
+
50
+ export function parseTranscript(text: string, cutoffMs = -Infinity): Event[] {
51
+ const events: Event[] = [];
52
+ let lastTs: number | null = null;
53
+ let lastMode: string | null = null;
54
+ let pendingModeChanges = 0;
55
+ // Claude Code writes one record per content block of a response, repeating
56
+ // the requestId and usage; only the first qualifying record counts.
57
+ const seenRequestIds = new Set<string>();
58
+ // Ids of the two tools whose result the human writes; every other
59
+ // `tool_result` is the machine reporting back.
60
+ const askedIds = new Set<string>();
61
+
62
+ // Claude Code writes no byte order mark, but an editor can; left in, it would
63
+ // make the first record invalid JSON.
64
+ const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
65
+ for (const line of body.split("\n")) {
66
+ if (line.trim() === "") continue;
67
+ if (lastTs !== null && lastTs < cutoffMs && olderThan(line, cutoffMs)) continue;
68
+ let rec: unknown;
69
+ try { rec = JSON.parse(line); } catch { continue; }
70
+ if (!isObj(rec)) continue;
71
+ const type = str(rec.type);
72
+ const sessionId = str(rec.sessionId);
73
+ if (type === null || sessionId === null) continue;
74
+ if (rec.isSidechain === true) continue;
75
+ if (str(rec.entrypoint)?.startsWith("sdk-")) continue; // a script ran `claude -p` or the Agent SDK
76
+
77
+ if (type === "permission-mode") {
78
+ const m = str(rec.permissionMode);
79
+ if (m === null) continue;
80
+ // A switch before the first timestamped record is how a session often
81
+ // starts; it waits and is attributed to that record.
82
+ if (lastMode !== null && m !== lastMode) {
83
+ if (lastTs === null) pendingModeChanges++;
84
+ else events.push({ ts: lastTs, sessionId, kind: "mode_change" });
85
+ }
86
+ lastMode = m;
87
+ continue;
88
+ }
89
+
90
+ if (type !== "user" && type !== "assistant") continue;
91
+ const ts = Date.parse(str(rec.timestamp) ?? "");
92
+ if (Number.isNaN(ts)) continue;
93
+ lastTs = ts;
94
+ events.push({ ts, sessionId, kind: "activity" });
95
+ for (; pendingModeChanges > 0; pendingModeChanges--) events.push({ ts, sessionId, kind: "mode_change" });
96
+
97
+ const content = isObj(rec.message) ? rec.message.content : undefined;
98
+ if (type === "user") {
99
+ const blocks = Array.isArray(content) ? content : [];
100
+ for (const b of blocks) {
101
+ if (!isObj(b) || b.type !== "tool_result") continue;
102
+ const t = firstText(b.content);
103
+ if (t !== null && t.startsWith(REJECT_PREFIX)) events.push({ ts, sessionId, kind: "reject" });
104
+ const toolUseId = str(b.tool_use_id);
105
+ if (toolUseId !== null && askedIds.has(toolUseId)) events.push({ ts, sessionId, kind: "answer" });
106
+ }
107
+ const head = firstText(content);
108
+ if (head === null) continue;
109
+ if (head.startsWith(INTERRUPT_PREFIX)) events.push({ ts, sessionId, kind: "interrupt" });
110
+ else if (rec.isMeta !== true) {
111
+ if (AGENT_MARKERS.some((marker) => head.startsWith(marker))) events.push({ ts, sessionId, kind: "report" });
112
+ else events.push({ ts, sessionId, kind: "prompt" });
113
+ }
114
+ } else {
115
+ const blocks = Array.isArray(content) ? content : [];
116
+ for (const b of blocks) {
117
+ if (!isObj(b) || b.type !== "tool_use") continue;
118
+ if (b.name !== QUESTION_TOOL && b.name !== PLAN_TOOL) continue;
119
+ events.push({ ts, sessionId, kind: b.name === QUESTION_TOOL ? "question" : "plan_review" });
120
+ const id = str(b.id);
121
+ if (id !== null) askedIds.add(id);
122
+ }
123
+ // A response of only tool_use blocks is not text the human reads and carries
124
+ // no output tokens. A count must be a finite non-negative integer: `1e309`
125
+ // parses to Infinity, and a day once summed to NaN.
126
+ const requestId = str(rec.requestId);
127
+ const usage = isObj(rec.message) ? rec.message.usage : undefined;
128
+ const outputTokens = isObj(usage) ? usage.output_tokens : undefined;
129
+ const tokens = typeof outputTokens === "number" && Number.isSafeInteger(outputTokens) && outputTokens >= 0 ? outputTokens : null;
130
+ const hasText = blocks.some((b) => isObj(b) && b.type === "text");
131
+ if (requestId !== null && tokens !== null && hasText && !seenRequestIds.has(requestId)) {
132
+ seenRequestIds.add(requestId);
133
+ events.push({ ts, sessionId, kind: "output", tokens });
134
+ }
135
+ }
136
+ }
137
+ return events;
138
+ }
@@ -0,0 +1,75 @@
1
+ import { constants, type Dirent } from "node:fs";
2
+ import { access, open, readdir, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+
5
+ // What --verbose reports about the walk: transcripts seen, and how many of them
6
+ // were opened only to read the tail of a file older than the window by mtime.
7
+ export type ScanStats = { files: number; tailChecks: number };
8
+ export type ScanEntry = { path: string; dev: number; ino: number; size: number; mtimeMs: number };
9
+
10
+ // A `subagents` directory holds the parent agent's conversation, not the human's.
11
+ export async function scan(projects: string, cutoffMs: number, stats: ScanStats = { files: 0, tailChecks: 0 }): Promise<ScanEntry[]> {
12
+ // No path in any message: the CLI never prints one. A directory that can be
13
+ // listed but not entered (mode 444) would otherwise read as one with no activity.
14
+ let root;
15
+ try {
16
+ if (!(await stat(projects)).isDirectory()) throw Object.assign(new Error("not a directory"), { code: "ENOTDIR" });
17
+ await access(projects, constants.R_OK | constants.X_OK);
18
+ root = await readdir(projects, { withFileTypes: true });
19
+ } catch (err) {
20
+ const code = (err as { code?: string }).code;
21
+ if (code === "EACCES" || code === "EPERM") throw new Error("projects directory cannot be read (check its permissions)");
22
+ if (code === "ENOTDIR") throw new Error("projects path is not a directory (pass --projects <dir>)");
23
+ throw new Error("projects directory not found (pass --projects <dir>)");
24
+ }
25
+ const out: ScanEntry[] = [];
26
+ await collect(projects, root, cutoffMs, out, stats);
27
+ return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
28
+ }
29
+
30
+ // One unreadable directory costs only itself. Symlinks are not followed: Claude
31
+ // Code never writes one, and following one is how a loop or $HOME would get in.
32
+ async function collect(dir: string, entries: Dirent[], cutoffMs: number, out: ScanEntry[], stats: ScanStats): Promise<void> {
33
+ for (const entry of entries) {
34
+ const full = join(dir, entry.name);
35
+ if (entry.isDirectory()) {
36
+ if (entry.name === "subagents") continue;
37
+ try {
38
+ await collect(full, await readdir(full, { withFileTypes: true }), cutoffMs, out, stats);
39
+ } catch {}
40
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
41
+ stats.files++;
42
+ try {
43
+ const st = await stat(full);
44
+ if (st.mtimeMs < cutoffMs) {
45
+ stats.tailChecks++;
46
+ if ((await lastTimestampMs(full)) < cutoffMs) continue;
47
+ }
48
+ out.push({ path: full, dev: st.dev, ino: st.ino, size: st.size, mtimeMs: st.mtimeMs });
49
+ } catch {}
50
+ }
51
+ }
52
+ }
53
+
54
+ // mtime can be older than the records inside (sync, restore, clock skew), so for
55
+ // a file mtime would drop, the last "timestamp" in its final 64 KB decides. 64 KB
56
+ // because the last record is often a big tool result with its timestamp in front.
57
+ const TAIL_BYTES = 65_536;
58
+ async function lastTimestampMs(path: string): Promise<number> {
59
+ const fh = await open(path, "r");
60
+ try {
61
+ const size = (await fh.stat()).size;
62
+ const start = Math.max(0, size - TAIL_BYTES);
63
+ const buf = Buffer.alloc(size - start);
64
+ await fh.read(buf, 0, buf.length, start);
65
+ const tail = buf.toString("utf8");
66
+ let last = -Infinity;
67
+ for (const m of tail.matchAll(/"timestamp":"([^"]{20,40})"/g)) {
68
+ const ms = Date.parse(m[1]!);
69
+ if (!Number.isNaN(ms)) last = ms;
70
+ }
71
+ return last;
72
+ } finally {
73
+ await fh.close();
74
+ }
75
+ }
@@ -0,0 +1,22 @@
1
+ export type EventKind = "prompt" | "report" | "output" | "interrupt" | "reject" | "answer" | "question" | "plan_review" | "mode_change" | "activity";
2
+ export type Event = { ts: number; sessionId: string; kind: EventKind; tokens?: number };
3
+ export type Transcript = { path: string; text: string };
4
+ // to = "YYYY-MM-DD" local. `streakFrom` reads further back than the 3 h look-back,
5
+ // for `presence` only: the live streak is traced to its first action, up to it.
6
+ export type Window = { to: string; days: number; now?: Date; streakFrom?: Date };
7
+ export type Metrics = {
8
+ sessions: number; prompts: number; reports: number; outputTokens: number; interrupts: number; rejects: number; questions: number;
9
+ plans: number; modeSwitches: number; decisions: number; contextSwitches: number;
10
+ activeMin: number; streakMin: number; lateNight: boolean;
11
+ };
12
+ export type Level = "Calm" | "Warming" | "Heating" | "Fried";
13
+ export type Parts = { parallel: number; pace: number; supervision: number; reading: number; streak: number; late: number }; // weighted points, sum ≈ index
14
+ export type Score = { index: number; level: Level; parts: Parts };
15
+ export type LiveBucket = Metrics & { score: Score | null };
16
+ export type HourBucket = LiveBucket & { hour: number };
17
+ export type Totals = { prompts: number; reports: number; outputTokens: number; interrupts: number; rejects: number; questions: number; plans: number; modeSwitches: number; decisions: number; contextSwitches: number; maxSessions: number };
18
+ // `asOf` and `live` exist only on the day containing `now`: `live` is the sixty
19
+ // minutes `(asOf − 60 min, asOf]`, by the hour bucket's rule, look-back included.
20
+ // `presence` is the day's last human action and the start of its streak, which
21
+ // may lie on an earlier day; instants are ISO 8601 UTC.
22
+ export type Day = { date: string; peak: number | null; mean: number | null; activeMin: number; presence: { lastAt: string; streakStartAt: string } | null; totals: Totals; buckets: HourBucket[]; asOf?: string; live?: LiveBucket };