sigrank 0.19.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/MCP_SERVER_DESCRIPTION.md +172 -0
  3. package/README.md +89 -41
  4. package/adapters/index.mjs +1100 -0
  5. package/adapters/tokenpull.mjs +568 -0
  6. package/adapters.mjs +1 -865
  7. package/analytics/cascade.mjs +338 -0
  8. package/cascade.mjs +1 -274
  9. package/cli.mjs +1 -1853
  10. package/connect.mjs +1 -13
  11. package/identity/connect.mjs +13 -0
  12. package/identity/keystore.mjs +231 -0
  13. package/identity/sign.mjs +106 -0
  14. package/index.mjs +47 -162
  15. package/keystore.mjs +1 -242
  16. package/lib/constants.mjs +137 -0
  17. package/lib/pkg-version.mjs +59 -0
  18. package/manifest.json +46 -0
  19. package/narrate.mjs +1 -77
  20. package/package.json +41 -16
  21. package/preflight.mjs +1 -191
  22. package/presentation/cli.mjs +1926 -0
  23. package/presentation/narrate.mjs +219 -0
  24. package/presentation/tui-themes.mjs +189 -0
  25. package/presentation/tui.mjs +3316 -0
  26. package/prompts/check-my-efficiency.md +1 -0
  27. package/prompts/compare-with-leader.md +1 -0
  28. package/prompts/simulate-improvement.md +1 -0
  29. package/proxy.mjs +492 -0
  30. package/resources/class-tiers.md +81 -0
  31. package/resources/data-policy.md +31 -0
  32. package/resources/install-guide.md +59 -0
  33. package/resources/privacy-model.md +44 -0
  34. package/resources/scoring-formula.md +24 -0
  35. package/review.mjs +263 -0
  36. package/sign.mjs +1 -106
  37. package/submit/index.mjs +297 -0
  38. package/submit/preflight.mjs +191 -0
  39. package/submit.mjs +1 -303
  40. package/tokenpull.mjs +1 -576
  41. package/tokscale_analytics.mjs +864 -0
  42. package/tools/_framing.mjs +217 -0
  43. package/tools/_helpers.mjs +253 -0
  44. package/tools/_peer-matching.mjs +361 -0
  45. package/tools/_report.mjs +262 -0
  46. package/tools/_schemas.mjs +492 -0
  47. package/tools/_verifiers.mjs +148 -0
  48. package/tools/compare-operators.mjs +80 -0
  49. package/tools/compare-self.mjs +124 -0
  50. package/tools/describe-power-user.mjs +78 -0
  51. package/tools/diagnose-cascade.mjs +192 -0
  52. package/tools/discover-peers.mjs +198 -0
  53. package/tools/enroll.mjs +119 -0
  54. package/tools/get-best-operator.mjs +59 -0
  55. package/tools/get-leaderboard.mjs +27 -0
  56. package/tools/get-operator.mjs +33 -0
  57. package/tools/index.mjs +229 -0
  58. package/tools/optimize-efficiency.mjs +170 -0
  59. package/tools/rank-paste.mjs +51 -0
  60. package/tools/rank-windows.mjs +120 -0
  61. package/tools/self-improve.mjs +423 -0
  62. package/tools/simulate-change.mjs +207 -0
  63. package/tools/submit-paste.mjs +121 -0
  64. package/tools/submit-verified.mjs +153 -0
  65. package/tools/suggest-improvements.mjs +168 -0
  66. package/tools/tokenpull-compare.mjs +123 -0
  67. package/tools/tokenpull-submit.mjs +235 -0
  68. package/tools/tokenpull.mjs +113 -0
  69. package/tools/tokscale-breakdown.mjs +119 -0
  70. package/tools/tokscale-competitive-intel.mjs +45 -0
  71. package/tools/tokscale-cost-analysis.mjs +31 -0
  72. package/tools/tokscale-developer-profile.mjs +36 -0
  73. package/tools/tokscale-device-profile.mjs +35 -0
  74. package/tools/tokscale-market-share.mjs +38 -0
  75. package/tools/tokscale-mcp-usage.mjs +33 -0
  76. package/tools/tokscale-model-trends.mjs +32 -0
  77. package/tools/watch-tokenpull.mjs +134 -0
  78. package/tools.mjs +1 -3897
  79. package/tui.mjs +4 -2650
  80. package/banner.svg +0 -7
