opencode-statboard 2.0.8 → 2.0.10

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,34 @@
1
+ # npm trusted publishing (OIDC) — no token needed.
2
+ # Requires: npmjs.com → opencode-statboard → Settings → Trusted Publisher →
3
+ # GitHub Actions: org `thumb2086`, repo `opencode-usage-dashboard`,
4
+ # workflow filename `publish.yml`, no environment,
5
+ # Allowed actions: enable BOTH `npm stage publish` AND `npm publish`.
6
+ name: Publish Package
7
+
8
+ on:
9
+ push:
10
+ tags:
11
+ - 'v*'
12
+
13
+ permissions:
14
+ id-token: write # required for OIDC token exchange with npm
15
+ contents: read
16
+
17
+ jobs:
18
+ publish:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v6
22
+ - uses: actions/setup-node@v6
23
+ with:
24
+ node-version: '24'
25
+ registry-url: 'https://registry.npmjs.org'
26
+ package-manager-cache: false # never use caching in release builds
27
+ - run: npm ci
28
+ - run: npm test
29
+ # Fail fast if the tag and package.json version disagree, so the tag
30
+ # always identifies exactly what gets published.
31
+ - run: node -e "const v=require('./package.json').version; const t=process.env.GITHUB_REF_NAME; if (t !== 'v'+v) { console.error('tag '+t+' != package.json v'+v); process.exit(1); }"
32
+ # OIDC auth is automatic with npm >= 11.5.1; provenance is generated
33
+ # automatically for public repos — no token, no --provenance flag.
34
+ - run: npm publish
package/AGENTS.md CHANGED
@@ -22,6 +22,19 @@ opencode-dashboard
22
22
 
23
23
  All data comes from `opencode.db` (read-only via `better-sqlite3` with WAL mode). The DB is opened once and health-checked before each query (`SELECT 1`); if the connection is stale, it re-opens automatically.
24
24
 
