llmtop 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llmtop",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Local usage and cost analytics dashboard and CLI for Claude Code, Codex and Antigravity",
6
6
  "author": "Trung Nguyen",
package/src/db.mjs CHANGED
@@ -10,6 +10,7 @@ CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT);
10
10
  CREATE TABLE files(id INTEGER PRIMARY KEY, provider TEXT, path TEXT, kind TEXT, session_id TEXT, agent_id TEXT,
11
11
  generation INTEGER DEFAULT 0, offset INTEGER DEFAULT 0, lines INTEGER DEFAULT 0, head_hash TEXT,
12
12
  archive_size INTEGER DEFAULT 0, first_ts TEXT, own_first TEXT, own_last TEXT, cwd TEXT, live INTEGER DEFAULT 1,
13
+ ctime_ms REAL,
13
14
  UNIQUE(provider, path));
14
15
  CREATE TABLE records(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, type TEXT, ts TEXT);
15
16
  CREATE INDEX files_session ON files(session_id);
@@ -20,10 +21,12 @@ CREATE TABLE requests(message_id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER
20
21
  rebuild TEXT, rebuild_gap INTEGER, rebuild_extra REAL);
21
22
  CREATE INDEX requests_session ON requests(session_id);
22
23
  CREATE INDEX requests_day ON requests(day);
24
+ CREATE INDEX requests_file ON requests(file_id);
23
25
  CREATE TABLE repeats(file_id INTEGER, message_id TEXT, PRIMARY KEY(file_id, message_id));
24
26
  CREATE TABLE owner_messages(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, ts TEXT,
25
27
  kind TEXT, text TEXT);
26
28
  CREATE INDEX owner_messages_session ON owner_messages(session_id);
29
+ CREATE INDEX owner_messages_file ON owner_messages(file_id);
27
30
  CREATE VIRTUAL TABLE owner_text USING fts5(text, content='owner_messages', content_rowid='rowid',
28
31
  tokenize="unicode61 remove_diacritics 2");
29
32
  CREATE TRIGGER owner_messages_ai AFTER INSERT ON owner_messages BEGIN
@@ -33,15 +36,18 @@ CREATE TRIGGER owner_messages_ad AFTER DELETE ON owner_messages BEGIN
33
36
  CREATE TABLE tool_calls(id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT,
34
37
  ts TEXT, name TEXT, model TEXT, is_error INTEGER);
35
38
  CREATE INDEX tool_calls_session ON tool_calls(session_id);
39
+ CREATE INDEX tool_calls_file ON tool_calls(file_id);
36
40
  CREATE TABLE skills(id TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, ts TEXT, name TEXT, via TEXT,
37
41
  source TEXT, is_error INTEGER DEFAULT 0);
38
42
  CREATE INDEX skills_session ON skills(session_id);
43
+ CREATE INDEX skills_file ON skills(file_id);
39
44
  CREATE TABLE subagents(agent_id TEXT PRIMARY KEY, session_id TEXT, type TEXT, tool_use_id TEXT);
40
45
  CREATE TABLE file_meta(file_id INTEGER PRIMARY KEY, parent_session_id TEXT, subagent_type TEXT, tool_use_id TEXT,
41
46
  api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER, repo_url TEXT, target_paths TEXT);
42
47
  CREATE TABLE compactions(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT, ts TEXT,
43
48
  trigger TEXT, pre_tokens INTEGER, post_tokens INTEGER, duration_ms INTEGER);
44
49
  CREATE INDEX compactions_session ON compactions(session_id);
50
+ CREATE INDEX compactions_file ON compactions(file_id);
45
51
  CREATE TABLE cost_states(file_id INTEGER, line INTEGER, session_id TEXT, start_ms INTEGER, cost REAL,
46
52
  incomplete INTEGER, api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER,
47
53
  model_usage TEXT, PRIMARY KEY(file_id, line));
@@ -55,6 +61,27 @@ CREATE TABLE sessions(id TEXT PRIMARY KEY, provider TEXT, slug TEXT, cwd TEXT, p
55
61
  // Tables holding rows ingested from one transcript file; used when a file starts a new generation.
56
62
  export const FILE_TABLES = ["records", "requests", "repeats", "owner_messages", "tool_calls", "skills", "compactions", "cost_states", "titles", "file_meta"];
57
63
 
64
+ function configureDb(db) {
65
+ db.exec(`
66
+ PRAGMA journal_mode = WAL;
67
+ PRAGMA synchronous = NORMAL;
68
+ PRAGMA temp_store = MEMORY;
69
+ PRAGMA cache_size = -64000;
70
+ `);
71
+ }
72
+
73
+ function upgradeInPlace(db) {
74
+ const cols = db.prepare("PRAGMA table_info(files)").all();
75
+ if (!cols.some((c) => c.name === "ctime_ms")) db.exec("ALTER TABLE files ADD COLUMN ctime_ms REAL");
76
+ db.exec(`
77
+ CREATE INDEX IF NOT EXISTS requests_file ON requests(file_id);
78
+ CREATE INDEX IF NOT EXISTS tool_calls_file ON tool_calls(file_id);
79
+ CREATE INDEX IF NOT EXISTS skills_file ON skills(file_id);
80
+ CREATE INDEX IF NOT EXISTS compactions_file ON compactions(file_id);
81
+ CREATE INDEX IF NOT EXISTS owner_messages_file ON owner_messages(file_id);
82
+ `);
83
+ }
84
+
58
85
  export function openDb(path) {
59
86
  mkdirSync(dirname(path), { recursive: true });
60
87
  if (existsSync(path)) {
@@ -66,12 +93,16 @@ export function openDb(path) {
66
93
  return undefined;
67
94
  }
68
95
  })();
69
- if (version === String(SCHEMA_VERSION)) return old;
96
+ if (version === String(SCHEMA_VERSION)) {
97
+ configureDb(old);
98
+ upgradeInPlace(old);
99
+ return old;
100
+ }
70
101
  old.close();
71
102
  for (const f of [path, `${path}-wal`, `${path}-shm`]) rmSync(f, { force: true });
72
103
  }
73
104
  const db = new DatabaseSync(path);
74
- db.exec("PRAGMA journal_mode = WAL");
105
+ configureDb(db);
75
106
  db.exec(SCHEMA);
76
107
  db.prepare("INSERT INTO meta(key, value) VALUES ('schema', ?)").run(String(SCHEMA_VERSION));
77
108
  return db;
package/src/derive.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // Per-session values computed after every scan from the ingested rows. Cheap: one pass over sessions.
2
+ import { createHash } from "node:crypto";
2
3
  import { existsSync, readFileSync, statSync } from "node:fs";
3
4
  import { homedir, tmpdir } from "node:os";
