sigrank 1.0.52 → 1.0.54

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.
@@ -31,6 +31,13 @@ import { ensureIdentity, keystorePath } from "../keystore.mjs";
31
31
  import { pkgVersion } from "../lib/pkg-version.mjs";
32
32
  import { cachedUpdateNotice, checkForUpdate } from "../lib/update-check.mjs";
33
33
  import { submitSignedWindow } from "../submit.mjs";
34
+ import {
35
+ normalizeSource,
36
+ otelBaseUrl,
37
+ OTEL_SOURCE_TAG,
38
+ sourceMarker,
39
+ } from "../adapters/otel.mjs";
40
+ import { evaluatePublication } from "../submit/publication.mjs";
34
41
  import {
35
42
  LEADERBOARD_METRIC,
36
43
  TOKSCALE_CLIENT_MAP,
@@ -819,12 +826,28 @@ export async function detectActivePulls(platform, opts = {}) {
819
826
  return (await detectActivePullsDetailed(platform, opts)).active;
820
827
  }
821
828
 
829
+ // Per-platform source marker for the watch grid (claude only can be otel-backed).
830
+ function watchSourceNote(d) {
831
+ if (d.source === OTEL_SOURCE_TAG) {
832
+ const m = sourceMarker(d);
833
+ return " " + (evaluatePublication(d).eligible ? green(m) : gold(m));
834
+ }
835
+ if (d.platform === "claude" && d.source === "transcripts")
836
+ return (
837
+ " " +
838
+ dim(`source: transcripts${d.otelFallback ? " (otel unreachable)" : ""}`)
839
+ );
840
+ return "";
841
+ }
842
+
822
843
  async function runWatch({
823
844
  platform,
824
845
  window: win,
825
846
  refresh = 30,
826
847
  submit = false,
848
+ source = "transcripts",
827
849
  } = {}) {
850
+ if (submit && source !== "transcripts") throw new Error("OTEL is preview-only; use --source transcripts to publish.");
828
851
  let lines = 0;
829
852
  const id = submit ? ensureIdentity() : null;
830
853
  const enrolled = !!(
@@ -848,7 +871,7 @@ async function runWatch({
848
871
  const draw = async () => {
849
872
  // Re-pull each tick so a platform that just started writing logs appears automatically.
850
873
  // Scoped by platFilter, so a focused watch never scans platforms it cannot display.
851
- const { active: pulls, failed: failedReads } = await detectActivePullsDetailed(platFilter);
874
+ const { active: pulls, failed: failedReads } = await detectActivePullsDetailed(platFilter, { source });
852
875
 
853
876
  if (lines > 0) write(CURSOR_UP(lines));
854
877
 
@@ -860,7 +883,9 @@ async function runWatch({
860
883
  const scopeLabel =
861
884
  (platFilter || "all active platforms") +
862
885
  " · " +
863
- (winFilter ? `window: ${winFilter}` : "all windows");
886
+ (winFilter ? `window: ${winFilter}` : "all windows") +
887
+ " · " +
888
+ `source: ${source}`;
864
889
 
865
890
  push();
866
891
  push(
@@ -871,6 +896,25 @@ async function runWatch({
871
896
  push(` ${red("!")} ${dim(`could not read ${failedReads.map((f) => f.platform).join(", ")} — totals below exclude it (it is not "no data")`)}`);
872
897
  }
873
898
 
899
+ // --source otel with the collector down: claude drops out of the grid (the pull
900
+ // throws instead of silently falling back) — say so instead of showing nothing.
901
+ if (
902
+ source === "otel" &&
903
+ (!platFilter || platFilter === "claude") &&
904
+ failedReads.some((d) => d.platform === "claude")
905
+ ) {
906
+ let url = "(invalid SIGRANK_OTEL_URL)";
907
+ try {
908
+ url = otelBaseUrl();
909
+ } catch {
910
+ /* keep placeholder */
911
+ }
912
+ push();
913
+ push(
914
+ ` ${red(`source otel: sigrank-otel collector unreachable at ${url}`)} ${dim("— start it or use --source auto")}`,
915
+ );
916
+ }
917
+
874
918
  if (pulls.length === 0) {
875
919
  push();
876
920
  push(
@@ -884,7 +928,9 @@ async function runWatch({
884
928
  const byWin = {};
885
929
  for (const ww of d.windows || []) byWin[ww.window] = ww;
886
930
  push();
887
- push(` ${cyan(plat)}${d.estimated ? dim(" (est)") : ""}`);
931
+ push(
932
+ ` ${cyan(plat)}${d.estimated ? dim(" (est)") : ""}${watchSourceNote(d)}`,
933
+ );
888
934
  for (const wk of windows) {
889
935
  const ww = byWin[wk];
890
936
  const cas = ww ? cascadeFromPillars(ww.pillars) : null;
@@ -907,7 +953,7 @@ async function runWatch({
907
953
  ww.pillars,
908
954
  ww.messages,
909
955
  id,
910
- { platform: plat },
956
+ { platform: plat, turns: ww.turns, sessions: ww.sessions },
911
957
  );
912
958
  // Pass 6: gate the ✓ on r.ranked (verified + persisted), NOT on
913
959
  // r.status === "received". An unenrolled/revoked device gets HTTP
@@ -1454,7 +1500,7 @@ async function runSigRank() {
1454
1500
  ww.pillars,
1455
1501
  ww.messages,
1456
1502
  id,
1457
- { platform: d.platform },
1503
+ { platform: d.platform, turns: ww.turns, sessions: ww.sessions },
1458
1504
  );
1459
1505
  const ok = r.status === "received";
1460
1506
  writeln(
@@ -1556,6 +1602,9 @@ async function showHelp() {
1556
1602
  writeln(` ${dim("--refresh")} poll interval in seconds (default: 30)`);
1557
1603
  writeln(` ${dim("--once")} print once and exit (board only)`);
1558
1604
  writeln(` ${dim("--port")} proxy port (default: 8787)`);
1605
+ writeln(
1606
+ ` ${dim("--source")} transcripts (default) · auto · otel (collector publishes only with complete coverage + real turns)`,
1607
+ );
1559
1608
  writeln();
1560
1609
  writeln(` ${bold("For AI clients (not typeable)")}`);
1561
1610
  writeln(
@@ -1699,7 +1748,7 @@ async function runEnroll({ label } = {}) {
1699
1748
  }
1700
1749
 
1701
1750
  // ── submit: publish your verified (signed) runs to the board (D7 §5/§8) ─────────
1702
- async function runSubmit({ platform = "claude", window } = {}) {
1751
+ async function runSubmit({ platform = "claude", window, source = "transcripts" } = {}) {
1703
1752
  const id = ensureIdentity();
1704
1753
  if (!id.codename || !id.operator_id) {
1705
1754
  writeln(
@@ -1721,6 +1770,7 @@ async function runSubmit({ platform = "claude", window } = {}) {
1721
1770
  window: typeof window === "string" ? window : undefined,
1722
1771
  dry_run: process.argv.includes("--dry-run"),
1723
1772
  confirm: true, // explicit CLI invocation is the confirmation
1773
+ source,
1724
1774
  });
1725
1775
  } catch (e) {
1726
1776
  writeln(red(` ✗ ${e.message}`));
@@ -1733,12 +1783,28 @@ async function runSubmit({ platform = "claude", window } = {}) {
1733
1783
  return;
1734
1784
  }
1735
1785
 
1736
- if (out.status === "error" && out.reason === "platform_read_failed") {
1786
+ if (out.status === "error") {
1737
1787
  writeln(red(` ✗ ${out.detail}`));
1738
1788
  process.exitCode = 1;
1739
1789
  return;
1740
1790
  }
1741
1791
 
1792
+ if (out.source) {
1793
+ writeln(
1794
+ ` ${dim("pillars from")} ${
1795
+ out.source === OTEL_SOURCE_TAG
1796
+ ? (out.publication_eligible === false ? gold : green)(
1797
+ out.publication_eligible === false
1798
+ ? "source: otel (live; preview only)"
1799
+ : "source: otel (live; complete coverage, real turns)",
1800
+ )
1801
+ : dim(
1802
+ `source: transcripts${out.otel_fallback ? " (otel unreachable)" : ""}`,
1803
+ )
1804
+ }`,
1805
+ );
1806
+ }
1807
+ if (out.source_note) writeln(dim(` ${out.source_note}`));
1742
1808
  writeln();
1743
1809
  let anyRanked = false;
1744
1810
  let anyReceivedNotRanked = false;
@@ -1805,6 +1871,7 @@ export async function runCli(argv) {
1805
1871
  "cache-read",
1806
1872
  "combined-input",
1807
1873
  "port",
1874
+ "source",
1808
1875
  ]);
1809
1876
  const flags = {};
1810
1877
  for (let i = 1; i < args.length; i++) {
@@ -1885,6 +1952,7 @@ export async function runCli(argv) {
1885
1952
  window: typeof flags.window === "string" ? flags.window : undefined,
1886
1953
  refresh: Number(flags.refresh) || 30,
1887
1954
  submit: flags.submit === true || flags.submit === "true",
1955
+ source: normalizeSource(flags.source),
1888
1956
  });
1889
1957
  } else if (cmd === "proxy") {
1890
1958
  await runProxy({ port: flags.port ?? 8787 });
@@ -1899,6 +1967,7 @@ export async function runCli(argv) {
1899
1967
  await runSubmit({
1900
1968
  platform: flags.platform ?? "claude",
1901
1969
  window: flags.window,
1970
+ source: normalizeSource(flags.source),
1902
1971
  });
1903
1972
  } else if (cmd === "--help" || cmd === "-h" || cmd === "help") {
1904
1973
  await showHelp();
@@ -15,7 +15,8 @@
15
15
  import { callTool, DEFAULT_API_BASE, pullActivePlatforms } from "../tools.mjs";
16
16
  import { ALL_PLATFORMS } from "../adapters.mjs";
17
17
  import { cascade, CLASS_TIERS, UNCLASSED, tierOf } from "../cascade.mjs";
18
- import { freshVerifierPillars } from "../tokenpull.mjs";
18
+ import { freshVerifierPillars, pullWithSource, OTEL_SOURCE_TAG, sourceMarker } from "../tokenpull.mjs";
19
+ import { evaluatePublication } from "../submit/publication.mjs";
19
20
  import { isSignedIn, isCodeChar } from "../connect.mjs";
20
21
  import { loadIdentity, clearIdentity } from "../keystore.mjs";
21
22
  import { execFile } from "child_process";
@@ -26,6 +27,7 @@ import { pathToFileURL } from "node:url";
26
27
  import { pkgVersion } from "../lib/pkg-version.mjs";
27
28
  import { cachedUpdateNotice, checkForUpdate } from "../lib/update-check.mjs";
28
29
  import { LEADERBOARD_METRIC } from "../lib/constants.mjs";
30
+ import { readIntegrityCache, refreshIntegrityInBackground, renderIntegrityBlock, retryInMinutes } from "../lib/integrity.mjs";
29
31
 
30
32
  // Version read from the shared pkg-version helper (single source of truth —
31
33
  // matches cli.mjs; never hardcode, that's what caused the version drift).
@@ -34,6 +36,9 @@ const VERSION = pkgVersion();
34
36
  // "sigrank X available" text for the header; null unless runTui found a newer
35
37
  // release (cached result at launch, registry refresh in the background).
36
38
  let _updateNotice = null;
39
+ // Tokenpull Integrity status: last cached result (counts only), refreshed in a separate
40
+ // process at launch. Null until a result exists → the lines read "not checked".
41
+ let _integrityCache = null;
37
42
  const _updateVersion = () => (_updateNotice ? _updateNotice.split(" ")[1] : null);
38
43
 
39
44
  // Expensive platform readers that the Dashboard only runs on explicit user
@@ -1363,6 +1368,19 @@ function renderDashboard(data, status = "", scrollState = 0) {
1363
1368
  );
1364
1369
  }
1365
1370
 
1371
+ // Integrity block (checks × windows matrix) from the cached last result; never computed
1372
+ // here (a background process refreshes the cache). Falls back to one line, then nothing,
1373
+ // when there is no spare room. NO_COLOR / non-TTY: plain glyphs, no ANSI.
1374
+ {
1375
+ const spare = budget - used - 8;
1376
+ const useColor = !process.env.NO_COLOR && !!process.stdout.isTTY;
1377
+ const painters = useColor
1378
+ ? { ok: green, flag: (t) => paint(c.gold, t), off: dim, head: bold }
1379
+ : null;
1380
+ for (const line of renderIntegrityBlock(_integrityCache, { width: w, rows: spare, color: painters, retryIn: retryInMinutes() })) emit(` ${line}`);
1381
+ if (spare >= 1) emit();
1382
+ }
1383
+
1366
1384
  // (Υ Trend moved to the dedicated Trends tab [2] — every metric, with sub-views.)
1367
1385
 
1368
1386
  // ── Token Composition — lifetime per platform (owner 2026-10-15: "combine token
@@ -2665,8 +2683,12 @@ async function loadWatchData(platform = "all", win = "all-windows") {
2665
2683
  const winFilter = win && win !== "all-windows" ? win : null;
2666
2684
  // Detect active platforms (any window with input+output > 0), respecting an optional [P] focus.
2667
2685
  const candidates = platFilter ? [platFilter] : ALL_PLATFORMS;
2686
+ // source auto: claude reads the live sigrank-otel collector when it answers the
2687
+ // ≤300 ms probe, else the transcripts (same rule as `sigrank watch`).
2668
2688
  const settled = await Promise.allSettled(
2669
- candidates.map((p) => tokenpullAny(p)),
2689
+ candidates.map((p) =>
2690
+ pullWithSource(p, { source: "auto" }, () => tokenpullAny(p)),
2691
+ ),
2670
2692
  );
2671
2693
  const active = [];
2672
2694
  for (const r of settled) {
@@ -2722,7 +2744,13 @@ function renderWatchData(data) {
2722
2744
  const byWin = {};
2723
2745
  for (const ww of d.windows || []) byWin[ww.window] = ww;
2724
2746
  emit();
2725
- emit(` ${cyan(d.platform)}${d.estimated ? dim(" (est)") : ""}`);
2747
+ const srcNote =
2748
+ d.source === OTEL_SOURCE_TAG
2749
+ ? " " + (evaluatePublication(d).eligible ? green : gold)(sourceMarker(d))
2750
+ : d.platform === "claude"
2751
+ ? " " + dim(d.otelFallback ? "source: transcripts (collector fallback)" : "source: transcripts")
2752
+ : "";
2753
+ emit(` ${cyan(d.platform)}${d.estimated ? dim(" (est)") : ""}${srcNote}`);
2726
2754
  for (const wk of WINS) {
2727
2755
  if (used >= budget - 1) break;
2728
2756
  const ww = byWin[wk];
@@ -3375,6 +3403,14 @@ export async function runTui({
3375
3403
  })
3376
3404
  .catch(() => {});
3377
3405
 
3406
+ // Integrity status: show the cached last result at once, refresh in a separate process
3407
+ // when stale (never blocks the TUI; lines read "not checked" until a result exists).
3408
+ _integrityCache = readIntegrityCache();
3409
+ refreshIntegrityInBackground(() => {
3410
+ _integrityCache = readIntegrityCache();
3411
+ redraw().catch(() => {});
3412
+ });
3413
+
3378
3414
  // ── Initial data load
3379
3415
  const loadAll = async () => {
3380
3416
  // A2 (2026-06-27): paint the frame + a clear "reading your cascade…" status IMMEDIATELY,
@@ -3701,7 +3737,13 @@ export async function runTui({
3701
3737
  multiAbort = null;
3702
3738
  for (const p of platforms) {
3703
3739
  try {
3704
- const out = await callTool("submit_verified", { platform: p, confirm: true });
3740
+ // source: transcripts — the preview above was built from the transcript
3741
+ // dashboard; submitting collector numbers would break see→confirm→send.
3742
+ const out = await callTool("submit_verified", {
3743
+ platform: p,
3744
+ confirm: true,
3745
+ source: "transcripts",
3746
+ });
3705
3747
  const ws = out.windows || [];
3706
3748
  const received = ws.filter((w) => w.status === "received");
3707
3749
  const verified = received.filter(
@@ -3722,6 +3764,7 @@ export async function runTui({
3722
3764
  const out = await callTool("submit_verified", {
3723
3765
  platform: "multi",
3724
3766
  confirm: true,
3767
+ source: "transcripts",
3725
3768
  });
3726
3769
  if (out.status === "error" && out.reason === "platform_read_failed") {
3727
3770
  // A platform read failed: the combined total was NOT submitted.
package/proxy.mjs CHANGED
@@ -45,13 +45,13 @@ export function parseProxyPort(value, { allowZero = false } = {}) {
45
45
 
46
46
  function routeFor(pathname) {
47
47
  if (pathname === "/v1/messages") {
48
- return { backend: "anthropic", endpoint: "messages" };
48
+ return { backend: "anthropic", endpoint: "messages", path: "/v1/messages" };
49
49
  }
50
50
  if (pathname === "/v1/chat/completions") {
51
- return { backend: "openai", endpoint: "chat-completions" };
51
+ return { backend: "openai", endpoint: "chat-completions", path: "/v1/chat/completions" };
52
52
  }
53
53
  if (pathname === "/v1/responses") {
54
- return { backend: "openai", endpoint: "responses" };
54
+ return { backend: "openai", endpoint: "responses", path: "/v1/responses" };
55
55
  }
56
56
  return null;
57
57
  }
@@ -376,7 +376,10 @@ export async function startProxy({
376
376
  return;
377
377
  }
378
378
 
379
- const upstreamUrl = new URL(parsedUrl.pathname + parsedUrl.search, upstreamBase);
379
+ // Build the upstream URL from the fixed route path, never from the raw
380
+ // request target, so the client can only choose the query string.
381
+ const upstreamUrl = new URL(route.path, upstreamBase);
382
+ upstreamUrl.search = parsedUrl.search;
380
383
  // Defense-in-depth: verify the constructed URL origin matches the intended
381
384
  // upstream. This prevents an absolute-form request target (e.g.
382
385
  // "http://attacker.example/v1/messages") from overriding upstreamBase via
package/submit/index.mjs CHANGED
@@ -3,11 +3,13 @@
3
3
  // operator_id + private key). The server re-derives the ranked Υ from the 4 raw pillars,
4
4
  // so the core/background metrics here are schema-valid, plausibility-clean DISPLAY inputs.
5
5
  //
6
- // raw_telemetry sessions/turns/active are conservative PROXIES: tokenpull yields the 4
7
- // pillars + a message count, not session structure. They are chosen to pass the
8
- // plausibility gate WITHOUT flagging (a flag downgrades verified→flagged → not ranked).
9
- // TODO(tokenpull): emit real sessions_count / turns_total / active_minutes per window so
10
- // the display signa_rate reflects true session shape (the ranked Υ is already exact).
6
+ // raw_telemetry turns/sessions are REAL when the reader supplies them (opts.turns /
7
+ // opts.sessions from tokenpull's Claude prompt reader; turn = one user prompt + the reply).
8
+ // Otherwise (non-Claude readers, or a window with tokens but no countable prompts) they
9
+ // fall back to message-count PROXIES (turns = messages, sessions = messages/8).
10
+ // active_minutes_est is always a PROXY. Proxies are chosen to pass the plausibility gate
11
+ // WITHOUT flagging (a flag downgrades verified→flagged → not ranked).
12
+ // TODO(tokenpull): emit real active_minutes per window, and prompts() for non-Claude readers.
11
13
 
12
14
  import { snapshotHash, signPayload } from "../identity/sign.mjs";
13
15
  import { preflight } from "./preflight.mjs";
@@ -89,10 +91,27 @@ export function buildPayload(
89
91
 
90
92
  // Proxies — plausibility-clean (see file header).
91
93
  const msgs = Math.max(0, Math.round(messages || 0));
92
- const turnsTotal = Math.max(output > 0 ? 1 : 0, msgs);
94
+ // Real turns/sessions (turn = A+B = one user prompt + Claude's reply; canon B.01
95
+ // "a turn = one exchange") when the reader supplied them. Otherwise fall back to the
96
+ // legacy message-count proxy (readers with no prompt data, e.g. non-Claude adapters).
97
+ // turns<=0 with tokens>0 (prompts lacking timestamps, subagent-only windows) is
98
+ // "no real data", not "one turn": use the proxy instead of forcing 1 turn.
99
+ const hasReal =
100
+ Number.isFinite(opts.turns) &&
101
+ Number.isFinite(opts.sessions) &&
102
+ (tokensTotal === 0 || opts.turns > 0);
103
+ const turnsTotal = hasReal
104
+ ? Math.max(output > 0 ? 1 : 0, Math.round(opts.turns))
105
+ : Math.max(output > 0 ? 1 : 0, msgs);
93
106
  const sessionsCount =
94
107
  tokensTotal > 0
95
- ? clamp(Math.round(msgs / 8) || 1, 1, Math.max(1, turnsTotal))
108
+ ? clamp(
109
+ hasReal
110
+ ? Math.round(opts.sessions) || 1
111
+ : Math.round(msgs / 8) || 1,
112
+ 1,
113
+ Math.max(1, turnsTotal),
114
+ )
96
115
  : 0;
97
116
  const spanMinutes = spanDays * 1440;
98
117
  const minActive = Math.ceil(output / 19000) + 1; // keep output/active under the 20k/min flag
@@ -168,6 +187,13 @@ export function buildPayload(
168
187
  if (opts.report && typeof opts.report === "object") {
169
188
  payload.report = opts.report;
170
189
  }
190
+
191
+ // Optional Tokenpull Integrity block (submit_verified integrity:true). Scores and
192
+ // counts only — built by lib/integrity.mjs integrityBlock(). Absent unless the
193
+ // caller passes it, so the payload (and its signed bytes) are unchanged when off.
194
+ if (opts.integrity && typeof opts.integrity === "object") {
195
+ payload.integrity = opts.integrity;
196
+ }
171
197
  payload.agent.snapshot_hash = snapshotHash(payload);
172
198
  return payload;
173
199
  }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * submit/publication.mjs — the one place that decides whether a pull may be
3
+ * published and how its turns/sessions are measured. Transcripts and the otel
4
+ * collector both go through here.
5
+ *
6
+ * transcripts: always eligible (turns/sessions are real when the reader counted
7
+ * prompts, otherwise the message proxy applies in buildPayload).
8
+ * otel-cc: eligible only when EVERY window has coverage.complete === true and
9
+ * turnsSource === "real" with turns > 0 whenever tokens > 0.
10
+ */
11
+
12
+ const OTEL = "otel-cc";
13
+ const tokensOf = (p) =>
14
+ (p?.input || 0) + (p?.output || 0) + (p?.cacheCreate || 0) + (p?.cacheRead || 0);
15
+
16
+ /** "real" when the window carries countable turns (>0) and sessions, else "proxy". */
17
+ export function turnsBasis(w) {
18
+ return Number.isFinite(w?.turns) && Number.isFinite(w?.sessions) && w.turns > 0
19
+ ? "real"
20
+ : "proxy";
21
+ }
22
+
23
+ const TURN_TOL_FRAC = 0.1;
24
+ const TURN_TOL_ABS = 5;
25
+ const TOKEN_TOL_FRAC = 0.02; // each pillar total within 2% of the transcripts path, both ways
26
+ const PILLARS = ["input", "output", "cacheCreate", "cacheRead"];
27
+
28
+ /** Coverage fields must agree with complete:true; returns contradiction texts. */
29
+ function coverageContradictions(w) {
30
+ const c = w.coverage;
31
+ const out = [];
32
+ if (c.gapDays?.length) out.push(`gap days ${c.gapDays.slice(0, 5).join(", ")}`);
33
+ if ((c.duplicates ?? 0) !== 0) out.push(`${c.duplicates} duplicates`);
34
+ if (c.missingRequests != null && c.missingRequests !== 0)
35
+ out.push(`${c.missingRequests} missing requests`);
36
+ if (w.window !== "all") {
37
+ if (c.firstAnyMs == null || c.windowStartMs == null)
38
+ out.push("window start / first record unknown");
39
+ else if (c.firstAnyMs > c.windowStartMs)
40
+ out.push("collector history starts after the window start");
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** Per-window reasons an otel window is not publishable ([] when it is). */
46
+ function otelWindowReasons(w, local) {
47
+ const out = [];
48
+ const label = w.window;
49
+ const cov = w.coverage;
50
+ if (!cov) out.push(`${label}: collector reported no coverage (older collector?)`);
51
+ else if (cov.complete !== true) {
52
+ const why = cov.reasons?.length
53
+ ? cov.reasons.join("; ")
54
+ : cov.gapDays?.length
55
+ ? `gap days ${cov.gapDays.slice(0, 5).join(", ")}${cov.gapDays.length > 5 ? "…" : ""}`
56
+ : "coverage incomplete";
57
+ out.push(`${label}: coverage incomplete (${why})`);
58
+ } else {
59
+ const bad = coverageContradictions(w);
60
+ if (bad.length)
61
+ out.push(`${label}: coverage says complete but contradicts itself (${bad.join("; ")})`);
62
+ }
63
+ if (w.turnsSource !== "real" || w.turns == null || w.sessions == null)
64
+ out.push(`${label}: no real turns/sessions from collector`);
65
+ else if (tokensOf(w.pillars) > 0 && w.turns <= 0)
66
+ out.push(`${label}: tokens present but turns = 0`);
67
+
68
+ // Cross-check against our own transcript count (local === undefined: display only).
69
+ if (local !== undefined) {
70
+ const lw = (local?.windows || []).find((x) => x.window === w.window);
71
+ if (!lw) out.push(`${label}: no local transcript window to cross-check`);
72
+ else {
73
+ const below = PILLARS.filter((k) => (w.pillars?.[k] || 0) < (lw.pillars?.[k] || 0) * (1 - TOKEN_TOL_FRAC));
74
+ const above = PILLARS.filter((k) => (w.pillars?.[k] || 0) > (lw.pillars?.[k] || 0) * (1 + TOKEN_TOL_FRAC));
75
+ if (below.length)
76
+ out.push(`${label}: collector ${below.join("/")} below transcripts`);
77
+ if (above.length)
78
+ out.push(`${label}: collector history beyond the transcripts on disk can't be verified (${above.join("/")})`);
79
+ if (tokensOf(lw.pillars) > 0 && turnsBasis(lw) !== "real")
80
+ out.push(`${label}: no local transcript turns to cross-check`);
81
+ else if (Number.isFinite(w.turns) && Number.isFinite(lw.turns)) {
82
+ const d = Math.abs(w.turns - lw.turns);
83
+ if (d > TURN_TOL_ABS && d > TURN_TOL_FRAC * Math.max(w.turns, lw.turns))
84
+ out.push(`${label}: collector turns ${w.turns} disagree with local transcripts ${lw.turns}`);
85
+ }
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /**
92
+ * evaluatePublication(pulled, local, { window }) → { eligible, reasons, blocked }.
93
+ * Non-otel pulls are always eligible. An otel pull needs every selected window
94
+ * verified. `local` is the transcripts pull of the same platform: it supplies the
95
+ * cross-check (turns within tolerance, tokens not below) and is REQUIRED for
96
+ * publishing paths (pass null if unavailable); leave undefined for display only.
97
+ */
98
+ export function evaluatePublication(pulled, local, opts = {}) {
99
+ if (!pulled || pulled.source !== OTEL) return { eligible: true, reasons: [], blocked: [] };
100
+ const windows = (pulled.windows || []).filter((w) => !opts.window || w.window === opts.window);
101
+ if (!windows.length) return { eligible: false, reasons: ["collector returned no matching windows"], blocked: [] };
102
+ const per = windows.map((w) => ({ w: w.window, r: otelWindowReasons(w, local) }));
103
+ const reasons = per.flatMap((x) => x.r);
104
+ return { eligible: reasons.length === 0, reasons, blocked: per.filter((x) => x.r.length).map((x) => x.w) };
105
+ }
106
+
107
+ /**
108
+ * Turns/sessions to submit for one pulled window. The collector's own counts are
109
+ * never submitted: for an otel pull the window's numbers come from our transcript
110
+ * count (`local` pull of the same platform); transcripts pulls use themselves.
111
+ */
112
+ export function measureWindow(w, local) {
113
+ const lw = local ? (local.windows || []).find((x) => x.window === w.window) : null;
114
+ const src = lw || w;
115
+ return { turns: src.turns, sessions: src.sessions, turns_source: turnsBasis(src) };
116
+ }
117
+
118
+ /** Compact, count-only collector summary carried in submission metadata. */
119
+ export function otelSubmissionMeta(w) {
120
+ const c = w.coverage;
121
+ return {
122
+ source: OTEL,
123
+ provenance: w.provenance ?? null,
124
+ coverage: c
125
+ ? { complete: c.complete, gap_days: c.gapDays?.length ?? 0, duplicates: c.duplicates ?? 0 }
126
+ : null,
127
+ };
128
+ }
129
+
130
+ /** Result-level fields describing eligibility, shared by submit/watch/tokenpull. */
131
+ export function publicationFields(pulled, ev = evaluatePublication(pulled)) {
132
+ if (pulled?.source !== OTEL) return {};
133
+ return ev.eligible
134
+ ? { publication_eligible: true }
135
+ : {
136
+ publication_eligible: false,
137
+ publication_blockers: ev.reasons,
138
+ source_note: `Preview only: ${ev.reasons.join(" | ")}`,
139
+ };
140
+ }
package/tokenpull.mjs CHANGED
@@ -1 +1,2 @@
1
1
  export * from './adapters/tokenpull.mjs';
2
+ export * from './adapters/otel.mjs';
@@ -17,6 +17,7 @@ import {
17
17
  tokenpullCodex as pullCodex,
18
18
  tokenpullAny,
19
19
  } from "../adapters/tokenpull.mjs";
20
+ import { pullWithSource } from "../adapters/otel.mjs";
20
21
 
21
22
  // Resolve local node_modules/.bin for bundled deps (ccusage, tokscale)
22
23
  const _pkgRoot = path.dirname(fileURLToPath(import.meta.url));
@@ -177,7 +178,19 @@ export function uploadStamp(content) {
177
178
  // Pull a platform's local usage → 4 windows of canonical pillars. Routes through
178
179
  // tokenpullAny() which handles Claude (native), Codex (estimated io_ratio), and all
179
180
  // other adapters from the registry. opts.adapter overrides for tests.
181
+ //
182
+ // opts.source ('auto' | 'otel' | 'transcripts') opts into the live sigrank-otel
183
+ // collector for platform 'claude' (see adapters/otel.mjs). When opts.source is
184
+ // unset the pull is exactly the pre-otel transcript path.
180
185
  export async function pullByPlatform(platform, opts = {}) {
186
+ if (opts.source != null)
187
+ return pullWithSource(platform || "claude", opts, () =>
188
+ _pullTranscripts(platform, opts),
189
+ );
190
+ return _pullTranscripts(platform, opts);
191
+ }
192
+
193
+ async function _pullTranscripts(platform, opts = {}) {
181
194
  if (opts.adapter) {
182
195
  // Test injection: bypass registry and use the mock adapter directly
183
196
  if (platform === "codex") {
@@ -306,6 +306,15 @@ export const SUBMIT_OUTPUT = {
306
306
  type: "string",
307
307
  description: "Error or skip reason if status is not ok",
308
308
  },
309
+ source: {
310
+ type: "string",
311
+ description:
312
+ "Pillar source for signed payload or preview: otel-cc or transcripts",
313
+ },
314
+ publication_eligible: { type: "boolean" },
315
+ publication_blockers: { type: "array", items: { type: "string" } },
316
+ source_note: { type: "string" },
317
+ otel_fallback: { type: "string" },
309
318
  },
310
319
  };
311
320
 
@@ -335,6 +344,22 @@ export const TOKENPULL_OUTPUT = {
335
344
  cascade: CASCADE_OUTPUT,
336
345
  card: { type: "string", description: "Deterministic prose summary" },
337
346
  generatedAt: { type: "string", description: "ISO timestamp of the pull" },
347
+ source: {
348
+ type: "string",
349
+ description:
350
+ "Where the pillars came from: 'otel-cc' (live sigrank-otel collector) or 'transcripts' (local session logs)",
351
+ },
352
+ publication_eligible: { type: "boolean" },
353
+ source_grade: { type: ["string", "null"] },
354
+ source_note: { type: "string" },
355
+ source_marker: {
356
+ type: ["string", "null"],
357
+ description: "Human marker, e.g. 'source: otel (live; complete coverage, real turns)'",
358
+ },
359
+ otel_fallback: {
360
+ type: "string",
361
+ description: "Present when source=auto fell back to transcripts — why the collector was not used",
362
+ },
338
363
  poll_interval_s: {
339
364
  type: "number",
340
365
  description: "Advisory poll cadence echoed back (does not make the call block)",
@@ -490,3 +515,31 @@ export const SUGGEST_OUTPUT = {
490
515
  },
491
516
  },
492
517
  };
518
+
519
+ export const INTEGRITY_OUTPUT = {
520
+ type: "object",
521
+ properties: {
522
+ tool: { type: "string", description: "Integrity tool name" },
523
+ version: { type: "string", description: "Integrity tool version" },
524
+ hash: { type: "string", description: "Hash of the integrity tool code that ran" },
525
+ overall: { type: "string", description: "One-line summary across the windows checked" },
526
+ windows: {
527
+ type: "array",
528
+ description: "One entry per window checked",
529
+ items: {
530
+ type: "object",
531
+ properties: {
532
+ window: { type: "string", enum: ["7d", "30d", "90d", "all"] },
533
+ flags: { type: "number", description: "Total flags across every check; a flag means worth a look, not cheating" },
534
+ population: { type: "object", description: "Requests, finished requests and sessions checked" },
535
+ checks: {
536
+ type: "object",
537
+ description:
538
+ "Result per check, keyed by check name: flags, score, codes (counts per flag code), a few samples as transcript-file ordinal + line. A check that could not run carries a status instead.",
539
+ },
540
+ overall: { type: "string", description: "One-line summary for this window" },
541
+ },
542
+ },
543
+ },
544
+ },
545
+ };