25
+ `detectSchema()` runs on every open and picks the table set:
26
+
27
+ - **OpenCode V2** — sessions in `session_v2`, messages in `session_message`, tool parts embedded in `session_message.data.content[]` (part objects use `name`, e.g. `{"type":"tool","name":"shell",...}`). Model IDs are nested (`data.model.id` / `data.model.providerID`). Message rows have a `type` column (`user`/`assistant` plus non-chat `idle`/`synthetic`/`compaction`/...), filtered to `user`/`assistant` to keep V1 counting semantics.
28
+ - **OpenCode V1 (fallback)** — `session`, `message`, `part` tables; `data.modelID`/`data.providerID` top-level; tool parts in `part` (`{"type":"tool","tool":"bash",...}`).
29
+
30
+ **V1+V2 merge — never switch.** The V2 migration is lossy, so the schema expressions combine both eras (verified 2026-09 against the live DB):
31
+
32
+ - `session` → per-field `MAX(v2, v1)` over shared rows + V1-only rows. **455/734 migrated sessions lost their lifetime totals (−196M input tokens)**: V2 recomputed totals from surviving messages, dropping pruned compaction history (fully-pruned sessions went to 0; V1's frozen totals are authoritative). MAX, never SUM — shared rows are the same lifetime counter. No shared session continued after the freeze, so MAX is exact. Result: all-time input is ~467M (V1 439.96M + 29 post-upgrade sessions), not 270M.
33
+ - `message` → `session_message(user/assistant)` ∪ V1 rows whose ids are not in `session_message` (30 rows, 4.3M input, never migrated; their sessions all exist in `session_v2`).
34
+ - tools → embedded content (already covers migrated V1 parts — dedup by id is impossible because migration rewrote `prt_` ids to `call_`) ∪ `part` rows whose `message_id` is absent from `session_message` (the double-count-safe remainder, currently 1 part).
35
+
36
+ On a V1-only database every expression collapses to the plain V1 tables.
37
+
25
38
  ### Hybrid Attribution (`attributeUsage`)
26
39
 
27
40
  Token/cost attribution uses a hybrid model:
@@ -56,22 +69,56 @@ node check-trend-verify.js 7
56
69
  node check-report-verify.js
57
70
  ```
58
71
 
72
+ Checks time-travel via API `generatedAt`, so live chat (sessions mutating mid-check) can still cause drift. For exact verification while chatting, run both server and checks against a frozen snapshot:
73
+
74
+ ```bash
75
+ # 1. snapshot the live DB (SQLite backup API = consistent even on a live WAL DB;
76
+ # a raw file copy can tear)
77
+ node -e "const D=require('better-sqlite3'),p=require('path'),f=require('fs');const s=p.join(process.env.USERPROFILE,'.local/share/opencode/opencode.db');const d=p.join(f.mkdtempSync(p.join(f.realpathSync(require('os').tmpdir()),'oc-snap-')),'opencode.db');new D(s,{readonly:true}).backup(d).then(()=>console.log(d))"
78
+
79
+ # 2. server reads the snapshot: OPENCODE_DATA=<snapdir> node server.js
80
+ # 3. checks read the snapshot: OC_STATS_SNAP_DB=<snapdir>\opencode.db node check-stats-verify.js
81
+ ```
82
+
83
+ `check-lib.js` honors `OC_STATS_SNAP_DB`; `server.js` honors `OPENCODE_DATA` (both expect a directory containing `opencode.db`).
84
+
59
85
  ## Publishing
60
86
 
87
+ Publishing is automated via GitHub Actions + npm **trusted publishing (OIDC)** — no npm token involved. Workflow: `.github/workflows/publish.yml`, triggered by pushing a `v*` tag.
88
+
89
+ One-time setup on npmjs.com → `opencode-statboard` → Settings → **Trusted Publisher** → GitHub Actions:
90
+
91
+ | Field | Value |
92
+ |-------|-------|
93
+ | Organization or user | `thumb2086` |
94
+ | Repository | `opencode-usage-dashboard` |
95
+ | Workflow filename | `publish.yml` (exact, with extension) |
96
+ | Environment name | leave empty |
97
+ | Allowed actions | enable **both** `npm stage publish` **and** `npm publish` (configs made after Sep 2026 default to stage-only, which rejects `npm publish`) |
98
+
99
+ Release flow:
100
+
61
101
  ```bash
62
- npm set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
63
102
  npm version patch --no-git-tag-version
64
- npm publish
65
- npm install -g opencode-statboard # auto-install after publish
66
- npm config delete //registry.npmjs.org/:_authToken
103
+ git commit -am "vX.Y.Z"
104
+ git tag vX.Y.Z
105
+ git push --follow-tags # tag push runs publish.yml → npm publish (OIDC)
106
+ npm install -g opencode-statboard # after the Actions run is green
67
107
  ```
68
108
 
69
- NPM token stored in user env var `NPM_TOKEN` and `oc-stats/.env` (gitignored).
109
+ - The workflow fails fast if the tag doesn't match `package.json` version.
110
+ - `repository.url` must exactly match the GitHub repo (npm requirement for OIDC publishes) — `npm pkg fix` keeps it normalized.
111
+ - Provenance attestations are generated automatically for public repos; no `--provenance` flag.
112
+ - Requires npm CLI ≥ 11.5.1 / Node ≥ 22.14 (CI uses Node 24).
113
+ - The old `NPM_TOKEN` flow is retired (token revoked 2026-09); revoke leftover tokens on npmjs.com.
70
114
 
71
115
  ## Known Constraints
72
116
 
73
117
  - `better-sqlite3` is a native addon; must match Node.js ABI
74
- - `attributeUsage` does a full DB scan (~22k messages); cached 300s via `getAttrAll()`
75
- - Trend and report share the same `getAttrAll()` cache so daily values are consistent
118
+ - `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
119
+ - Trend buckets are sliced from the same `getAttrAll()` attribution the report uses — never a separate windowed call (windowed calls inflate in-window days via residual growth; fixed 2026-09-29 after measuring +0.25–1.7M input/day). Remaining panel differences are cache ages only (trend ≤60s, report ≤10min, both timestamps shown)
120
+ - V2 tool counts use `json_each` over `session_message` content (~1.2s full scan) and run on every 15s refresh; legacy V1 DBs scan `part` instead (~0.8s)
121
+ - OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
76
122
  - `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
77
123
  - Backup is deferred 30s after startup — heavy disk I/O (500MB copy+compress) during startup causes Windows to terminate the process
124
+ - Backup file ops are async (`fs.promises.copyFile`/`rm`): with the DB now ~2.7GB, synchronous copy+`rmSync` cleanup starved the event loop during the daily auto-backup and the process was terminated mid-cleanup (no log output, exit 1)
package/README.md CHANGED
@@ -18,6 +18,7 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
18
18
 
19
19
  - Node.js (tested on v24)
20
20
  - [opencode](https://opencode.ai) CLI installed globally via npm
21
+ - Reads the local `opencode.db`; supports both OpenCode V2 (`session_v2` / `session_message`) and legacy V1 (`session` / `message` / `part`) database schemas
21
22
 
22
23
  ## Install
23
24
 
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.0.8",
3
+ "version": "2.0.10",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
7
7
  "opencode-dashboard": "server.js"
8
8
  },
9
9
  "scripts": {
10
- "start": "node server.js"
10
+ "start": "node server.js",
11
+ "test": "node --check server.js && node --check check-lib.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js"
11
12
  },
12
13
  "keywords": [
13
14
  "opencode",
@@ -20,7 +21,7 @@
20
21
  "license": "MIT",
21
22
  "repository": {
22
23
  "type": "git",
23
- "url": "https://github.com/thumb2086/opencode-usage-dashboard"
24
+ "url": "git+https://github.com/thumb2086/opencode-usage-dashboard.git"
24
25
  },
25
26
  "dependencies": {
26
27
  "better-sqlite3": "^13.0.3"
package/public/index.html CHANGED
@@ -338,12 +338,13 @@ function renderTrend(data) {
338
338
  const maxAll = Math.max(...data.input, ...data.output, ...(data.reasoning || []), ...data.cacheRead);
339
339
  const hasCost = data.cost.some((v) => v >= 0.0001);
340
340
 
341
+ const trendTime = data.generatedAt ? new Date(data.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
341
342
  $('trend-tokens').innerHTML = data.labels.map((l, i) => {
342
343
  const hi = maxAll > 0 ? (data.input[i] / maxAll) * 100 : 0;
343
344
  const ho = maxAll > 0 ? (data.output[i] / maxAll) * 100 : 0;
344
345
  const hr = maxAll > 0 && data.reasoning ? (data.reasoning[i] / maxAll) * 100 : 0;
345
346
  const hc = maxAll > 0 ? (data.cacheRead[i] / maxAll) * 100 : 0;
346
- const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Reas ' + fmt(data.reasoning ? data.reasoning[i] : 0) + ' · Cache ' + fmt(data.cacheRead[i]);
347
+ const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Reas ' + fmt(data.reasoning ? data.reasoning[i] : 0) + ' · Cache ' + fmt(data.cacheRead[i]) + ' · ' + trendTime;
347
348
  return `<div class="col" title="${tip}">
348
349
  <div style="display:flex;gap:2px;align-items:flex-end;width:100%;height:170px;justify-content:center">
349
350
  <div style="position:relative;width:100%;height:100%">
package/server.js CHANGED
@@ -47,20 +47,25 @@ function compressFile(srcPath) {
47
47
  }
48
48
 
49
49
  function cleanupOldBackups() {
50
- if (BACKUP_RETENTION <= 0) return;
51
- try {
52
- const dirs = fs.readdirSync(BACKUP_DIR)
53
- .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
54
- .sort();
55
- if (dirs.length > BACKUP_RETENTION) {
56
- const toDelete = dirs.slice(0, dirs.length - BACKUP_RETENTION);
57
- for (const f of toDelete) {
58
- const dirPath = path.join(BACKUP_DIR, f);
59
- fs.rmSync(dirPath, { recursive: true, force: true });
60
- console.log(`backup cleaned: ${f}`);
50
+ if (BACKUP_RETENTION <= 0) return Promise.resolve();
51
+ return (async () => {
52
+ try {
53
+ const dirs = fs.readdirSync(BACKUP_DIR)
54
+ .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
55
+ .sort();
56
+ if (dirs.length > BACKUP_RETENTION) {
57
+ const toDelete = dirs.slice(0, dirs.length - BACKUP_RETENTION);
58
+ for (const f of toDelete) {
59
+ const dirPath = path.join(BACKUP_DIR, f);
60
+ // Async: recursive rm of multi-hundred-MB gzip dirs is slow on
61
+ // Windows; doing it synchronously starves the event loop long
62
+ // enough that the process gets terminated during backup cleanup.
63
+ await fs.promises.rm(dirPath, { recursive: true, force: true });
64
+ console.log(`backup cleaned: ${f}`);
65
+ }
61
66
  }
62
- }
63
- } catch (_) {}
67
+ } catch (_) {}
68
+ })();
64
69
  }
65
70
 
66
71
  const EXE = (() => {
@@ -71,6 +76,51 @@ const EXE = (() => {
71
76
  return 'opencode';
72
77
  })();
73
78
 
79
+ // OpenCode V2 writes sessions to session_v2 and messages to session_message
80
+ // (tool parts embedded in message content); V1 used session/message/part and
81
+ // froze at the upgrade. The V2 migration is LOSSY, so merge — never switch:
82
+ // - 455/734 migrated sessions LOST their lifetime totals (196M input tokens):
83
+ // V2 recomputed them from surviving messages, dropping pruned compaction
84
+ // history (sessions whose messages were fully pruned went to 0). V1's frozen
85
+ // totals are the authoritative record, so take per-field MAX of the shared
86
+ // rows (same lifetime counter — never SUM, that would double count).
87
+ // - 30 messages were never migrated (4.3M input tokens) → union them in.
88
+ // - Tool parts: embedded content already covers migrated V1 parts, so only
89
+ // parts of never-migrated messages are added from `part` (everything else
90
+ // would double count).
91
+ const schema = { session: 'session', message: 'message', embeddedTools: false };
92
+ function detectSchema(d) {
93
+ const has = (t) => !!d.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(t);
94
+ const sV2 = has('session_v2'), sV1 = has('session');
95
+ const mV2 = has('session_message'), mV1 = has('message');
96
+ schema.embeddedTools = mV2;
97
+ schema.session = (sV2 && sV1)
98
+ ? `(SELECT v.id AS id, v.agent AS agent, v.model AS model,
99
+ v.time_created AS time_created,
100
+ MAX(v.time_updated, COALESCE(s.time_updated, 0)) AS time_updated,
101
+ MAX(v.tokens_input, COALESCE(s.tokens_input, 0)) AS tokens_input,
102
+ MAX(v.tokens_output, COALESCE(s.tokens_output, 0)) AS tokens_output,
103
+ MAX(v.tokens_reasoning, COALESCE(s.tokens_reasoning, 0)) AS tokens_reasoning,
104
+ MAX(v.tokens_cache_read, COALESCE(s.tokens_cache_read, 0)) AS tokens_cache_read,
105
+ MAX(v.tokens_cache_write, COALESCE(s.tokens_cache_write, 0)) AS tokens_cache_write,
106
+ MAX(v.cost, COALESCE(s.cost, 0)) AS cost
107
+ FROM session_v2 v LEFT JOIN session s ON s.id = v.id
108
+ UNION ALL
109
+ SELECT id, agent, model, time_created, time_updated, tokens_input, tokens_output,
110
+ tokens_reasoning, tokens_cache_read, tokens_cache_write, cost
111
+ FROM session WHERE id NOT IN (SELECT id FROM session_v2))`
112
+ : sV2 ? 'session_v2' : 'session';
113
+ // V2 adds non-chat message types (idle/synthetic/compaction/...): keep V1
114
+ // user+assistant semantics by filtering inside the union.
115
+ schema.message = (mV2 && mV1)
116
+ ? `(SELECT id, session_id, time_created, time_updated, data
117
+ FROM session_message WHERE type IN ('user','assistant')
118
+ UNION ALL
119
+ SELECT id, session_id, time_created, time_updated, data
120
+ FROM message WHERE id NOT IN (SELECT id FROM session_message))`
121
+ : mV2 ? 'session_message' : 'message';
122
+ }
123
+
74
124
  let db = null;
75
125
  function getDb() {
76
126
  if (!Database) return null;
@@ -83,6 +133,7 @@ function getDb() {
83
133
  db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
84
134
  db.pragma('journal_mode = WAL');
85
135
  db.pragma('busy_timeout = 5000');
136
+ detectSchema(db);
86
137
  try {
87
138
  db.exec("CREATE INDEX IF NOT EXISTS idx_message_time_created ON message(time_created)");
88
139
  db.exec("CREATE INDEX IF NOT EXISTS idx_message_session_time ON message(session_id, time_created)");
@@ -156,12 +207,16 @@ function cleanExpiredCache(cache, ttl) {
156
207
  }
157
208
 
158
209
  async function generateTrend(days) {
159
- const now = Date.now();
160
-
161
210
  // Buckets: local midnights, today -> (days-1) days ago.
162
- // Values come from attributeUsage (hybrid message+session-residual
163
- // attribution), so multi-day sessions don't dump everything on one day
164
- // and pruned (message-less) history isn't lost either.
211
+ // Values are sliced from the SHARED all-time attribution (getAttrAll(),
212
+ // the same object the usage report uses) — never a separate windowed
213
+ // attributeUsage call. Windowed attribution inflates in-window days:
214
+ // messages before the window are excluded from msgTok, so the session
215
+ // residual grows and lands entirely on windowed days (measured
216
+ // +0.25–1.7M input/day on 2026-09-29). One shared attribution makes
217
+ // trend buckets and report periods structurally identical; any remaining
218
+ // panel difference is only cache age (trend ≤60s, report ≤10min, both
219
+ // timestamps shown in the UI).
165
220
  const buckets = [];
166
221
  const today = new Date();
167
222
  for (let i = 0; i < days; i++) {
@@ -170,7 +225,7 @@ async function generateTrend(days) {
170
225
  d.setHours(0, 0, 0, 0);
171
226
  buckets.push(d);
172
227
  }
173
- const a = attributeUsage(buckets[buckets.length - 1].getTime(), now);
228
+ const a = getAttrAll();
174
229
  const at = (b, f) => {
175
230
  const D = a.perDay[localDayKey(b)];
176
231
  return D ? D[f] : 0;
@@ -181,7 +236,7 @@ async function generateTrend(days) {
181
236
  };
182
237
 
183
238
  return {
184
- generatedAt: now,
239
+ generatedAt: attrAllCache.at, // attribution build time, not response time
185
240
  step: 1,
186
241
  labels: buckets.map((b) => (b.getMonth() + 1) + '/' + b.getDate()),
187
242
  sessions: buckets.map(sess),
@@ -243,7 +298,7 @@ function attributeUsage(startMs, endMs) {
243
298
  // 1. messages in period (exact timing)
244
299
  const msgTok = {};
245
300
  const msgW = {};
246
- const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost FROM message WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
301
+ const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), json_extract(data, '$.model.id'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
247
302
  for (const r of mrows) {
248
303
  const key = localDayKey(new Date(r.t));
249
304
  const D = ensureDay(key);
@@ -271,12 +326,11 @@ function attributeUsage(startMs, endMs) {
271
326
  }
272
327
 
273
328
  // 2. sessions intersecting the period: spread residual
274
- const srows = dbQuery(`SELECT id, agent, COALESCE(json_extract(model, '$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model, '$.id'), 'unknown') AS model, time_created AS tc, time_updated AS tu, tokens_input AS si, tokens_output AS so, tokens_reasoning AS sr, tokens_cache_read AS scr, tokens_cache_write AS scw, cost AS sc FROM session WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
329
+ const srows = dbQuery(`SELECT id, agent, COALESCE(json_extract(model, '$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model, '$.id'), 'unknown') AS model, time_created AS tc, time_updated AS tu, tokens_input AS si, tokens_output AS so, tokens_reasoning AS sr, tokens_cache_read AS scr, tokens_cache_write AS scw, cost AS sc FROM ${schema.session} WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
275
330
  for (const s of srows) {
276
- // Use the session's FULL span for residual distribution so that
277
- // trend (7d window) and report (1d window) distribute the same
278
- // residual across the same days. This keeps daily breakdown
279
- // consistent regardless of the caller's time window.
331
+ // Use the session's FULL span for residual distribution. All consumers
332
+ // share one all-time attribution (getAttrAll), so per-day values are
333
+ // identical whichever period slices them.
280
334
  const d0 = new Date(new Date(s.tc).setHours(0, 0, 0, 0));
281
335
  const d1 = new Date(new Date(s.tu).setHours(0, 0, 0, 0));
282
336
  const spanKeys = [];
@@ -355,11 +409,21 @@ function getStatsFromDb(days) {
355
409
  // NOTE: days is only ever 0 here (overview totals); per-period stats are
356
410
  // built by buildReportFromDb via attributeUsage. Local-day count so the
357
411
  // number matches the trend chart buckets.
358
- const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM session s ${timeFilterWhere};`);
359
- const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM message m ${startMs ? `WHERE m.time_updated >= ${startMs}` : ''};`);
360
- const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_reasoning),0) AS reasoning, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM session s ${timeFilterWhere};`);
361
-
362
- const toolRows = dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
412
+ const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM ${schema.session} s ${timeFilterWhere};`);
413
+ const msgConds = [];
414
+ if (startMs) msgConds.push('m.time_updated >= ' + startMs);
415
+ const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM ${schema.message} m ${msgConds.length ? 'WHERE ' + msgConds.join(' AND ') : ''};`);
416
+ const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_reasoning),0) AS reasoning, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM ${schema.session} s ${timeFilterWhere};`);
417
+
418
+ // V2: tool parts are embedded in session_message content (part table froze
419
+ // at the upgrade and its migrated rows were rebuilt into content, so
420
+ // querying all of part would double count — only parts of messages that
421
+ // were never migrated are added from `part`).
422
+ const toolRows = schema.embeddedTools
423
+ ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
424
+ UNION ALL
425
+ SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
426
+ : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
363
427
  const toolCounts = {};
364
428
  for (const row of toolRows) {
365
429
  if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
@@ -369,7 +433,7 @@ function getStatsFromDb(days) {
369
433
  .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
370
434
  .sort((a, b) => b.count - a.count);
371
435
 
372
- const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM session s ${timeFilterWhere};`) || [];
436
+ const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM ${schema.session} s ${timeFilterWhere};`) || [];
373
437
  const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
374
438
  const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
375
439
  const medianTokens = computeMedian(tokenVals);
@@ -482,7 +546,7 @@ async function performBackup(auto) {
482
546
  for (const n of files) {
483
547
  const srcPath = path.join(srcDir, n);
484
548
  const dstPath = path.join(destDir, n);
485
- fs.copyFileSync(srcPath, dstPath);
549
+ await fs.promises.copyFile(srcPath, dstPath);
486
550
  try {
487
551
  const { origSize, compSize } = await compressFile(dstPath);
488
552
  totalOrigSize += origSize;
@@ -499,7 +563,7 @@ async function performBackup(auto) {
499
563
  const p = (n) => String(n).padStart(2, '0');
500
564
  lastAutoBackupDay = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
501
565
  }
502
- cleanupOldBackups();
566
+ await cleanupOldBackups();
503
567
  const ratio = totalOrigSize > 0 ? ((1 - totalCompSize / totalOrigSize) * 100).toFixed(1) : 0;
504
568
  console.log(`backup ok: ${dir} (${(totalCompSize / 1024 / 1024).toFixed(1)} MB, compressed ${ratio}%)`);
505
569
  return { ok: true, file: dir, size: totalCompSize, origSize: totalOrigSize, files: compressedFiles };
@@ -564,8 +628,13 @@ function buildReportFromDb(days) {
564
628
  }
565
629
  const t = periodTotals;
566
630
  const activeDays = pdVals.length || 1;
567
- const sessVals = Object.values(a.perSession)
568
- .filter((s) => s.input > 0 || s.output > 0 || s.reasoning > 0)
631
+ // Avg/median over the PERIOD's token-bearing sessions (same session set
632
+ // the providers/agents tables are built from) — not all-time, so Daily and
633
+ // Weekly reports differ.
634
+ const periodSessionIds = [...periodTotals.sessions];
635
+ const sessVals = periodSessionIds
636
+ .map((sid) => a.perSession[sid])
637
+ .filter((s) => s && (s.input > 0 || s.output > 0 || s.reasoning > 0))
569
638
  .map((s) => s.input + s.output + s.reasoning)
570
639
  .filter(Number.isFinite);
571
640
  const avgTokens = sessVals.length ? sessVals.reduce((x, v) => x + v, 0) / sessVals.length : 0;
@@ -584,13 +653,12 @@ function buildReportFromDb(days) {
584
653
  };
585
654
  const r4 = (v) => Math.round((v || 0) * 10000) / 10000;
586
655
 
587
- // Rebuild per-agent and per-model for the period.
588
- // Collect session IDs active in the period, then query their actual
589
- // agent/model from the session table (since perSession doesn't store that).
590
- const periodSessionIds = [...periodTotals.sessions];
656
+ // Rebuild per-agent and per-model for the period from session-table meta
657
+ // (perSession doesn't store agent/model). periodSessionIds was computed
658
+ // above for avg/median.
591
659
  if (periodSessionIds.length) {
592
660
  const placeholders = periodSessionIds.map(() => '?').join(',');
593
- const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model FROM session WHERE id IN (${placeholders})`, periodSessionIds) || [];
661
+ const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model FROM ${schema.session} WHERE id IN (${placeholders})`, periodSessionIds) || [];
594
662
  const metaMap = {};
595
663
  for (const s of sessMeta) metaMap[s.id] = s;
596
664