sigrank 0.18.5 → 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 +94 -41
  4. package/adapters/index.mjs +1100 -0
  5. package/adapters/tokenpull.mjs +568 -0
  6. package/adapters.mjs +1 -857
  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/tui.mjs CHANGED
@@ -1,2654 +1,8 @@
1
- /**
2
- * tui.mjs — SigRank full tabbed TUI.
3
- *
4
- * Tabs: [1] Dashboard [2] Compare [3] Board [4] Watch
5
- * Navigation: ← → arrow keys, 1-4 number keys, or tab letter shortcuts.
6
- * No external dependencies — pure ANSI/Node.js stdin raw mode.
7
- *
8
- * Architecture:
9
- * - State machine: activeTab + per-tab data cache.
10
- * - On tab switch: clear screen, redraw active tab.
11
- * - Board + Watch tabs auto-refresh on a timer.
12
- * - Dashboard + Compare load once, refresh on [R].
13
- */
1
+ import { runTui } from './presentation/tui.mjs';
2
+ export * from './presentation/tui.mjs';
14
3
 
15
- import { callTool, DEFAULT_API_BASE, pullActivePlatforms } from "./tools.mjs";
16
- import { ALL_PLATFORMS } from "./adapters.mjs";
17
- import { freshVerifierPillars } from "./tokenpull.mjs";
18
- import { isSignedIn, isCodeChar } from "./connect.mjs";
19
- import { loadIdentity, clearIdentity } from "./keystore.mjs";
20
- import { execFile } from "child_process";
21
- import { existsSync, readFileSync } from "fs";
22
- import os from "os";
23
- import path from "path";
24
- import { createRequire } from "module";
25
-
26
- // Version read from package.json (single source of truth — matches cli.mjs;
27
- // never hardcode, that's what caused the version drift).
28
- const VERSION = (() => {
29
- try {
30
- return createRequire(import.meta.url)("./package.json").version;
31
- } catch {
32
- return "?";
33
- }
34
- })();
35
-
36
- // ── ANSI ───────────────────────────────────────────────────────────────────
37
- const ESC = "\x1b[";
38
- const c = {
39
- reset: `${ESC}0m`,
40
- bold: `${ESC}1m`,
41
- dim: `${ESC}2m`,
42
- gold: `${ESC}33m`,
43
- boldGold: `${ESC}1;33m`,
44
- cyan: `${ESC}36m`,
45
- boldCyan: `${ESC}1;36m`,
46
- green: `${ESC}32m`,
47
- red: `${ESC}31m`,
48
- white: `${ESC}97m`,
49
- boldWhite: `${ESC}1;97m`,
50
- magenta: `${ESC}35m`,
51
- blue: `${ESC}34m`,
52
- bgDim: `${ESC}48;5;236m`, // dark grey bg for active tab
53
- bgCyan: `${ESC}48;5;23m`, // dark teal bg for active tab
54
- };
55
- const paint = (col, s) => `${col}${s}${c.reset}`;
56
- const bold = (s) => paint(c.bold, s);
57
- const dim = (s) => paint(c.dim, s);
58
- const gold = (s) => paint(c.boldGold, s);
59
- const cyan = (s) => paint(c.boldCyan, s);
60
- const hdr = (s) => paint(c.boldCyan, s); // table column-header label color (readability)
61
- const green = (s) => paint(c.green, s);
62
- const red = (s) => paint(c.red, s);
63
-
64
- const CLEAR = `${ESC}H${ESC}2J`; // home + erase visible area
65
- const CLEAR_SB = `${ESC}3J`; // clear scrollback/saved lines (prevents scroll-up past TUI)
66
- const ENTER_ALT = `${ESC}?1049h`; // enter alternate screen buffer
67
- const EXIT_ALT = `${ESC}?1049l`; // exit alternate screen buffer (restores original)
68
- const HIDE = `${ESC}?25l`;
69
- const SHOW = `${ESC}?25h`;
70
- const UP = (n) => `${ESC}${n}A`;
71
- const ERLINE = `${ESC}2K`;
72
- const GOTO = (r, col = 1) => `${ESC}${r};${col}H`; // absolute cursor position
73
-
74
- const W = () => process.stdout.columns || 100;
75
- // FIX 0b: safe default 24 (not 40) when rows is undefined (non-TTY / IDE terminals).
76
- // A 40-row assumption into a 24-row window scrolls the alt-screen → footer smears off.
77
- const H = () => process.stdout.rows || 24;
78
-
79
- // ── Screen buffer: collect lines, then paint only what fits ─────────────
80
- // Render functions call write/writeln as before; the buffer captures them.
81
- // flushScreen() paints to the real terminal using absolute cursor positioning
82
- // so the TUI never scrolls — it's a locked frame like tokscale.
83
- let _screenBuf = null; // null = direct mode (unbuffered); string[] = buffered
84
- const write = (s) => {
85
- if (_screenBuf) {
86
- const parts = s.split("\n");
87
- if (parts.length === 1) {
88
- _screenBuf[_screenBuf.length - 1] += s;
89
- } else {
90
- _screenBuf[_screenBuf.length - 1] += parts[0];
91
- for (let i = 1; i < parts.length; i++) _screenBuf.push(parts[i]);
92
- }
93
- } else {
94
- process.stdout.write(s);
95
- }
96
- };
97
- const writeln = (s = "") => {
98
- if (_screenBuf) {
99
- _screenBuf[_screenBuf.length - 1] += s;
100
- _screenBuf.push("");
101
- } else {
102
- process.stdout.write(s + "\n");
103
- }
104
- };
105
-
106
- let _footerBuf = null; // footer lines pinned to bottom
107
- function startBuffer() {
108
- _screenBuf = [""];
109
- _footerBuf = null;
110
- }
111
- function setFooter(lines) {
112
- _footerBuf = lines;
113
- }
114
- function flushScreen() {
115
- if (!_screenBuf) return;
116
- const lines = _screenBuf;
117
- const footer = _footerBuf || [];
118
- _screenBuf = null;
119
- _footerBuf = null;
120
- const h = H();
121
- const w = W();
122
- // FIX 0b: footer is SACROSANCT. Clamp CONTENT to h - footer.length first, then
123
- // always append every footer line. The footer must NEVER be the thing dropped
124
- // (it was — footer painted last, clamp cut the tail = footer first → lost hints
125
- // + lost lower cascade rows, together, because they're the same tail of the frame).
126
- const contentRows = Math.max(0, h - footer.length);
127
- const content = lines.slice(0, contentRows);
128
- const frame = [...content, ...footer];
129
- const maxRows = Math.min(frame.length, h);
130
- let out = "";
131
- for (let i = 0; i < maxRows; i++) {
132
- out += GOTO(i + 1) + ERLINE + ansiTrunc(frame[i], w);
133
- }
134
- // Clear any rows below the frame left over from a taller previous frame.
135
- for (let i = maxRows; i < h; i++) {
136
- out += GOTO(i + 1) + ERLINE;
137
- }
138
- process.stdout.write(out);
139
- }
140
-
141
- function stripAnsi(s) {
142
- return s.replace(/\x1b\[[0-9;]*m/g, "");
143
- }
144
- // ANSI-aware truncate: cut to `w` VISIBLE columns while keeping color escapes
145
- // intact (escapes don't count toward width, and we never slice mid-sequence).
146
- // Replaces raw `.slice(0, w)`, which corrupts color codes + miscounts width.
147
- function ansiTrunc(s, w) {
148
- if (stripAnsi(s).length <= w) return s;
149
- let out = "",
150
- vis = 0,
151
- i = 0;
152
- while (i < s.length && vis < w) {
153
- if (s[i] === "\x1b") {
154
- const m = s.slice(i).match(/^\x1b\[[0-9;]*m/);
155
- if (m) {
156
- out += m[0];
157
- i += m[0].length;
158
- continue;
159
- }
160
- }
161
- out += s[i];
162
- vis++;
163
- i++;
164
- }
165
- return out + "\x1b[0m"; // reset so a cut mid-color doesn't bleed into next line
166
- }
167
- function padEnd(s, w) {
168
- const v = stripAnsi(s).length;
169
- return v >= w ? s : s + " ".repeat(w - v);
170
- }
171
- function padStart(s, w) {
172
- const v = stripAnsi(s).length;
173
- return v >= w ? s : " ".repeat(w - v) + s;
174
- }
175
- function trunc(s, w) {
176
- return stripAnsi(s).length <= w ? s : s.slice(0, w - 1) + "…";
177
- }
178
- function hr(ch = "─") {
179
- return dim(ch.repeat(Math.max(0, W() - 4)));
180
- }
181
-
182
- // ── Number formatters ───────────────────────────────────────────────────────
183
- const fmtY = (y) =>
184
- y == null
185
- ? "—"
186
- : y >= 10000
187
- ? `${(y / 1000).toFixed(1)}K`
188
- : y >= 1000
189
- ? `${(y / 1000).toFixed(2)}K`
190
- : y.toFixed(1);
191
- const fmtLev = (l) =>
192
- l == null ? "—" : l >= 1000 ? `${(l / 1000).toFixed(1)}K` : l.toFixed(0);
193
- const fmtSNR = (n) => (n == null ? "—" : `${(n * 100).toFixed(1)}%`);
194
- const fmtTok = (n) =>
195
- n == null
196
- ? "—"
197
- : n >= 1e9
198
- ? `${(n / 1e9).toFixed(1)}B`
199
- : n >= 1e6
200
- ? `${(n / 1e6).toFixed(1)}M`
201
- : n >= 1e3
202
- ? `${(n / 1e3).toFixed(1)}K`
203
- : String(n);
204
- const fmtMov = (n) =>
205
- n == null || n === 0 ? dim("—") : n > 0 ? green(`+${n}`) : red(`${n}`);
206
-
207
- // ── Class tier colors ────────────────────────────────────────────────────────
208
- const CLS = {
209
- TRANSMITTER: (s) => paint(c.boldGold, s),
210
- "ARCH+": (s) => paint(c.boldCyan, s),
211
- ARCH: (s) => paint(c.cyan, s),
212
- POWER: (s) => paint(c.boldWhite, s),
213
- BASE: (s) => paint(c.white, s),
214
- SEEKER: (s) => paint(c.magenta, s),
215
- REFINER: (s) => paint(c.blue, s),
216
- BEARER: (s) => paint(c.dim, s),
217
- IGNITER: (s) => paint(c.dim, s),
218
- };
219
- const colorCls = (cls) => (CLS[cls] ?? ((s) => s))(cls);
220
-
221
- // ── Cascade math (inline, no dep) ───────────────────────────────────────────
222
- function cascadeFrom(p) {
223
- if (!p) return null;
224
- const i = p.input ?? 0,
225
- o = p.output ?? 0,
226
- cr = p.cacheRead ?? 0;
227
- if (i === 0 || o === 0) return null;
228
- const leverage = cr / i;
229
- const velocity = o / i;
230
- const yld = leverage * velocity;
231
- const dev10x =
232
- i > 0 && o > 0 && (p.cacheCreate ?? 0) > 0 && cr > 0
233
- ? Math.log10(cr / i)
234
- : null;
235
- const snr = o / (i + o);
236
-
237
- let cls = "IGNITER";
238
- if (yld >= 1000 || dev10x >= 3) cls = "TRANSMITTER";
239
- else if (dev10x != null && dev10x >= 1.45) cls = "ARCH+";
240
- else if (dev10x != null && dev10x >= 1.35) cls = "ARCH";
241
- else if (dev10x != null && dev10x >= 1.2) cls = "POWER";
242
- else if (dev10x != null && dev10x >= 1.0) cls = "BASE";
243
- else if (dev10x != null && dev10x >= 0) cls = "SEEKER";
244
- else if (dev10x != null && dev10x >= -0.3) cls = "REFINER";
245
-
246
- return { yield: yld, snr, leverage, velocity, dev10x, class: cls };
247
- }
248
-
249
- // ── Unicode bar chart (no dep) ───────────────────────────────────────────────
250
- const BLOCKS = " ▏▎▍▌▋▊▉█";
251
-
252
- // Linear bar — use when all values are the same order of magnitude.
253
- function barChart(values, labels, opts = {}) {
254
- const { width = 30, colorFn = (s) => s, maxVal } = opts;
255
- const max = maxVal ?? Math.max(...values.filter(Number.isFinite), 1);
256
- const lines = [];
257
- for (let i = 0; i < values.length; i++) {
258
- const v = values[i] ?? 0;
259
- const pct = Math.min(v / max, 1);
260
- const full = Math.floor(pct * width);
261
- const frac = Math.floor((pct * width - full) * 8);
262
- const bar = colorFn("█".repeat(full) + (frac > 0 ? BLOCKS[frac] : ""));
263
- const lbl = padEnd(dim(labels[i] ?? ""), 10);
264
- const val = padStart(fmtTok(v), 8);
265
- lines.push(` ${lbl} ${padEnd(bar, width)} ${val}`);
266
- }
267
- return lines;
268
- }
269
-
270
- // Log-scale bar — use when values span multiple orders of magnitude (e.g. token pillars
271
- // where cacheRead >> input). Maps log10(v) to bar width so each 10x = same visual step.
272
- // minLog floor prevents zero/tiny values from going negative.
273
- function logBar(v, maxLog, width = 40, colorCode = c.cyan) {
274
- if (!v || v <= 0) return { bar: dim("·".repeat(width)), pct: 0 };
275
- const log = Math.log10(v);
276
- const pct = Math.min(log / maxLog, 1);
277
- const full = Math.floor(pct * width);
278
- const frac = Math.floor((pct * width - full) * 8);
279
- const bar = paint(
280
- colorCode,
281
- "█".repeat(full) + (frac > 0 ? BLOCKS[frac] : ""),
282
- );
283
- return { bar, pct };
284
- }
285
-
286
- // ── Sparkline (no dep) ────────────────────────────────────────────────────────
287
- const SPARK = "▁▂▃▄▅▆▇█";
288
- function sparkline(values) {
289
- const valid = values.filter(Number.isFinite);
290
- if (valid.length === 0) return dim("no data");
291
- const min = Math.min(...valid),
292
- max = Math.max(...valid);
293
- return values
294
- .map((v) => {
295
- if (!Number.isFinite(v)) return dim("·");
296
- const idx = max === min ? 7 : Math.round(((v - min) / (max - min)) * 7);
297
- return SPARK[idx];
298
- })
299
- .join("");
300
- }
301
-
302
- // ── Data sources ─────────────────────────────────────────────────────────────
303
- // (0.12.1 FIX 4) The local verifier readers (ccusage / tokscale / token-dashboard)
304
- // moved to `freshVerifierPillars()` in tokenpull.mjs — FRESH on-demand pulls used by
305
- // the Compare tab (#9). The old in-tui copies were dead after A1 removed the Dashboard
306
- // verifierMap loop and #9 routed Compare through the fresh helper; removed here.
307
- // (tools.mjs keeps its own `_ccusagePillars`/`_tokscalePillars`/`_tokenDashPillars` —
308
- // still used by the `tokenpull_compare` MCP tool.)
309
-
310
- async function loadDashboardData() {
311
- const boardPromise = Promise.race([
312
- fetch(`${DEFAULT_API_BASE}/api/v1/leaderboard?window=30d&metric=yield_`, {
313
- headers: { accept: "application/json" },
314
- })
315
- .then((r) => (r.ok ? r.json() : null))
316
- .catch(() => null),
317
- new Promise((r) => setTimeout(() => r(null), 5000)),
318
- ]);
319
-
320
- // FIX 0 + unify (0.14): progressive load via the SHARED loader (pullActivePlatforms) — paint the
321
- // primary platform (claude) FAST, then fill the rest in fillDashboardRest. This is the SAME loader
322
- // `me` and `watch` use, so the three views can't drift apart. (Verifier comparison still runs
323
- // FRESH + on-demand in the Compare tab — see loadCompareData — never on this Dashboard path.)
324
- const active = await pullActivePlatforms({ platforms: ["claude"] }).catch(
325
- () => [],
326
- );
327
-
328
- const boardData = await boardPromise;
329
- return {
330
- active,
331
- verifierMap: {},
332
- tdPillars: null,
333
- boardData,
334
- _loading: true,
335
- _remaining: ALL_PLATFORMS.filter((p) => p !== "claude"),
336
- };
337
- }
338
-
339
- /** FIX 0: fill the remaining platforms after the primary render. Mutates dashData.active. */
340
- async function fillDashboardRest(dashData) {
341
- if (!dashData?._remaining) return false;
342
- // Unify: fill the remaining platforms through the SAME shared loader.
343
- const rest = await pullActivePlatforms({
344
- platforms: dashData._remaining,
345
- }).catch(() => []);
346
- for (const d of rest) {
347
- if (!dashData.active.find((a) => a.platform === d.platform))
348
- dashData.active.push(d);
349
- }
350
- // stable display order: claude → codex → rest (matches the shared loader)
351
- const rank = (p) =>
352
- p === "claude" ? -2 : p === "codex" ? -1 : ALL_PLATFORMS.indexOf(p);
353
- dashData.active.sort((a, b) => rank(a.platform) - rank(b.platform));
354
- dashData._loading = false;
355
- dashData._remaining = null;
356
- return true;
357
- }
358
-
359
- // #9 / C1 (2026-06-27): Compare pulls the three external verifier sources FRESH + on-demand
360
- // (ccusage + tokscale models + a token-dashboard rescan), via tokenpull.freshVerifierPillars —
361
- // NOT the old stale snapshot readers (static tokscale_report.json / 3-day-old db). This runs ONLY
362
- // when the Compare tab opens (it's a 5–60s scan), never on the Dashboard load path. Scoped to the
363
- // current platform. tokenpull (the canonical board/cascade source) stays the fast/fresh tpData.
364
- async function loadCompareData(platform = "claude") {
365
- const tpData = await callTool("tokenpull", { platform }).catch(() => null);
366
- // Fresh pull — { ccusage, tokscale, tokendash }, each null or window-keyed pillars.
367
- const fresh = await freshVerifierPillars(platform).catch(() => ({
368
- ccusage: null,
369
- tokscale: null,
370
- tokendash: null,
371
- }));
372
- return {
373
- tpData,
374
- cc: fresh.ccusage,
375
- ts: fresh.tokscale,
376
- td: fresh.tokendash,
377
- platform,
378
- };
379
- }
380
-
381
- // #8 (2026-06-27): the Board tab shows ALL SUBMISSIONS ranked (raw submission rows), not operator
382
- // aggregates. Try the NEW GET /api/v1/submissions first; if it's not deployed yet (non-200 / 404),
383
- // FALL BACK to the existing /api/v1/leaderboard so nothing breaks pre-deploy. The return is tagged
384
- // with `_source` ('submissions' | 'leaderboard') so renderBoard picks the right column layout.
385
- async function loadBoardData(window = "30d") {
386
- // Primary: submissions endpoint (ranked submission rows).
387
- try {
388
- const res = await fetch(
389
- `${DEFAULT_API_BASE}/api/v1/submissions?window=${window}&metric=yield_`,
390
- {
391
- headers: { accept: "application/json" },
392
- },
393
- );
394
- if (res.ok) {
395
- const data = await res.json();
396
- return { ...data, _source: "submissions" };
397
- }
398
- } catch {
399
- /* fall through to leaderboard */
400
- }
401
- // Fallback: existing leaderboard endpoint + current render (pre-deploy safety).
402
- try {
403
- const res = await fetch(
404
- `${DEFAULT_API_BASE}/api/v1/leaderboard?window=${window}&metric=yield_`,
405
- {
406
- headers: { accept: "application/json" },
407
- },
408
- );
409
- if (!res.ok) return null;
410
- const data = await res.json();
411
- return { ...data, _source: "leaderboard" };
412
- } catch {
413
- return null;
414
- }
415
- }
416
-
417
- // ── TAB BAR ──────────────────────────────────────────────────────────────────
418
- const TABS = [
419
- { key: "1", label: "Dashboard", short: "D" },
420
- { key: "2", label: "Trends", short: "T" }, // every metric across windows (sub-views: You/Platform/Field)
421
- { key: "3", label: "Compare", short: "C" },
422
- { key: "4", label: "Board", short: "B" },
423
- { key: "5", label: "Watch", short: "W" }, // in-TUI landing panel; [Enter] launches the watcher
424
- { key: "6", label: "Connect", short: "N" }, // sign in / switch device — the whole app is the TUI
425
- ];
426
-
427
- // Three Degrees of Leverage — reference values pulled from signalaf.com/wiki (2026-06-25).
428
- // base = AI avg (modeled 7:2:1 baseline) · field = SigRank avg (wild field median) · top = best operator.
429
- // STATIC for now; goes live (field/top computed from the board) once there's real user volume.
430
- const TD = {
431
- base: { yield: 1.57, snr: 0.33, vel: 0.5, lev: 3.2, d10: 0.5 },
432
- field: { yield: 1.51, snr: 0.07, vel: 0.08, lev: 22.3, d10: 1.35 },
433
- top: { yield: 745.4, snr: 0.63, vel: 1.7, lev: 438.6, d10: 2.64 },
434
- };
435
-
436
- function renderTabBar(activeIdx) {
437
- const w = W();
438
- const ts = new Date().toLocaleTimeString("en-US", { hour12: false });
439
-
440
- // logo
441
- const logo = ` ${gold("⊙ SigRank")}`;
442
- // tabs
443
- const tabStr = TABS.map((t, i) => {
444
- const lbl = ` ${t.key}:${t.label} `;
445
- return i === activeIdx
446
- ? `${c.bgCyan}${c.boldCyan}${lbl}${c.reset}`
447
- : `${c.bgDim}${c.dim}${lbl}${c.reset}`;
448
- }).join("");
449
- // right side — version (single source of truth) · site · clock
450
- const right = dim(
451
- `${gold("v" + VERSION)}${c.reset}${c.dim} · signalaf.com · ${ts}`,
452
- );
453
-
454
- const logoVis = stripAnsi(logo).length;
455
- const tabsVis = TABS.reduce((a, t) => a + t.label.length + 4, 0);
456
- const rightVis = stripAnsi(right).length;
457
- const gap = Math.max(1, w - logoVis - tabsVis - rightVis - 2);
458
-
459
- writeln(`${logo} ${tabStr}${" ".repeat(gap)}${right}`);
460
- writeln(` ${hr()}`);
461
- }
462
-
463
- // ── GRAPHICS helpers ─────────────────────────────────────────────────────────
464
-
465
- // Horizontal stacked bar: input | cacheW | cacheR | output
466
- function tokenBar(p, width = 40) {
467
- if (!p) return dim(" no data");
468
- const total =
469
- (p.input ?? 0) +
470
- (p.output ?? 0) +
471
- (p.cacheCreate ?? 0) +
472
- (p.cacheRead ?? 0);
473
- if (total === 0) return dim(" no data");
474
- const seg = (val, colorCode) => {
475
- const w = Math.round((val / total) * width);
476
- return w > 0 ? paint(colorCode, "█".repeat(w)) : "";
477
- };
478
- const bar =
479
- seg(p.input, c.cyan) +
480
- seg(p.cacheCreate, c.blue) +
481
- seg(p.cacheRead, c.boldGold) +
482
- seg(p.output, c.green);
483
- return bar;
484
- }
485
-
486
- // Generalized cascade-metric sparkline across windows (7d→30d→90d→all).
487
- // pick: (cas) => number · fmt: (v) => string. Used by the Trends tab for every metric.
488
- // FIX G1: window headers are rendered once at the top of each metric block (mirror
489
- // renderCompare's column layout). metricSpark/yieldSpark now return sparkline + RIGHT-
490
- // ALIGNED values in fixed COL_W columns — NO per-value `w:` prefix (the header row
491
- // carries the window labels). Null windows render a dim `—` (columns stay aligned).
492
- const TREND_COL_W = 10;
493
- const TREND_WINS = ["7d", "30d", "90d", "all"];
494
-
495
- function trendHeader() {
496
- return (
497
- padEnd(dim(""), 12) +
498
- TREND_WINS.map((w) => padStart(dim(w), TREND_COL_W)).join(" ")
499
- );
500
- }
501
-
502
- function metricSpark(d, pick, fmt) {
503
- const vals = TREND_WINS.map((w) => {
504
- const wd = d.windows?.find((x) => x.window === w);
505
- if (!wd) return null;
506
- const cas = cascadeFrom(wd.pillars);
507
- return cas ? pick(cas, wd.pillars) : null; // pick gets (cascade, pillars)
508
- });
509
- const cols = vals.map((v) =>
510
- v != null ? padStart(fmt(v), TREND_COL_W) : padStart(dim("—"), TREND_COL_W),
511
- );
512
- return sparkline(vals) + ` ${cols.join(" ")}`;
513
- }
514
-
515
- // Yield sparkline across windows
516
- function yieldSpark(d) {
517
- const vals = TREND_WINS.map((w) => {
518
- const wd = d.windows?.find((x) => x.window === w);
519
- if (!wd) return null;
520
- const cas = cascadeFrom(wd.pillars);
521
- return cas?.yield ?? null;
522
- });
523
- const cols = vals.map((v) =>
524
- v != null
525
- ? padStart(fmtY(v), TREND_COL_W)
526
- : padStart(dim("—"), TREND_COL_W),
527
- );
528
- return sparkline(vals) + ` ${cols.join(" ")}`;
529
- }
530
-
531
- // ── TAB 1: DASHBOARD ─────────────────────────────────────────────────────────
532
-
533
- // SCROLL-VIEW (2026-06-27): section-scoped scroll for the cascade table.
534
- // The cascade section gets a real scroll viewport — up/down arrows scroll just
535
- // the cascade rows while the rest of the dashboard (header, token composition,
536
- // board, footer) stays pinned. This replaces the misleading "+N more — resize /
537
- // scroll" text (A3) which implied scroll existed but didn't (alt-screen locked
538
- // frame = no terminal scroll). The scroll is IN-SECTION only, on the Dashboard tab.
539
-
540
- const DASH_WINS = ["7d", "30d", "90d", "all"];
541
-
542
- // Count how many cascade rows the active platforms would produce (every window
543
- // with data across all active platforms). This is the "total wanted" count.
544
- function cascadeScrollableCount(active) {
545
- return active.reduce(
546
- (n, d) =>
547
- n +
548
- DASH_WINS.filter((wk) => {
549
- const wd = d.windows?.find((x) => x.window === wk);
550
- return wd && wd.pillars.input + wd.pillars.output > 0;
551
- }).length,
552
- 0,
553
- );
554
- }
555
-
556
- // Compute the max cascade rows that fit in the current terminal height budget.
557
- // Mirrors the calculation in renderDashboard (budget - used - sectionsBelow).
558
- function maxCascadeRowsFor(active) {
559
- const budget = H() - 4; // 2 tab bar + 2 footer
560
- const platformCount = active.length;
561
- const barLines = 4 + platformCount + (platformCount > 1 ? 1 : 0);
562
- const boardLines = 17;
563
- const sectionsBelow = barLines + boardLines;
564
- // used before cascade = header(2) + blank(1) + title(1) + blank(1) + col-header(1) + separator(1) = 7
565
- const usedBeforeCascade = 7;
566
- return Math.max(8, budget - usedBeforeCascade - sectionsBelow);
567
- }
568
-
569
- function renderDashboard(data, status = "", scrollOffset = 0) {
570
- const w = W();
571
- const budget = H() - 4; // 2 tab bar + 2 footer
572
- const WINS = ["7d", "30d", "90d", "all"];
573
- let used = 0;
574
- const emit = (s = "") => {
575
- if (used < budget) {
576
- writeln(s);
577
- used++;
578
- }
579
- };
580
-
581
- // A2 (2026-06-27): tolerate null/empty dashData so the FIRST paint can happen BEFORE the
582
- // initial load resolves (loadAll renders an empty frame + "reading your cascade…" immediately,
583
- // then re-renders with real data). Guard the destructure: no data → header + status + return.
584
- if (!data || !Array.isArray(data.active)) {
585
- emit();
586
- emit(` ${bold("Your Cascade")} ${dim("all platforms · all windows")}`);
587
- emit();
588
- emit(` ${dim(" reading token logs… (press [R] to refresh)")}`);
589
- if (status && used < budget) emit(` ${dim(status)}`);
590
- return;
591
- }
592
-
593
- const { active } = data;
594
-
595
- // Responsive: the full 12-col table is ~124 wide. On terminals narrower than
596
- // that, drop the two derived columns (Vel, 10x) and tighten the inter-column
597
- // gap from 2 spaces to 1, so the core pillars + Υ/SNR/Lev/Class still fit.
598
- const narrow = w < 124;
599
- const gap = narrow ? " " : " ";
600
- const renderRow = (label, colorFn, winKey, p, est = false) => {
601
- const cas = cascadeFrom(p);
602
- if (!cas) return;
603
- const clsFn = CLS[cas.class] ?? ((s) => s);
604
- const cols = [
605
- padEnd(colorFn(label), 12),
606
- padEnd(dim(winKey), 5),
607
- padStart(est ? dim("~") + fmtTok(p.input) : fmtTok(p.input), 8),
608
- padStart(fmtTok(p.output), 8),
609
- padStart(
610
- (p.cacheCreate ?? 0) > 0
611
- ? est
612
- ? dim("~") + fmtTok(p.cacheCreate)
613
- : fmtTok(p.cacheCreate)
614
- : dim("—"),
615
- 8,
616
- ),
617
- padStart((p.cacheRead ?? 0) > 0 ? fmtTok(p.cacheRead) : dim("—"), 9),
618
- padStart(cas.yield > 10000 ? gold(fmtY(cas.yield)) : fmtY(cas.yield), 9),
619
- padStart(fmtSNR(cas.snr), 7),
620
- padStart(fmtLev(cas.leverage) + "×", 7),
621
- ...(narrow
622
- ? []
623
- : [
624
- padStart(cas.velocity?.toFixed(2) ?? "—", 6),
625
- padStart(cas.dev10x?.toFixed(2) ?? "—", 6),
626
- ]),
627
- padEnd(clsFn(cas.class), 13),
628
- ];
629
- emit(` ${cols.join(gap)}`);
630
- };
631
-
632
- // ── Cascade table
633
- emit();
634
- emit(` ${bold("Your Cascade")} ${dim("all platforms · all windows")}`);
635
- emit();
636
-
637
- // header (matches renderRow's responsive column set + gap)
638
- const CH = [
639
- padEnd(hdr("Platform"), 12),
640
- padEnd(hdr("Win"), 5),
641
- padStart(hdr("Input"), 8),
642
- padStart(hdr("Output"), 8),
643
- padStart(hdr("CacheW"), 8),
644
- padStart(hdr("CacheR"), 9),
645
- padStart(hdr("Υ Yield"), 9),
646
- padStart(hdr("SNR"), 7),
647
- padStart(hdr("Lev"), 7),
648
- ...(narrow ? [] : [padStart(hdr("Vel"), 6), padStart(hdr("10x"), 6)]),
649
- padEnd(hdr("Class"), 13),
650
- ];
651
- emit(` ${CH.join(gap)}`);
652
- emit(` ${dim("·".repeat(Math.max(0, Math.min(w - 4, narrow ? 96 : 114))))}`);
653
-
654
- if (active.length === 0) {
655
- emit(
656
- ` ${dim(" reading token logs… (14 platforms, ~5s · press [R] to refresh)")}`,
657
- );
658
- }
659
-
660
- // Calculate how many cascade rows we can fit — reserve space for lower sections.
661
- // (Υ-trend section moved to the Trends tab; its old `sparkLines` reservation is gone,
662
- // which is what was starving codex's cascade rows after the Your-Read/Three-Degrees panels landed.)
663
- const platformCount = active.length;
664
- const barLines = 4 + platformCount + (platformCount > 1 ? 1 : 0); // Token Composition: hr + header + platforms + combined + note
665
- // Your Read (hr+header+~3 wins+1 gap = 6) + Three Degrees (blank+hr+header+col-header+5 rows+note = 10) + status
666
- const boardLines = 17;
667
- const sectionsBelow = barLines + boardLines;
668
- const maxCascadeRows = Math.max(8, budget - used - sectionsBelow);
669
-
670
- // SCROLL-VIEW (2026-06-27): Build the full list of cascade rows first, then
671
- // slice by [scrollOffset, scrollOffset + maxCascadeRows]. This gives a real
672
- // in-section scroll viewport — up/down arrows scroll just the cascade rows
673
- // while the rest of the dashboard stays pinned. Replaces the A3 "+N more —
674
- // resize / scroll" text which implied scroll existed but didn't.
675
- let firstWin = {};
676
- const allCascadeRows = []; // flat list: { platform, winKey, pillars, estimated }
677
- for (const d of active) {
678
- firstWin[d.platform] = WINS.find((wk) => {
679
- const wd = d.windows?.find((w) => w.window === wk);
680
- return wd && wd.pillars.input + wd.pillars.output > 0;
681
- });
682
- for (const wk of WINS) {
683
- const wd = d.windows?.find((x) => x.window === wk);
684
- if (!wd || wd.pillars.input + wd.pillars.output === 0) continue;
685
- allCascadeRows.push({
686
- platform: d.platform,
687
- winKey: wk,
688
- pillars: wd.pillars,
689
- estimated: d.estimated,
690
- });
691
- }
692
- }
693
-
694
- const totalWanted = allCascadeRows.length;
695
- const canScroll = totalWanted > maxCascadeRows;
696
- // Clamp scroll offset to valid range [0, totalWanted - maxCascadeRows]
697
- const maxOffset = Math.max(0, totalWanted - maxCascadeRows);
698
- const effectiveOffset = Math.min(scrollOffset, maxOffset);
699
- const visibleRows = allCascadeRows.slice(
700
- effectiveOffset,
701
- effectiveOffset + maxCascadeRows,
702
- );
703
-
704
- // ▲ indicator: rows above the current viewport
705
- if (canScroll && effectiveOffset > 0) {
706
- emit(
707
- ` ${dim(` ▲ ${effectiveOffset} row${effectiveOffset > 1 ? "s" : ""} above`)}`,
708
- );
709
- }
710
-
711
- // Render the visible slice — group by platform (emit a blank line between platforms)
712
- let lastPlatform = null;
713
- for (const row of visibleRows) {
714
- if (lastPlatform !== null && row.platform !== lastPlatform) emit();
715
- renderRow(
716
- row.platform,
717
- (s) => (row.winKey === firstWin[row.platform] ? cyan(s) : dim(s)),
718
- row.winKey,
719
- row.pillars,
720
- row.estimated,
721
- );
722
- lastPlatform = row.platform;
723
- }
724
- if (visibleRows.length > 0) emit();
725
-
726
- // ▼ indicator: rows below the current viewport
727
- const rowsBelow = totalWanted - effectiveOffset - visibleRows.length;
728
- if (canScroll && rowsBelow > 0) {
729
- emit(
730
- ` ${dim(` ▼ ${rowsBelow} row${rowsBelow > 1 ? "s" : ""} below · ↑↓ scroll`)}${effectiveOffset > 0 ? dim(` · ${effectiveOffset}/${maxOffset}`) : ""}`,
731
- );
732
- }
733
-
734
- // combined
735
- if (active.length > 1 && used < budget - sectionsBelow) {
736
- const lbl = active.map((d) => d.platform).join("+");
737
- const hasEst = active.some((d) => d.estimated);
738
- let fst = true;
739
- for (const wk of WINS) {
740
- const cp = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
741
- let any = false;
742
- for (const d of active) {
743
- const wd = d.windows?.find((x) => x.window === wk);
744
- if (!wd || wd.pillars.input + wd.pillars.output === 0) continue;
745
- cp.input += wd.pillars.input ?? 0;
746
- cp.output += wd.pillars.output ?? 0;
747
- cp.cacheCreate += wd.pillars.cacheCreate ?? 0;
748
- cp.cacheRead += wd.pillars.cacheRead ?? 0;
749
- any = true;
750
- }
751
- if (!any) continue;
752
- renderRow(lbl, (s) => (fst ? bold(cyan(s)) : dim(s)), wk, cp, hasEst);
753
- fst = false;
754
- }
755
- emit();
756
- }
757
-
758
- // (Υ Trend moved to the dedicated Trends tab [2] — every metric, with sub-views.)
759
-
760
- // ── Token bar charts (skip if no room)
761
- if (used < budget - boardLines) {
762
- emit(` ${hr()}`);
763
- emit(
764
- ` ${bold("Token Composition")} ${dim("█")}${paint(c.cyan, "I")}${dim(" in █")}${paint(c.blue, "W")}${dim(" cW █")}${paint(c.boldGold, "R")}${dim(" cR █")}${paint(c.green, "O")}${dim(" out")}`,
765
- );
766
- for (const d of active) {
767
- if (used >= budget - boardLines) break;
768
- const all = d.windows?.find((w) => w.window === "all");
769
- if (!all) continue;
770
- emit(
771
- ` ${padEnd(cyan(d.platform), 10)} ${tokenBar(all.pillars, 50)} ${dim(fmtTok((all.pillars.input ?? 0) + (all.pillars.output ?? 0) + (all.pillars.cacheCreate ?? 0) + (all.pillars.cacheRead ?? 0)))}`,
772
- );
773
- }
774
- if (active.length > 1) {
775
- const cp = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
776
- for (const d of active) {
777
- const all = d.windows?.find((w) => w.window === "all");
778
- if (!all) continue;
779
- cp.input += all.pillars.input ?? 0;
780
- cp.output += all.pillars.output ?? 0;
781
- cp.cacheCreate += all.pillars.cacheCreate ?? 0;
782
- cp.cacheRead += all.pillars.cacheRead ?? 0;
783
- }
784
- emit(
785
- ` ${padEnd(bold(active.map((d) => d.platform).join("+")), 10)} ${tokenBar(cp, 50)} ${dim(fmtTok(cp.input + cp.output + cp.cacheCreate + cp.cacheRead))}`,
786
- );
787
- }
788
- }
789
-
790
- // ── Your insights + the Three Degrees panel (replaces the old top-3 mini board)
791
- // The user's own cascade (the firstWin/combined row computed above) read against the
792
- // Three Degrees reference so the Dashboard says "here's you, here's the field, here's the ceiling."
793
- const you = (() => {
794
- // Best available cascade for the user: prefer claude's first-window, else any computed row.
795
- for (const d of active) {
796
- const wk = firstWin[d.platform];
797
- const wd = d.windows?.find((x) => x.window === wk);
798
- const cas = wd && cascadeFrom(wd.pillars);
799
- if (cas) return cas; // cascadeFrom already returns null for non-compounding rows
800
- }
801
- return null;
802
- })();
803
-
804
- if (used < budget - 8) {
805
- // ── Custom insights — comparison vs the field + a concrete tip for the weakest metric
806
- emit(` ${hr()}`);
807
- emit(
808
- ` ${bold("Your Read")} ${dim("how your cascade sits vs the field")}`,
809
- );
810
- if (you) {
811
- const wins = [],
812
- gaps = [];
813
- const chk = (label, val, fieldAvg, top, fmt, tip) => {
814
- if (val == null) return;
815
- if (val >= top * 0.9)
816
- wins.push(`${label} ${fmt(val)} — ${gold("top tier")}`);
817
- else if (val >= fieldAvg)
818
- wins.push(`${label} ${fmt(val)} — above field avg`);
819
- else
820
- gaps.push({
821
- label,
822
- txt: `${label} ${fmt(val)} — below field (${fmt(fieldAvg)}): ${tip}`,
823
- val,
824
- fieldAvg,
825
- });
826
- };
827
- chk(
828
- "Υ Yield",
829
- you.yield,
830
- TD.field.yield,
831
- TD.top.yield,
832
- fmtY,
833
- "compound more — reuse cache, raise output",
834
- );
835
- chk(
836
- "SNR",
837
- you.snr,
838
- TD.field.snr,
839
- TD.top.snr,
840
- fmtSNR,
841
- "tighten prompts — less input per unit output",
842
- );
843
- chk(
844
- "Leverage",
845
- you.leverage,
846
- TD.field.lev,
847
- TD.top.lev,
848
- (v) => fmtLev(v) + "×",
849
- "lean on cache-read — amplify prior context",
850
- );
851
- chk(
852
- "Velocity",
853
- you.velocity,
854
- TD.field.vel,
855
- TD.top.vel,
856
- (v) => v.toFixed(2),
857
- "more output per input token",
858
- );
859
- for (const w of wins.slice(0, 3)) emit(` ${paint(c.green, "▲")} ${w}`);
860
- // weakest gap gets the prescriptive tip
861
- const weakest = gaps.sort(
862
- (a, b) => a.val / a.fieldAvg - b.val / b.fieldAvg,
863
- )[0];
864
- if (weakest) emit(` ${paint(c.magenta, "▽")} ${dim(weakest.txt)}`);
865
- if (!wins.length && !weakest) emit(` ${dim(" building your read…")}`);
866
- } else {
867
- emit(` ${dim(" reading your cascade… (press [R] to refresh)")}`);
868
- }
869
-
870
- // ── Three Degrees — AI avg · SigRank avg · Top (live values from signalaf.com)
871
- emit();
872
- emit(` ${hr()}`);
873
- emit(
874
- ` ${bold("Three Degrees")} ${dim("AI avg · SigRank avg · top — signalaf.com/wiki")}`,
875
- );
876
- const tdHead = [
877
- padEnd(hdr("Metric"), 10),
878
- padStart(hdr("AI avg"), 9),
879
- padStart(hdr("SigRank avg"), 12),
880
- padStart(hdr("Top"), 9),
881
- ];
882
- emit(` ${tdHead.join(" ")}`);
883
- const white = (s) => paint(c.white, s);
884
- const tdRow = (label, b, f, t, fmt) =>
885
- emit(
886
- ` ${padEnd(label, 10)} ${padStart(white(fmt(b)), 9)} ${padStart(fmt(f), 12)} ${padStart(gold(fmt(t)), 9)}`,
887
- );
888
- tdRow("Υ Yield", TD.base.yield, TD.field.yield, TD.top.yield, fmtY);
889
- tdRow("SNR", TD.base.snr, TD.field.snr, TD.top.snr, fmtSNR);
890
- tdRow("Velocity", TD.base.vel, TD.field.vel, TD.top.vel, (v) =>
891
- v.toFixed(2),
892
- );
893
- tdRow(
894
- "Leverage",
895
- TD.base.lev,
896
- TD.field.lev,
897
- TD.top.lev,
898
- (v) => fmtLev(v) + "×",
899
- );
900
- tdRow("10xDEV", TD.base.d10, TD.field.d10, TD.top.d10, (v) => v.toFixed(2));
901
- emit(
902
- ` ${dim("reference values until live user volume calibrates SigRank avg")}`,
903
- );
904
- }
905
-
906
- if (status && used < budget) emit(` ${dim(status)}`);
907
- }
908
-
909
- // ── TAB 2: TRENDS ─────────────────────────────────────────────────────────────
910
- // Every cascade metric (+ rank) as a 7d→30d→90d→all sparkline. Three sub-tabs:
911
- // You — your own trajectory (+ rank trend, "calculating" until wired)
912
- // Platform — per-platform (claude / codex / combined)
913
- // Field — board-wide trend (calculating until window-history materializes)
914
- // Switch sub-tabs with [T] (cycles You · Platform · Field). Data: the same `active` the Dashboard loads.
915
- const TREND_SUBTABS = ["You", "Platform", "Field"];
916
- // All leaderboard metrics. Most derive from the per-window cascade (pick takes the
917
- // cascade obj + its pillars); §IGNA (proprietary composite) and $/1M (needs cost data)
918
- // aren't computed client-side yet → rendered "calculating", same honest pattern as Rank.
919
- const AA_EFF_BASELINE = 4.0; // efficiency is measured vs the AA 4.0 baseline (per the wiki)
920
- const TREND_METRICS = [
921
- {
922
- label: "∑ Total",
923
- pick: (c, p) =>
924
- (p.input ?? 0) +
925
- (p.output ?? 0) +
926
- (p.cacheCreate ?? 0) +
927
- (p.cacheRead ?? 0),
928
- fmt: fmtTok,
929
- },
930
- { label: "Υ Yield", pick: (c) => c.yield, fmt: fmtY },
931
- { label: "SNR", pick: (c) => c.snr, fmt: fmtSNR },
932
- { label: "Velocity", pick: (c) => c.velocity, fmt: (v) => v.toFixed(2) },
933
- { label: "Leverage", pick: (c) => c.leverage, fmt: (v) => fmtLev(v) + "×" },
934
- { label: "10xDEV", pick: (c) => c.dev10x, fmt: (v) => v.toFixed(2) },
935
- {
936
- label: "Eff",
937
- pick: (c) => (c.yield != null ? c.yield / AA_EFF_BASELINE : null),
938
- fmt: (v) => v.toFixed(1) + "×",
939
- },
940
- {
941
- label: "§IGNA",
942
- pick: () => null,
943
- fmt: () => "—",
944
- stub: "composite calibrating (needs user volume)",
945
- },
946
- // FIX A4 (2026-06-27): operating ratio is INPUT-NORMALIZED `cache : 1 : output` (matches web canon —
947
- // ThreeDegreesChart / OperatingRatioBar, e.g. "3.5 : 1 : 0.50"), not raw token counts (which also
948
- // overflowed the Trends columns).
949
- {
950
- label: "Op Ratio",
951
- pick: (c, p) =>
952
- (p.input ?? 0) > 0
953
- ? {
954
- cacheRead: p.cacheRead ?? 0,
955
- input: p.input ?? 0,
956
- output: p.output ?? 0,
957
- }
958
- : null,
959
- fmt: (v) => {
960
- const i = v.input || 1;
961
- return `${(v.cacheRead / i).toFixed(1)} : 1 : ${(v.output / i).toFixed(2)}`;
962
- },
963
- },
964
- {
965
- label: "$/1M",
966
- pick: () => null,
967
- fmt: () => "—",
968
- stub: "cost data wires post-ingest",
969
- },
970
- ];
971
- function renderTrends(data, subIdx = 0) {
972
- const { active } = data ?? {};
973
- const budget = H() - 4;
974
- let used = 0;
975
- const emit = (s = "") => {
976
- if (used < budget) {
977
- writeln(s);
978
- used++;
979
- }
980
- };
981
- const sub = TREND_SUBTABS[subIdx] ?? "You";
982
-
983
- // sub-tab switcher row
984
- const subBar = TREND_SUBTABS.map((t, i) =>
985
- i === subIdx
986
- ? `${c.bgCyan}${c.boldCyan} ${t} ${c.reset}`
987
- : `${dim(` ${t} `)}`,
988
- ).join(" ");
989
- emit();
990
- emit(
991
- ` ${bold("Trends")} ${dim("every metric across windows (7d → all)")} ${subBar}`,
992
- );
993
- emit(` ${dim("·".repeat(Math.min(W() - 4, 70)))}`);
994
- emit();
995
-
996
- if (sub === "You" || sub === "Platform") {
997
- const rows =
998
- sub === "You"
999
- ? active?.length
1000
- ? [{ platform: "you", windows: active[0]?.windows }]
1001
- : [] // primary cascade
1002
- : (active ?? []);
1003
- if (!rows.length) {
1004
- emit(` ${dim(" reading your cascade… (press [R] to refresh)")}`);
1005
- }
1006
- // A3 (2026-06-27): count metric/rank rows dropped by the height budget so we can show a
1007
- // "+N more — resize / scroll" note instead of silently truncating. Each rendered block wants
1008
- // TREND_METRICS.length metric rows + 1 rank row. (Fit logic below unchanged — observe only.)
1009
- let trendsDropped = 0;
1010
- for (let ri = 0; ri < rows.length; ri++) {
1011
- const d = rows[ri];
1012
- if (used >= budget - 2) {
1013
- trendsDropped += (rows.length - ri) * (TREND_METRICS.length + 1);
1014
- break;
1015
- }
1016
- emit(` ${bold(sub === "You" ? "Your trajectory" : cyan(d.platform))}`);
1017
- // FIX G1: window column headers (mirror renderCompare) — one header row, then
1018
- // values in fixed-width columns below. No per-value `w:` prefix.
1019
- emit(` ${trendHeader()}`);
1020
- let mi = 0;
1021
- for (; mi < TREND_METRICS.length; mi++) {
1022
- const m = TREND_METRICS[mi];
1023
- if (used >= budget - 2) break;
1024
- if (m.stub) {
1025
- emit(
1026
- ` ${padEnd(dim(m.label), 10)} ${dim("▁▁▁▁ calculating… (" + m.stub + ")")}`,
1027
- );
1028
- } else {
1029
- emit(
1030
- ` ${padEnd(cyan(m.label), 10)} ${metricSpark(d, m.pick, m.fmt)}`,
1031
- );
1032
- }
1033
- }
1034
- trendsDropped += TREND_METRICS.length - mi; // metrics this block couldn't fit
1035
- // rank trend — wired later; honest placeholder for now
1036
- if (used < budget - 1)
1037
- emit(
1038
- ` ${padEnd(dim("Rank"), 10)} ${dim("▁▁▁▁ calculating… (rank history wires post-ingest)")}`,
1039
- );
1040
- else trendsDropped += 1;
1041
- emit();
1042
- }
1043
- // A3: surface the dropped count instead of hiding it.
1044
- // SCROLL-VIEW (2026-06-27): changed "resize / scroll" → "resize to see more"
1045
- // because these tabs don't have a real scroll viewport (only Dashboard cascade does).
1046
- if (trendsDropped > 0)
1047
- emit(` ${dim(` +${trendsDropped} more — resize to see more`)}`);
1048
- } else {
1049
- // Field
1050
- emit(` ${dim(" Field-wide trends — calculating…")}`);
1051
- emit(
1052
- ` ${dim(" (needs per-window board history; materializes once live ingest lands)")}`,
1053
- );
1054
- }
1055
- }
1056
-
1057
- // ── TAB 3: COMPARE ───────────────────────────────────────────────────────────
1058
- function renderCompare(data) {
1059
- const { tpData, cc, ts, td, platform } = data;
1060
- const WINS = ["7d", "30d", "90d", "all"];
1061
- const w = W();
1062
- const budget = H() - 4;
1063
- let used = 0;
1064
- const emit = (s = "") => {
1065
- if (used < budget) {
1066
- writeln(s);
1067
- used++;
1068
- }
1069
- };
1070
-
1071
- const tpPillars = {};
1072
- for (const win of tpData?.windows ?? []) tpPillars[win.window] = win.pillars;
1073
-
1074
- const SOURCES = [
1075
- {
1076
- name: "tokenpull",
1077
- color: (s) => paint(c.boldCyan, s),
1078
- pillars: tpPillars,
1079
- note: "JSONL canon",
1080
- },
1081
- {
1082
- name: "ccusage",
1083
- color: (s) => paint(c.green, s),
1084
- pillars: cc ?? {},
1085
- note: "ccusage CLI",
1086
- },
1087
- {
1088
- name: "token-dash",
1089
- color: (s) => paint(c.magenta, s),
1090
- pillars: td ?? {},
1091
- note: "SQLite",
1092
- },
1093
- {
1094
- name: "tokscale",
1095
- color: (s) => paint(c.blue, s),
1096
- pillars: ts ?? {},
1097
- note: "report.json",
1098
- },
1099
- ].filter((s) => Object.keys(s.pillars).length > 0);
1100
-
1101
- emit();
1102
- emit(
1103
- ` ${bold("Source Comparison")} ${dim(`platform: ${platform}`)} ${dim("· tokenpull vs ccusage vs token-dash vs tokscale")}`,
1104
- );
1105
-
1106
- if (!tpData) {
1107
- emit(
1108
- ` ${dim("tokenpull: no JSONL data found — check ~/.claude/projects/")}`,
1109
- );
1110
- } else {
1111
- const all = tpPillars["all"];
1112
- if (all) {
1113
- emit(
1114
- ` ${dim("tokenpull all-time:")} In ${cyan(fmtTok(all.input))} Out ${green(fmtTok(all.output))} CW ${paint(c.blue, fmtTok(all.cacheCreate))} CR ${gold(fmtTok(all.cacheRead))}`,
1115
- );
1116
- }
1117
- }
1118
- emit();
1119
-
1120
- const COL_W = 11;
1121
- const hcols = [
1122
- padEnd(dim("Source"), 12),
1123
- padEnd(dim("Pillar"), 10),
1124
- ...WINS.map((wn) => padStart(dim(wn), COL_W)),
1125
- ];
1126
- emit(` ${hcols.join(" ")}`);
1127
- emit(
1128
- ` ${dim("·".repeat(Math.min(w - 4, 12 + 12 + WINS.length * (COL_W + 2))))}`,
1129
- );
1130
-
1131
- const PILLARS = [
1132
- { key: "input", label: "Input" },
1133
- { key: "output", label: "Output" },
1134
- { key: "cacheWrite", label: "CacheW", dbKey: "cacheCreate" },
1135
- { key: "cacheRead", label: "CacheR" },
1136
- ];
1137
-
1138
- // Reserve space for cascade metrics below (~8 lines)
1139
- const metricsLines = 6 + SOURCES.length;
1140
- for (const src of SOURCES) {
1141
- let firstRow = true;
1142
- for (const pil of PILLARS) {
1143
- if (used >= budget - metricsLines) break;
1144
- const dbKey = pil.dbKey ?? pil.key;
1145
- const cells = WINS.map((win) => {
1146
- const p = src.pillars[win];
1147
- const val = p?.[dbKey] ?? null;
1148
- if (val == null) return padStart(dim("—"), COL_W);
1149
- const baseVal = tpPillars[win]?.[dbKey];
1150
- if (src.name !== "tokenpull" && baseVal != null && baseVal > 0) {
1151
- const delta = ((val - baseVal) / baseVal) * 100;
1152
- const dStr =
1153
- delta === 0
1154
- ? ""
1155
- : delta > 0
1156
- ? green(` +${delta.toFixed(0)}%`)
1157
- : red(` ${delta.toFixed(0)}%`);
1158
- return padStart(`${fmtTok(val)}${dStr}`, COL_W);
1159
- }
1160
- return padStart(fmtTok(val), COL_W);
1161
- });
1162
- const srcLabel = firstRow
1163
- ? padEnd(src.color(src.name), 12)
1164
- : padEnd(dim(""), 12);
1165
- emit(
1166
- ` ${srcLabel} ${padEnd(dim(pil.label), 10)} ${cells.join(" ")}`,
1167
- );
1168
- firstRow = false;
1169
- }
1170
- emit();
1171
- }
1172
-
1173
- if (used < budget - 4) {
1174
- emit(` ${hr()}`);
1175
- emit(
1176
- ` ${bold("Cascade Metrics")} ${dim("all-time · computed from each source")}`,
1177
- );
1178
- const MCH = [
1179
- padEnd(hdr("Source"), 12),
1180
- padStart(hdr("Υ Yield"), 9),
1181
- padStart(hdr("SNR"), 7),
1182
- padStart(hdr("Lev"), 8),
1183
- padStart(hdr("Vel"), 6),
1184
- padStart(hdr("10x"), 6),
1185
- padEnd(hdr("Class"), 13),
1186
- ];
1187
- emit(` ${MCH.join(" ")}`);
1188
- emit(` ${dim("·".repeat(Math.min(w - 4, 72)))}`);
1189
- for (const src of SOURCES) {
1190
- if (used >= budget) break;
1191
- const p = src.pillars["all"];
1192
- if (!p) continue;
1193
- const cas = cascadeFrom(p);
1194
- if (!cas) continue;
1195
- const clsFn = CLS[cas.class] ?? ((s) => s);
1196
- const cols = [
1197
- padEnd(src.color(src.name), 12),
1198
- padStart(
1199
- cas.yield > 10000 ? gold(fmtY(cas.yield)) : fmtY(cas.yield),
1200
- 9,
1201
- ),
1202
- padStart(fmtSNR(cas.snr), 7),
1203
- padStart(fmtLev(cas.leverage) + "×", 8),
1204
- padStart(cas.velocity?.toFixed(2) ?? "—", 6),
1205
- padStart(cas.dev10x?.toFixed(2) ?? "—", 6),
1206
- padEnd(clsFn(cas.class), 13),
1207
- ];
1208
- emit(` ${cols.join(" ")}`);
1209
- }
1210
- }
1211
- }
1212
-
1213
- // ── TAB 3: BOARD — submissions view (#8) ──────────────────────────────────────
1214
- // Renders ALL submissions ranked (raw submission rows from GET /api/v1/submissions), not operator
1215
- // aggregates. Columns: rank · codename · platform · window · Υ Yield · op_ratio · class · tokens.
1216
- // Field names are read defensively (the endpoint is new) so a slightly different server shape still
1217
- // renders. [Y] "just me" filtering + the you-highlight carry over from the leaderboard view.
1218
- function renderSubmissions(
1219
- boardData,
1220
- window = "30d",
1221
- filterCodename = null,
1222
- highlightCodename = null,
1223
- ) {
1224
- const rows =
1225
- boardData?.submissions ??
1226
- boardData?.entries ??
1227
- boardData?.rows ??
1228
- (Array.isArray(boardData) ? boardData : []);
1229
- const w = W();
1230
- const budget = H() - 4;
1231
- let used = 0;
1232
- const emit = (s = "") => {
1233
- if (used < budget) {
1234
- writeln(s);
1235
- used++;
1236
- }
1237
- };
1238
-
1239
- // Defensive field readers (server shape is new / not yet pinned).
1240
- const gName = (e) =>
1241
- e.display_name || e.codename || e.operator_codename || "—";
1242
- const gPlat = (e) => e.platform ?? e.platform_primary ?? "—";
1243
- const gWin = (e) => e.window ?? e.window_type ?? "—";
1244
- const gYield = (e) => e.yield_ ?? e.yield ?? e.y ?? null;
1245
- const gOpRatio = (e) => e.op_ratio ?? e.operating_ratio ?? e.opRatio ?? null;
1246
- const gClass = (e) => e.class_tier ?? e.class ?? e.class_ ?? "—";
1247
- const gTokens = (e) => e.tokens ?? e.total_tokens ?? e.token_total ?? null;
1248
-
1249
- const modeLabel = filterCodename
1250
- ? `${dim(" · just you")}`
1251
- : highlightCodename
1252
- ? `${dim(" · you highlighted")}`
1253
- : "";
1254
- emit();
1255
- emit(
1256
- ` ${bold("Submissions")} ${dim(`window: ${window} · all submissions ranked by Υ Yield · signalaf.com`)}${modeLabel}`,
1257
- );
1258
- emit();
1259
-
1260
- if (!Array.isArray(rows) || rows.length === 0) {
1261
- emit(` ${dim(" no submissions for this window")}`);
1262
- return;
1263
- }
1264
-
1265
- let sorted = [...rows].sort((a, b) => (gYield(b) ?? 0) - (gYield(a) ?? 0));
1266
- if (filterCodename) {
1267
- sorted = sorted.filter(
1268
- (e) => (gName(e) ?? "").toLowerCase() === filterCodename.toLowerCase(),
1269
- );
1270
- if (sorted.length === 0) {
1271
- emit(` ${dim(` you have no submissions in the ${window} window yet`)}`);
1272
- emit(` ${dim(" press [S] from a read tab to submit your cascade")}`);
1273
- return;
1274
- }
1275
- }
1276
-
1277
- // op_ratio may arrive as a preformatted string ("3.5 : 1 : 0.50") or a number — render either.
1278
- const fmtOp = (v) =>
1279
- v == null
1280
- ? "—"
1281
- : typeof v === "string"
1282
- ? v
1283
- : typeof v === "number"
1284
- ? v.toFixed(2)
1285
- : String(v);
1286
-
1287
- const SH = [
1288
- padStart(hdr("#"), 4),
1289
- padEnd(hdr("Codename"), 20),
1290
- padEnd(hdr("Platform"), 10),
1291
- padEnd(hdr("Win"), 6),
1292
- padStart(hdr("Υ Yield"), 9),
1293
- padEnd(hdr("Op Ratio"), 18),
1294
- padEnd(hdr("Class"), 12),
1295
- padStart(hdr("Tokens"), 9),
1296
- ];
1297
- emit(` ${SH.join(" ")}`);
1298
- emit(` ${dim("·".repeat(Math.min(w - 4, 100)))}`);
1299
-
1300
- let shown = 0;
1301
- for (let idx = 0; idx < sorted.length; idx++) {
1302
- if (used >= budget) break;
1303
- const e = sorted[idx];
1304
- const isYou =
1305
- highlightCodename &&
1306
- (gName(e) ?? "").toLowerCase() === highlightCodename.toLowerCase();
1307
- const rk =
1308
- idx === 0
1309
- ? gold(`#${idx + 1}`)
1310
- : idx < 3
1311
- ? cyan(`#${idx + 1}`)
1312
- : `#${idx + 1}`;
1313
- const nmRaw = trunc(gName(e), 20);
1314
- const nm = isYou
1315
- ? `${c.bgCyan}${c.boldCyan}${padEnd(` ${trunc(gName(e), 18)} `, 20)}${c.reset}`
1316
- : padEnd(nmRaw, 20);
1317
- const yv = gYield(e);
1318
- const yld = padStart(
1319
- yv != null ? (yv > 10000 ? gold(fmtY(yv)) : fmtY(yv)) : "—",
1320
- 9,
1321
- );
1322
- const cls = padEnd(colorCls(gClass(e)), 12);
1323
- const tk = gTokens(e);
1324
- const youMark = isYou ? ` ${c.bgCyan}${c.boldCyan}YOU${c.reset}` : "";
1325
- emit(
1326
- ` ${padStart(rk, 4)} ${nm} ${padEnd(cyan(trunc(gPlat(e), 10)), 10)} ${padEnd(dim(trunc(gWin(e), 6)), 6)} ${yld} ${padEnd(dim(fmtOp(gOpRatio(e))), 18)} ${cls} ${padStart(tk != null ? fmtTok(tk) : "—", 9)}${youMark}`,
1327
- );
1328
- shown++;
1329
- }
1330
- // A3-style: if the height budget dropped rows, say so instead of silently truncating.
1331
- // SCROLL-VIEW (2026-06-27): changed "resize / scroll" → "resize to see more"
1332
- // (Board tab doesn't have a real scroll viewport — only Dashboard cascade does).
1333
- const dropped = sorted.length - shown;
1334
- if (dropped > 0 && used < budget)
1335
- emit(` ${dim(` +${dropped} more — resize to see more`)}`);
1336
- }
1337
-
1338
- // ── TAB 3: BOARD ─────────────────────────────────────────────────────────────
1339
- // FIX I2: hybrid board model. `filterCodename` (non-null = "just me" mode) shows
1340
- // ONLY the signed-in operator's rows. `highlightCodename` (non-null = global mode)
1341
- // highlights the signed-in operator's row in the global board. Both come from the
1342
- // signed-in identity's codename; the [Y] key toggles between the two modes.
1343
- function renderBoard(
1344
- boardData,
1345
- window = "30d",
1346
- filterCodename = null,
1347
- highlightCodename = null,
1348
- ) {
1349
- // #8 (2026-06-27): when the data came from the NEW /api/v1/submissions endpoint, render ALL
1350
- // submissions ranked (raw rows). Otherwise fall through to the existing leaderboard render
1351
- // (pre-deploy fallback). loadBoardData tags the payload with `_source`.
1352
- if (boardData?._source === "submissions") {
1353
- renderSubmissions(boardData, window, filterCodename, highlightCodename);
1354
- return;
1355
- }
1356
- const entries = boardData?.entries ?? boardData?.operators ?? boardData ?? [];
1357
- const w = W();
1358
- const budget = H() - 4;
1359
- let used = 0;
1360
- const emit = (s = "") => {
1361
- if (used < budget) {
1362
- writeln(s);
1363
- used++;
1364
- }
1365
- };
1366
-
1367
- const modeLabel = filterCodename
1368
- ? `${dim(" · just you")}`
1369
- : highlightCodename
1370
- ? `${dim(" · you highlighted")}`
1371
- : "";
1372
- emit();
1373
- emit(
1374
- ` ${bold("Leaderboard")} ${dim(`window: ${window} · sorted by Υ Yield · signalaf.com/leaderboard`)}${modeLabel}`,
1375
- );
1376
- emit();
1377
-
1378
- if (!Array.isArray(entries) || entries.length === 0) {
1379
- emit(` ${dim(" board unavailable")}`);
1380
- return;
1381
- }
1382
-
1383
- // FIX I2: "just me" mode — filter to the signed-in operator's rows only.
1384
- let sorted = [...entries].sort((a, b) => (b.yield_ ?? 0) - (a.yield_ ?? 0));
1385
- if (filterCodename) {
1386
- sorted = sorted.filter(
1387
- (e) => (e.codename ?? "").toLowerCase() === filterCodename.toLowerCase(),
1388
- );
1389
- if (sorted.length === 0) {
1390
- emit(` ${dim(` you have no ranked rows in the ${window} window yet`)}`);
1391
- emit(` ${dim(" press [S] from a read tab to submit your cascade")}`);
1392
- return;
1393
- }
1394
- }
1395
-
1396
- // Per-column top-3 "shadowbox": medal bg-tint (gold/silver/bronze) on the 1st/2nd/3rd
1397
- // best DISTINCT value in each metric column, mirroring the website's podium boxes.
1398
- const MEDAL_BG = { 1: 220, 2: 250, 3: 130 }; // gold · silver · bronze (256-color)
1399
- const top3 = (pick) => {
1400
- const distinct = [
1401
- ...new Set(sorted.map(pick).filter((v) => v != null && isFinite(v))),
1402
- ].sort((a, b) => b - a);
1403
- const m = new Map();
1404
- distinct.slice(0, 3).forEach((v, i) => m.set(v, i + 1));
1405
- return m;
1406
- };
1407
- const pods = {
1408
- yield: top3((e) => e.yield_),
1409
- snr: top3((e) => e.snr ?? e.compression_ratio),
1410
- lev: top3((e) => e.leverage),
1411
- vel: top3((e) => e.velocity),
1412
- d10: top3((e) => e.dev10x),
1413
- };
1414
- // Wrap a padded cell in a medal bg-tint (dark fg on the medal color) when its value places top-3.
1415
- const medal = (map, val, padded) => {
1416
- const place = val == null ? null : map.get(val);
1417
- if (!place) return padded;
1418
- return `${ESC}48;5;${MEDAL_BG[place]}m${ESC}38;5;232m${padded}${c.reset}`;
1419
- };
1420
-
1421
- const BH = [
1422
- padStart(hdr("#"), 4),
1423
- padEnd(hdr("Codename"), 22),
1424
- padEnd(hdr("Class"), 13),
1425
- padStart(hdr("Υ Yield"), 9),
1426
- padStart(hdr("SNR"), 7),
1427
- padStart(hdr("Lev"), 7),
1428
- padStart(hdr("Vel"), 6),
1429
- padStart(hdr("10x"), 6),
1430
- padStart(hdr("Pct"), 5),
1431
- padStart(hdr("7d↕"), 5),
1432
- ];
1433
- emit(` ${BH.join(" ")}`);
1434
- emit(` ${dim("·".repeat(Math.min(w - 4, 98)))}`);
1435
-
1436
- for (let idx = 0; idx < sorted.length; idx++) {
1437
- if (used >= budget) break;
1438
- const e = sorted[idx];
1439
- // FIX I2: highlight the signed-in operator's row (global mode) with a cyan bg-tint.
1440
- const isYou =
1441
- highlightCodename &&
1442
- (e.codename ?? "").toLowerCase() === highlightCodename.toLowerCase();
1443
- const rk =
1444
- idx === 0
1445
- ? gold(`#${idx + 1}`)
1446
- : idx < 3
1447
- ? cyan(`#${idx + 1}`)
1448
- : `#${idx + 1}`;
1449
- const nmRaw = trunc(e.display_name || e.codename || "—", 22);
1450
- // FIX I2: pad the visible content INSIDE the ANSI codes so the cyan bg fills
1451
- // the full column width (padEnd after reset would leave uncolored trailing spaces).
1452
- const nm = isYou
1453
- ? `${c.bgCyan}${c.boldCyan}${padEnd(` ${nmRaw} `, 22)}${c.reset}`
1454
- : padEnd(nmRaw, 22);
1455
- const cls = padEnd(colorCls(e.class_tier ?? "—"), 13);
1456
- const snrVal = e.snr ?? e.compression_ratio;
1457
- // value cells: pad first, then medal-wrap so the tint fills the whole column width
1458
- const yld = medal(
1459
- pods.yield,
1460
- e.yield_,
1461
- padStart(e.yield_ != null ? fmtY(e.yield_) : "—", 9),
1462
- );
1463
- const snr = medal(
1464
- pods.snr,
1465
- snrVal,
1466
- padStart(snrVal != null ? fmtSNR(snrVal) : "—", 7),
1467
- );
1468
- const lev = medal(
1469
- pods.lev,
1470
- e.leverage,
1471
- padStart(e.leverage != null ? fmtLev(e.leverage) + "×" : "—", 7),
1472
- );
1473
- const vel = medal(
1474
- pods.vel,
1475
- e.velocity,
1476
- padStart(e.velocity != null ? e.velocity.toFixed(2) : "—", 6),
1477
- );
1478
- const d10 = medal(
1479
- pods.d10,
1480
- e.dev10x,
1481
- padStart(e.dev10x != null ? e.dev10x.toFixed(2) : "—", 6),
1482
- );
1483
- const pct = padStart(e.percentile != null ? `${e.percentile}%` : "—", 5);
1484
- const mv = padStart(fmtMov(e.movement_7d), 5);
1485
- const youMark = isYou ? ` ${c.bgCyan}${c.boldCyan}YOU${c.reset}` : "";
1486
- emit(
1487
- ` ${padStart(rk, 4)} ${nm} ${cls} ${yld} ${snr} ${lev} ${vel} ${d10} ${pct} ${mv}${youMark}`,
1488
- );
1489
- }
1490
- }
1491
-
1492
- // ── TAB 4: WATCH — landing panel (instructions + why it matters) ─────────────
1493
- // Explains what the live watcher does and why it's the point of the agent: it
1494
- // re-reads your local logs on an interval and feeds your verified cascade to the
1495
- // leaderboard. Launched (in its own window) with [Enter]; interval is tunable.
1496
- // A5 (2026-06-27): Watch defaults to ALL active platforms × ALL windows (mirror the cli.mjs watch
1497
- // change). `platform`/`win` are OPTIONAL focus filters — null/'all' means "everything". [P]/[W]
1498
- // cycle the focus (including back to "all"); the spawned watcher + this copy show everything by default.
1499
- function renderWatchInfo(platform, win, refresh) {
1500
- const platLabel =
1501
- !platform || platform === "all" ? "all active platforms" : platform;
1502
- const winLabel = !win || win === "all-windows" ? "all windows" : win;
1503
- const allDefault =
1504
- platLabel === "all active platforms" && winLabel === "all windows";
1505
- writeln();
1506
- writeln(
1507
- ` ${bold("Live Watch")} ${dim("the agent that keeps your rank current")}`,
1508
- );
1509
- writeln();
1510
- writeln(` ${dim("What it does")}`);
1511
- writeln(
1512
- ` Re-reads your local token logs for ${cyan(platLabel)} across ${cyan(winLabel)} every`,
1513
- );
1514
- writeln(
1515
- ` ${gold(refresh + "s")} and recomputes each cascade (Υ Yield · SNR · Leverage · class) live, on`,
1516
- );
1517
- writeln(
1518
- ` this machine. ${dim("By default it watches everything — every platform you actually use.")}`,
1519
- );
1520
- writeln();
1521
- writeln(` ${dim("Why it matters")}`);
1522
- writeln(
1523
- ` Watch is how the board stays ${bold("current")}: each refresh submits your latest`,
1524
- );
1525
- writeln(
1526
- ` verified cascade so ${cyan("signalaf.com/leaderboard")} ${bold("auto-updates")} as you work —`,
1527
- );
1528
- writeln(
1529
- ` no manual re-submit. Tokens never leave your machine; only the metrics post.`,
1530
- );
1531
- writeln();
1532
- writeln(` ${dim("Settings")}`);
1533
- writeln(
1534
- ` ${dim("Platform")} ${cyan(platLabel)} ${dim("Window")} ${cyan(winLabel)} ${dim("Refresh")} ${gold(refresh + "s")}`,
1535
- );
1536
- writeln(
1537
- ` ${dim(allDefault ? "watching everything (default)" : "focused — press [P]/[W] to widen back to all")}`,
1538
- );
1539
- writeln();
1540
- writeln(
1541
- ` ${dim("[Enter]")} launch watcher (new window) ${dim("[+]/[-]")} refresh ±5s ${dim("[P]")} platform focus ${dim("[W]")} window focus`,
1542
- );
1543
- writeln();
1544
- }
1545
-
1546
- // ── TAB 6: CONNECT ───────────────────────────────────────────────────────────
1547
- // Sign in (paste a connect code) / show signed-in status. The whole app lives in
1548
- // the TUI; this replaces every "go run the CLI to enroll" hint. Uses only helpers
1549
- // already defined above (bold/dim/cyan/green/red/hr/writeln).
1550
- function renderConnect(id, codeBuf = "", msg = "") {
1551
- writeln();
1552
- if (isSignedIn(id)) {
1553
- writeln(` ${bold("Connect")} ${dim("your account")}`);
1554
- writeln(` ${hr()}`);
1555
- writeln(` ${green("✓")} Signed in as ${cyan(id.codename)}`);
1556
- writeln(` ${dim(`device ${id.device_id}`)}`);
1557
- writeln();
1558
- writeln(
1559
- ` ${dim("Press")} ${bold("[S]")} ${dim("from any read tab to submit your runs to the board.")}`,
1560
- );
1561
- writeln();
1562
- writeln(
1563
- ` ${dim('Need a new key? Click "New key" at signalaf.com → Settings, then paste it here.')}`,
1564
- );
1565
- writeln(
1566
- ` ${dim("Signed in on the wrong device, or want a fresh start?")} ${bold("[X]")} ${dim("signs out — next paste provisions a fresh device.")}`,
1567
- );
1568
- } else {
1569
- writeln(` ${bold("Log in to submit to board")}`);
1570
- writeln(` ${hr()}`);
1571
- writeln(` ${dim("status:")} ${red("not signed in")}`);
1572
- writeln();
1573
- writeln(` ${dim("Paste your key, then")} ${bold("[Enter]")}${dim(":")}`);
1574
- }
1575
- writeln(` ${cyan(">")} ${codeBuf}${dim("▏")}`);
1576
- writeln();
1577
- writeln(
1578
- ` ${dim('Get a key at signalaf.com → Settings → "New key" (or "Generate connect code").')}`,
1579
- );
1580
- if (msg) {
1581
- writeln();
1582
- writeln(` ${msg}`);
1583
- }
1584
- }
1585
-
1586
- // ── TAB 4: WATCH (live grid) ──────────────────────────────────────────────────
1587
- // A5 (2026-06-27): renders ALL active platforms × ALL windows by default (mirror the cli.mjs
1588
- // watch grid), instead of a single platform/window. `platform`/`win` are OPTIONAL focus filters —
1589
- // null/'all'/'all-windows' means "everything". Each row is a (platform, window) cascade cell:
1590
- // Υ Yield + SNR/Lev/Vel/class. Iterates active platforms (input+output > 0 in any window).
1591
- async function renderWatch(platform = "all", win = "all-windows") {
1592
- const { tokenpullAny } = await import("./tokenpull.mjs");
1593
- const ALL_PLATFORMS = [
1594
- "claude",
1595
- "codex",
1596
- "amp",
1597
- "gemini",
1598
- "kimi",
1599
- "qwen",
1600
- "goose",
1601
- "kilo",
1602
- "hermes",
1603
- "droid",
1604
- "codebuff",
1605
- "copilot",
1606
- "openclaw",
1607
- "pi",
1608
- ];
1609
- const platFilter = platform && platform !== "all" ? platform : null;
1610
- const winFilter = win && win !== "all-windows" ? win : null;
1611
- const WINS = winFilter ? [winFilter] : ["7d", "30d", "90d", "all"];
1612
- const w = W();
1613
- const budget = H() - 4;
1614
- let used = 0;
1615
- const emit = (s = "") => {
1616
- if (used < budget) {
1617
- writeln(s);
1618
- used++;
1619
- }
1620
- };
1621
-
1622
- // Detect active platforms (any window with input+output > 0), respecting an optional [P] focus.
1623
- const candidates = platFilter ? [platFilter] : ALL_PLATFORMS;
1624
- const settled = await Promise.allSettled(
1625
- candidates.map((p) => tokenpullAny(p)),
1626
- );
1627
- const active = [];
1628
- for (const r of settled) {
1629
- if (r.status !== "fulfilled" || !r.value) continue;
1630
- const d = r.value;
1631
- if (
1632
- (d.windows || []).some((ww) => ww.pillars.input + ww.pillars.output > 0)
1633
- )
1634
- active.push(d);
1635
- }
1636
- // stable display order
1637
- active.sort(
1638
- (a, b) =>
1639
- ALL_PLATFORMS.indexOf(a.platform) - ALL_PLATFORMS.indexOf(b.platform),
1640
- );
1641
-
1642
- const scopeLabel =
1643
- (platFilter || "all active platforms") +
1644
- " · " +
1645
- (winFilter ? `${winFilter} window` : "all windows");
1646
- emit();
1647
- emit(` ${bold("Live Watch")} ${dim(scopeLabel)}`);
1648
- emit(` ${dim("·".repeat(Math.min(w - 4, 80)))}`);
1649
-
1650
- if (active.length === 0) {
1651
- emit();
1652
- emit(
1653
- ` ${dim(" no active platforms detected — run some sessions, this picks them up automatically")}`,
1654
- );
1655
- return;
1656
- }
1657
-
1658
- for (const d of active) {
1659
- if (used >= budget - 1) break;
1660
- const byWin = {};
1661
- for (const ww of d.windows || []) byWin[ww.window] = ww;
1662
- emit();
1663
- emit(` ${cyan(d.platform)}${d.estimated ? dim(" (est)") : ""}`);
1664
- for (const wk of WINS) {
1665
- if (used >= budget - 1) break;
1666
- const ww = byWin[wk];
1667
- const cas = ww ? cascadeFrom(ww.pillars) : null;
1668
- const winLabel = wk === "all" ? "all-time" : wk;
1669
- if (!cas) {
1670
- emit(` ${padEnd(dim(winLabel), 9)} ${dim("no data")}`);
1671
- continue;
1672
- }
1673
- const clsFn = CLS[cas.class] ?? ((s) => s);
1674
- const yDisplay =
1675
- cas.yield > 1000 ? gold(fmtY(cas.yield)) : cyan(fmtY(cas.yield));
1676
- const metrics = `${dim("SNR")} ${fmtSNR(cas.snr)} ${dim("Lev")} ${cas.leverage != null ? fmtLev(cas.leverage) + "×" : "—"} ${dim("Vel")} ${cas.velocity != null ? cas.velocity.toFixed(2) : "—"} ${clsFn(cas.class)}`;
1677
- emit(
1678
- ` ${padEnd(dim(winLabel), 9)} ${bold("Υ")} ${yDisplay} ${metrics}`,
1679
- );
1680
- }
1681
- }
1682
- }
1683
-
1684
- // ── SUBMIT PREVIEW (FIX I1 / FIX E) — see→confirm→send ───────────────────────
1685
- // Renders a platform × window grid of what submit_verified WOULD send, using the
1686
- // already-loaded dashData. [Enter] confirms → fires submit_verified per platform;
1687
- // [Esc] cancels → back to the read tab. Mirrors the Connect focused-field pattern.
1688
- function renderSubmitPreview(dashData, id) {
1689
- const budget = H() - 4;
1690
- let used = 0;
1691
- const emit = (s = "") => {
1692
- if (used < budget) {
1693
- writeln(s);
1694
- used++;
1695
- }
1696
- };
1697
- const WINS = ["7d", "30d", "90d", "all"];
1698
- const COL_W = 14;
1699
-
1700
- emit();
1701
- emit(` ${bold("Submit Preview")} ${dim("what will publish to the board")}`);
1702
- emit(
1703
- ` ${dim(`signed in as ${id?.codename ?? "—"} · device ${id?.device_id?.slice(0, 8) ?? "—"}…`)}`,
1704
- );
1705
- emit();
1706
- // header row: platform | 7d | 30d | 90d | all
1707
- const hcols = [
1708
- padEnd(hdr("Platform"), 12),
1709
- ...WINS.map((w) => padStart(hdr(w), COL_W)),
1710
- ];
1711
- emit(` ${hcols.join(" ")}`);
1712
- emit(
1713
- ` ${dim("·".repeat(Math.min(W() - 4, 12 + WINS.length * (COL_W + 2))))}`,
1714
- );
1715
-
1716
- const active = dashData?.active ?? [];
1717
- for (const d of active) {
1718
- if (used >= budget - 3) break;
1719
- const cells = WINS.map((w) => {
1720
- const wd = d.windows?.find((x) => x.window === w);
1721
- if (!wd || wd.pillars.input + wd.pillars.output === 0)
1722
- return padStart(dim("—"), COL_W);
1723
- const cas = cascadeFrom(wd.pillars);
1724
- if (!cas) return padStart(dim("—"), COL_W);
1725
- return padStart(gold(fmtY(cas.yield)), COL_W);
1726
- });
1727
- emit(` ${padEnd(cyan(d.platform), 12)} ${cells.join(" ")}`);
1728
- }
1729
- if (active.length === 0) {
1730
- emit(` ${dim(" no platforms with data — press [R] to refresh")}`);
1731
- }
1732
- emit();
1733
- emit(
1734
- ` ${dim("[Enter]")} confirm + submit all platforms ${dim("[Esc]")} cancel`,
1735
- );
1736
- }
1737
-
1738
- // ── DEBUG: render a tab once (no TTY/alt-screen) + audit each line's visible
1739
- // width vs terminal columns. Usage: `node tui.mjs --render [0|1|2]`. Prints a
1740
- // width report (>w = would overflow/wrap) then the raw frame. For diagnosing
1741
- // layout overflow without an interactive session.
1742
- async function renderOnce(tabIdx = 0) {
1743
- const w = W();
1744
- const data = {
1745
- 0: await loadDashboardData().catch((e) => ({ error: e.message })),
1746
- 1: await loadCompareData("claude").catch(() => null),
1747
- 2: await loadBoardData("30d").catch(() => null),
1748
- }[tabIdx];
1749
- startBuffer();
1750
- if (tabIdx === 0) renderDashboard(data, "debug");
1751
- else if (tabIdx === 1) renderCompare(data);
1752
- else if (tabIdx === 2) renderBoard(data, "30d");
1753
- else if (tabIdx === 4) await renderWatch("all", "all-windows");
1754
- else if (tabIdx === 5) renderConnect(loadIdentity(), "", "");
1755
- const lines = _screenBuf || [];
1756
- _screenBuf = null;
1757
- _footerBuf = null;
1758
- process.stdout.write(
1759
- `\n=== WIDTH AUDIT (terminal w=${w}) — lines exceeding w wrap/overflow ===\n`,
1760
- );
1761
- lines.forEach((ln, i) => {
1762
- const vis = stripAnsi(ln).length;
1763
- if (vis > w)
1764
- process.stdout.write(
1765
- ` OVERFLOW line ${i}: visible=${vis} (>${w} by ${vis - w}) «${stripAnsi(ln).slice(0, 60)}…»\n`,
1766
- );
1767
- });
1768
- const maxVis = Math.max(0, ...lines.map((l) => stripAnsi(l).length));
1769
- process.stdout.write(
1770
- ` widest visible line = ${maxVis} (terminal w=${w}) → ${maxVis > w ? "OVERFLOWS" : "fits"}\n`,
1771
- );
1772
- process.stdout.write(`\n=== RAW FRAME (stripAnsi) ===\n`);
1773
- lines.forEach((ln) => process.stdout.write(stripAnsi(ln) + "\n"));
1774
- }
1775
-
1776
- // ── OPENING SPLASH ───────────────────────────────────────────────────────────
1777
- // Block-letter SIGRANK wordmark that flashes through colors CONTINUOUSLY until a
1778
- // key is pressed (owner 2026-06-25: "keep the animation going"). Randomizes the
1779
- // mode each launch (moses gold-shimmer / rainbow / chaos per-letter). Centered to
1780
- // terminal width. Any key dismisses → the dashboard loads.
1781
- const SPLASH_ART = [
1782
- "███████ ██ ██████ ██████ █████ ███ ██ ██ ██",
1783
- "██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ",
1784
- "███████ ██ ██ ███ ██████ ███████ ██ ██ ██ █████ ",
1785
- " ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ",
1786
- "███████ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██",
1787
- ];
1788
- const SPLASH_RULE = "◈ ─────────────────────────────────────────── ◈";
1789
- const MOSES_PAL = [220, 178, 214, 208, 222, 230];
1790
- const RAINBOW_PAL = [196, 202, 226, 46, 51, 21, 201, 213];
1791
- const col256 = (n, s) => `${ESC}38;5;${n}m${s}${c.reset}`;
1792
- const stripA = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
1793
- const ctr = (s) => {
1794
- const pad = Math.max(0, Math.floor((W() - stripA(s).length) / 2));
1795
- return " ".repeat(pad) + s;
1796
- };
1797
-
1798
- function splashFrame(mode) {
1799
- const pick = (a) => a[Math.floor(Math.random() * a.length)];
1800
- const out = ["", "", ctr(dim(SPLASH_RULE)), ""];
1801
- for (const line of SPLASH_ART) {
1802
- if (mode === "chaos") {
1803
- out.push(
1804
- ctr(
1805
- [...line]
1806
- .map((ch) =>
1807
- ch === " " ? " " : col256(Math.floor(Math.random() * 256), ch),
1808
- )
1809
- .join(""),
1810
- ),
1811
- );
1812
- } else {
1813
- const n = mode === "rainbow" ? pick(RAINBOW_PAL) : pick(MOSES_PAL);
1814
- out.push(ctr(col256(n, line)));
1815
- }
1816
- }
1817
- out.push("", ctr(dim(SPLASH_RULE)), "");
1818
- out.push(ctr(bold("For all builders, burners and 10xers")));
1819
- out.push(ctr(dim("signalaf")), "");
1820
- out.push(ctr(`${dim("powered by")} ${gold("MO§ES™")}`));
1821
- out.push(ctr(dim("$ npx sigrank")), "");
1822
- out.push(ctr(`${gold("▸")} ${dim("press any key")} ${gold("◂")}`));
1823
- return out.join("\n");
1824
- }
1825
-
1826
- // Animated splash. Controls: [P] pause/resume the color animation · [Enter] (or
1827
- // any other key) enter the TUI · Ctrl-C quit. Mode (moses/rainbow/chaos) varies
1828
- // per launch. Frozen frame keeps the last colors so a pause reads as intentional.
1829
- function showSplash() {
1830
- const modes = ["moses", "rainbow", "chaos"];
1831
- const mode = modes[Math.floor((Date.now() / 1000) % modes.length)];
1832
- return new Promise((resolve) => {
1833
- let paused = false;
1834
- const interactive = !!process.stdin.isTTY; // can we read raw keypresses to dismiss?
1835
- const hint = () =>
1836
- interactive
1837
- ? `${dim(" [P]")} ${paused ? "resume" : "pause"} ${dim("[Enter]")} enter`
1838
- : dim(" loading…");
1839
- // FIXED-WINDOW FIX (2026-06-27): paint the splash via the buffered flushScreen
1840
- // path (GOTO positioning), NOT raw write('\n'). Raw \n scrolls the alt-screen
1841
- // buffer, creating scrollback above the TUI — that's why you could scroll up
1842
- // to see what was above it. flushScreen uses absolute cursor positioning so
1843
- // nothing ever scrolls the buffer. This matches how tokscale renders its frame.
1844
- const paint = () => {
1845
- startBuffer();
1846
- const lines = splashFrame(mode).split("\n");
1847
- lines.forEach((ln) => writeln(ln));
1848
- writeln(ctr(hint()));
1849
- setFooter([]);
1850
- flushScreen();
1851
- };
1852
- paint();
1853
- let timer = setInterval(paint, 110);
1854
-
1855
- // Non-interactive stdin (some IDE/integrated terminals): still SHOW the animated
1856
- // wordmark, but auto-advance after a short run instead of waiting for a key (which
1857
- // would never arrive → hang). ~2.2s of animation, then enter the TUI.
1858
- if (!interactive) {
1859
- setTimeout(() => {
1860
- clearInterval(timer);
1861
- write(CLEAR);
1862
- resolve();
1863
- }, 2200);
1864
- return;
1865
- }
1866
-
1867
- process.stdin.setRawMode?.(true);
1868
- process.stdin.resume();
1869
- process.stdin.setEncoding("utf8");
1870
- const onKey = (key) => {
1871
- const k = key.toLowerCase();
1872
- if (k === "p") {
1873
- // toggle pause — don't enter
1874
- paused = !paused;
1875
- if (paused) {
1876
- clearInterval(timer);
1877
- timer = null;
1878
- paint();
1879
- } // freeze on current frame
1880
- else {
1881
- timer = setInterval(paint, 110);
1882
- } // resume animating
1883
- return;
1884
- }
1885
- if (timer) clearInterval(timer);
1886
- process.stdin.removeListener("data", onKey);
1887
- if (key === "\x03") {
1888
- write(SHOW);
1889
- write(EXIT_ALT);
1890
- process.exit(0);
1891
- } // Ctrl-C
1892
- resolve(); // Enter / any other key → enter the TUI
1893
- };
1894
- process.stdin.on("data", onKey);
1895
- });
1896
- }
1897
-
1898
- // ── MAIN TUI LOOP ─────────────────────────────────────────────────────────────
1899
- export async function runTui({
1900
- platform: initPlatform = "claude",
1901
- window: win = "7d",
1902
- } = {}) {
1903
- // FIX J: platform is mutable — [P] cycles it on Compare + Watch tabs. Was a const
1904
- // param (permanently locked to 'claude'); now a let so the user can switch + [S]
1905
- // submits the selected platform (needed for Phase 4 multi-platform submit).
1906
- let platform = initPlatform;
1907
- // Debug render mode — non-interactive, dumps a tab + width audit, then exits.
1908
- const ri = process.argv.indexOf("--render");
1909
- if (ri !== -1) {
1910
- const tab = parseInt(process.argv[ri + 1] ?? "0", 10) || 0;
1911
- await renderOnce(tab);
1912
- return;
1913
- }
1914
-
1915
- write(ENTER_ALT); // switch to alternate screen — original terminal state preserved on exit
1916
- write(CLEAR_SB); // FIXED-WINDOW (2026-06-27): clear scrollback so nothing is above the TUI
1917
- write(HIDE);
1918
- write(CLEAR);
1919
-
1920
- // Opening splash — animated SIGRANK wordmark.
1921
- // Gate on stdOUT.isTTY (can we draw the animation?), matching the launch guard —
1922
- // NOT stdin.isTTY, which was skipping the splash in terminals whose input isn't a
1923
- // raw TTY (some IDE/integrated terminals). showSplash() itself auto-advances when
1924
- // stdin can't be read raw, so it never hangs. (Skippable with --no-splash.)
1925
- if (!process.argv.includes("--no-splash") && process.stdout.isTTY) {
1926
- await showSplash();
1927
- write(CLEAR);
1928
- }
1929
-
1930
- // ── State
1931
- let activeTab = 0;
1932
- let dashData = null;
1933
- let compareData = null;
1934
- let boardData = null;
1935
- let boardWindow = "30d";
1936
- // A5 (2026-06-27): Watch defaults to "all" focus — all active platforms × all windows. [P]/[W]
1937
- // optionally narrow the focus and cycle back to 'all'. ('all-windows' is the window sentinel so
1938
- // it never collides with the real 'all' window bucket in the cli watcher's optional --window.)
1939
- let watchPlatform = "all";
1940
- let watchWindow = "all-windows";
1941
- let watchRefresh = 30; // [5] Watch poll interval (seconds) — [+]/[-] adjust
1942
- let trendSub = 0; // [2] Trends sub-view index (You/Platform/Field) — [T] cycles
1943
- let loading = true;
1944
- let status = "loading…";
1945
- let refreshTimer = null;
1946
- let codeBuf = ""; // [6] Connect tab in-place code field buffer
1947
- let connectMsg = ""; // [6] Connect last-action message (signed in / invalid code)
1948
- let submitMsg = ""; // [S] in-place submit result, shown in the read-tab footer
1949
- let submitPreview = false; // FIX I1: [S] opens a preview grid before sending (see→confirm→send)
1950
- let boardYouOnly = false; // FIX I2: [Y] toggles the Board to "just me" (hybrid model)
1951
- let cascadeScroll = 0; // SCROLL-VIEW (2026-06-27): cascade-section scroll offset (Dashboard only)
1952
-
1953
- // ── Redraw (buffered: renders into memory, then paints as a locked frame)
1954
- const redraw = async () => {
1955
- startBuffer();
1956
- renderTabBar(activeTab);
1957
-
1958
- const hint = ` ${dim("← → or 1-6")} switch tabs ${dim("[R]")} refresh ${dim("[Q]")} quit`;
1959
- const submitHint = ` ${dim("[S]")} submit to board · ${dim("[C]")} sign in`;
1960
- // Read-tab footer: hr + hint, plus the in-place submit result line when present.
1961
- const readFooter = (hintLine) =>
1962
- submitMsg
1963
- ? [` ${hr()}`, hintLine, ` ${submitMsg}`]
1964
- : [` ${hr()}`, hintLine];
1965
-
1966
- // FIX I1: submit preview is a focused overlay — renders INSTEAD of the tab
1967
- // content, with its own footer. [Enter] sends, [Esc] cancels.
1968
- if (submitPreview) {
1969
- renderSubmitPreview(dashData, loadIdentity());
1970
- setFooter([
1971
- ` ${hr()}`,
1972
- ` ${dim("[Enter]")} submit all platforms ${dim("[Esc]")} cancel ${dim("[Q]")} quit`,
1973
- ]);
1974
- flushScreen();
1975
- return;
1976
- }
1977
-
1978
- if (activeTab === 0) {
1979
- // Dashboard
1980
- if (!dashData) {
1981
- writeln(`\n ${dim("loading dashboard…")}`);
1982
- } else {
1983
- renderDashboard(dashData, status, cascadeScroll);
1984
- }
1985
- // SCROLL-VIEW: show ↑↓ hint only when there are cascade rows to scroll
1986
- const scrollHint =
1987
- dashData && Array.isArray(dashData.active)
1988
- ? cascadeScrollableCount(dashData.active) >
1989
- maxCascadeRowsFor(dashData.active)
1990
- ? ` ${dim("↑↓ scroll cascade")}`
1991
- : ""
1992
- : "";
1993
- setFooter(readFooter(`${hint}${scrollHint}${submitHint}`));
1994
- } else if (activeTab === 1) {
1995
- // Trends
1996
- if (!dashData) {
1997
- writeln(`\n ${dim("loading trends…")}`);
1998
- } else {
1999
- renderTrends(dashData, trendSub);
2000
- }
2001
- setFooter(readFooter(`${hint} ${dim("[T]")} view${submitHint}`));
2002
- } else if (activeTab === 2) {
2003
- // Compare
2004
- if (!compareData) {
2005
- // #9 (2026-06-27): Compare runs a FRESH on-demand pull of the external verifier sources
2006
- // (ccusage + tokscale + token-dashboard rescan) — it can take several seconds. Show a clear
2007
- // spinner line while it runs, instead of a bare "loading…".
2008
- writeln(
2009
- `\n ${bold("Source Comparison")} ${dim(`platform: ${platform}`)}`,
2010
- );
2011
- writeln(
2012
- `\n ${gold("◇")} ${dim(`pulling fresh sources… (ccusage · tokscale · token-dash — this can take several seconds)`)}`,
2013
- );
2014
- } else {
2015
- renderCompare(compareData);
2016
- }
2017
- setFooter(
2018
- readFooter(`${hint} ${dim("[P]")} switch platform${submitHint}`),
2019
- );
2020
- } else if (activeTab === 3) {
2021
- // Board
2022
- if (!boardData) {
2023
- writeln(`\n ${dim(`loading board (${boardWindow})…`)}`);
2024
- } else {
2025
- // FIX I2: hybrid board model — global board + your row highlighted, [Y]
2026
- // toggles "just me" (your placements only). Pass the signed-in codename so
2027
- // renderBoard can highlight/filter.
2028
- const id = loadIdentity();
2029
- renderBoard(
2030
- boardData,
2031
- boardWindow,
2032
- boardYouOnly ? id?.codename : null,
2033
- id?.codename ?? null,
2034
- );
2035
- }
2036
- const youHint = isSignedIn(loadIdentity())
2037
- ? ` ${dim("[Y]")} ${boardYouOnly ? "all" : "just me"}`
2038
- : "";
2039
- setFooter(
2040
- readFooter(`${hint} ${dim("[W]")} window${youHint}${submitHint}`),
2041
- );
2042
- } else if (activeTab === 4) {
2043
- // Watch
2044
- renderWatchInfo(watchPlatform, watchWindow, watchRefresh);
2045
- setFooter(readFooter(`${hint}${submitHint}`));
2046
- } else if (activeTab === 5) {
2047
- // Connect
2048
- const connectId = loadIdentity();
2049
- renderConnect(connectId, codeBuf, connectMsg);
2050
- const signOutHint = isSignedIn(connectId)
2051
- ? ` ${dim("[X]")} sign out`
2052
- : " " + dim("[X]") + " reset device";
2053
- setFooter([
2054
- ` ${hr()}`,
2055
- ` ${dim("[Enter]")} sign in ${dim("[Esc]")} clear/back${signOutHint} ${dim("← →")} tabs ${dim("[Q]")} quit`,
2056
- ]);
2057
- }
2058
- flushScreen();
2059
- };
2060
-
2061
- // ── Initial data load
2062
- const loadAll = async () => {
2063
- // A2 (2026-06-27): paint the frame + a clear "reading your cascade…" status IMMEDIATELY,
2064
- // BEFORE the await — so the very first thing on screen is the table header + a live status,
2065
- // not a blank "loading dashboard…". renderDashboard tolerates this empty dashData (guarded).
2066
- status = "reading your cascade…";
2067
- dashData = { active: [], _loading: true };
2068
- await redraw();
2069
- // FIX 0: progressive Dashboard load — claude first (fast), render it, THEN fill
2070
- // the other 13 platforms in the background + redraw. The user sees their cascade
2071
- // within ~1 read instead of a 7s blank "loading dashboard…".
2072
- dashData = await loadDashboardData().catch((e) => {
2073
- status = `dashboard error: ${e.message}`;
2074
- return null;
2075
- });
2076
- status = `last refreshed ${new Date().toLocaleTimeString("en-US", { hour12: false })}`;
2077
- await redraw();
2078
- // Keep a "filling other platforms…" status visible while fillDashboardRest runs.
2079
- // #9 (2026-06-27): Compare is NO LONGER eagerly loaded here — loadCompareData now runs the
2080
- // FRESH verifier pull (ccusage + tokscale + token-dash rescan, 5–60s), which would re-introduce
2081
- // a slow Dashboard load path. Compare loads lazily ON-DEMAND when the Compare tab is opened.
2082
- // Board still preloads (fast, cached) in parallel with the platform fill.
2083
- if (dashData?._remaining) {
2084
- status = "claude ready · filling other platforms…";
2085
- await redraw();
2086
- }
2087
- [, boardData] = await Promise.all([
2088
- dashData?._remaining
2089
- ? fillDashboardRest(dashData)
2090
- : Promise.resolve(false),
2091
- loadBoardData(boardWindow).catch(() => null),
2092
- ]);
2093
- status = `last refreshed ${new Date().toLocaleTimeString("en-US", { hour12: false })}`;
2094
- await redraw();
2095
- };
2096
-
2097
- // Always restore terminal on unexpected exit
2098
- const cleanup = () => {
2099
- write(SHOW);
2100
- write(EXIT_ALT);
2101
- process.exit(0);
2102
- };
2103
- process.once("SIGINT", cleanup);
2104
- process.once("SIGTERM", cleanup);
2105
-
2106
- // FIX 0b: re-render on terminal resize so the frame refits the new dimensions.
2107
- process.stdout.on("resize", () => {
2108
- redraw().catch(() => {});
2109
- });
2110
-
2111
- // Soft-landing: if not signed in, open on the Connect tab (a prompt, not a gate —
2112
- // the user can still tab away to read Board/Dashboard while signed out).
2113
- if (!isSignedIn(loadIdentity())) activeTab = 5;
2114
-
2115
- // Draw loading state immediately so user sees tab bar + border
2116
- await redraw();
2117
- await loadAll();
2118
-
2119
- // auto-refresh board every 30s
2120
- const startAutoRefresh = () => {
2121
- if (refreshTimer) clearInterval(refreshTimer);
2122
- refreshTimer = setInterval(async () => {
2123
- if (activeTab === 3) {
2124
- // Board tab (now index 3)
2125
- boardData = await loadBoardData(boardWindow).catch(() => null);
2126
- await redraw();
2127
- }
2128
- }, 30000);
2129
- };
2130
- startAutoRefresh();
2131
-
2132
- // ── Keyboard
2133
- if (!process.stdin.isTTY) return;
2134
-
2135
- process.stdin.setRawMode(true);
2136
- process.stdin.resume();
2137
- process.stdin.setEncoding("utf8");
2138
-
2139
- // Esc-sequence buffer: some terminals (SSH, tmux, certain emulators) split an
2140
- // arrow key (\x1b[C) into two data events: \x1b then [C. Without buffering, the
2141
- // lone \x1b triggers the Esc handler (clearing the code buffer / leaving the tab)
2142
- // before the [C arrives. We hold \x1b for 25ms; if more bytes follow, we
2143
- // reassemble and deliver the full sequence. If nothing follows, it's a real Esc.
2144
- let escBuf = null;
2145
- let escTimer = null;
2146
- const ESC_HOLD_MS = 25;
2147
-
2148
- await new Promise((resolve) => {
2149
- const handleKey = async (key) => {
2150
- const k = key.toLowerCase();
2151
-
2152
- if (k === "q" || k === "\x03") {
2153
- if (refreshTimer) clearInterval(refreshTimer);
2154
- write(SHOW);
2155
- write(EXIT_ALT);
2156
- resolve();
2157
- return;
2158
- }
2159
-
2160
- // ── Connect tab is a FOCUSED code field (the one modal tab). Printable code
2161
- // chars feed the buffer; Enter signs in; Esc clears or leaves; arrows switch.
2162
- // Sits AFTER the quit block (so Q/Ctrl-C always escape) and BEFORE everything
2163
- // else (so single-letter hotkeys don't fire while you're typing a code).
2164
- if (activeTab === 5) {
2165
- if (key === "\r" || key === "\n") {
2166
- // [Enter] → sign in
2167
- const code = codeBuf.trim();
2168
- if (!code) {
2169
- connectMsg = dim("paste a connect code first");
2170
- await redraw();
2171
- return;
2172
- }
2173
- connectMsg = dim("signing in…");
2174
- await redraw();
2175
- try {
2176
- const out = await callTool("enroll", { code });
2177
- if (out.status === "enrolled") {
2178
- connectMsg = out.recovered
2179
- ? `${green("✓")} recovered account: ${cyan(out.codename || "(operator)")} ${dim("(device was already bound)")}`
2180
- : `${green("✓")} signed in as ${cyan(out.codename || "(operator)")}`;
2181
- codeBuf = "";
2182
- } else {
2183
- const reasons = {
2184
- code_invalid:
2185
- "that code is invalid, expired, or already used — generate a fresh one.",
2186
- device_already_enrolled:
2187
- 'this device is already bound. Press [X] to reset the device, then paste a fresh code from signalaf.com → Settings → "New key".',
2188
- bad_request: "the code or device key was malformed.",
2189
- rate_limited:
2190
- "too many attempts — wait a few minutes and retry.",
2191
- persistence_unavailable:
2192
- "sign-in is temporarily unavailable — try again shortly.",
2193
- };
2194
- connectMsg = `${red("✗")} ${reasons[out.reason] || `sign-in failed (${out.reason || "unknown"}).`}`;
2195
- codeBuf = ""; // auto-clear on failure — the code is consumed/invalid
2196
- }
2197
- } catch (e) {
2198
- connectMsg = `${red("✗")} ${e.message}`;
2199
- codeBuf = ""; // auto-clear on error too
2200
- }
2201
- await redraw();
2202
- return;
2203
- }
2204
- if (key === "\x1b") {
2205
- // [Esc] → clear, or leave when empty
2206
- if (codeBuf) {
2207
- codeBuf = "";
2208
- connectMsg = "";
2209
- } else {
2210
- activeTab = 0;
2211
- }
2212
- await redraw();
2213
- return;
2214
- }
2215
- if (key === "\x1b[C") {
2216
- activeTab = Math.min(5, activeTab + 1);
2217
- await redraw();
2218
- return;
2219
- } // → tab
2220
- if (key === "\x1b[D") {
2221
- activeTab = Math.max(0, activeTab - 1);
2222
- await redraw();
2223
- return;
2224
- } // ← tab
2225
- if (key === "\x7f" || key === "\b") {
2226
- codeBuf = codeBuf.slice(0, -1);
2227
- await redraw();
2228
- return;
2229
- } // backspace
2230
- // [X] sign out / reset — only when the code field is empty (so 'x'/'X' typed
2231
- // mid-code still feeds the buffer — codes can contain X). The auto-clear on
2232
- // sign-in failure (above) ensures the buffer is empty after a failed attempt,
2233
- // so X works immediately when the user wants to reset. Drops the local
2234
- // credential so a server-revoked OR server-enrolled-but-locally-unbound device
2235
- // stops holding a stale device_id, and the next enroll provisions a fresh
2236
- // device_id (escapes the Frankenstein-identity / 409-re-enroll deadlock).
2237
- if (k === "x" && !codeBuf) {
2238
- const wasSignedIn = isSignedIn(loadIdentity());
2239
- clearIdentity();
2240
- codeBuf = "";
2241
- connectMsg = wasSignedIn
2242
- ? `${green("✓")} signed out — paste a new code to sign in`
2243
- : `${green("✓")} device reset — paste a new code to sign in`;
2244
- await redraw();
2245
- return;
2246
- }
2247
- // A typed code char (len 1) or a pasted code (one multi-char chunk). Exclude any
2248
- // escape sequence (↑/↓/etc.) so stray control bytes never pollute the buffer.
2249
- if (!key.startsWith("\x1b") && (key.length > 1 || isCodeChar(key))) {
2250
- codeBuf += key.split("").filter(isCodeChar).join("");
2251
- await redraw();
2252
- return;
2253
- }
2254
- return; // swallow any other key while focused (never falls through to global hotkeys)
2255
- }
2256
-
2257
- // FIX I1: submit preview is a focused overlay (like Connect). [Enter] sends
2258
- // all platforms, [Esc] cancels. Intercepts keys BEFORE the tab/ESC handlers.
2259
- if (submitPreview) {
2260
- if (key === "\r" || key === "\n") {
2261
- // [Enter] → confirm + submit all platforms
2262
- submitPreview = false;
2263
- submitMsg = dim("submitting…");
2264
- await redraw();
2265
- const id = loadIdentity();
2266
- if (!isSignedIn(id)) {
2267
- submitMsg = `${red("✗")} sign in to submit`;
2268
- activeTab = 5;
2269
- await redraw();
2270
- return;
2271
- }
2272
- // FIX I1: submit every active platform (data already loaded for the Dashboard).
2273
- // Each platform is a separate submit_verified call → its own (platform, window) slot.
2274
- const platforms = (dashData?.active ?? []).map((d) => d.platform);
2275
- let totalVerified = 0,
2276
- totalReceived = 0,
2277
- hadFail = false,
2278
- didMulti = false;
2279
- for (const p of platforms) {
2280
- try {
2281
- const out = await callTool("submit_verified", { platform: p });
2282
- const ws = out.windows || [];
2283
- const received = ws.filter((w) => w.status === "received");
2284
- const verified = received.filter(
2285
- (w) => w.verification_tier === "verified",
2286
- );
2287
- totalReceived += received.length;
2288
- totalVerified += verified.length;
2289
- if (received.length > 0 && verified.length < received.length)
2290
- hadFail = true;
2291
- } catch {
2292
- hadFail = true;
2293
- }
2294
- }
2295
- // MULTI: the combined cross-platform cascade (claude+codex+… summed). Only
2296
- // meaningful with 2+ active platforms; submit_verified('multi') aggregates them.
2297
- if (platforms.length >= 2) {
2298
- try {
2299
- const out = await callTool("submit_verified", {
2300
- platform: "multi",
2301
- });
2302
- const ws = out.windows || [];
2303
- const received = ws.filter((w) => w.status === "received");
2304
- const verified = received.filter(
2305
- (w) => w.verification_tier === "verified",
2306
- );
2307
- totalReceived += received.length;
2308
- totalVerified += verified.length;
2309
- if (received.length > 0 && verified.length < received.length)
2310
- hadFail = true;
2311
- if (received.length > 0) didMulti = true;
2312
- } catch {
2313
- hadFail = true;
2314
- }
2315
- }
2316
- if (totalReceived && !hadFail && totalVerified === totalReceived) {
2317
- submitMsg = `${green("✓")} submitted · ${totalVerified} window${totalVerified > 1 ? "s" : ""} across ${platforms.length} platform${platforms.length > 1 ? "s" : ""}${didMulti ? " + combined" : ""} · verified`;
2318
- } else if (hadFail && totalReceived) {
2319
- submitMsg = `${red("✗")} device not verified — sign in again ([C])`;
2320
- } else if (totalReceived === 0) {
2321
- submitMsg = `${red("✗")} nothing to submit — no windows with data`;
2322
- } else {
2323
- submitMsg = `${red("✗")} submit failed`;
2324
- }
2325
- await redraw();
2326
- return;
2327
- }
2328
- if (key === "\x1b") {
2329
- // [Esc] → cancel
2330
- submitPreview = false;
2331
- await redraw();
2332
- return;
2333
- }
2334
- return; // swallow all other keys while the preview is open
2335
- }
2336
-
2337
- // ESC → go back to Dashboard from any tab
2338
- if (key === "\x1b" && activeTab !== 0) {
2339
- activeTab = 0;
2340
- await redraw();
2341
- return;
2342
- }
2343
-
2344
- // SCROLL-VIEW (2026-06-27): ↑/↓ (or j/k) scroll the cascade section on the
2345
- // Dashboard tab ONLY. The rest of the dashboard stays pinned. Only active
2346
- // when there are more cascade rows than fit in the viewport.
2347
- if (activeTab === 0 && dashData && Array.isArray(dashData.active)) {
2348
- const total = cascadeScrollableCount(dashData.active);
2349
- const maxRows = maxCascadeRowsFor(dashData.active);
2350
- if (total > maxRows) {
2351
- const maxOff = total - maxRows;
2352
- if (key === "\x1b[A" || k === "k") {
2353
- // ↑ / k → scroll up
2354
- cascadeScroll = Math.max(0, cascadeScroll - 1);
2355
- await redraw();
2356
- return;
2357
- }
2358
- if (key === "\x1b[B" || k === "j") {
2359
- // ↓ / j → scroll down
2360
- cascadeScroll = Math.min(maxOff, cascadeScroll + 1);
2361
- await redraw();
2362
- return;
2363
- }
2364
- if (key === "\x1b[5~") {
2365
- // PageUp → scroll up by viewport
2366
- cascadeScroll = Math.max(0, cascadeScroll - maxRows);
2367
- await redraw();
2368
- return;
2369
- }
2370
- if (key === "\x1b[6~") {
2371
- // PageDown → scroll down by viewport
2372
- cascadeScroll = Math.min(maxOff, cascadeScroll + maxRows);
2373
- await redraw();
2374
- return;
2375
- }
2376
- }
2377
- }
2378
-
2379
- // tab switching (6 tabs: 0=Dashboard 1=Trends 2=Compare 3=Board 4=Watch 5=Connect)
2380
- let switched = false;
2381
- if (key === "\x1b[C") {
2382
- activeTab = Math.min(5, activeTab + 1);
2383
- switched = true;
2384
- }
2385
- if (key === "\x1b[D") {
2386
- activeTab = Math.max(0, activeTab - 1);
2387
- switched = true;
2388
- }
2389
- if (k === "1") {
2390
- activeTab = 0;
2391
- switched = true;
2392
- }
2393
- if (k === "2") {
2394
- activeTab = 1;
2395
- switched = true;
2396
- }
2397
- if (k === "3") {
2398
- activeTab = 2;
2399
- switched = true;
2400
- }
2401
- if (k === "4") {
2402
- activeTab = 3;
2403
- switched = true;
2404
- }
2405
- if (k === "5") {
2406
- activeTab = 4;
2407
- switched = true;
2408
- } // Watch = an in-TUI landing panel
2409
- if (k === "6") {
2410
- activeTab = 5;
2411
- switched = true;
2412
- } // Connect = sign in / switch device
2413
- if (k === "c" && activeTab !== 5) {
2414
- activeTab = 5;
2415
- switched = true;
2416
- } // [C] → Connect from any read tab
2417
-
2418
- // SCROLL-VIEW: reset cascade scroll when leaving the Dashboard tab
2419
- if (switched && activeTab !== 0) cascadeScroll = 0;
2420
-
2421
- // #9 (2026-06-27): Compare loads its FRESH verifier pull ON-DEMAND when the tab opens
2422
- // (NOT on the Dashboard load path — that pull is a 5–60s scan). Paint the "pulling fresh
2423
- // sources…" spinner first (compareData null → redraw shows it), then run the pull + re-render.
2424
- // ASYNC FIX (2026-06-27): with execFile (async), the event loop keeps running during the
2425
- // pull — key presses are NOT blocked. Guard: only render the result if the user is still
2426
- // on the Compare tab (they may have switched away during the pull).
2427
- if (switched && activeTab === 2 && !compareData) {
2428
- submitMsg = "";
2429
- await redraw(); // show the spinner line before the (slow) fresh pull
2430
- const result = await loadCompareData(platform).catch(() => null);
2431
- if (activeTab === 2) {
2432
- // still on Compare? render the result
2433
- compareData = result;
2434
- await redraw();
2435
- }
2436
- return;
2437
- }
2438
-
2439
- // Trends tab: [T] cycles the sub-view (You · Platform · Field)
2440
- if (activeTab === 1 && k === "t") {
2441
- trendSub = (trendSub + 1) % 3;
2442
- await redraw();
2443
- return;
2444
- }
2445
-
2446
- // Watch tab: [+]/[-] tune the refresh interval (5–600s), [Enter] launches the watcher
2447
- if (activeTab === 4 && (k === "+" || k === "=")) {
2448
- watchRefresh = Math.min(600, watchRefresh + 5);
2449
- await redraw();
2450
- return;
2451
- }
2452
- if (activeTab === 4 && (k === "-" || k === "_")) {
2453
- watchRefresh = Math.max(5, watchRefresh - 5);
2454
- await redraw();
2455
- return;
2456
- }
2457
-
2458
- // FIX J: [P] cycles platform on Compare + Watch tabs (was a dead hinted key).
2459
- // Compare reloads compareData for the new platform; Watch just re-renders.
2460
- const CYCLE_PLATFORMS = [
2461
- "claude",
2462
- "codex",
2463
- "amp",
2464
- "gemini",
2465
- "kimi",
2466
- "qwen",
2467
- "goose",
2468
- "kilo",
2469
- "hermes",
2470
- "droid",
2471
- "codebuff",
2472
- "copilot",
2473
- "openclaw",
2474
- "pi",
2475
- ];
2476
- if (k === "p" && (activeTab === 2 || activeTab === 4)) {
2477
- if (activeTab === 2) {
2478
- // Compare: real platforms only (no 'all' — Compare is per-platform by design).
2479
- const idx = CYCLE_PLATFORMS.indexOf(platform);
2480
- platform = CYCLE_PLATFORMS[(idx + 1) % CYCLE_PLATFORMS.length];
2481
- // #9: clearing compareData makes redraw show the "pulling fresh sources…" spinner
2482
- // for the new platform while the fresh on-demand verifier pull runs.
2483
- compareData = null;
2484
- status = `loading ${platform}…`;
2485
- await redraw();
2486
- // ASYNC FIX: guard — only render if still on Compare (user may have switched away)
2487
- const result = await loadCompareData(platform).catch(() => null);
2488
- if (activeTab === 2) {
2489
- compareData = result;
2490
- status = `last refreshed ${new Date().toLocaleTimeString("en-US", { hour12: false })}`;
2491
- }
2492
- } else {
2493
- // A5: Watch [P] cycles 'all' → claude → codex → … → 'all' (optional focus; default 'all').
2494
- const WATCH_PLAT_CYCLE = ["all", ...CYCLE_PLATFORMS];
2495
- const idx = WATCH_PLAT_CYCLE.indexOf(watchPlatform);
2496
- watchPlatform = WATCH_PLAT_CYCLE[(idx + 1) % WATCH_PLAT_CYCLE.length];
2497
- }
2498
- await redraw();
2499
- return;
2500
- }
2501
-
2502
- // FIX J / A5: [W] cycles window FOCUS on the Watch tab. 'all-windows' (default) → 7d → 30d →
2503
- // 90d → all → back to 'all-windows'. Board tab's [W] (activeTab === 3) is handled below.
2504
- if (k === "w" && activeTab === 4) {
2505
- const WATCH_WIN_CYCLE = ["all-windows", "7d", "30d", "90d", "all"];
2506
- const idx = WATCH_WIN_CYCLE.indexOf(watchWindow);
2507
- watchWindow = WATCH_WIN_CYCLE[(idx + 1) % WATCH_WIN_CYCLE.length];
2508
- await redraw();
2509
- return;
2510
- }
2511
-
2512
- if (activeTab === 4 && (key === "\r" || key === "\n")) {
2513
- // A5 (2026-06-27): launch the live watcher in its own window. By default (focus = 'all')
2514
- // pass NO --platform/--window so the cli watcher auto-loads ALL active platforms × ALL
2515
- // windows. Only add a filter flag when the user has set an explicit [P]/[W] focus.
2516
- try {
2517
- let watchCmd = "sigrank watch";
2518
- if (watchPlatform && watchPlatform !== "all")
2519
- watchCmd += ` --platform ${watchPlatform}`;
2520
- if (watchWindow && watchWindow !== "all-windows")
2521
- watchCmd += ` --window ${watchWindow}`;
2522
- watchCmd += ` --refresh ${watchRefresh}`;
2523
- // ASYNC FIX (2026-06-27): execFile instead of execSync — no shell
2524
- // interpolation. osascript args passed as array (defense-in-depth).
2525
- execFile(
2526
- "osascript",
2527
- ["-e", `tell application "Terminal" to do script "${watchCmd}"`],
2528
- { stdio: "ignore" },
2529
- () => {},
2530
- );
2531
- const scope =
2532
- (!watchPlatform || watchPlatform === "all") &&
2533
- (!watchWindow || watchWindow === "all-windows")
2534
- ? "all platforms × all windows"
2535
- : "focused";
2536
- status = `watcher launched (${scope}, ${watchRefresh}s) in a new window`;
2537
- } catch {
2538
- status = "could not open Terminal.app — run: sigrank watch";
2539
- }
2540
- await redraw();
2541
- return;
2542
- }
2543
-
2544
- if (k === "r") {
2545
- status = "refreshing…";
2546
- cascadeScroll = 0; // SCROLL-VIEW: reset scroll on refresh
2547
- // #9: on the Compare tab, [R] re-runs the FRESH verifier pull for the current platform
2548
- // (loadAll no longer touches Compare). Clearing compareData shows the spinner first.
2549
- if (activeTab === 2) {
2550
- compareData = null;
2551
- await redraw();
2552
- // ASYNC FIX: guard — only render if still on Compare
2553
- const result = await loadCompareData(platform).catch(() => null);
2554
- if (activeTab === 2) {
2555
- compareData = result;
2556
- status = `last refreshed ${new Date().toLocaleTimeString("en-US", { hour12: false })}`;
2557
- await redraw();
2558
- }
2559
- return;
2560
- }
2561
- await redraw();
2562
- await loadAll();
2563
- return;
2564
- }
2565
-
2566
- if (k === "s" && activeTab !== 5) {
2567
- // FIX I1/E: [S] opens a submit PREVIEW (see→confirm→send) instead of firing
2568
- // blind. The preview shows a platform × window grid of what will publish;
2569
- // [Enter] sends all platforms, [Esc] cancels. (On the Connect tab, 's' is a
2570
- // code char handled by the focused field above.)
2571
- const id = loadIdentity();
2572
- if (!isSignedIn(id)) {
2573
- // not signed in → open Connect, never error
2574
- activeTab = 5;
2575
- connectMsg = dim("sign in to submit to board");
2576
- await redraw();
2577
- return;
2578
- }
2579
- submitPreview = true;
2580
- submitMsg = "";
2581
- await redraw();
2582
- return;
2583
- }
2584
-
2585
- // FIX I2: [Y] toggles the Board between global+highlighted and "just me"
2586
- // (hybrid model — owner decision 2026-06-26). Only when signed in.
2587
- if (k === "y" && activeTab === 3 && isSignedIn(loadIdentity())) {
2588
- boardYouOnly = !boardYouOnly;
2589
- await redraw();
2590
- return;
2591
- }
2592
-
2593
- if (k === "w" && activeTab === 3) {
2594
- // Board tab (now index 3)
2595
- const windows = ["7d", "30d", "90d", "all"];
2596
- const idx = windows.indexOf(boardWindow);
2597
- boardWindow = windows[(idx + 1) % windows.length];
2598
- boardData = await loadBoardData(boardWindow).catch(() => null);
2599
- }
2600
-
2601
- if (switched) submitMsg = ""; // submit result is tied to the tab it was sent from
2602
- if (switched || k === "w") await redraw();
2603
- };
2604
-
2605
- // Buffered stdin listener: reassembles split Esc sequences before dispatch.
2606
- process.stdin.on("data", (chunk) => {
2607
- // If we have a pending \x1b held from a previous chunk, combine it with
2608
- // this chunk to reassemble the full escape sequence (\x1b + [C = \x1b[C).
2609
- if (escBuf) {
2610
- clearTimeout(escTimer);
2611
- const combined = escBuf + chunk;
2612
- escBuf = null;
2613
- escTimer = null;
2614
- // If the combined result is \x1b followed by more \x1b (rare), just
2615
- // deliver the first as Esc and re-buffer the second. Otherwise deliver
2616
- // the combined sequence.
2617
- if (combined.length > 1) {
2618
- handleKey(combined);
2619
- return;
2620
- }
2621
- // combined is still just \x1b (chunk was empty?) → fall through to hold
2622
- }
2623
-
2624
- // Fast path: chunk doesn't start with \x1b → deliver immediately.
2625
- if (chunk[0] !== "\x1b") {
2626
- handleKey(chunk);
2627
- return;
2628
- }
2629
- // Chunk starts with \x1b and is longer than 1 byte → complete escape
2630
- // sequence → deliver immediately.
2631
- if (chunk.length > 1) {
2632
- handleKey(chunk);
2633
- return;
2634
- }
2635
- // Chunk is exactly \x1b → hold for ESC_HOLD_MS to see if more bytes follow.
2636
- escBuf = chunk;
2637
- escTimer = setTimeout(() => {
2638
- handleKey(escBuf);
2639
- escBuf = null;
2640
- escTimer = null;
2641
- }, ESC_HOLD_MS);
2642
- });
2643
- });
2644
-
2645
- process.stdin.setRawMode(false);
2646
- process.stdin.pause();
2647
- writeln();
2648
- }
2649
-
2650
- // Direct-run entry (e.g. `node tui.mjs --render 0`). Normal launch is via cli.mjs.
2651
- if (import.meta.url === `file://${process.argv[1]}`) {
4
+ import { pathToFileURL } from 'node:url';
5
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) {
2652
6
  runTui().catch((e) => {
2653
7
  console.error(e);
2654
8
  process.exit(1);