package/cli.mjs CHANGED
@@ -1,1853 +1 @@
1
- /**
2
- * cli.mjs — SigRank terminal UI.
3
- *
4
- * Default (no command): full unified view — all platforms, all windows, token pillars,
5
- * board position, [S] submit prompt.
6
- *
7
- * Commands:
8
- * npx sigrank full unified view (default)
9
- * npx sigrank board live leaderboard, refreshes every 30s
10
- * npx sigrank board --window 7d board for a specific window
11
- * npx sigrank board --once print once and exit (no live refresh)
12
- * npx sigrank compare raw pillar comparison: ccusage vs tokenpull vs token-dashboard
13
- * npx sigrank watch RT tune meter — ALL active platforms × all windows
14
- * npx sigrank watch --platform X watch one platform only (optional filter)
15
- * npx sigrank watch --window 7d watch one window only (optional filter)
16
- *
17
- * Color palette mirrors the SigRank web dark theme:
18
- * gold = class TRANSMITTER headline + rank #1
19
- * cyan = active metrics / your row highlight
20
- * dim = secondary data, separators
21
- * red = negative movement / delta
22
- * green = positive movement
23
- */
24
-
25
- import { callTool, DEFAULT_API_BASE, pullActivePlatforms } from "./tools.mjs";
26
- import { classify } from "./cascade.mjs";
27
- import { ensureIdentity, keystorePath } from "./keystore.mjs";
28
- import { submitSignedWindow } from "./submit.mjs";
29
- import { execFile } from "child_process";
30
- import { existsSync, readFileSync } from "fs";
31
- import os from "os";
32
- import path from "path";
33
- import { fileURLToPath } from "url";
34
-
35
- // Resolve local node_modules/.bin for bundled deps (ccusage, tokscale)
36
- const _pkgRoot = path.dirname(fileURLToPath(import.meta.url));
37
- const _localBin = path.join(_pkgRoot, "node_modules", ".bin");
38
- const _envPath = `${_localBin}${process.env.PATH ? ":" + process.env.PATH : ""}`;
39
-
40
- // ASYNC FIX (2026-06-27): execFile wrapped in a Promise — replaces execSync for
41
- // defense-in-depth (shell injection prevention). execFile passes args as an
42
- // array, so no shell parsing occurs — even if platform contained special chars,
43
- // they'd be treated as literal arguments, not shell commands.
44
- // BIN FIX (2026-06-27): PATH includes local node_modules/.bin so bundled deps
45
- // are found even when sigrank isn't globally installed.
46
- function execFileAsync(cmd, args, timeoutMs) {
47
- return new Promise((resolve, reject) => {
48
- execFile(
49
- cmd,
50
- args,
51
- {
52
- timeout: timeoutMs,
53
- stdio: ["ignore", "pipe", "ignore"],
54
- maxBuffer: 10 * 1024 * 1024,
55
- env: { ...process.env, PATH: _envPath },
56
- },
57
- (err, stdout) => {
58
- if (err) reject(err);
59
- else resolve(stdout.toString());
60
- },
61
- );
62
- });
63
- }
64
-
65
- // ── ANSI helpers (no chalk dep) ────────────────────────────────────────────
66
- const ESC = "\x1b[";
67
- const c = {
68
- reset: `${ESC}0m`,
69
- bold: `${ESC}1m`,
70
- dim: `${ESC}2m`,
71
- gold: `${ESC}33m`,
72
- boldGold: `${ESC}1;33m`,
73
- cyan: `${ESC}36m`,
74
- boldCyan: `${ESC}1;36m`,
75
- green: `${ESC}32m`,
76
- red: `${ESC}31m`,
77
- white: `${ESC}97m`,
78
- boldWhite: `${ESC}1;97m`,
79
- magenta: `${ESC}35m`,
80
- blue: `${ESC}34m`,
81
- };
82
- const paint = (color, str) => `${color}${str}${c.reset}`;
83
- const bold = (str) => paint(c.bold, str);
84
- const dim = (str) => paint(c.dim, str);
85
- const gold = (str) => paint(c.boldGold, str);
86
- const cyan = (str) => paint(c.boldCyan, str);
87
- const green = (str) => paint(c.green, str);
88
- const red = (str) => paint(c.red, str);
89
-
90
- // ── Class tier → color ─────────────────────────────────────────────────────
91
- const CLASS_COLOR = {
92
- TRANSMITTER: (s) => paint(c.boldGold, s),
93
- "ARCH+": (s) => paint(c.boldCyan, s),
94
- ARCH: (s) => paint(c.cyan, s),
95
- POWER: (s) => paint(c.boldWhite, s),
96
- BASE: (s) => paint(c.white, s),
97
- SEEKER: (s) => paint(c.magenta, s),
98
- REFINER: (s) => paint(c.blue, s),
99
- BEARER: (s) => paint(c.dim, s),
100
- IGNITER: (s) => paint(c.dim, s),
101
- };
102
- const colorClass = (cls) => (CLASS_COLOR[cls] ?? ((s) => s))(cls);
103
-
104
- // ── Terminal utils ──────────────────────────────────────────────────────────
105
- const CLEAR_SCREEN = `${ESC}2J${ESC}H`;
106
- const CURSOR_UP = (n) => `${ESC}${n}A`;
107
- const ERASE_LINE = `${ESC}2K`;
108
- const HIDE_CURSOR = `${ESC}?25l`;
109
- const SHOW_CURSOR = `${ESC}?25h`;
110
- const termWidth = () => process.stdout.columns || 80;
111
- const write = (s) => process.stdout.write(s);
112
- const writeln = (s = "") => process.stdout.write(s + "\n");
113
-
114
- // Right-pad or truncate to exact width (ANSI-escape-aware via strip helper)
115
- function stripAnsi(s) {
116
- return s.replace(/\x1b\[[0-9;]*m/g, "");
117
- }
118
- function padEnd(s, w) {
119
- const vis = stripAnsi(s).length;
120
- return vis >= w ? s : s + " ".repeat(w - vis);
121
- }
122
- function padStart(s, w) {
123
- const vis = stripAnsi(s).length;
124
- return vis >= w ? s : " ".repeat(w - vis) + s;
125
- }
126
- function trunc(s, w) {
127
- const stripped = stripAnsi(s);
128
- if (stripped.length <= w) return s;
129
- // truncate the raw string, not the escape-aware one — safe for plain strings
130
- return s.slice(0, w - 1) + "…";
131
- }
132
-
133
- // ── Number formatters ───────────────────────────────────────────────────────
134
- const fmtYield = (y) => {
135
- if (y == null) return "—";
136
- if (y >= 10000) return `${(y / 1000).toFixed(1)}K`;
137
- if (y >= 1000) return `${(y / 1000).toFixed(2)}K`;
138
- return y.toFixed(1);
139
- };
140
- const fmtLev = (l) => {
141
- if (l == null) return "—";
142
- if (l >= 1000) return `${(l / 1000).toFixed(1)}K`;
143
- return l.toFixed(0);
144
- };
145
- const fmtPct = (n) => (n != null ? `${(n * 100).toFixed(0)}%` : "—");
146
- const fmtSNR = (n) => (n != null ? `${(n * 100).toFixed(1)}%` : "—");
147
- const fmtMove = (n) => {
148
- if (n == null || n === 0) return dim(" —");
149
- return n > 0 ? green(`+${n}`) : red(`${n}`);
150
- };
151
- const fmtTokens = (n) => {
152
- if (n == null) return "—";
153
- if (n >= 1e9) return `${(n / 1e9).toFixed(1)}B`;
154
- if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
155
- if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
156
- return String(n);
157
- };
158
-
159
- // ── Header / footer ─────────────────────────────────────────────────────────
160
- function renderHeader(title, subtitle = "") {
161
- const w = termWidth();
162
- const ts = new Date().toLocaleTimeString("en-US", { hour12: false });
163
- const right = dim(`signalaf.com ${ts}`);
164
- const rightVis = stripAnsi(right).length;
165
- const leftVis = stripAnsi(title).length;
166
- const gap = Math.max(1, w - leftVis - rightVis);
167
- writeln();
168
- writeln(` ${title}${" ".repeat(gap)}${right}`);
169
- if (subtitle) writeln(` ${dim(subtitle)}`);
170
- writeln(` ${dim("─".repeat(w - 4))}`);
171
- }
172
-
173
- function renderFooter(hint = "") {
174
- const w = termWidth();
175
- writeln(` ${dim("─".repeat(w - 4))}`);
176
- if (hint) writeln(` ${dim(hint)}`);
177
- writeln();
178
- }
179
-
180
- // ── BOARD command ────────────────────────────────────────────────────────────
181
-
182
- const BOARD_COLS = [
183
- { key: "rank", label: "#", w: 4, align: "r" },
184
- { key: "codename", label: "Operator", w: 20, align: "l" },
185
- { key: "class_tier", label: "Class", w: 13, align: "l" },
186
- { key: "yield_", label: "Υ Yield", w: 9, align: "r" },
187
- { key: "compression_ratio", label: "SNR", w: 6, align: "r" },
188
- { key: "session_depth", label: "Depth", w: 6, align: "r" },
189
- { key: "token_throughput", label: "Tokens", w: 8, align: "r" },
190
- { key: "movement_7d", label: "7d Δ", w: 6, align: "r" },
191
- ];
192
-
193
- function renderBoardRow(entry, highlight = false) {
194
- const rank = entry.rank === 1 ? gold(`#${entry.rank}`) : `#${entry.rank}`;
195
- const name = highlight
196
- ? cyan(trunc(entry.codename, 19))
197
- : trunc(entry.codename, 19);
198
- const cls = colorClass(entry.class_tier ?? "—");
199
- const yld = entry.yield_ != null ? fmtYield(entry.yield_) : "—";
200
- const snr = fmtSNR(entry.compression_ratio);
201
- const dep =
202
- entry.session_depth != null ? entry.session_depth.toFixed(1) : "—";
203
- const tok = fmtTokens(entry.token_throughput);
204
- const mv = fmtMove(entry.movement_7d);
205
-
206
- const cols = [
207
- padStart(rank, 4),
208
- padEnd(name, 20),
209
- padEnd(cls, 13),
210
- padStart(yld, 9),
211
- padStart(snr, 6),
212
- padStart(dep, 6),
213
- padStart(tok, 8),
214
- padStart(mv, 6),
215
- ];
216
- const prefix = highlight ? `${c.boldCyan}▶${c.reset} ` : " ";
217
- writeln(prefix + cols.join(" "));
218
- }
219
-
220
- function renderBoardHeader(window = "30d") {
221
- renderHeader(
222
- `${gold("⊙ SigRank")} ${bold("Leaderboard")}`,
223
- `window: ${window} · sorted by Υ Yield · top 25 operators`,
224
- );
225
- // column headers
226
- const headers = BOARD_COLS.map((col) =>
227
- col.align === "r"
228
- ? padStart(dim(col.label), col.w)
229
- : padEnd(dim(col.label), col.w),
230
- );
231
- writeln(` ${headers.join(" ")}`);
232
- writeln(` ${dim("·".repeat(termWidth() - 4))}`);
233
- }
234
-
235
- async function fetchBoard(window = "30d") {
236
- const res = await fetch(
237
- `${DEFAULT_API_BASE}/api/v1/leaderboard?window=${window}&metric=yield_`,
238
- {
239
- headers: {
240
- accept: "application/json",
241
- "user-agent": `node/${process.version} sigrank-mcp/cli`,
242
- },
243
- },
244
- );
245
- if (!res.ok) throw new Error(`Board API → HTTP ${res.status}`);
246
- return res.json();
247
- }
248
-
249
- async function runBoard({ window = "30d", once = false, refresh = 30 } = {}) {
250
- let lines = 0;
251
-
252
- const draw = async () => {
253
- let data;
254
- try {
255
- data = await fetchBoard(window);
256
- } catch (e) {
257
- writeln(red(` ✗ Could not reach signalaf.com: ${e.message}`));
258
- return;
259
- }
260
-
261
- if (!once && lines > 0) {
262
- // move cursor up and redraw in-place
263
- write(CURSOR_UP(lines));
264
- }
265
-
266
- const out = [];
267
- const push = (s = "") => out.push(s);
268
-
269
- push();
270
- const ts = new Date().toLocaleTimeString("en-US", { hour12: false });
271
- const right = `signalaf.com ${ts}`;
272
- const title = `⊙ SigRank Leaderboard`;
273
- const w = termWidth();
274
- const gap = Math.max(1, w - 2 - title.length - right.length);
275
- push(
276
- ` ${gold("⊙ SigRank")} ${bold("Leaderboard")}${" ".repeat(gap)}${dim(right)}`,
277
- );
278
- push(
279
- ` ${dim(`window: ${data.window ?? window} · ${data.total_operators ?? data.entries?.length ?? 0} operators`)}`,
280
- );
281
- push(` ${dim("─".repeat(w - 4))}`);
282
-
283
- // column header row
284
- const headers = BOARD_COLS.map((col) =>
285
- col.align === "r"
286
- ? padStart(dim(col.label), col.w)
287
- : padEnd(dim(col.label), col.w),
288
- ).join(" ");
289
- push(` ${headers}`);
290
- push(` ${dim("·".repeat(w - 4))}`);
291
-
292
- const entries = data.entries ?? [];
293
- for (const entry of entries) {
294
- const rank = entry.rank === 1 ? gold(`#${entry.rank}`) : `#${entry.rank}`;
295
- const name = trunc(entry.codename ?? "—", 19);
296
- const cls = colorClass(entry.class_tier ?? "—");
297
- const yld = entry.yield_ != null ? fmtYield(entry.yield_) : "—";
298
- const snr = fmtSNR(entry.compression_ratio);
299
- const dep =
300
- entry.session_depth != null ? entry.session_depth.toFixed(1) : "—";
301
- const tok = fmtTokens(entry.token_throughput);
302
- const mv = fmtMove(entry.movement_7d);
303
- const cols = [
304
- padStart(rank, 4),
305
- padEnd(name, 20),
306
- padEnd(cls, 13),
307
- padStart(yld, 9),
308
- padStart(snr, 6),
309
- padStart(dep, 6),
310
- padStart(tok, 8),
311
- padStart(mv, 6),
312
- ];
313
- push(` ${cols.join(" ")}`);
314
- }
315
-
316
- push(` ${dim("─".repeat(w - 4))}`);
317
- if (!once)
318
- push(` ${dim(`auto-refresh every ${refresh}s · ctrl+c to exit`)}`);
319
- push();
320
-
321
- // write all at once to minimize flicker
322
- const rendered = out.join("\n");
323
- write(rendered);
324
- lines = out.length;
325
- };
326
-
327
- if (!once) write(HIDE_CURSOR);
328
- try {
329
- await draw();
330
- if (!once) {
331
- const iv = setInterval(draw, refresh * 1000);
332
- await new Promise((resolve) => {
333
- process.on("SIGINT", () => {
334
- clearInterval(iv);
335
- resolve();
336
- });
337
- });
338
- }
339
- } finally {
340
- if (!once) write(SHOW_CURSOR + "\n");
341
- }
342
- }
343
-
344
- // ── COMPARE command ───────────────────────────────────────────────────────────
345
- // Side-by-side: ccusage (JSON) vs tokenpull vs token-dashboard (SQLite)
346
- //
347
- // NOTE (P3 2026-06-27): These sync verifier readers (ccusagePillars / tokscalePillars /
348
- // tokenDashPillars / appPillars) are INTENTIONALLY separate from tokenpull.mjs
349
- // `freshVerifierPillars()`. The compare command uses cached/file-based data sources
350
- // (tokscale_report.json, direct db read with windowed+model-filtered queries) for a
351
- // quick side-by-side, while freshVerifierPillars runs all three live (bunx tokscale,
352
- // scan+read tokendash) for the dashboard. Merging them would change compare's data
353
- // source and lose the windowed tokendash breakdown. ccusagePillars IS functionally
354
- // identical to _freshCcusage and could be consolidated in a future pass if compare
355
- // switches to live data — but that's a behavior change, not a refactor.
356
-
357
- async function ccusagePillars(platform = "claude") {
358
- // ccusage <platform> daily --json → sum by window
359
- try {
360
- const raw = await execFileAsync(
361
- "ccusage",
362
- [platform, "daily", "--json"],
363
- 15000,
364
- );
365
- const data = JSON.parse(raw);
366
- const rows = data.daily ?? data; // ccusage may return {daily:[...]} or [...]
367
-
368
- const now = Date.now();
369
- const cutoff = { "7d": 7, "30d": 30, "90d": 90 };
370
- const result = {};
371
-
372
- for (const [win, days] of Object.entries(cutoff)) {
373
- const since = new Date(now - days * 86400000);
374
- let input = 0,
375
- output = 0,
376
- cacheCreate = 0,
377
- cacheRead = 0;
378
- for (const row of rows) {
379
- const d = new Date(row.date ?? row.day ?? row.week ?? "1970-01-01");
380
- if (d >= since) {
381
- input += row.inputTokens ?? row.input_tokens ?? 0;
382
- output += row.outputTokens ?? row.output_tokens ?? 0;
383
- cacheCreate +=
384
- row.cacheCreationTokens ?? row.cache_create_tokens ?? 0;
385
- cacheRead += row.cacheReadTokens ?? row.cache_read_tokens ?? 0;
386
- }
387
- }
388
- result[win] = { input, output, cacheCreate, cacheRead };
389
- }
390
- // all-time = sum everything
391
- let input = 0,
392
- output = 0,
393
- cacheCreate = 0,
394
- cacheRead = 0;
395
- for (const row of rows) {
396
- input += row.inputTokens ?? row.input_tokens ?? 0;
397
- output += row.outputTokens ?? row.output_tokens ?? 0;
398
- cacheCreate += row.cacheCreationTokens ?? row.cache_create_tokens ?? 0;
399
- cacheRead += row.cacheReadTokens ?? row.cache_read_tokens ?? 0;
400
- }
401
- result["all"] = { input, output, cacheCreate, cacheRead };
402
- return result;
403
- } catch {
404
- return null;
405
- }
406
- }
407
-
408
- async function tokscalePillars(platform = "claude") {
409
- // Try the bundled tokscale CLI first (fresh data), fall back to saved report file.
410
- try {
411
- const raw = await execFileAsync("tokscale", ["models", "--json"], 60000);
412
- const data = JSON.parse(raw);
413
- const entries = Array.isArray(data?.entries)
414
- ? data.entries
415
- : Array.isArray(data)
416
- ? data
417
- : [];
418
- const rows = entries.filter(
419
- (e) =>
420
- e &&
421
- e.client === platform &&
422
- e.model !== "<synthetic>" &&
423
- e.model !== "unknown" &&
424
- ((Number(e.input) || 0) > 0 || (Number(e.output) || 0) > 0),
425
- );
426
- if (rows.length) {
427
- const p = rows.reduce(
428
- (acc, e) => ({
429
- input: acc.input + (Number(e.input) || 0),
430
- output: acc.output + (Number(e.output) || 0),
431
- cacheCreate: acc.cacheCreate + (Number(e.cacheWrite) || 0),
432
- cacheRead: acc.cacheRead + (Number(e.cacheRead) || 0),
433
- }),
434
- { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 },
435
- );
436
- return { all: p };
437
- }
438
- } catch {
439
- /* fall through to file-based read */
440
- }
441
- // Fallback: read saved tokscale_report.json — all-time only (no timestamps in export)
442
- const reportPath = path.join(os.homedir(), "tokscale_report.json");
443
- if (!existsSync(reportPath)) return null;
444
- try {
445
- const data = JSON.parse(readFileSync(reportPath, "utf8"));
446
- const entries = data.entries ?? [];
447
- const rows = entries.filter(
448
- (e) =>
449
- e.client === platform &&
450
- e.model !== "<synthetic>" &&
451
- e.model !== "unknown" &&
452
- (e.input > 0 || e.output > 0),
453
- );
454
- if (rows.length === 0) return null;
455
- const p = rows.reduce(
456
- (acc, e) => ({
457
- input: acc.input + (e.input ?? 0),
458
- output: acc.output + (e.output ?? 0),
459
- cacheCreate: acc.cacheCreate + (e.cacheWrite ?? 0),
460
- cacheRead: acc.cacheRead + (e.cacheRead ?? 0),
461
- }),
462
- { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 },
463
- );
464
- // tokscale export has no timestamps → only all-time available
465
- return { all: p };
466
- } catch {
467
- return null;
468
- }
469
- }
470
-
471
- function appPillars() {
472
- // App numbers from screenshots — all-time, per model (no cache fields)
473
- // Hard-coded from 2026-06-23 screenshot capture (update when re-screenshotted)
474
- return {
475
- all: {
476
- input: 6_378_000, // sum of all models: 5.6M + 102.1K + 92.9K + 130.3K + 418.9K + 33.5K
477
- output: 38_682_400, // sum: 19.6M + 6.5M + 5.4M + 6.6M + 292.4K + 290.4K
478
- cacheCreate: null, // not shown in App UI
479
- cacheRead: null, // not shown in App UI
480
- },
481
- _note:
482
- "App UI — all-time, per-model sum from screenshots 2026-06-23. No cache fields. Update when re-screenshotted.",
483
- _perModel: [
484
- { model: "claude-opus-4-8", input: 5_600_000, output: 19_600_000 },
485
- { model: "claude-sonnet-4-5", input: 102_100, output: 6_500_000 },
486
- { model: "claude-sonnet-4-6", input: 92_900, output: 5_400_000 },
487
- { model: "claude-opus-4-7", input: 130_300, output: 6_600_000 },
488
- { model: "claude-fable-5", input: 418_900, output: 292_400 },
489
- { model: "claude-haiku-4-5", input: 33_500, output: 290_400 },
490
- ],
491
- };
492
- }
493
-
494
- async function tokenDashPillars() {
495
- const dbPath = path.join(os.homedir(), ".claude", "token-dashboard.db");
496
- if (!existsSync(dbPath)) return null;
497
- // Read directly with sqlite3 — DB created by Nate's token-dashboard (github.com/nateherkai/token-dashboard).
498
- // Windowed queries using sqlite3's datetime() function.
499
- const cf =
500
- "(model LIKE '%claude%' OR model LIKE '%fable%' OR model LIKE '%sonnet%' OR model LIKE '%opus%' OR model LIKE '%haiku%')";
501
- try {
502
- const wins = [
503
- ["7d", "datetime('now','-7 days')"],
504
- ["30d", "datetime('now','-30 days')"],
505
- ["90d", "datetime('now','-90 days')"],
506
- ];
507
- const sql = (cutoff) =>
508
- `SELECT SUM(input_tokens),SUM(output_tokens),SUM(cache_create_5m_tokens+cache_create_1h_tokens),SUM(cache_read_tokens) FROM messages WHERE timestamp>=${cutoff} AND ${cf}`;
509
- const allSql = `SELECT SUM(input_tokens),SUM(output_tokens),SUM(cache_create_5m_tokens+cache_create_1h_tokens),SUM(cache_read_tokens) FROM messages WHERE ${cf}`;
510
- const [d7, d30, d90, dAll] = await Promise.all([
511
- execFileAsync("sqlite3", [dbPath, sql(wins[0][1])], 5000),
512
- execFileAsync("sqlite3", [dbPath, sql(wins[1][1])], 5000),
513
- execFileAsync("sqlite3", [dbPath, sql(wins[2][1])], 5000),
514
- execFileAsync("sqlite3", [dbPath, allSql], 5000),
515
- ]);
516
- const parse = (raw) => {
517
- const [i, o, cw, cr] = raw.trim().split("|").map(Number);
518
- return {
519
- input: i || 0,
520
- output: o || 0,
521
- cacheCreate: cw || 0,
522
- cacheRead: cr || 0,
523
- };
524
- };
525
- return {
526
- "7d": parse(d7),
527
- "30d": parse(d30),
528
- "90d": parse(d90),
529
- all: parse(dAll),
530
- };
531
- } catch {
532
- return null;
533
- }
534
- }
535
-
536
- function fmtDelta(a, b) {
537
- if (a == null || b == null) return dim(" —");
538
- const d = b - a;
539
- if (d === 0) return dim(" =");
540
- const pct =
541
- a !== 0 ? `${d > 0 ? "+" : ""}${((d / a) * 100).toFixed(1)}%` : "";
542
- const abs = `${d > 0 ? "+" : ""}${fmtTokens(Math.abs(d))}`;
543
- const label = `${abs} ${pct}`;
544
- return d > 0 ? green(label) : red(label);
545
- }
546
-
547
- // Compute cascade metrics from raw pillars (mirrors bridge.ts computeCascadeMetrics)
548
- function cascadeFromPillars(p) {
549
- if (!p) return null;
550
- const i = p.input ?? 0;
551
- const o = p.output ?? 0;
552
- const cw = p.cacheCreate ?? 0;
553
- const cr = p.cacheRead ?? 0;
554
- if (i === 0 && o === 0) return null;
555
- const safeI = Math.max(i, 1);
556
- const total = i + o + cw + cr;
557
- const velocity = o / safeI;
558
- const leverage = cr / safeI;
559
- const yield_ = leverage * velocity;
560
- const snr = i + o > 0 ? o / (i + o) : 0;
561
- // dev10x = log10(T × C × R) — only when all four pillars present
562
- let dev10x = null;
563
- if (cw > 0 && o > 0 && i > 0 && cr > 0) {
564
- const T = o / i,
565
- C = cw / o,
566
- R = cr / cw;
567
- dev10x = Math.log10(T * C * R);
568
- }
569
- // efficiency = ((cr+cw+o)/i) / 4.0
570
- const efficiency = (cr + cw + o) / safeI / 4.0;
571
- const cls = classify(yield_, dev10x);
572
- return {
573
- yield: yield_,
574
- velocity,
575
- leverage,
576
- snr,
577
- dev10x,
578
- efficiency,
579
- class: cls,
580
- total,
581
- };
582
- }
583
-
584
- async function runCompare({ platform = "claude" } = {}) {
585
- write(HIDE_CURSOR);
586
-
587
- // Pull all five sources in parallel (verifiers now async via execFile)
588
- writeln(` ${dim("reading all 5 sources…")}`);
589
- const [ccPillars, tpData, tdPillars, tsPillars, apPillars] =
590
- await Promise.all([
591
- ccusagePillars(platform).catch(() => null),
592
- callTool("tokenpull", { platform }).catch(() => null),
593
- (platform === "claude"
594
- ? tokenDashPillars()
595
- : Promise.resolve(null)
596
- ).catch(() => null),
597
- tokscalePillars(platform).catch(() => null),
598
- Promise.resolve(platform === "claude" ? appPillars() : null),
599
- ]);
600
- write(CURSOR_UP(1) + ERASE_LINE);
601
-
602
- const w = termWidth();
603
- const WINS = ["7d", "30d", "90d", "all"];
604
- const WIN_LABEL = { "7d": "7d", "30d": "30d", "90d": "90d", all: "all-time" };
605
-
606
- // build tokenpull pillar lookup
607
- const tpPillars = {};
608
- for (const win of tpData?.windows ?? []) {
609
- tpPillars[win.window] = win.pillars;
610
- }
611
-
612
- // sources: name, color, pillars-by-window, note
613
- const SOURCES = [
614
- {
615
- name: "tokenpull",
616
- color: cyan,
617
- pillars: tpPillars,
618
- note: "JSONL deduped by msg id · canon source",
619
- },
620
- {
621
- name: "ccusage",
622
- color: (s) => paint(c.green, s),
623
- pillars: ccPillars ?? {},
624
- note: "ccusage claude subcommand · monthly only",
625
- },
626
- {
627
- name: "token-dash",
628
- color: (s) => paint(c.magenta, s),
629
- pillars: tdPillars ?? {},
630
- note: "SQLite — double-counts sessions · use with caution",
631
- },
632
- {
633
- name: "tokscale",
634
- color: (s) => paint(c.blue, s),
635
- pillars: tsPillars ?? {},
636
- note: "all-time only · partial export (~5% of opus-4-8)",
637
- },
638
- {
639
- name: "App",
640
- color: gold,
641
- pillars: apPillars ?? {},
642
- note: "screenshots 2026-06-23 · no cache fields · update manually",
643
- },
644
- ];
645
-
646
- writeln();
647
- writeln(
648
- ` ${gold("⊙ SigRank")} ${bold("Source Comparison")} ${dim(`platform: ${platform}`)} ${dim("tokenpull · ccusage · token-dash · tokscale")}`,
649
- );
650
- writeln(` ${dim("─".repeat(w - 4))}`);
651
-
652
- // ── PILLARS TABLE ──────────────────────────────────────────────────────────
653
- const PILLARS = [
654
- { key: "input", label: "Input" },
655
- { key: "output", label: "Output" },
656
- { key: "cacheCreate", label: "Cache Write" },
657
- { key: "cacheRead", label: "Cache Read" },
658
- ];
659
-
660
- for (const { key, label } of PILLARS) {
661
- writeln();
662
- writeln(` ${bold(label)}`);
663
- const hcols = [
664
- padEnd(dim("Source"), 14),
665
- ...WINS.map((win) => padStart(dim(WIN_LABEL[win]), 13)),
666
- ];
667
- writeln(` ${hcols.join(" ")}`);
668
- writeln(` ${dim("·".repeat(Math.min(w - 4, 14 + WINS.length * 15)))}`);
669
-
670
- for (const src of SOURCES) {
671
- const vals = WINS.map((win) => {
672
- const p = src.pillars[win];
673
- const v = p?.[key];
674
- if (v == null) return padStart(dim("—"), 13);
675
- return padStart(fmtTokens(v), 13);
676
- });
677
- writeln(` ${padEnd(src.color(src.name), 14)} ${vals.join(" ")}`);
678
- }
679
- }
680
-
681
- // ── SIGNATURE TABLE ────────────────────────────────────────────────────────
682
- writeln();
683
- writeln(` ${dim("─".repeat(w - 4))}`);
684
- writeln(
685
- ` ${bold("Cascade Signature")} ${dim("per source · all windows where data available")}`,
686
- );
687
- writeln();
688
-
689
- const SIG_METRICS = [
690
- { key: "yield", label: "Υ Yield", fmt: (v) => fmtYield(v), w: 9 },
691
- { key: "velocity", label: "Vel", fmt: (v) => v.toFixed(2), w: 6 },
692
- { key: "leverage", label: "Lev", fmt: (v) => `${fmtLev(v)}×`, w: 7 },
693
- { key: "snr", label: "SNR", fmt: (v) => fmtSNR(v), w: 6 },
694
- { key: "dev10x", label: "10x", fmt: (v) => v.toFixed(2), w: 5 },
695
- { key: "efficiency", label: "Eff", fmt: (v) => v.toFixed(1), w: 6 },
696
- { key: "class", label: "Class", fmt: (v) => colorClass(v), w: 12 },
697
- ];
698
-
699
- // header
700
- const sigHdr = [
701
- padEnd(dim("Source"), 14),
702
- padEnd(dim("Window"), 8),
703
- ...SIG_METRICS.map((m) => padStart(dim(m.label), m.w)),
704
- ];
705
- writeln(` ${sigHdr.join(" ")}`);
706
- writeln(` ${dim("·".repeat(Math.min(w - 4, 80)))}`);
707
-
708
- for (const src of SOURCES) {
709
- const availWins = WINS.filter((win) => src.pillars[win] != null);
710
- if (availWins.length === 0) {
711
- writeln(` ${padEnd(src.color(src.name), 14)} ${dim("no data")}`);
712
- continue;
713
- }
714
- let first = true;
715
- for (const win of availWins) {
716
- const p = src.pillars[win];
717
- // For tokenpull, use the pre-computed cascade from the tool if available
718
- let cas;
719
- if (src.name === "tokenpull") {
720
- const tpWin = tpData?.windows?.find((ww) => ww.window === win);
721
- cas = tpWin?.cascade
722
- ? {
723
- yield: tpWin.cascade.yield,
724
- velocity: tpWin.cascade.velocity,
725
- leverage: tpWin.cascade.leverage,
726
- snr: tpWin.cascade.snr,
727
- dev10x: tpWin.cascade.dev10x,
728
- efficiency: null,
729
- class: tpWin.cascade.class,
730
- }
731
- : cascadeFromPillars(p);
732
- } else {
733
- cas = cascadeFromPillars(p);
734
- }
735
-
736
- const srcLabel = first
737
- ? src.color(src.name)
738
- : " ".repeat(stripAnsi(src.name).length);
739
- const winLabel = win === "all" ? bold("all-time") : win;
740
- const sigCols = SIG_METRICS.map((m) => {
741
- const v = cas?.[m.key];
742
- return padStart(v != null ? m.fmt(v) : dim("—"), m.w);
743
- });
744
- writeln(
745
- ` ${padEnd(srcLabel, 14)} ${padEnd(winLabel, 8)} ${sigCols.join(" ")}`,
746
- );
747
- first = false;
748
- }
749
- }
750
-
751
- // ── NOTES ─────────────────────────────────────────────────────────────────
752
- writeln();
753
- writeln(` ${dim("─".repeat(w - 4))}`);
754
- for (const src of SOURCES) {
755
- writeln(` ${src.color(src.name.padEnd(12))} ${dim(src.note)}`);
756
- }
757
- writeln(
758
- ` ${dim("Eff = ((cacheRead+cacheWrite+output)/input)/4.0 vs AA baseline")}`,
759
- );
760
- writeln(
761
- ` ${dim("App has no cache fields → Υ/Lev/Eff/10x unavailable from App source")}`,
762
- );
763
- writeln();
764
- write(SHOW_CURSOR);
765
- }
766
-
767
- // ── WATCH command ─────────────────────────────────────────────────────────────
768
- //
769
- // A5: by default (no --platform / --window) the watcher auto-loads EVERYTHING — every
770
- // active platform (input+output > 0) × every window (7d/30d/90d/all), refreshed each tick.
771
- // --platform / --window remain OPTIONAL filters for back-compat (focus one cell). The
772
- // refresh loop + --submit behavior are preserved; submit publishes whichever windows are
773
- // shown whenever their Υ changes.
774
-
775
- const WATCH_WINDOWS = ["7d", "30d", "90d", "all"];
776
-
777
- // Detect which platforms have real local data (input+output > 0 in any window) via tokenpull.
778
- // Returns an array of pull results (the same shape tokenpullAny yields), one per active platform.
779
- async function detectActivePulls() {
780
- // Unified: one loader for me / watch / the TUI Dashboard (was a separate tokenpullAny loop).
781
- return pullActivePlatforms();
782
- }
783
-
784
- async function runWatch({
785
- platform,
786
- window: win,
787
- refresh = 30,
788
- submit = false,
789
- } = {}) {
790
- let lines = 0;
791
- const id = submit ? ensureIdentity() : null;
792
- const enrolled = !!(
793
- id &&
794
- id.codename &&
795
- id.operator_id &&
796
- id.private_key_pkcs8_b64
797
- );
798
-
799
- // Filters: when provided, narrow the grid; when absent, watch all active × all windows.
800
- const winFilter = typeof win === "string" && win ? win : null;
801
- const platFilter = typeof platform === "string" && platform ? platform : null;
802
- const windows = winFilter ? [winFilter] : WATCH_WINDOWS;
803
-
804
- // Per-cell Υ memory (key = `${platform}|${window}`) so each cell tracks its own change.
805
- const prevY = new Map();
806
- const lastSubmitMsg = new Map();
807
-
808
- write(HIDE_CURSOR);
809
-
810
- const draw = async () => {
811
- // Re-detect each tick so a platform that just started writing logs appears automatically.
812
- let pulls = await detectActivePulls().catch(() => []);
813
- if (platFilter) pulls = pulls.filter((d) => d.platform === platFilter);
814
-
815
- if (lines > 0) write(CURSOR_UP(lines));
816
-
817
- const out = [];
818
- const push = (s = "") => out.push(s);
819
- const w = termWidth();
820
- const ts = new Date().toLocaleTimeString("en-US", { hour12: false });
821
-
822
- const scopeLabel =
823
- (platFilter || "all active platforms") +
824
- " · " +
825
- (winFilter ? `window: ${winFilter}` : "all windows");
826
-
827
- push();
828
- push(
829
- ` ${gold("⊙ SigRank")} ${bold("Watch")} ${dim(`${scopeLabel} · ${ts}`)}`,
830
- );
831
- push(` ${dim("─".repeat(w - 4))}`);
832
-
833
- if (pulls.length === 0) {
834
- push();
835
- push(
836
- ` ${dim("no active platforms detected — run some sessions, this will pick them up automatically")}`,
837
- );
838
- push();
839
- }
840
-
841
- for (const d of pulls) {
842
- const plat = d.platform;
843
- const byWin = {};
844
- for (const ww of d.windows || []) byWin[ww.window] = ww;
845
- push();
846
- push(` ${cyan(plat)}${d.estimated ? dim(" (est)") : ""}`);
847
- for (const wk of windows) {
848
- const ww = byWin[wk];
849
- const cas = ww ? cascadeFromPillars(ww.pillars) : null;
850
- const key = `${plat}|${wk}`;
851
- const prev = prevY.get(key);
852
- const yNow = cas?.yield ?? null;
853
- const changed = prev !== undefined && prev !== yNow;
854
-
855
- // --submit: publish this cell on first observation + whenever its Υ changes.
856
- if (
857
- submit &&
858
- enrolled &&
859
- ww &&
860
- yNow != null &&
861
- (prev === undefined || changed)
862
- ) {
863
- try {
864
- const r = await submitSignedWindow(
865
- wk,
866
- ww.pillars,
867
- ww.messages,
868
- id,
869
- { platform: plat },
870
- );
871
- lastSubmitMsg.set(
872
- key,
873
- r.status === "received"
874
- ? green(`✓ tier=${r.verification_tier || "—"}`)
875
- : red(`✗ ${r.reason || r.status}`),
876
- );
877
- } catch (e) {
878
- lastSubmitMsg.set(key, red(`✗ ${e.message}`));
879
- }
880
- }
881
- prevY.set(key, yNow);
882
-
883
- const winLabel = wk === "all" ? "all-time" : wk;
884
- const yDisplay =
885
- cas?.yield != null ? gold(fmtYield(cas.yield)) : dim("—");
886
- const indicator = changed ? green(" ▲") : dim(" ·");
887
- const metrics = cas
888
- ? `${dim("SNR")} ${fmtSNR(cas.snr)} ${dim("Lev")} ${cas.leverage != null ? fmtLev(cas.leverage) + "×" : "—"} ${dim("Vel")} ${cas.velocity != null ? cas.velocity.toFixed(2) : "—"} ${colorClass(cas.class ?? "—")}`
889
- : dim("no data");
890
- const submitNote =
891
- submit && enrolled ? " " + (lastSubmitMsg.get(key) || dim("…")) : "";
892
- push(
893
- ` ${padEnd(winLabel, 8)} ${bold("Υ")} ${yDisplay}${indicator} ${metrics}${submitNote}`,
894
- );
895
- }
896
- }
897
-
898
- push();
899
- push(` ${dim("─".repeat(w - 4))}`);
900
- if (submit && !enrolled) {
901
- push(
902
- ` ${red("not enrolled — run `npx sigrank enroll` to auto-submit")}`,
903
- );
904
- }
905
- push(
906
- ` ${dim(`polling every ${refresh}s · ${submit ? "auto-submit ON · " : ""}tokens stay on your machine · ctrl+c to exit`)}`,
907
- );
908
- push();
909
-
910
- write(out.join("\n"));
911
- lines = out.length;
912
- };
913
-
914
- try {
915
- await draw();
916
- const iv = setInterval(draw, refresh * 1000);
917
- await new Promise((resolve) => {
918
- process.on("SIGINT", () => {
919
- clearInterval(iv);
920
- resolve();
921
- });
922
- });
923
- } finally {
924
- write(SHOW_CURSOR + "\n");
925
- }
926
- }
927
-
928
- // ── UNIFIED DEFAULT VIEW ──────────────────────────────────────────────────────
929
- // npx sigrank (no args) — pulls everything at once:
930
- // - all platforms in parallel (only shows ones with data)
931
- // - all 4 windows per platform
932
- // - token pillars table (transparency layer)
933
- // - comparison sources (ccusage, tokscale, token-dashboard) if available
934
- // - live board position
935
- // - [S] submit [B] board [Q] quit
936
-
937
- const ALL_PLATFORMS = [
938
- "claude",
939
- "codex",
940
- "devin",
941
- "amp",
942
- "gemini",
943
- "kimi",
944
- "qwen",
945
- "goose",
946
- "kilo",
947
- "hermes",
948
- "droid",
949
- "codebuff",
950
- "copilot",
951
- "opencode",
952
- "openclaw",
953
- "pi",
954
- "other",
955
- ];
956
-
957
- async function runSigRank() {
958
- write(HIDE_CURSOR);
959
- const w = termWidth();
960
-
961
- // ── 1. Show immediate header so screen isn't blank ────────────────────────
962
- writeln();
963
- writeln(` ${gold("⊙ SigRank")} ${bold("Operator Dashboard")}`);
964
- writeln(` ${dim("reading local data…")}`);
965
-
966
- const { tokenpullAny, freshVerifierPillars } =
967
- await import("./tokenpull.mjs");
968
-
969
- // Local sources first (fast) — board fetch with 5s timeout runs in parallel
970
- const boardPromise = Promise.race([
971
- callTool("get_leaderboard", {}).catch(() => null),
972
- new Promise((r) => setTimeout(() => r(null), 5000)),
973
- ]);
974
-
975
- // FIX A1-CLI (2026-06-27): verifiers (ccusage/tokscale/tokendash) are fetched
976
- // ON-DEMAND for ACTIVE platforms only — not synchronously for all 15 platforms
977
- // upfront (which blocked Dashboard paint up to ~40s, same class of bug as TUI
978
- // FIX A1). The sync ccusagePillars()/tokscalePillars()/tokenDashPillars() loop
979
- // over ALL_PLATFORMS is replaced by parallel freshVerifierPillars() calls after
980
- // we know which platforms actually have local data.
981
- const [platformResults] = await Promise.all([
982
- Promise.allSettled(ALL_PLATFORMS.map((p) => tokenpullAny(p))),
983
- ]);
984
-
985
- const boardData = await boardPromise;
986
-
987
- // filter to platforms with actual data
988
- const active = [];
989
- for (let i = 0; i < ALL_PLATFORMS.length; i++) {
990
- const r = platformResults[i];
991
- if (r.status !== "fulfilled") continue;
992
- const d = r.value;
993
- const all = d.windows?.find((w) => w.window === "all");
994
- if (!all) continue;
995
- const total = (all.pillars.input ?? 0) + (all.pillars.output ?? 0);
996
- if (total === 0) continue;
997
- active.push(d);
998
- }
999
-
1000
- // Fetch verifiers on-demand for active platforms only (parallel, never throws).
1001
- // tdPillars (token-dashboard) is claude-only and pulled from the claude fresh result.
1002
- const verifierMap = {};
1003
- let tdPillars = null;
1004
- if (active.length > 0) {
1005
- const fresh = await Promise.all(
1006
- active.map((d) =>
1007
- freshVerifierPillars(d.platform).catch(() => ({
1008
- ccusage: null,
1009
- tokscale: null,
1010
- tokendash: null,
1011
- })),
1012
- ),
1013
- );
1014
- for (let i = 0; i < active.length; i++) {
1015
- const f = fresh[i];
1016
- verifierMap[active[i].platform] = { cc: f.ccusage, ts: f.tokscale };
1017
- if (active[i].platform === "claude" && f.tokendash)
1018
- tdPillars = f.tokendash;
1019
- }
1020
- }
1021
-
1022
- // clear the 3 loading lines (blank + header + "reading…")
1023
- write(
1024
- CURSOR_UP(3) +
1025
- ERASE_LINE +
1026
- CURSOR_UP(1) +
1027
- ERASE_LINE +
1028
- CURSOR_UP(1) +
1029
- ERASE_LINE,
1030
- );
1031
-
1032
- // ── 2. Header ─────────────────────────────────────────────────────────────
1033
- const ts = new Date().toLocaleTimeString("en-US", { hour12: false });
1034
- const header = ` ${gold("⊙ SigRank")} ${bold("Operator Dashboard")}`;
1035
- const right = dim(`signalaf.com ${ts}`);
1036
- const gap = Math.max(
1037
- 1,
1038
- w - stripAnsi(header).length - stripAnsi(right).length,
1039
- );
1040
- writeln();
1041
- writeln(`${header}${" ".repeat(gap)}${right}`);
1042
-
1043
- const platformSummary = active
1044
- .map((d) => {
1045
- const all = d.windows.find((w) => w.window === "all");
1046
- return `${cyan(d.platform)} ${dim(`${d.files ?? "?"} files · ${(all?.messages ?? 0).toLocaleString()} msgs`)}`;
1047
- })
1048
- .join(" ");
1049
- writeln(
1050
- ` ${dim("Detected:")} ${platformSummary || dim("no local data found")}`,
1051
- );
1052
- writeln(` ${dim("─".repeat(w - 4))}`);
1053
-
1054
- // ── 3. Cascade table — all platforms × all windows ─────────────────────────
1055
- writeln();
1056
- writeln(` ${bold("Your Cascade")}`);
1057
- const CH = [
1058
- padEnd(dim("Platform"), 10),
1059
- padEnd(dim("Win"), 5),
1060
- padStart(dim("Input"), 8),
1061
- padStart(dim("Output"), 8),
1062
- padStart(dim("CacheW"), 8),
1063
- padStart(dim("CacheR"), 9),
1064
- padStart(dim("Υ Yield"), 9),
1065
- padStart(dim("SNR"), 7),
1066
- padStart(dim("Leverage"), 10),
1067
- padStart(dim("Vel"), 6),
1068
- padStart(dim("10x"), 6),
1069
- padEnd(dim("Class"), 13),
1070
- ];
1071
- writeln(` ${CH.join(" ")}`);
1072
- writeln(` ${dim("·".repeat(Math.min(w - 4, 110)))}`);
1073
-
1074
- const WINS = ["7d", "30d", "90d", "all"];
1075
-
1076
- // helper to render one platform/combined row
1077
- const renderCascadeRow = (label, labelColorFn, winKey, p, est = false) => {
1078
- const cas = cascadeFromPillars(p);
1079
- if (!cas) return;
1080
- const clsFn = CLASS_COLOR[cas.class] ?? ((s) => s);
1081
- const cols = [
1082
- padEnd(labelColorFn(label), 10),
1083
- padEnd(dim(winKey), 5),
1084
- padStart(est ? dim("~") + fmtTokens(p.input) : fmtTokens(p.input), 8),
1085
- padStart(fmtTokens(p.output), 8),
1086
- padStart(
1087
- p.cacheCreate > 0
1088
- ? est
1089
- ? dim("~") + fmtTokens(p.cacheCreate)
1090
- : fmtTokens(p.cacheCreate)
1091
- : dim("—"),
1092
- 8,
1093
- ),
1094
- padStart(p.cacheRead > 0 ? fmtTokens(p.cacheRead) : dim("—"), 9),
1095
- padStart(
1096
- cas.yield != null
1097
- ? cas.yield > 10000
1098
- ? gold(fmtYield(cas.yield))
1099
- : fmtYield(cas.yield)
1100
- : "—",
1101
- 9,
1102
- ),
1103
- padStart(fmtSNR(cas.snr), 7),
1104
- padStart(cas.leverage != null ? `${fmtLev(cas.leverage)}×` : "—", 10),
1105
- padStart(cas.velocity != null ? cas.velocity.toFixed(2) : "—", 6),
1106
- padStart(cas.dev10x != null ? cas.dev10x.toFixed(2) : "—", 6),
1107
- padEnd(clsFn(cas.class), 13),
1108
- ];
1109
- writeln(` ${cols.join(" ")}`);
1110
- };
1111
-
1112
- // per-platform rows
1113
- for (const d of active) {
1114
- const isFirst = (winKey) =>
1115
- winKey === "7d" ||
1116
- (winKey === "30d" &&
1117
- !d.windows?.find(
1118
- (w) => w.window === "7d" && w.pillars.input + w.pillars.output > 0,
1119
- ));
1120
- for (const winKey of WINS) {
1121
- const wdata = d.windows?.find((ww) => ww.window === winKey);
1122
- if (!wdata) continue;
1123
- renderCascadeRow(
1124
- d.platform,
1125
- (s) => (isFirst(winKey) ? cyan(s) : dim(s)),
1126
- winKey,
1127
- wdata.pillars,
1128
- d.estimated === true,
1129
- );
1130
- }
1131
- writeln();
1132
- }
1133
-
1134
- // combined row (only when 2+ platforms active)
1135
- if (active.length > 1) {
1136
- const combinedLabel = active.map((d) => d.platform).join("+");
1137
- const hasEstimated = active.some((d) => d.estimated === true);
1138
- let isFirstWin = true;
1139
- for (const winKey of WINS) {
1140
- const combinedP = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
1141
- let hasData = false;
1142
- for (const d of active) {
1143
- const wdata = d.windows?.find((ww) => ww.window === winKey);
1144
- if (!wdata) continue;
1145
- const p = wdata.pillars;
1146
- if (p.input + p.output === 0) continue;
1147
- combinedP.input += p.input ?? 0;
1148
- combinedP.output += p.output ?? 0;
1149
- combinedP.cacheCreate += p.cacheCreate ?? 0;
1150
- combinedP.cacheRead += p.cacheRead ?? 0;
1151
- hasData = true;
1152
- }
1153
- if (!hasData) continue;
1154
- renderCascadeRow(
1155
- combinedLabel,
1156
- (s) => (isFirstWin ? bold(cyan(s)) : dim(s)),
1157
- winKey,
1158
- combinedP,
1159
- hasEstimated,
1160
- );
1161
- isFirstWin = false;
1162
- }
1163
- writeln();
1164
- }
1165
-
1166
- // ── 4. Token Pillars — per-platform verification + combined ──────────────
1167
- writeln(` ${dim("─".repeat(w - 4))}`);
1168
- writeln();
1169
- writeln(
1170
- ` ${bold("Token Pillars")} ${dim("(all-time · per-platform verification)")}`,
1171
- );
1172
-
1173
- const PCOLS = [
1174
- padEnd(dim("Source"), 14),
1175
- padStart(dim("Input"), 10),
1176
- padStart(dim("Output"), 10),
1177
- padStart(dim("Cache Write"), 12),
1178
- padStart(dim("Cache Read"), 12),
1179
- padStart(dim("Total"), 10),
1180
- ];
1181
- writeln(` ${PCOLS.join(" ")}`);
1182
- writeln(` ${dim("·".repeat(Math.min(w - 4, 74)))}`);
1183
-
1184
- const printPillarRow = (label, colorFn, p, note = "") => {
1185
- if (!p) return;
1186
- const i = p.input ?? 0;
1187
- const o = p.output ?? 0;
1188
- const cw = p.cacheCreate ?? 0;
1189
- const cr = p.cacheRead ?? 0;
1190
- const total = i + o + cw + cr;
1191
- const cols = [
1192
- padEnd(colorFn(label), 14),
1193
- padStart(fmtTokens(i), 10),
1194
- padStart(fmtTokens(o), 10),
1195
- padStart(cw > 0 ? fmtTokens(cw) : dim("—"), 12),
1196
- padStart(cr > 0 ? fmtTokens(cr) : dim("—"), 12),
1197
- padStart(fmtTokens(total), 10),
1198
- ];
1199
- writeln(` ${cols.join(" ")}${note ? " " + dim(note) : ""}`);
1200
- };
1201
-
1202
- // ── Per-platform blocks ─────────────────────────────────────────────────
1203
- for (const d of active) {
1204
- const all = d.windows?.find((ww) => ww.window === "all");
1205
- if (!all) continue;
1206
- const v = verifierMap[d.platform] ?? {};
1207
- const estMarker = d.estimated ? dim(" ~ estimated") : "";
1208
- printPillarRow(d.platform, cyan, all.pillars, `tokenpull${estMarker}`);
1209
- if (d.estimated) {
1210
- // show the estimation formula inline
1211
- const ratio = d.ioRatio != null ? d.ioRatio.toFixed(3) : "?";
1212
- writeln(
1213
- ` ${dim(` ~ input = output × ioRatio(${ratio}) cacheCreate = uncached − input cacheRead = exact`)}`,
1214
- );
1215
- }
1216
- if (v.cc?.all)
1217
- printPillarRow(
1218
- " ccusage",
1219
- (s) => paint(c.green, s),
1220
- v.cc.all,
1221
- "ccusage CLI",
1222
- );
1223
- if (d.platform === "claude" && tdPillars?.all)
1224
- printPillarRow(
1225
- " token-dash",
1226
- (s) => paint(c.magenta, s),
1227
- tdPillars.all,
1228
- "token-dashboard.db",
1229
- );
1230
- if (v.ts?.all)
1231
- printPillarRow(
1232
- " tokscale",
1233
- (s) => paint(c.blue, s),
1234
- v.ts.all,
1235
- "tokscale_report.json",
1236
- );
1237
- if (d.estimated && (v.cc?.all || v.ts?.all)) {
1238
- writeln(
1239
- ` ${dim(" ^ verifiers show raw uncached input (input_tokens − cached) — different field than estimated input above")}`,
1240
- );
1241
- }
1242
- writeln();
1243
- }
1244
-
1245
- // ── Combined (if more than one platform) ───────────────────────────────
1246
- if (active.length > 1) {
1247
- const combined = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
1248
- for (const d of active) {
1249
- const all = d.windows?.find((ww) => ww.window === "all");
1250
- if (!all) continue;
1251
- combined.input += all.pillars.input ?? 0;
1252
- combined.output += all.pillars.output ?? 0;
1253
- combined.cacheCreate += all.pillars.cacheCreate ?? 0;
1254
- combined.cacheRead += all.pillars.cacheRead ?? 0;
1255
- }
1256
- // sum verifiers across all active platforms
1257
- const ccCombined = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
1258
- const tsCombined = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
1259
- let hasCc = false,
1260
- hasTs = false;
1261
- for (const d of active) {
1262
- const v = verifierMap[d.platform] ?? {};
1263
- if (v.cc?.all) {
1264
- ccCombined.input += v.cc.all.input ?? 0;
1265
- ccCombined.output += v.cc.all.output ?? 0;
1266
- ccCombined.cacheCreate += v.cc.all.cacheCreate ?? 0;
1267
- ccCombined.cacheRead += v.cc.all.cacheRead ?? 0;
1268
- hasCc = true;
1269
- }
1270
- if (v.ts?.all) {
1271
- tsCombined.input += v.ts.all.input ?? 0;
1272
- tsCombined.output += v.ts.all.output ?? 0;
1273
- tsCombined.cacheCreate += v.ts.all.cacheCreate ?? 0;
1274
- tsCombined.cacheRead += v.ts.all.cacheRead ?? 0;
1275
- hasTs = true;
1276
- }
1277
- }
1278
- printPillarRow(
1279
- "combined",
1280
- (s) => bold(s),
1281
- combined,
1282
- active.map((d) => d.platform).join("+"),
1283
- );
1284
- if (hasCc)
1285
- printPillarRow(
1286
- " ccusage",
1287
- (s) => paint(c.green, s),
1288
- ccCombined,
1289
- "ccusage CLI",
1290
- );
1291
- if (tdPillars?.all)
1292
- printPillarRow(
1293
- " token-dash",
1294
- (s) => paint(c.magenta, s),
1295
- tdPillars.all,
1296
- "token-dashboard.db",
1297
- );
1298
- if (hasTs)
1299
- printPillarRow(
1300
- " tokscale",
1301
- (s) => paint(c.blue, s),
1302
- tsCombined,
1303
- "tokscale_report.json",
1304
- );
1305
- }
1306
-
1307
- // ── 5. Board position ─────────────────────────────────────────────────────
1308
- writeln();
1309
- writeln(` ${dim("─".repeat(w - 4))}`);
1310
- writeln();
1311
- writeln(
1312
- ` ${bold("Board")} ${dim("30d window · signalaf.com · sorted by Υ Yield")}`,
1313
- );
1314
-
1315
- const entries = boardData?.operators ?? boardData?.entries ?? boardData ?? [];
1316
- if (Array.isArray(entries) && entries.length > 0) {
1317
- const top5 = entries.slice(0, 5);
1318
- // header
1319
- const BH = [
1320
- padStart(dim("#"), 4),
1321
- padEnd(dim("Codename"), 20),
1322
- padEnd(dim("Class"), 13),
1323
- padStart(dim("Υ Yield"), 9),
1324
- padStart(dim("SNR"), 6),
1325
- padStart(dim("Depth"), 6),
1326
- padStart(dim("Tokens"), 8),
1327
- padStart(dim("Force"), 6),
1328
- padStart(dim("Pct"), 5),
1329
- padStart(dim("7d↕"), 5),
1330
- ];
1331
- writeln(` ${BH.join(" ")}`);
1332
- writeln(` ${dim("·".repeat(Math.min(w - 4, 92)))}`);
1333
- for (const e of top5) {
1334
- const rank = e.rank === 1 ? gold(`#${e.rank}`) : `#${e.rank}`;
1335
- const name = padEnd(trunc(e.codename ?? "—", 20), 20);
1336
- const cls = padEnd(colorClass(e.class_tier ?? "—"), 13);
1337
- const yld = padStart(e.yield_ != null ? fmtYield(e.yield_) : "—", 9);
1338
- const snr = padStart(
1339
- e.compression_ratio != null ? fmtSNR(e.compression_ratio) : "—",
1340
- 6,
1341
- );
1342
- const depth = padStart(
1343
- e.session_depth != null ? e.session_depth.toFixed(1) : "—",
1344
- 6,
1345
- );
1346
- const tok = padStart(
1347
- e.token_throughput != null ? fmtTokens(e.token_throughput) : "—",
1348
- 8,
1349
- );
1350
- const force = padStart(
1351
- e.signal_force != null ? e.signal_force.toFixed(1) : "—",
1352
- 6,
1353
- );
1354
- const pct = padStart(e.percentile != null ? `${e.percentile}%` : "—", 5);
1355
- const mv7 = padStart(fmtMove(e.movement_7d), 5);
1356
- writeln(
1357
- ` ${padStart(rank, 4)} ${name} ${cls} ${yld} ${snr} ${depth} ${tok} ${force} ${pct} ${mv7}`,
1358
- );
1359
- }
1360
- if (entries.length > 5)
1361
- writeln(
1362
- ` ${dim(` … ${entries.length - 5} more operators on signalaf.com`)}`,
1363
- );
1364
- } else {
1365
- writeln(` ${dim(" board unavailable")}`);
1366
- }
1367
-
1368
- // ── 6. Footer / submit prompt ────────────────────────────────────────────
1369
- writeln();
1370
- writeln(` ${dim("─".repeat(w - 4))}`);
1371
- writeln(
1372
- ` ${dim("[S]")} submit to board ${dim("[B]")} open board in browser ${dim("[Q]")} quit`,
1373
- );
1374
- writeln();
1375
-
1376
- // ── 7. Keypress handler ───────────────────────────────────────────────────
1377
- if (process.stdin.isTTY) {
1378
- process.stdin.setRawMode(true);
1379
- process.stdin.resume();
1380
- process.stdin.setEncoding("utf8");
1381
-
1382
- await new Promise((resolve) => {
1383
- process.stdin.on("data", async (key) => {
1384
- const k = key.toLowerCase();
1385
- if (k === "q" || key === "\u0003") {
1386
- // q or ctrl+c
1387
- resolve();
1388
- } else if (k === "b") {
1389
- // ASYNC FIX (2026-06-27): execFile instead of dynamic execSync import
1390
- execFile(
1391
- "open",
1392
- ["https://signalaf.com"],
1393
- { stdio: "ignore" },
1394
- () => {},
1395
- );
1396
- resolve();
1397
- } else if (k === "s") {
1398
- const id = ensureIdentity();
1399
- const enrolled = !!(
1400
- id.codename &&
1401
- id.operator_id &&
1402
- id.private_key_pkcs8_b64
1403
- );
1404
- process.stdin.setRawMode(false);
1405
- write(SHOW_CURSOR);
1406
- if (enrolled) {
1407
- // VERIFIED path (D7 §7): signed submit from the enrolled device. No codename
1408
- // prompt — it comes from the keystore. Only signed submissions rank on the board.
1409
- writeln();
1410
- writeln(
1411
- ` ${dim("Publishing verified runs for")} ${cyan(id.codename)}${dim("…")}`,
1412
- );
1413
- write(HIDE_CURSOR);
1414
- try {
1415
- for (const d of active) {
1416
- for (const ww of d.windows ?? []) {
1417
- const r = await submitSignedWindow(
1418
- ww.window,
1419
- ww.pillars,
1420
- ww.messages,
1421
- id,
1422
- { platform: d.platform },
1423
- );
1424
- const ok = r.status === "received";
1425
- writeln(
1426
- ` ${ok ? green("✓") : red("✗")} ${d.platform} ${ww.window}${ok ? dim(` tier=${r.verification_tier || "—"}`) : dim(` ${r.reason || r.status}`)}`,
1427
- );
1428
- }
1429
- }
1430
- writeln();
1431
- writeln(
1432
- ` ${green("✓")} Published. Reload ${cyan(`signalaf.com/user/${id.codename}`)}`,
1433
- );
1434
- } catch (e) {
1435
- writeln(red(` ✗ ${e.message}`));
1436
- }
1437
- resolve();
1438
- return;
1439
- }
1440
- // NOT enrolled → the anonymous paste path (preview-only; does NOT rank) + a hint.
1441
- writeln();
1442
- writeln(
1443
- ` ${dim("Not enrolled — run")} ${bold("npx sigrank enroll")} ${dim("to rank as a verified operator. Anonymous paste below:")}`,
1444
- );
1445
- process.stdout.write(" Codename: ");
1446
- let codename = "";
1447
- process.stdin.on("data", async function onData(chunk) {
1448
- if (chunk === "\r" || chunk === "\n") {
1449
- process.stdin.removeListener("data", onData);
1450
- codename = codename.trim();
1451
- if (!codename) {
1452
- writeln(red(" ✗ codename required"));
1453
- resolve();
1454
- return;
1455
- }
1456
- writeln();
1457
- writeln(
1458
- ` ${dim("Submitting all windows for")} ${cyan(codename)}${dim("…")}`,
1459
- );
1460
- write(HIDE_CURSOR);
1461
- try {
1462
- for (const d of active) {
1463
- const apiBase = DEFAULT_API_BASE;
1464
- const WINDOW_TYPE = {
1465
- "7d": "7d",
1466
- "30d": "30d",
1467
- "90d": "90d",
1468
- all: "all_time",
1469
- };
1470
- for (const ww of d.windows ?? []) {
1471
- const rawPaste = `${ww.pillars.input} ${ww.pillars.output} ${ww.pillars.cacheCreate} ${ww.pillars.cacheRead}`;
1472
- const windowType = WINDOW_TYPE[ww.window] || ww.window;
1473
- const now = new Date();
1474
- const ddmmyy = `${String(now.getDate()).padStart(2, "0")}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getFullYear()).slice(-2)}`;
1475
- const content_hash = `sha256:${codename}|${windowType}|${rawPaste}|${ddmmyy}`;
1476
- const res = await fetch(`${apiBase}/api/v1/ingest-paste`, {
1477
- method: "POST",
1478
- headers: {
1479
- "content-type": "application/json",
1480
- accept: "application/json",
1481
- "user-agent": `node/${process.version} sigrank-mcp/cli`,
1482
- },
1483
- body: JSON.stringify({
1484
- codename,
1485
- raw_paste: rawPaste,
1486
- window_type: windowType,
1487
- telemetry: { platform: { primary: d.platform } },
1488
- content_hash,
1489
- submitted_ddmmyy: ddmmyy,
1490
- submitted_at: now.toISOString(),
1491
- }),
1492
- }).catch(() => null);
1493
- const ok = res?.ok ?? false;
1494
- const status = ok ? green("✓") : red("✗");
1495
- writeln(
1496
- ` ${status} ${d.platform} ${ww.window}${!ok ? dim(` HTTP ${res?.status ?? "err"}`) : ""}`,
1497
- );
1498
- }
1499
- }
1500
- writeln();
1501
- writeln(
1502
- ` ${green("✓")} Submitted. Visit ${cyan(`signalaf.com/user/${codename}`)}`,
1503
- );
1504
- } catch (e) {
1505
- writeln(red(` ✗ ${e.message}`));
1506
- }
1507
- resolve();
1508
- } else if (chunk === "\u007f") {
1509
- // backspace
1510
- if (codename.length > 0) {
1511
- codename = codename.slice(0, -1);
1512
- process.stdout.write("\b \b");
1513
- }
1514
- } else {
1515
- codename += chunk;
1516
- process.stdout.write(chunk);
1517
- }
1518
- });
1519
- process.stdin.resume();
1520
- }
1521
- });
1522
- });
1523
- }
1524
-
1525
- write(SHOW_CURSOR);
1526
- if (process.stdin.isTTY) {
1527
- process.stdin.setRawMode(false);
1528
- process.stdin.pause();
1529
- }
1530
- }
1531
-
1532
- // ── HELP ─────────────────────────────────────────────────────────────────────
1533
-
1534
- async function showHelp() {
1535
- const { createRequire } = await import("module");
1536
- const pkg = createRequire(import.meta.url)("./package.json");
1537
- writeln();
1538
- writeln(` ${gold("⊙ SigRank")} ${bold("CLI")} ${dim("v" + pkg.version)}`);
1539
- writeln();
1540
- writeln(` ${bold("Default (no args)")}`);
1541
- writeln(
1542
- ` ${cyan("sigrank")} unified dashboard: cascade + token pillars + board`,
1543
- );
1544
- writeln();
1545
- writeln(` ${bold("Commands")}`);
1546
- writeln(
1547
- ` ${cyan("enroll")} sign in: paste a connect code (get one at signalaf.com → Settings)`,
1548
- );
1549
- writeln(
1550
- ` ${cyan("submit")} publish your verified runs to the board (sign in first)`,
1551
- );
1552
- writeln(
1553
- ` ${cyan("board")} live leaderboard (refreshes every 30s)`,
1554
- );
1555
- writeln(
1556
- ` ${cyan("board --window 7d")} board for a specific window (7d, 30d, 90d, all)`,
1557
- );
1558
- writeln(` ${cyan("board --once")} print once and exit`);
1559
- writeln(
1560
- ` ${cyan("compare")} raw pillar audit: tokenpull vs ccusage vs token-dash vs tokscale`,
1561
- );
1562
- writeln(
1563
- ` ${cyan("compare --platform codex")} compare for a specific platform`,
1564
- );
1565
- writeln(
1566
- ` ${cyan("tui")} full tabbed TUI: Dashboard / Compare / Board / Watch`,
1567
- );
1568
- writeln(
1569
- ` ${cyan("tui --platform codex")} TUI with a different default platform`,
1570
- );
1571
- writeln(
1572
- ` ${cyan("watch")} live tune meter — ALL active platforms × all windows, every 30s`,
1573
- );
1574
- writeln(
1575
- ` ${cyan("watch --platform codex")} watch only one platform (optional filter)`,
1576
- );
1577
- writeln(
1578
- ` ${cyan("watch --window 7d")} watch only one window (optional filter)`,
1579
- );
1580
- writeln();
1581
- writeln(` ${bold("Options")}`);
1582
- writeln(
1583
- ` ${dim("--window")} 7d · 30d · 90d · all (default: 30d for board; all windows for watch)`,
1584
- );
1585
- writeln(
1586
- ` ${dim("--platform")} claude · codex · amp · gemini · opencode · goose · …`,
1587
- );
1588
- writeln(` ${dim("--refresh")} poll interval in seconds (default: 30)`);
1589
- writeln(` ${dim("--once")} print once and exit (board only)`);
1590
- writeln();
1591
- writeln(` ${bold("For AI clients (not typeable)")}`);
1592
- writeln(
1593
- ` ${dim("In a piped/non-TTY context, sigrank is an MCP stdio server.")}`,
1594
- );
1595
- writeln(
1596
- ` ${dim("AI clients (Claude, Cursor, …) call its tools automatically — these are")}`,
1597
- );
1598
- writeln(` ${dim("NOT shell commands. Humans use the commands above.")}`);
1599
- writeln();
1600
- writeln(` ${bold("Examples")}`);
1601
- writeln(` ${dim("sigrank")} # unified dashboard`);
1602
- writeln(` ${dim("sigrank board")} # live leaderboard`);
1603
- writeln(
1604
- ` ${dim("sigrank compare")} # pillar audit (claude)`,
1605
- );
1606
- writeln(` ${dim("sigrank compare --platform codex")}`);
1607
- writeln(` ${dim("sigrank watch --window 7d --refresh 60")}`);
1608
- writeln(` ${dim("sigrank board --window all --once")}`);
1609
- writeln();
1610
- }
1611
-
1612
- // ── ENTRY POINT ───────────────────────────────────────────────────────────────
1613
-
1614
- // ── enroll: bind this device to your operator via a web connect code (D7 §4.5) ──
1615
- async function runEnroll({ label } = {}) {
1616
- const id = ensureIdentity();
1617
- writeln();
1618
- writeln(` ${gold("⊙ SigRank")} ${bold("Connect this device")}`);
1619
- writeln(` ${dim(`device ${id.device_id}`)}`);
1620
- if (id.codename && id.operator_id) {
1621
- writeln(
1622
- ` ${dim(`already enrolled as ${id.codename} — re-enrolling a bound device is rejected this slice.`)}`,
1623
- );
1624
- }
1625
- writeln(
1626
- ` ${dim("Get a code at signalaf.com → Settings → Connect a device.")}`,
1627
- );
1628
- writeln();
1629
-
1630
- const { createInterface } = await import("node:readline/promises");
1631
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1632
- let code;
1633
- try {
1634
- code = (await rl.question(" Paste your connect code: ")).trim();
1635
- } finally {
1636
- rl.close();
1637
- }
1638
- if (!code) {
1639
- writeln(red(" ✗ No code entered."));
1640
- process.exitCode = 1;
1641
- return;
1642
- }
1643
-
1644
- let out;
1645
- try {
1646
- out = await callTool("enroll", {
1647
- code,
1648
- device_label: typeof label === "string" ? label : undefined,
1649
- });
1650
- } catch (e) {
1651
- writeln(red(` ✗ ${e.message}`));
1652
- process.exitCode = 1;
1653
- return;
1654
- }
1655
-
1656
- if (out.status === "enrolled") {
1657
- writeln();
1658
- writeln(
1659
- ` ${green("✓")} Signed in as ${cyan(out.codename || "(operator)")}.`,
1660
- );
1661
- writeln(
1662
- ` ${dim("Your runs now cascade to the board. Publish with ")}${bold("npx sigrank submit")}${dim(" (one-shot) or ")}${bold("npx sigrank watch --submit")}${dim(" (continuous).")}`,
1663
- );
1664
- writeln(` ${dim(`identity: ${keystorePath()}`)}`);
1665
- return;
1666
- }
1667
-
1668
- const msg =
1669
- {
1670
- code_invalid:
1671
- "That code is invalid, expired, or already used — generate a fresh one.",
1672
- device_already_enrolled:
1673
- 'This device is already enrolled. Need a new key? Click "New key" at signalaf.com → Settings, then paste it here.',
1674
- bad_request: "The code or device key was malformed.",
1675
- rate_limited: "Too many attempts — wait a few minutes and retry.",
1676
- persistence_unavailable:
1677
- "Enrollment is temporarily unavailable — try again shortly.",
1678
- }[out.reason] || `Enrollment failed (${out.reason || "unknown"}).`;
1679
- writeln(red(` ✗ ${msg}`));
1680
- process.exitCode = 1;
1681
- }
1682
-
1683
- // ── submit: publish your verified (signed) runs to the board (D7 §5/§8) ─────────
1684
- async function runSubmit({ platform = "claude", window } = {}) {
1685
- const id = ensureIdentity();
1686
- if (!id.codename || !id.operator_id) {
1687
- writeln(
1688
- red(" ✗ This device is not enrolled. Run `npx sigrank enroll` first."),
1689
- );
1690
- process.exitCode = 1;
1691
- return;
1692
- }
1693
- writeln();
1694
- writeln(
1695
- ` ${gold("⊙ SigRank")} ${bold("Publishing verified runs")} ${dim(`as ${id.codename}`)}`,
1696
- );
1697
- writeln(` ${dim("reading local token logs + signing…")}`);
1698
-
1699
- let out;
1700
- try {
1701
- out = await callTool("submit_verified", {
1702
- platform,
1703
- window: typeof window === "string" ? window : undefined,
1704
- dry_run: process.argv.includes("--dry-run"),
1705
- });
1706
- } catch (e) {
1707
- writeln(red(` ✗ ${e.message}`));
1708
- process.exitCode = 1;
1709
- return;
1710
- }
1711
- if (out.status === "not_enrolled") {
1712
- writeln(red(" ✗ Not enrolled — run `npx sigrank enroll`."));
1713
- process.exitCode = 1;
1714
- return;
1715
- }
1716
-
1717
- writeln();
1718
- let anyRanked = false;
1719
- let anyReceivedNotRanked = false;
1720
- for (const w of out.windows || []) {
1721
- const label = String(w.window).padEnd(8);
1722
- if (w.status === "dry_run") {
1723
- writeln(
1724
- ` ${gold("◇")} ${bold(label)} ${gold("DRY RUN")} ${dim("· nothing sent")}`,
1725
- );
1726
- } else if (w.ranked) {
1727
- anyRanked = true;
1728
- writeln(
1729
- ` ${green("✓")} ${bold(label)} ${green("RANKED")} ${dim("· live on the board")}`,
1730
- );
1731
- } else if (w.status === "received") {
1732
- anyReceivedNotRanked = true;
1733
- writeln(
1734
- ` ${gold("⚠")} ${bold(label)} ${gold("received · NOT ranked")} ${dim(`(tier=${w.verification_tier || "—"})`)}`,
1735
- );
1736
- } else {
1737
- writeln(
1738
- ` ${red("✗")} ${bold(label)} ${dim(w.reason || w.status || "failed")}`,
1739
- );
1740
- }
1741
- }
1742
- writeln();
1743
- if (anyRanked) {
1744
- writeln(
1745
- ` ${dim("Your board row:")} ${cyan(`signalaf.com/user/${id.codename}`)}`,
1746
- );
1747
- } else if (anyReceivedNotRanked) {
1748
- writeln(
1749
- ` ${gold("Received, but NOT ranked")} ${dim("— this device is unenrolled or revoked. Re-enroll to rank:")} ${cyan("npx sigrank enroll")}`,
1750
- );
1751
- }
1752
- }
1753
-
1754
- export async function runCli(argv) {
1755
- const args = argv.slice(2); // strip 'node' + script path
1756
- const cmd = args[0];
1757
-
1758
- // parse --key value AND --key=value flags. E4: validate against the known set and warn
1759
- // (don't crash) on anything unknown, so a typo'd flag is visible instead of silently ignored.
1760
- const KNOWN_FLAGS = new Set([
1761
- "window",
1762
- "platform",
1763
- "refresh",
1764
- "once",
1765
- "submit",
1766
- "compare",
1767
- "label",
1768
- "dry-run",
1769
- ]);
1770
- const flags = {};
1771
- for (let i = 1; i < args.length; i++) {
1772
- const a = args[i];
1773
- if (!a.startsWith("--")) continue;
1774
- const body = a.slice(2);
1775
- let key, val;
1776
- const eq = body.indexOf("=");
1777
- if (eq !== -1) {
1778
- // --flag=value form
1779
- key = body.slice(0, eq);
1780
- val = body.slice(eq + 1);
1781
- } else {
1782
- // --flag [value] form: consume the next token as the value unless it's another flag
1783
- key = body;
1784
- val = args[i + 1] && !args[i + 1].startsWith("--") ? args[++i] : true;
1785
- }
1786
- if (!key) continue;
1787
- if (!KNOWN_FLAGS.has(key)) {
1788
- writeln(
1789
- dim(
1790
- ` (ignoring unknown flag --${key}; known: ${[...KNOWN_FLAGS].join(", ")})`,
1791
- ),
1792
- );
1793
- continue;
1794
- }
1795
- flags[key] = val;
1796
- }
1797
-
1798
- try {
1799
- if (cmd === "board") {
1800
- await runBoard({
1801
- window: flags.window ?? "30d",
1802
- once: flags.once === true || flags.once === "true",
1803
- refresh: Number(flags.refresh) || 30,
1804
- });
1805
- } else if (cmd === "compare") {
1806
- await runCompare({ platform: flags.platform ?? "claude" });
1807
- } else if (cmd === "tui") {
1808
- const { runTui } = await import("./tui.mjs");
1809
- await runTui({
1810
- platform: flags.platform ?? "claude",
1811
- window: flags.window ?? "7d",
1812
- });
1813
- } else if (cmd === "watch") {
1814
- // A5: no --platform/--window → watch ALL active platforms × ALL windows. Pass the raw
1815
- // flags through (undefined = no filter) so runWatch's auto-all mode engages by default;
1816
- // a provided flag narrows the grid (back-compat).
1817
- await runWatch({
1818
- platform:
1819
- typeof flags.platform === "string" ? flags.platform : undefined,
1820
- window: typeof flags.window === "string" ? flags.window : undefined,
1821
- refresh: Number(flags.refresh) || 30,
1822
- submit: flags.submit === true || flags.submit === "true",
1823
- });
1824
- } else if (cmd === "enroll") {
1825
- await runEnroll({ label: flags.label });
1826
- } else if (cmd === "submit") {
1827
- await runSubmit({
1828
- platform: flags.platform ?? "claude",
1829
- window: flags.window,
1830
- });
1831
- } else if (cmd === "--help" || cmd === "-h" || cmd === "help") {
1832
- await showHelp();
1833
- } else if (cmd === "--version" || cmd === "-v") {
1834
- const { createRequire } = await import("module");
1835
- const req = createRequire(import.meta.url);
1836
- const pkg = req("./package.json");
1837
- writeln(pkg.version);
1838
- } else if (!cmd || cmd === "start" || cmd === "run") {
1839
- // default: full unified view
1840
- await runSigRank();
1841
- } else {
1842
- // unknown command: show help + exit non-zero so typos fail loudly (index.mjs now
1843
- // routes ALL arg'd invocations here instead of falling through to the MCP server)
1844
- writeln(red(`\n ✗ unknown command: ${cmd}`));
1845
- await showHelp();
1846
- process.exit(2);
1847
- }
1848
- } catch (e) {
1849
- write(SHOW_CURSOR);
1850
- writeln(red(`\n ✗ ${e.message}`));
1851
- process.exit(1);
1852
- }
1853
- }
1
+ export * from './presentation/cli.mjs';