4
5
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -12,6 +13,14 @@ const GENERIC_DIR_RE = /^(?:repo|src|worktree|checkout|tmp|temp|home|code|docs|t
12
13
  const validRepoName = (n) => Boolean(n && n.length >= 3 && !n.startsWith(".") && !GENERIC_DIR_RE.test(n));
13
14
  const inTmpDir = (p) => p.startsWith(tmpdir() + sep) || p.startsWith("/tmp/") || p.startsWith("/var/tmp/");
14
15
 
16
+ const checkExists = (p, existsCache) => {
17
+ if (!existsCache) return existsSync(p);
18
+ if (existsCache.has(p)) return existsCache.get(p);
19
+ const v = existsSync(p);
20
+ existsCache.set(p, v);
21
+ return v;
22
+ };
23
+
15
24
  function manifestNameOf(dir) {
16
25
  try {
17
26
  const pkg = join(dir, "package.json");
@@ -75,15 +84,29 @@ function resolveGitDirName(dir, gitDir, depth = 0) {
75
84
  return base;
76
85
  }
77
86
 
78
- function gitRepoOf(p) {
79
- if (!p || !existsSync(p)) return null;
87
+ function gitRepoOf(p, gitCache = null, existsCache = null) {
88
+ if (!p) return null;
89
+ if (gitCache?.has(p)) return gitCache.get(p);
90
+ const save = (val) => {
91
+ gitCache?.set(p, val);
92
+ return val;
93
+ };
94
+ if (!checkExists(p, existsCache)) return save(null);
80
95
  let dir = p;
81
96
  try {
82
97
  if (!statSync(dir).isDirectory()) dir = dirname(dir);
83
98
  } catch {
84
- return null;
99
+ return save(null);
85
100
  }
101
+ if (dir !== p && gitCache?.has(dir)) return save(gitCache.get(dir));
102
+ const walked = [];
103
+ let hit = null;
86
104
  for (; ; dir = dirname(dir)) {
105
+ if (gitCache?.has(dir)) {
106
+ hit = gitCache.get(dir);
107
+ break;
108
+ }
109
+ walked.push(dir);
87
110
  if (!IGNORE_GIT_ROOTS.has(dir)) {
88
111
  const g = join(dir, ".git");
89
112
  if (existsSync(g)) {
@@ -98,28 +121,32 @@ function gitRepoOf(p) {
98
121
  const mainRoot = wt[1];
99
122
  let name = resolveGitDirName(mainRoot, join(mainRoot, ".git"));
100
123
  if (GENERIC_DIR_RE.test(name)) name = manifestNameOf(dir) || name;
101
- return { root: mainRoot, name };
124
+ hit = { root: mainRoot, name };
125
+ break;
102
126
  }
103
127
  }
104
128
  } else if (st.isDirectory()) {
105
- return { root: dir, name: resolveGitDirName(dir, g) };
129
+ hit = { root: dir, name: resolveGitDirName(dir, g) };
130
+ break;
106
131
  }
107
132
  } catch { /* unreadable .git metadata; fall back to dir name */ }
108
- return { root: dir, name: basename(dir) };
133
+ hit = { root: dir, name: basename(dir) };
134
+ break;
109
135
  }
110
136
  }
111
137
  if (dirname(dir) === dir) break;
112
138
  }
113
- return null;
139
+ for (const w of walked) gitCache?.set(w, hit);
140
+ return save(hit);
114
141
  }
115
142
 
116
143
  // The nearest directory at or above cwd that holds .git (skipping root/home/tmp, resolving worktrees/temp clones), else cwd's own name.
117
144
  // onDisk tells whether cwd still exists, so a session whose folder is gone keeps the project it had without climbing parent repos.
118
- export function projectOf(cwd) {
145
+ export function projectOf(cwd, gitCache = null, existsCache = null) {
119
146
  if (!cwd) return null;
120
- const onDisk = existsSync(cwd);
147
+ const onDisk = checkExists(cwd, existsCache);
121
148
  if (onDisk) {
122
- const g = gitRepoOf(cwd);
149
+ const g = gitRepoOf(cwd, gitCache, existsCache);
123
150
  if (g) return { name: g.name, onDisk: true };
124
151
  }
125
152
  return { name: basename(cwd) || "(no project)", onDisk };
@@ -152,13 +179,13 @@ function matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown) {
152
179
  return null;
153
180
  }
154
181
 
155
- function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, knownRepos, sortedKnown) {
156
- const cwdRepo = cwd ? gitRepoOf(cwd) : null;
182
+ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, knownRepos, sortedKnown, gitCache, existsCache) {
183
+ const cwdRepo = cwd ? gitRepoOf(cwd, gitCache, existsCache) : null;
157
184
  const urlRepo = repoFromUrl(repoUrl);
158
185
  const byRepo = new Map();
159
186
  for (const [dir, [w, r]] of Object.entries(pathWeights ?? {})) {
160
- let name = gitRepoOf(dir)?.name ?? null;
161
- if (!name && (!existsSync(dir) || inTmpDir(dir))) name = matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown);
187
+ let name = gitRepoOf(dir, gitCache, existsCache)?.name ?? null;
188
+ if (!name && (!checkExists(dir, existsCache) || inTmpDir(dir))) name = matchFallbackPath(dir, cwdRepo, knownRepos, sortedKnown);
162
189
  if (!name) continue;
163
190
  const cur = byRepo.get(name) ?? { name, w: 0, r: 0 };
164
191
  cur.w += w;
@@ -189,7 +216,7 @@ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, known
189
216
  return cwdRepo.name;
190
217
  }
191
218
  if (urlRepo) return urlRepo;
192
- const p = projectOf(cwd);
219
+ const p = projectOf(cwd, gitCache, existsCache);
193
220
  if (p && !p.onDisk) {
194
221
  const segHit = matchSeg(basename(cwd), new Set(), knownRepos, sortedKnown);
195
222
  if (segHit) return segHit;
@@ -198,8 +225,52 @@ function resolveSessionProject(cwd, repoUrl, pathWeights, existingProject, known
198
225
  }
199
226
 
200
227
  const firstLine = (text) => text.split("\n").find((l) => l.trim())?.trim().slice(0, 80) ?? null;
228
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
229
+
230
+ function expandDirtySessions(db, dirtySessions) {
231
+ const expanded = new Set(dirtySessions);
232
+ const dependents = new Map();
233
+ const addEdge = (prev, next) => {
234
+ if (!prev || !next || prev === next) return;
235
+ let set = dependents.get(prev);
236
+ if (!set) dependents.set(prev, (set = new Set()));
237
+ set.add(next);
238
+ };
239
+ for (const r of db.prepare("SELECT id, carried_from FROM sessions WHERE carried_from IS NOT NULL").all()) {
240
+ addEdge(r.carried_from, r.id);
241
+ }
242
+ for (const r of db.prepare(`SELECT DISTINCT f.session_id id, q.session_id prev_id FROM repeats p
243
+ JOIN requests q ON q.message_id = p.message_id JOIN files f ON f.id = p.file_id AND f.kind = 'main'`).all()) {
244
+ addEdge(r.prev_id, r.id);
245
+ }
246
+ const queue = [...expanded];
247
+ while (queue.length) {
248
+ const cur = queue.pop();
249
+ const nexts = dependents.get(cur);
250
+ if (!nexts) continue;
251
+ for (const n of nexts) {
252
+ if (!expanded.has(n)) {
253
+ expanded.add(n);
254
+ queue.push(n);
255
+ }
256
+ }
257
+ }
258
+ return expanded;
259
+ }
260
+
261
+ export function derive(db, config, { dirtySessions = null, full = false } = {}) {
262
+ const pricesText = existsSync(config.prices) ? readFileSync(config.prices, "utf8") : "";
263
+ const deriveKey = sha256(`${config.timeZone}\n${pricesText}`);
264
+ const getMeta = db.prepare("SELECT value FROM meta WHERE key = ?");
265
+ const putMeta = db.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
266
+ const prevKey = getMeta.get("derive_key")?.value;
267
+ const forceFull = full || dirtySessions === null || prevKey !== deriveKey;
268
+ if (!forceFull && dirtySessions.size === 0) return;
269
+
270
+ const expandedDirty = forceFull ? null : expandDirtySessions(db, dirtySessions);
271
+ const gitCache = new Map();
272
+ const existsCache = new Map();
201
273
 
202
- export function derive(db, config) {
203
274
  const files = db.prepare("SELECT id, provider, session_id, path, cwd, own_first first_ts, own_last last_ts FROM files WHERE kind = 'main'").all();
204
275
  const existing = new Map(db.prepare("SELECT id, project FROM sessions").all().map((s) => [s.id, s.project]));
205
276
  const titles = db.prepare("SELECT kind, title FROM titles WHERE file_id = ? ORDER BY line DESC");
@@ -207,7 +278,7 @@ export function derive(db, config) {
207
278
  const lastCost = db.prepare("SELECT * FROM cost_states WHERE file_id = ? ORDER BY line DESC LIMIT 1");
208
279
  const knownRepos = new Set();
209
280
  for (const f of files) {
210
- const g = f.cwd ? gitRepoOf(f.cwd) : null;
281
+ const g = f.cwd ? gitRepoOf(f.cwd, gitCache, existsCache) : null;
211
282
  if (g && validRepoName(g.name)) knownRepos.add(g.name);
212
283
  }
213
284
  const sessionMeta = new Map();
@@ -234,13 +305,18 @@ export function derive(db, config) {
234
305
  const prev = cur.pathWeights[dir] ?? (cur.pathWeights[dir] = [0, 0]);
235
306
  prev[0] += Number(pair[0]) || 0;
236
307
  prev[1] += Number(pair[1]) || 0;
237
- const g = gitRepoOf(dir);
308
+ const g = gitRepoOf(dir, gitCache, existsCache);
238
309
  if (g && validRepoName(g.name)) knownRepos.add(g.name);
239
310
  }
240
311
  } catch { /* ignore malformed json */ }
241
312
  }
242
313
  }
243
314
  const sortedKnown = [...knownRepos].sort((a, b) => b.length - a.length);
315
+ const knownReposHash = sha256(sortedKnown.join("\n"));
316
+ const prevReposHash = getMeta.get("known_repos_hash")?.value;
317
+ const deriveAll = forceFull || knownReposHash !== prevReposHash;
318
+ const targetFiles = deriveAll ? files : files.filter((f) => expandedDirty.has(f.session_id));
319
+
244
320
  // The session this file continues or forks: of the sessions owning the requests it repeats, the latest to start.
245
321
  // CROSS JOIN keeps the order from the file's few repeats; left to the planner it scanned every file and request per file.
246
322
  const predecessor = db.prepare(`SELECT f.session_id id FROM repeats p CROSS JOIN requests q ON q.message_id = p.message_id
@@ -258,21 +334,26 @@ export function derive(db, config) {
258
334
  api_ms = excluded.api_ms, tool_ms = excluded.tool_ms, lines_added = excluded.lines_added, lines_removed = excluded.lines_removed,
259
335
  carried_from = excluded.carried_from, model_cost = excluded.model_cost, model_tokens = excluded.model_tokens`);
260
336
 
337
+ const fileBySession = new Map(files.map((f) => [f.session_id, f]));
261
338
  const raw = new Map();
262
- for (const f of files) {
263
- const c = lastCost.get(f.id);
264
- raw.set(f.session_id, c ? { ...c, models: JSON.parse(c.model_usage) } : null);
265
- }
339
+ const rawOf = (sessionId) => {
340
+ if (raw.has(sessionId)) return raw.get(sessionId);
341
+ const f = fileBySession.get(sessionId);
342
+ const c = f ? lastCost.get(f.id) : null;
343
+ const val = c ? { ...c, models: JSON.parse(c.model_usage) } : null;
344
+ raw.set(sessionId, val);
345
+ return val;
346
+ };
266
347
 
267
348
  db.exec("BEGIN");
268
349
  try {
269
- for (const f of files) {
350
+ for (const f of targetFiles) {
270
351
  const ms = sessionMeta.get(f.session_id);
271
- const project = resolveSessionProject(f.cwd, ms?.repo_url ?? null, ms?.pathWeights ?? null, existing.get(f.session_id), knownRepos, sortedKnown);
352
+ const project = resolveSessionProject(f.cwd, ms?.repo_url ?? null, ms?.pathWeights ?? null, existing.get(f.session_id), knownRepos, sortedKnown, gitCache, existsCache);
272
353
  const t = titles.all(f.id);
273
354
  const title = t.find((x) => x.kind === "custom")?.title ?? t.find((x) => x.kind === "ai")?.title ?? (firstOwner.get(f.session_id)?.text ? firstLine(firstOwner.get(f.session_id).text) : null);
274
355
 
275
- const c = raw.get(f.session_id);
356
+ const c = rawOf(f.session_id);
276
357
  let cost = null;
277
358
  let models = null;
278
359
  let tokens = null;
@@ -289,7 +370,7 @@ export function derive(db, config) {
289
370
  // A host record that started with the earlier session's record is cumulative and holds all of it;
290
371
  // a fork or a resume in a new process starts its own record shortly before its first own line.
291
372
  const earlier = predecessor.get(f.id, f.session_id);
292
- prev = earlier ? raw.get(earlier.id) : null;
373
+ prev = earlier ? rawOf(earlier.id) : null;
293
374
  if (prev && c.start_ms !== null && prev.start_ms !== null && c.start_ms <= prev.start_ms + 1000) {
294
375
  carriedFrom = earlier.id;
295
376
  const less = (v, w) => (v === null ? null : Math.max(0, v - (w ?? 0)));
@@ -337,10 +418,12 @@ export function derive(db, config) {
337
418
  upsert.run(f.session_id, f.provider, f.path.split(sep)[0], f.cwd, project, title, f.first_ts, f.last_ts, cost,
338
419
  c ? (c.incomplete ? 1 : 0) : null, estimated, check ? JSON.stringify(check) : null, api, tool, added, removed, carriedFrom, models ? JSON.stringify(models) : null, tokens ? JSON.stringify(tokens) : null);
339
420
  }
421
+ putMeta.run("derive_key", deriveKey);
422
+ putMeta.run("known_repos_hash", knownReposHash);
340
423
  db.exec("COMMIT");
341
424
  } catch (err) {
342
425
  db.exec("ROLLBACK");
343
426
  throw err;
344
427
  }
345
- markRebuilds(db, prices);
428
+ markRebuilds(db, prices, forceFull ? null : expandedDirty);
346
429
  }
package/src/prices.mjs CHANGED
@@ -32,17 +32,37 @@ export function readPrices(config) {
32
32
  return { rows, errors };
33
33
  }
34
34
 
35
+ const PRICE_INDEX = new WeakMap();
36
+
37
+ function indexPrices(rows) {
38
+ let entry = PRICE_INDEX.get(rows);
39
+ if (!entry || entry.len !== rows.length) {
40
+ const byModel = new Map();
41
+ for (const r of rows) {
42
+ let list = byModel.get(r.model);
43
+ if (!list) byModel.set(r.model, (list = []));
44
+ list.push(r);
45
+ }
46
+ entry = { len: rows.length, byModel };
47
+ PRICE_INDEX.set(rows, entry);
48
+ }
49
+ return entry.byModel;
50
+ }
51
+
35
52
  // The row in force for a model id on a local day; strips context suffixes, effort suffixes and date snapshots.
36
53
  export function priceAt(rows, model, day) {
54
+ const byModel = indexPrices(rows);
37
55
  const noCtx = model.replace(/\[.*\]$/, "");
38
56
  const noEff = noCtx.replace(/-(?:low|medium|high|xhigh|max)$/, "");
39
57
  const noDate = noCtx.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
40
58
  const bare = noEff.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
41
59
  for (const id of new Set([model, noCtx, noEff, noDate, bare])) {
60
+ const cand = byModel.get(id);
61
+ if (!cand) continue;
42
62
  let hit = null;
43
- for (const r of rows) if (r.model === id && r.from <= day && (!hit || r.from > hit.from)) hit = r;
63
+ for (const r of cand) if (r.from <= day && (!hit || r.from > hit.from)) hit = r;
44
64
  if (hit) return hit;
45
- if (rows.some((r) => r.model === id)) return null;
65
+ return null;
46
66
  }
47
67
  return null;
48
68
  }
@@ -232,7 +232,7 @@ export function createIngester(db, timeZone) {
232
232
  const AGY_WRITE_TOOLS = new Set(["edit_file", "write_file", "replace_file_content", "multi_replace_file_content", "write_to_file"]);
233
233
  const AGY_READ_TOOLS = new Set(["read_file", "view_file", "grep_search", "find_by_name", "list_dir", "run_command"]);
234
234
 
235
- return function ingestLine(file, line, text) {
235
+ function ingestLine(file, line, text) {
236
236
  let rec;
237
237
  try {
238
238
  rec = JSON.parse(text);
@@ -248,6 +248,7 @@ export function createIngester(db, timeZone) {
248
248
  apiMs: prevStats?.api_ms ?? 0, toolMs: prevStats?.tool_ms ?? 0,
249
249
  linesAdded: prevStats?.lines_added ?? 0, linesRemoved: prevStats?.lines_removed ?? 0,
250
250
  paths: createPathTracker(prevStats?.target_paths ?? null),
251
+ statsDirty: false, pathsDirty: false,
251
252
  };
252
253
  stateByFile.set(file.id, st);
253
254
  }
@@ -261,18 +262,16 @@ export function createIngester(db, timeZone) {
261
262
  const tsMs = Number.isFinite(parsedTs) ? parsedTs : null;
262
263
  const uuid = `agy:${ownId}:${step}`;
263
264
  let added = 0;
264
- let statsDirty = false;
265
- let pathsDirty = false;
266
265
 
267
266
  if (tsMs !== null && st.lastTsMs !== null) {
268
267
  const dt = tsMs - st.lastTsMs;
269
268
  if (dt > 0 && dt < 600_000) {
270
269
  if (rec.type === "PLANNER_RESPONSE" && (st.lastType === "USER_INPUT" || st.lastType === "GENERIC" || st.lastType === "SYSTEM_MESSAGE")) {
271
270
  st.apiMs += Math.round(dt);
272
- statsDirty = true;
271
+ st.statsDirty = true;
273
272
  } else if (rec.type === "GENERIC" && st.lastType === "PLANNER_RESPONSE") {
274
273
  st.toolMs += Math.round(dt);
275
- statsDirty = true;
274
+ st.statsDirty = true;
276
275
  }
277
276
  }
278
277
  }
@@ -298,28 +297,28 @@ export function createIngester(db, timeZone) {
298
297
  if (diff.added || diff.removed) {
299
298
  st.linesAdded += diff.added;
300
299
  st.linesRemoved += diff.removed;
301
- statsDirty = true;
300
+ st.statsDirty = true;
302
301
  }
303
302
  if (tc.args && typeof tc.args === "object") {
304
303
  if (AGY_WRITE_TOOLS.has(tc.name)) {
305
304
  for (const k of ["Path", "TargetFile", "AbsolutePath"]) {
306
305
  const val = unquote(tc.args[k]);
307
- if (val && st.paths.add(val, { isFile: true, write: true })) pathsDirty = true;
306
+ if (val && st.paths.add(val, { isFile: true, write: true })) st.pathsDirty = true;
308
307
  }
309
308
  } else if (AGY_READ_TOOLS.has(tc.name)) {
310
309
  for (const k of ["Path", "AbsolutePath"]) {
311
310
  const val = unquote(tc.args[k]);
312
- if (val && st.paths.add(val, { isFile: true, write: false })) pathsDirty = true;
311
+ if (val && st.paths.add(val, { isFile: true, write: false })) st.pathsDirty = true;
313
312
  }
314
313
  for (const k of ["SearchPath", "DirectoryPath", "Cwd"]) {
315
314
  const val = unquote(tc.args[k]);
316
- if (val && st.paths.add(val, { isFile: false, write: false })) pathsDirty = true;
315
+ if (val && st.paths.add(val, { isFile: false, write: false })) st.pathsDirty = true;
317
316
  }
318
317
  if (tc.name === "run_command" && tc.args.CommandLine) {
319
318
  const cmd = unquote(tc.args.CommandLine);
320
319
  const cmdCwd = unquote(tc.args.Cwd) || null;
321
320
  for (const dir of extractCommandDirs(cmd, cmdCwd)) {
322
- if (st.paths.add(dir, { write: false })) pathsDirty = true;
321
+ if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
323
322
  }
324
323
  }
325
324
  }
@@ -362,26 +361,36 @@ export function createIngester(db, timeZone) {
362
361
  st.lastTsMs = tsMs;
363
362
  st.lastType = rec.type;
364
363
  }
365
- if (statsDirty && (st.apiMs > 0 || st.toolMs > 0 || st.linesAdded > 0 || st.linesRemoved > 0)) {
366
- q.upsertStats.run(file.id, st.apiMs, st.toolMs, st.linesAdded, st.linesRemoved);
364
+
365
+ return { added, cwd: null, ts, own: true };
366
+ }
367
+ ingestLine.flush = (fileId) => {
368
+ const st = stateByFile.get(fileId);
369
+ if (!st) return;
370
+ if (st.statsDirty) {
371
+ st.statsDirty = false;
372
+ if (st.apiMs > 0 || st.toolMs > 0 || st.linesAdded > 0 || st.linesRemoved > 0) {
373
+ q.upsertStats.run(fileId, st.apiMs, st.toolMs, st.linesAdded, st.linesRemoved);
374
+ }
367
375
  }
368
- if (pathsDirty) {
376
+ if (st.pathsDirty) {
377
+ st.pathsDirty = false;
369
378
  const json = st.paths.toJSON();
370
- if (json) q.upsertTargetPaths.run(file.id, json);
379
+ if (json) q.upsertTargetPaths.run(fileId, json);
371
380
  }
372
-
373
- return { added, cwd: null, ts, own: true };
374
381
  };
382
+ ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
383
+ return ingestLine;
375
384
  }
376
385
 
377
386
  export function postScan(db, archiveDir) {
378
387
  const path = join(archiveDir, "summaries.json");
379
- if (!existsSync(path)) return;
388
+ if (!existsSync(path)) return new Set();
380
389
  let meta;
381
390
  try {
382
391
  meta = JSON.parse(readFileSync(path, "utf8"));
383
392
  } catch {
384
- return;
393
+ return new Set();
385
394
  }
386
395
 
387
396
  const allFiles = db.prepare("SELECT id, kind, session_id, agent_id, cwd FROM files WHERE provider = 'agy'").all();
@@ -400,39 +409,64 @@ export function postScan(db, archiveDir) {
400
409
  return cur === id ? null : cur;
401
410
  };
402
411
 
412
+ const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
413
+ const existingTitles = new Map(db.prepare("SELECT file_id, session_id, title FROM titles WHERE line = 0 AND kind = 'ai'").all().map((t) => [t.file_id, t]));
414
+
403
415
  const setCwd = db.prepare("UPDATE files SET cwd = ? WHERE id = ?");
404
416
  const setFileSub = db.prepare("UPDATE files SET kind = 'sub', session_id = ?, agent_id = ? WHERE id = ?");
405
417
  const setReqSub = db.prepare("UPDATE requests SET session_id = ?, agent_id = ?, is_sub = 1 WHERE file_id = ?");
406
418
  const setCallSub = db.prepare("UPDATE tool_calls SET session_id = ?, agent_id = ? WHERE file_id = ?");
407
419
  const setSkillSess = db.prepare("UPDATE skills SET session_id = ? WHERE file_id = ?");
408
420
  const setTitleSess = db.prepare("UPDATE titles SET session_id = ? WHERE file_id = ?");
421
+ const delSession = db.prepare("DELETE FROM sessions WHERE id = ?");
409
422
  const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, NULL)");
410
423
  const putTitle = db.prepare("INSERT OR REPLACE INTO titles(file_id, line, session_id, kind, title) VALUES (?, 0, ?, 'ai', ?)");
411
424
 
425
+ const dirty = new Set();
412
426
  db.exec("BEGIN");
413
427
  try {
414
428
  for (const f of allFiles) {
415
429
  const ownId = f.agent_id ?? f.session_id;
416
430
  const m = meta[ownId];
417
431
  if (!m) continue;
418
- if (m.cwd && !f.cwd) setCwd.run(m.cwd, f.id);
419
432
  const root = rootOf(ownId);
420
433
  const sess = root ?? f.session_id;
434
+ if (m.cwd && !f.cwd) {
435
+ setCwd.run(m.cwd, f.id);
436
+ dirty.add(sess);
437
+ }
421
438
  if (root) {
422
- setFileSub.run(root, ownId, f.id);
423
- setReqSub.run(root, ownId, f.id);
424
- setCallSub.run(root, ownId, f.id);
425
- setSkillSess.run(root, f.id);
426
- setTitleSess.run(root, f.id);
427
- putSub.run(ownId, root, m.agentName || "subagent");
439
+ if (f.kind !== "sub" || f.session_id !== root || f.agent_id !== ownId) {
440
+ setFileSub.run(root, ownId, f.id);
441
+ setReqSub.run(root, ownId, f.id);
442
+ setCallSub.run(root, ownId, f.id);
443
+ setSkillSess.run(root, f.id);
444
+ setTitleSess.run(root, f.id);
445
+ if (f.kind === "main") delSession.run(f.session_id);
446
+ dirty.add(f.session_id);
447
+ dirty.add(root);
448
+ }
449
+ const type = m.agentName || "subagent";
450
+ const curSub = existingSubs.get(ownId);
451
+ if (!curSub || curSub.session_id !== root || curSub.type !== type || curSub.tool_use_id !== null) {
452
+ putSub.run(ownId, root, type);
453
+ dirty.add(root);
454
+ }
455
+ }
456
+ if (m.title) {
457
+ const curTitle = existingTitles.get(f.id);
458
+ if (!curTitle || curTitle.session_id !== sess || curTitle.title !== m.title) {
459
+ putTitle.run(f.id, sess, m.title);
460
+ dirty.add(sess);
461
+ }
428
462
  }
429
- if (m.title) putTitle.run(f.id, sess, m.title);
430
463
  }
431
464
  db.exec("COMMIT");
432
465
  } catch (err) {
433
466
  db.exec("ROLLBACK");
434
467
  throw err;
435
468
  }
469
+ return dirty;
436
470
  }
437
471
 
438
472
  export const agy = { name: "agy", label, defaultPath, describe, listHost, syncMeta, createIngester, postScan, familyOf, displayModel };
@@ -128,7 +128,7 @@ export function createIngester(db, timeZone, hasFile = () => false) {
128
128
  const CLAUDE_READ_TOOLS = new Set(["Read", "Grep", "Glob"]);
129
129
 
130
130
  // file: { id, kind, session_id, agent_id }. Returns how many records were added, and the line's cwd and timestamp.
131
- return function ingestLine(file, line, text) {
131
+ function ingestLine(file, line, text) {
132
132
  let rec;
133
133
  try {
134
134
  rec = JSON.parse(text);
@@ -144,20 +144,14 @@ export function createIngester(db, timeZone, hasFile = () => false) {
144
144
  let st = stateByFile.get(file.id);
145
145
  if (!st) {
146
146
  const prev = file.lines > 0 ? q.getTargetPaths.get(file.id) : null;
147
- st = { launchCwd: file.cwd ?? null, cwd: file.cwd ?? null, paths: createPathTracker(prev?.target_paths ?? null) };
147
+ st = { launchCwd: file.cwd ?? null, cwd: file.cwd ?? null, paths: createPathTracker(prev?.target_paths ?? null), pathsDirty: false };
148
148
  stateByFile.set(file.id, st);
149
149
  }
150
- let pathsDirty = false;
151
150
  if (!foreign && rec.cwd) {
152
151
  st.launchCwd ??= rec.cwd;
153
152
  st.cwd = rec.cwd;
154
- if (rec.cwd !== st.launchCwd && st.paths.add(rec.cwd, { write: false })) pathsDirty = true;
153
+ if (rec.cwd !== st.launchCwd && st.paths.add(rec.cwd, { write: false })) st.pathsDirty = true;
155
154
  }
156
- const flushPaths = () => {
157
- if (!pathsDirty) return;
158
- const json = st.paths.toJSON();
159
- if (json) q.upsertTargetPaths.run(file.id, json);
160
- };
161
155
 
162
156
  if (rec.type === "cost-state") {
163
157
  // Per model: the host's cost and the tokens it priced; `split` tells whether 5m and 1h cache writes are told apart.
@@ -168,20 +162,17 @@ export function createIngester(db, timeZone, hasFile = () => false) {
168
162
  }]));
169
163
  q.cost.run(file.id, line, session, rec.startTime ?? null, rec.totalCostUSD ?? null, rec.hasUnknownModelCost ? 1 : 0,
170
164
  rec.totalAPIDuration ?? null, rec.totalToolDuration ?? null, rec.totalLinesAdded ?? null, rec.totalLinesRemoved ?? null, JSON.stringify(models));
171
- flushPaths();
172
165
  return { added: 1, ...seen };
173
166
  }
174
167
  if (rec.type === "custom-title" && rec.customTitle) {
175
168
  q.title.run(file.id, line, session, "custom", rec.customTitle);
176
- flushPaths();
177
169
  return { added: 1, ...seen };
178
170
  }
179
171
  if (rec.type === "ai-title" && rec.aiTitle) {
180
172
  q.title.run(file.id, line, session, "ai", rec.aiTitle);
181
- flushPaths();
182
173
  return { added: 1, ...seen };
183
174
  }
184
- if (!rec.uuid) { flushPaths(); return { added: 0, ...seen }; }
175
+ if (!rec.uuid) return { added: 0, ...seen };
185
176
 
186
177
  // A copied record belongs to the file of the session that wrote it, whichever file is read first;
187
178
  // here only note which requests it repeats. A copy whose original file is gone is kept here.
@@ -211,13 +202,13 @@ export function createIngester(db, timeZone, hasFile = () => false) {
211
202
  q.call.run(b.id, file.id, line, session, agent, rec.timestamp ?? null, b.name ?? "unknown", msg.model ?? null);
212
203
  if (CLAUDE_WRITE_TOOLS.has(b.name)) {
213
204
  const fp = b.input?.file_path ?? b.input?.notebook_path;
214
- if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
205
+ if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
215
206
  } else if (CLAUDE_READ_TOOLS.has(b.name)) {
216
- if (b.input?.file_path && st.paths.add(b.input.file_path, { isFile: true, write: false, baseCwd: st.cwd })) pathsDirty = true;
217
- if (b.input?.path && st.paths.add(b.input.path, { isFile: false, write: false, baseCwd: st.cwd })) pathsDirty = true;
207
+ if (b.input?.file_path && st.paths.add(b.input.file_path, { isFile: true, write: false, baseCwd: st.cwd })) st.pathsDirty = true;
208
+ if (b.input?.path && st.paths.add(b.input.path, { isFile: false, write: false, baseCwd: st.cwd })) st.pathsDirty = true;
218
209
  } else if (b.name === "Bash" && typeof b.input?.command === "string") {
219
210
  for (const dir of extractCommandDirs(b.input.command, st.cwd)) {
220
- if (st.paths.add(dir, { write: false })) pathsDirty = true;
211
+ if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
221
212
  }
222
213
  }
223
214
  }
@@ -255,9 +246,17 @@ export function createIngester(db, timeZone, hasFile = () => false) {
255
246
  }
256
247
  }
257
248
  }
258
- flushPaths();
259
249
  return { added: 1, ...seen };
250
+ }
251
+ ingestLine.flush = (fileId) => {
252
+ const st = stateByFile.get(fileId);
253
+ if (!st || !st.pathsDirty) return;
254
+ st.pathsDirty = false;
255
+ const json = st.paths.toJSON();
256
+ if (json) q.upsertTargetPaths.run(fileId, json);
260
257
  };
258
+ ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
259
+ return ingestLine;
261
260
  }
262
261
 
263
262
  // The type and parent tool call of a subagent, from the meta file archived beside its transcript.
@@ -250,7 +250,7 @@ export function createIngester(db, timeZone) {
250
250
  };
251
251
  const stateByFile = new Map();
252
252
 
253
- return function ingestLine(file, line, text) {
253
+ function ingestLine(file, line, text) {
254
254
  let rec;
255
255
  try {
256
256
  rec = JSON.parse(text);
@@ -271,6 +271,7 @@ export function createIngester(db, timeZone) {
271
271
  baseAdded: prevStats?.lines_added ?? 0, baseRemoved: prevStats?.lines_removed ?? 0,
272
272
  sawFileChange: false, fcAdded: 0, fcRemoved: 0, patchAdded: 0, patchRemoved: 0,
273
273
  paths: createPathTracker(prevStats?.target_paths ?? null),
274
+ statsDirty: false, pathsDirty: false,
274
275
  };
275
276
  stateByFile.set(file.id, st);
276
277
  }
@@ -284,15 +285,13 @@ export function createIngester(db, timeZone) {
284
285
  const tsMs = Number.isFinite(parsedTs) ? parsedTs : null;
285
286
  let cwd = p.cwd ?? null;
286
287
  let added = 0;
287
- let statsDirty = false;
288
- let pathsDirty = false;
289
288
 
290
289
  const consumeOpenWait = () => {
291
290
  if (tsMs !== null && st.lastWaitFromMs !== null) {
292
291
  const dt = tsMs - st.lastWaitFromMs;
293
292
  if (dt > 0 && dt < 600_000) {
294
293
  st.openApiMs += dt;
295
- statsDirty = true;
294
+ st.statsDirty = true;
296
295
  }
297
296
  st.lastWaitFromMs = null;
298
297
  }
@@ -333,7 +332,7 @@ export function createIngester(db, timeZone) {
333
332
  if (p.cwd) {
334
333
  st.launchCwd ??= p.cwd;
335
334
  st.cwd = p.cwd;
336
- if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) pathsDirty = true;
335
+ if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) st.pathsDirty = true;
337
336
  }
338
337
  if (p.model) st.model = p.model;
339
338
  const eff = p.effort ?? p.collaboration_mode?.settings?.reasoning_effort;
@@ -383,12 +382,12 @@ export function createIngester(db, timeZone) {
383
382
  if (patch.added || patch.removed) {
384
383
  st.patchAdded += patch.added;
385
384
  st.patchRemoved += patch.removed;
386
- if (!st.sawFileChange) statsDirty = true;
385
+ if (!st.sawFileChange) st.statsDirty = true;
387
386
  }
388
387
  if (inputStr.includes("*** ")) {
389
388
  const unesc = inputStr.includes("*** Begin Patch\\n") ? inputStr.replace(/\\n/g, "\n") : inputStr;
390
389
  for (const m of unesc.matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*([^\r\n`"]+)/gm)) {
391
- if (st.paths.add(m[1].trim(), { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
390
+ if (st.paths.add(m[1].trim(), { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
392
391
  }
393
392
  }
394
393
  const vars = new Map();
@@ -397,10 +396,10 @@ export function createIngester(db, timeZone) {
397
396
  }
398
397
  for (const m of inputStr.matchAll(/(?:workdir|"workdir")\s*:\s*(?:["'`]([^"'`\n]+)["'`]|([A-Za-z_$][\w$]*))/g)) {
399
398
  const wd = m[1] ?? (m[2] ? vars.get(m[2]) : null);
400
- if (wd && st.paths.add(wd, { write: false, baseCwd: st.cwd })) pathsDirty = true;
399
+ if (wd && st.paths.add(wd, { write: false, baseCwd: st.cwd })) st.pathsDirty = true;
401
400
  }
402
401
  for (const dir of extractCommandDirs(inputStr, st.cwd)) {
403
- if (st.paths.add(dir, { write: false })) pathsDirty = true;
402
+ if (st.paths.add(dir, { write: false })) st.pathsDirty = true;
404
403
  }
405
404
  const loadedSkills = extractSkillPaths(inputStr);
406
405
  if (loadedSkills.length) {
@@ -429,7 +428,7 @@ export function createIngester(db, timeZone) {
429
428
  if (dur > 0) {
430
429
  st.toolMs += dur;
431
430
  st.turnToolMs += dur;
432
- statsDirty = true;
431
+ st.statsDirty = true;
433
432
  }
434
433
  if (tsMs !== null) st.lastWaitFromMs = tsMs;
435
434
  } else if (p.type === "compaction") {
@@ -454,10 +453,10 @@ export function createIngester(db, timeZone) {
454
453
  : (st.turnStartMs !== null && tsMs !== null ? Math.max(0, tsMs - st.turnStartMs) : null);
455
454
  if (totalTurn !== null) {
456
455
  st.completedApiMs += Math.max(0, totalTurn - Math.min(totalTurn, st.turnToolMs));
457
- statsDirty = true;
456
+ st.statsDirty = true;
458
457
  } else if (st.openApiMs > 0) {
459
458
  st.completedApiMs += st.openApiMs;
460
- statsDirty = true;
459
+ st.statsDirty = true;
461
460
  }
462
461
  st.turnStartMs = null;
463
462
  st.turnToolMs = 0;
@@ -478,7 +477,7 @@ export function createIngester(db, timeZone) {
478
477
  } else if (p.type === "item_completed" && p.item?.type === "FileChange") {
479
478
  if (!p.item.status || p.item.status === "completed") {
480
479
  for (const [fp, ch] of Object.entries(p.item.changes ?? {})) {
481
- if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) pathsDirty = true;
480
+ if (st.paths.add(fp, { isFile: true, write: true, baseCwd: st.cwd })) st.pathsDirty = true;
482
481
  if (ch?.type === "add") st.fcAdded += lineCount(ch.content);
483
482
  else if (ch?.type === "delete") st.fcRemoved += lineCount(ch.content);
484
483
  else if (ch?.type === "update" && typeof ch.unified_diff === "string") {
@@ -488,7 +487,7 @@ export function createIngester(db, timeZone) {
488
487
  }
489
488
  }
490
489
  st.sawFileChange = true;
491
- statsDirty = true;
490
+ st.statsDirty = true;
492
491
  }
493
492
  } else if (p.type === "token_count" && !st.sawTokenRec && p.info?.last_token_usage) {
494
493
  consumeOpenWait();
@@ -501,19 +500,28 @@ export function createIngester(db, timeZone) {
501
500
  }
502
501
  }
503
502
 
504
- const totalApiMs = Math.round(st.completedApiMs + st.openApiMs);
505
- const linesAdded = st.baseAdded + (st.sawFileChange ? st.fcAdded : st.patchAdded);
506
- const linesRemoved = st.baseRemoved + (st.sawFileChange ? st.fcRemoved : st.patchRemoved);
507
- if (statsDirty && (totalApiMs > 0 || st.toolMs > 0 || linesAdded > 0 || linesRemoved > 0)) {
508
- q.upsertStats.run(file.id, totalApiMs, Math.round(st.toolMs), linesAdded, linesRemoved);
503
+ return { added, cwd, ts, own: true };
504
+ }
505
+ ingestLine.flush = (fileId) => {
506
+ const st = stateByFile.get(fileId);
507
+ if (!st) return;
508
+ if (st.statsDirty) {
509
+ st.statsDirty = false;
510
+ const totalApiMs = Math.round(st.completedApiMs + st.openApiMs);
511
+ const linesAdded = st.baseAdded + (st.sawFileChange ? st.fcAdded : st.patchAdded);
512
+ const linesRemoved = st.baseRemoved + (st.sawFileChange ? st.fcRemoved : st.patchRemoved);
513
+ if (totalApiMs > 0 || st.toolMs > 0 || linesAdded > 0 || linesRemoved > 0) {
514
+ q.upsertStats.run(fileId, totalApiMs, Math.round(st.toolMs), linesAdded, linesRemoved);
515
+ }
509
516
  }
510
- if (pathsDirty) {
517
+ if (st.pathsDirty) {
518
+ st.pathsDirty = false;
511
519
  const json = st.paths.toJSON();
512
- if (json) q.upsertTargetPaths.run(file.id, json);
520
+ if (json) q.upsertTargetPaths.run(fileId, json);
513
521
  }
514
-
515
- return { added, cwd, ts, own: true };
516
522
  };
523
+ ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
524
+ return ingestLine;
517
525
  }
518
526
 
519
527
  export function postScan(db, archiveDir) {
@@ -530,13 +538,17 @@ export function postScan(db, archiveDir) {
530
538
  }
531
539
 
532
540
  const allFiles = db.prepare("SELECT id, kind, session_id, agent_id FROM files WHERE provider = 'codex'").all();
541
+ const byFileId = new Map();
533
542
  const byOwn = new Map();
534
- for (const f of allFiles) byOwn.set(f.agent_id ?? f.session_id, f);
543
+ for (const f of allFiles) {
544
+ byFileId.set(f.id, f);
545
+ byOwn.set(f.agent_id ?? f.session_id, f);
546
+ }
535
547
 
536
548
  const metas = db.prepare("SELECT m.file_id, m.parent_session_id, m.subagent_type, m.tool_use_id FROM file_meta m JOIN files f ON f.id = m.file_id WHERE f.provider = 'codex'").all();
537
549
  const parentOf = new Map();
538
550
  for (const m of metas) {
539
- const f = allFiles.find((x) => x.id === m.file_id);
551
+ const f = byFileId.get(m.file_id);
540
552
  if (f && m.parent_session_id) parentOf.set(f.agent_id ?? f.session_id, { parent: m.parent_session_id, type: m.subagent_type, toolUseId: m.tool_use_id });
541
553
  }
542
554
  const rootOf = (id) => {
@@ -551,15 +563,20 @@ export function postScan(db, archiveDir) {
551
563
  return cur === id ? null : cur;
552
564
  };
553
565
 
566
+ const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
567
+ const existingTitles = new Map(db.prepare("SELECT file_id, session_id, title FROM titles WHERE line = 0 AND kind = 'custom'").all().map((t) => [t.file_id, t]));
568
+
554
569
  const setFileSub = db.prepare("UPDATE files SET kind = 'sub', session_id = ?, agent_id = ? WHERE id = ?");
555
570
  const setReqSub = db.prepare("UPDATE requests SET session_id = ?, agent_id = ?, is_sub = 1 WHERE file_id = ?");
556
571
  const setCallSub = db.prepare("UPDATE tool_calls SET session_id = ?, agent_id = ? WHERE file_id = ?");
557
572
  const setSkillSess = db.prepare("UPDATE skills SET session_id = ? WHERE file_id = ?");
558
573
  const setCompSub = db.prepare("UPDATE compactions SET session_id = ?, agent_id = ? WHERE file_id = ?");
559
574
  const setTitleSess = db.prepare("UPDATE titles SET session_id = ? WHERE file_id = ?");
575
+ const delSession = db.prepare("DELETE FROM sessions WHERE id = ?");
560
576
  const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
561
577
  const putTitle = db.prepare("INSERT OR REPLACE INTO titles(file_id, line, session_id, kind, title) VALUES (?, 0, ?, 'custom', ?)");
562
578
 
579
+ const dirty = new Set();
563
580
  db.exec("BEGIN");
564
581
  try {
565
582
  for (const f of allFiles) {
@@ -567,23 +584,41 @@ export function postScan(db, archiveDir) {
567
584
  const root = rootOf(ownId);
568
585
  const sess = root ?? f.session_id;
569
586
  if (root) {
570
- setFileSub.run(root, ownId, f.id);
571
- setReqSub.run(root, ownId, f.id);
572
- setCallSub.run(root, ownId, f.id);
573
- setSkillSess.run(root, f.id);
574
- setCompSub.run(root, ownId, f.id);
575
- setTitleSess.run(root, f.id);
587
+ if (f.kind !== "sub" || f.session_id !== root || f.agent_id !== ownId) {
588
+ setFileSub.run(root, ownId, f.id);
589
+ setReqSub.run(root, ownId, f.id);
590
+ setCallSub.run(root, ownId, f.id);
591
+ setSkillSess.run(root, f.id);
592
+ setCompSub.run(root, ownId, f.id);
593
+ setTitleSess.run(root, f.id);
594
+ if (f.kind === "main") delSession.run(f.session_id);
595
+ dirty.add(f.session_id);
596
+ dirty.add(root);
597
+ }
576
598
  const meta = parentOf.get(ownId);
577
- putSub.run(ownId, root, meta?.type ?? "subagent", meta?.toolUseId ?? null);
599
+ const type = meta?.type ?? "subagent";
600
+ const toolUseId = meta?.toolUseId ?? null;
601
+ const curSub = existingSubs.get(ownId);
602
+ if (!curSub || curSub.session_id !== root || curSub.type !== type || curSub.tool_use_id !== toolUseId) {
603
+ putSub.run(ownId, root, type, toolUseId);
604
+ dirty.add(root);
605
+ }
578
606
  }
579
607
  const title = titles.get(ownId);
580
- if (title) putTitle.run(f.id, sess, title);
608
+ if (title) {
609
+ const curTitle = existingTitles.get(f.id);
610
+ if (!curTitle || curTitle.session_id !== sess || curTitle.title !== title) {
611
+ putTitle.run(f.id, sess, title);
612
+ dirty.add(sess);
613
+ }
614
+ }
581
615
  }
582
616
  db.exec("COMMIT");
583
617
  } catch (err) {
584
618
  db.exec("ROLLBACK");
585
619
  throw err;
586
620
  }
621
+ return dirty;
587
622
  }
588
623
 
589
624
  export const codex = { name: "codex", label, defaultPath, describe, listHost, syncMeta, createIngester, postScan, familyOf, displayModel };
package/src/rebuilds.mjs CHANGED
@@ -30,18 +30,20 @@ export function classify(requests, compactions, prices) {
30
30
  for (const r of requests) {
31
31
  if (r.model === "<synthetic>") continue;
32
32
  const key = `${r.session_id}\n${r.agent_id ?? ""}`;
33
- (threads.get(key) ?? threads.set(key, []).get(key)).push(r);
33
+ let list = threads.get(key);
34
+ if (!list) threads.set(key, (list = []));
35
+ list.push({ r, at: Date.parse(r.ts) });
34
36
  }
35
37
  const out = new Map();
36
- for (const list of threads.values()) {
37
- list.sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts) || a.line - b.line);
38
+ for (const [key, list] of threads) {
39
+ list.sort((a, b) => a.at - b.at || a.r.line - b.r.line);
40
+ const comps = compactions.get(key) ?? [];
38
41
  let prev = null;
39
42
  let lifetime = SHORT_LIFETIME;
40
- for (const r of list) {
41
- const at = Date.parse(r.ts);
43
+ for (const { r, at } of list) {
42
44
  // The first request after a compaction rewrites the new short history while it still reads the system prompt and
43
45
  // tools from the cache, so it often writes less than half of what it carries: it counts once it rewrites enough.
44
- const compacted = prev !== null && (compactions.get(`${r.session_id}\n${r.agent_id ?? ""}`) ?? []).some((c) => c > prev && c <= at);
46
+ const compacted = prev !== null && comps.some((c) => c > prev && c <= at);
45
47
  if (isRebuild(r) || (compacted && rewrittenTokens(r) >= MIN_REWRITE)) {
46
48
  const gap = prev === null ? null : Math.round((at - prev) / 1000);
47
49
  let cause;
@@ -60,12 +62,34 @@ export function classify(requests, compactions, prices) {
60
62
  return out;
61
63
  }
62
64
 
63
- // Recompute the rebuild columns of every request, writing only the rows that changed.
64
- export function markRebuilds(db, prices) {
65
- const requests = db.prepare(`SELECT message_id, session_id, agent_id, ts, line, model, day, input, cache_read, cache_write, cache_write_1h,
66
- rebuild, rebuild_gap, rebuild_extra FROM requests`).all();
65
+ const CHUNK = 500;
66
+
67
+ function queryBySessions(db, buildSql, sessions) {
68
+ const rows = [];
69
+ for (let i = 0; i < sessions.length; i += CHUNK) {
70
+ const slice = sessions.slice(i, i + CHUNK);
71
+ const placeholders = slice.map(() => "?").join(",");
72
+ for (const r of db.prepare(buildSql(placeholders)).all(...slice)) rows.push(r);
73
+ }
74
+ return rows;
75
+ }
76
+
77
+ // Recompute the rebuild columns of requests (all or only `dirtySessions`), writing only the rows that changed.
78
+ export function markRebuilds(db, prices, dirtySessions = null) {
79
+ if (dirtySessions instanceof Set && dirtySessions.size === 0) return;
80
+ const reqCols = "message_id, session_id, agent_id, ts, line, model, day, input, cache_read, cache_write, cache_write_1h, rebuild, rebuild_gap, rebuild_extra";
81
+ let requests;
82
+ let compRows;
83
+ if (dirtySessions instanceof Set) {
84
+ const list = [...dirtySessions];
85
+ requests = queryBySessions(db, (ph) => `SELECT ${reqCols} FROM requests WHERE session_id IN (${ph})`, list);
86
+ compRows = queryBySessions(db, (ph) => `SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL AND session_id IN (${ph})`, list);
87
+ } else {
88
+ requests = db.prepare(`SELECT ${reqCols} FROM requests`).all();
89
+ compRows = db.prepare("SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL").all();
90
+ }
67
91
  const compactions = new Map();
68
- for (const c of db.prepare("SELECT session_id, agent_id, ts FROM compactions WHERE ts IS NOT NULL").all()) {
92
+ for (const c of compRows) {
69
93
  const key = `${c.session_id}\n${c.agent_id ?? ""}`;
70
94
  (compactions.get(key) ?? compactions.set(key, []).get(key)).push(Date.parse(c.ts));
71
95
  }
package/src/scan.mjs CHANGED
@@ -42,17 +42,22 @@ export async function scan(config, { onProgress = () => {} } = {}) {
42
42
 
43
43
  const getFile = db.prepare("SELECT * FROM files WHERE provider = ? AND path = ?");
44
44
  const addFile = db.prepare("INSERT INTO files(provider, path, kind, session_id, agent_id) VALUES (?, ?, ?, ?, ?)");
45
- const saveCursor = db.prepare("UPDATE files SET offset = ?, lines = ?, head_hash = ?, archive_size = ?, first_ts = coalesce(first_ts, ?), cwd = coalesce(cwd, ?), live = ?, own_first = ?, own_last = ? WHERE id = ?");
46
- const resetFile = db.prepare("UPDATE files SET generation = generation + 1, offset = 0, lines = 0, head_hash = NULL, archive_size = 0, first_ts = NULL, own_first = NULL, own_last = NULL, cwd = NULL WHERE id = ?");
45
+ const saveCursor = db.prepare("UPDATE files SET offset = ?, lines = ?, head_hash = ?, archive_size = ?, first_ts = coalesce(first_ts, ?), cwd = coalesce(cwd, ?), live = ?, own_first = ?, own_last = ?, ctime_ms = ? WHERE id = ?");
46
+ const resetFile = db.prepare("UPDATE files SET generation = generation + 1, offset = 0, lines = 0, head_hash = NULL, archive_size = 0, first_ts = NULL, own_first = NULL, own_last = NULL, cwd = NULL, ctime_ms = NULL WHERE id = ?");
47
+ const stampCtime = db.prepare("UPDATE files SET ctime_ms = ? WHERE id = ?");
48
+ const setOffline = db.prepare("UPDATE files SET live = 0 WHERE id = ?");
47
49
  const clear = FILE_TABLES.map((t) => db.prepare(`DELETE FROM ${t} WHERE file_id = ?`));
48
50
 
49
51
  const fileRow = (d) => getFile.get(d.provider, d.rel) ?? (addFile.run(d.provider, d.rel, d.kind, d.sessionId, d.agentId), getFile.get(d.provider, d.rel));
50
52
 
51
53
  // Every transcript a provider's host still has or its archive holds, oldest first.
54
+ const hostLists = new Map();
52
55
  const work = new Map();
53
56
  for (const p of providers) {
54
57
  const base = { provider: p.name, dir: p.archive };
55
- for (const d of p.listHost(p.root).transcripts) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: join(p.root, d.rel) });
58
+ const listed = p.listHost(p.root);
59
+ hostLists.set(p.name, listed);
60
+ for (const d of listed.transcripts) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: join(p.root, d.rel) });
56
61
  for (const d of listArchived(p.archive, p.describe)) if (!work.has(`${p.name}/${d.rel}`)) work.set(`${p.name}/${d.rel}`, { ...d, ...base, src: null });
57
62
  }
58
63
  for (const d of work.values()) if (d.kind === "main") mains.add(d.sessionId);
@@ -66,9 +71,10 @@ export async function scan(config, { onProgress = () => {} } = {}) {
66
71
  const row = getFile.get(d.provider, d.rel);
67
72
  const src = d.src ?? archivePath(d.dir, d.rel);
68
73
  const stat = statSync(src);
69
- const arcSize = sizeOf(archivePath(d.dir, d.rel)) ?? 0;
74
+ const arc = archivePath(d.dir, d.rel);
75
+ const arcSize = sizeOf(arc) ?? 0;
70
76
  const weight = (arcSize !== (row?.archive_size ?? 0) ? arcSize : 0) + (d.src ? Math.max(0, stat.size - (row?.offset ?? 0)) : 0);
71
- jobs.push({ d, ts: row?.first_ts ?? (d.src ? peekFirstTs(d.src) : null) ?? "~", mtime: stat.mtimeMs, weight });
77
+ jobs.push({ d, row, stat, arc, arcSize, ts: row?.first_ts ?? (d.src ? peekFirstTs(d.src) : null) ?? "~", mtime: stat.mtimeMs, weight });
72
78
  }
73
79
  // A continuation starts with the same records as the file it continues, so ties go to the file last written first.
74
80
  jobs.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.mtime - b.mtime));
@@ -76,13 +82,39 @@ export async function scan(config, { onProgress = () => {} } = {}) {
76
82
  let bytes = 0, next = 0;
77
83
  const report = (done, extra = 0) => onProgress({ reason, step: "read", done, total: jobs.length, bytes: bytes + extra, totalBytes });
78
84
 
79
- for (const [done, { d, weight }] of jobs.entries()) {
85
+ const dirtyFiles = new Set();
86
+ const dirtySessions = new Set();
87
+ const ctimeUpdates = [];
88
+ const offlineUpdates = [];
89
+ const nowMs = Date.now();
90
+ const safeCtime = (ms, refNow = Date.now()) => (ms !== null && (refNow - ms) > 2000 ? ms : null);
91
+
92
+ for (const [done, { d, row, stat, arc, arcSize, weight }] of jobs.entries()) {
80
93
  bytes = next;
81
94
  next += weight;
95
+
96
+ // Racy-clean fast-path: skip liveHead and newChunks for quiescent live files whose size and ctime match.
97
+ if (row && arcSize === row.archive_size && d.src && row.offset > 0 && stat.size === row.offset && row.ctime_ms !== null && row.ctime_ms === stat.ctimeMs && (nowMs - stat.ctimeMs) > 2000) {
98
+ if (done % 256 === 0) {
99
+ report(done);
100
+ await yieldToLoop();
101
+ }
102
+ continue;
103
+ }
104
+
105
+ // Fast-path for unchanged archived-only files.
106
+ if (row && arcSize === row.archive_size && !d.src) {
107
+ if (row.live) offlineUpdates.push(row.id);
108
+ if (done % 256 === 0) {
109
+ report(done);
110
+ await yieldToLoop();
111
+ }
112
+ continue;
113
+ }
114
+
82
115
  report(done);
83
116
  await yieldToLoop();
84
- let file = fileRow(d);
85
- const arc = archivePath(d.dir, d.rel);
117
+ let file = row ?? fileRow(d);
86
118
  const ingest = ingesters.get(d.provider);
87
119
  let firstTs = null;
88
120
  let cwd = null;
@@ -101,13 +133,13 @@ export async function scan(config, { onProgress = () => {} } = {}) {
101
133
 
102
134
  // The archive is ahead of the cursor when a scan died between the append and the commit,
103
135
  // or when the database was rebuilt: ingest what the archive holds beyond the cursor, in batches.
104
- const arcSize = sizeOf(arc) ?? 0;
105
136
  if (arcSize !== file.archive_size) {
106
137
  if (arcSize < file.archive_size) throw new Error(`archive ${arc} is shorter than recorded; refusing to continue`);
107
138
  let { offset, lines } = file;
108
139
  const head = [];
109
140
  let headBytes = 0;
110
141
  let batch = 0;
142
+ const curCtime = d.src ? safeCtime(stat.ctimeMs) : null;
111
143
  db.exec("BEGIN");
112
144
  try {
113
145
  for await (const l of archiveLines(arc)) {
@@ -120,26 +152,36 @@ export async function scan(config, { onProgress = () => {} } = {}) {
120
152
  offset += l.bytes;
121
153
  lines = l.line;
122
154
  if (++batch % 5000 === 0) {
123
- saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), file.archive_size, firstTs, cwd, file.live, ownFirst, ownLast, file.id);
155
+ ingest.flush?.(file.id);
156
+ saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), file.archive_size, firstTs, cwd, file.live, ownFirst, ownLast, curCtime, file.id);
124
157
  db.exec("COMMIT");
125
158
  db.exec("BEGIN");
126
159
  }
127
160
  }
128
- saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), arcSize, firstTs, cwd, d.src ? 1 : 0, ownFirst, ownLast, file.id);
161
+ ingest.flush?.(file.id);
162
+ saveCursor.run(offset, lines, hashHead(Buffer.concat(head)), arcSize, firstTs, cwd, d.src ? 1 : 0, ownFirst, ownLast, curCtime, file.id);
129
163
  db.exec("COMMIT");
130
164
  } catch (err) {
131
165
  db.exec("ROLLBACK");
132
166
  throw err;
133
167
  }
168
+ dirtyFiles.add(file.id);
169
+ dirtySessions.add(file.session_id);
134
170
  file = getFile.get(d.provider, d.rel);
135
171
  }
136
172
 
137
173
  if (!d.src) {
138
- if (file.live) db.prepare("UPDATE files SET live = 0 WHERE id = ?").run(file.id);
174
+ if (file.live) offlineUpdates.push(file.id);
175
+ continue;
176
+ }
177
+ let curStat;
178
+ try {
179
+ curStat = statSync(d.src);
180
+ } catch {
139
181
  continue;
140
182
  }
141
- const size = sizeOf(d.src);
142
- if (size === null) continue;
183
+ const size = curStat.size;
184
+ const ctimeMs = curStat.ctimeMs;
143
185
 
144
186
  // A file that shrank or whose consumed head changed was rewritten: keep the old copy as a generation.
145
187
  if (file.offset > 0 && (size < file.offset || liveHead(d.src, file.offset) !== file.head_hash)) {
@@ -148,7 +190,10 @@ export async function scan(config, { onProgress = () => {} } = {}) {
148
190
  for (const c of clear) c.run(file.id);
149
191
  resetFile.run(file.id);
150
192
  });
193
+ ingest.reset?.(file.id);
151
194
  totals.generations++;
195
+ dirtyFiles.add(file.id);
196
+ dirtySessions.add(file.session_id);
152
197
  file = getFile.get(d.provider, d.rel);
153
198
  firstTs = cwd = ownFirst = ownLast = null;
154
199
  }
@@ -158,6 +203,7 @@ export async function scan(config, { onProgress = () => {} } = {}) {
158
203
  const archived = appendChunk(arc, chunk);
159
204
  const count = lineCount(chunk);
160
205
  const text = chunk.toString("utf8");
206
+ const stamped = safeCtime(ctimeMs);
161
207
  transaction(db, () => {
162
208
  let start = 0;
163
209
  for (let i = 0; i < count; i++) {
@@ -167,13 +213,27 @@ export async function scan(config, { onProgress = () => {} } = {}) {
167
213
  }
168
214
  offset += chunk.length;
169
215
  lines += count;
170
- saveCursor.run(offset, lines, liveHead(d.src, offset), archived, firstTs, cwd, 1, ownFirst, ownLast, file.id);
216
+ ingest.flush?.(file.id);
217
+ saveCursor.run(offset, lines, liveHead(d.src, offset), archived, firstTs, cwd, 1, ownFirst, ownLast, stamped, file.id);
171
218
  });
172
219
  totals.bytes += chunk.length;
220
+ dirtyFiles.add(file.id);
221
+ dirtySessions.add(file.session_id);
173
222
  report(done, Math.max(0, weight - (size - offset)));
174
223
  await yieldToLoop();
175
224
  }
176
- if (offset > file.offset) totals.files++;
225
+ if (offset > file.offset) {
226
+ totals.files++;
227
+ } else if (offset === file.offset && file.offset > 0 && file.ctime_ms !== ctimeMs) {
228
+ const stamped = safeCtime(ctimeMs);
229
+ if (stamped !== null) ctimeUpdates.push([stamped, file.id]);
230
+ }
231
+ }
232
+ if (ctimeUpdates.length || offlineUpdates.length) {
233
+ transaction(db, () => {
234
+ for (const [ms, id] of ctimeUpdates) stampCtime.run(ms, id);
235
+ for (const id of offlineUpdates) setOffline.run(id);
236
+ });
177
237
  }
178
238
  onProgress({ reason, step: "finish", done: jobs.length, total: jobs.length, bytes: totalBytes, totalBytes });
179
239
  await yieldToLoop();
@@ -181,23 +241,45 @@ export async function scan(config, { onProgress = () => {} } = {}) {
181
241
  // Other session-folder files; the subagent meta files among them give each subagent its type.
182
242
  const activeProviders = new Set(jobs.map((j) => j.d.provider));
183
243
  const copied = new Set();
244
+ const copiedMeta = new Set();
184
245
  for (const p of providers) {
185
- for (const rel of p.listHost(p.root).others) {
246
+ for (const rel of hostLists.get(p.name).others) {
186
247
  if (copied.has(`${p.name}/${rel}`)) continue;
187
248
  copied.add(`${p.name}/${rel}`);
188
- if (copyOther(join(p.root, rel), join(p.archive, rel))) totals.copied++;
249
+ if (copyOther(join(p.root, rel), join(p.archive, rel))) {
250
+ totals.copied++;
251
+ copiedMeta.add(`${p.name}/${rel}`);
252
+ }
189
253
  }
190
254
  if (p.syncMeta && activeProviders.has(p.name)) totals.copied += p.syncMeta(p.root, p.archive) ?? 0;
191
255
  }
256
+ const existingSubs = new Map(db.prepare("SELECT agent_id, session_id, type, tool_use_id FROM subagents").all().map((s) => [s.agent_id, s]));
192
257
  const putSub = db.prepare("INSERT OR REPLACE INTO subagents(agent_id, session_id, type, tool_use_id) VALUES (?, ?, ?, ?)");
193
- for (const { d } of jobs) {
258
+ const subUpdates = [];
259
+ for (const { d, row } of jobs) {
194
260
  if (d.kind !== "sub") continue;
261
+ const known = existingSubs.get(d.agentId);
262
+ const metaRel = `${d.provider}/${d.rel.replace(/\.jsonl$/, ".meta.json")}`;
263
+ if (known && !(row && dirtyFiles.has(row.id)) && !copiedMeta.has(metaRel)) continue;
195
264
  const meta = PROVIDERS[d.provider].subagentMeta?.(d.dir, d);
196
- if (meta) putSub.run(d.agentId, d.sessionId, meta.type, meta.toolUseId);
265
+ if (!meta) continue;
266
+ if (!known || known.session_id !== d.sessionId || known.type !== meta.type || known.tool_use_id !== meta.toolUseId) {
267
+ subUpdates.push([d.agentId, d.sessionId, meta.type, meta.toolUseId]);
268
+ dirtySessions.add(d.sessionId);
269
+ }
270
+ }
271
+ if (subUpdates.length) {
272
+ transaction(db, () => {
273
+ for (const args of subUpdates) putSub.run(...args);
274
+ });
275
+ }
276
+ for (const p of providers) {
277
+ if (!activeProviders.has(p.name)) continue;
278
+ const d = p.postScan?.(db, p.archive);
279
+ if (d) for (const s of d) dirtySessions.add(s);
197
280
  }
198
- for (const p of providers) if (activeProviders.has(p.name)) p.postScan?.(db, p.archive);
199
281
 
200
- derive(db, config);
282
+ derive(db, config, { dirtySessions, full: reason !== "update" });
201
283
  const sessionsAfter = db.prepare("SELECT COUNT(DISTINCT session_id) n FROM files WHERE kind = 'main' AND lines > 0").get().n;
202
284
  totals.sessions = sessionsAfter - sessionsBefore;
203
285
  totals.prices = { report: priceReport(db), errors: readPrices(config).errors };