sigrank 1.0.52 → 1.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/adapters/otel.mjs +268 -0
- package/adapters/tokenpull.mjs +98 -1
- package/manifest.json +1 -1
- package/package.json +2 -2
- package/presentation/cli.mjs +76 -7
- package/presentation/tui.mjs +22 -4
- package/submit/index.mjs +26 -7
- package/submit/publication.mjs +140 -0
- package/tokenpull.mjs +1 -0
- package/tools/_helpers.mjs +13 -0
- package/tools/_schemas.mjs +25 -0
- package/tools/submit-verified.mjs +72 -4
- package/tools/tokenpull.mjs +4 -0
- package/tools/watch-tokenpull.mjs +23 -1
package/README.md
CHANGED
|
@@ -36,6 +36,16 @@ npx sigrank board --window 7d --once
|
|
|
36
36
|
|
|
37
37
|
The dashboard includes Dashboard, Trends, Compare, Board, Watch, and Connect tabs. Use `1`–`6` or the arrow keys to switch, `R` to refresh, and `Q` to quit.
|
|
38
38
|
|
|
39
|
+
### Inspect live collector measurements
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
sigrank watch --platform claude --source otel # require local collector
|
|
43
|
+
sigrank watch --platform claude --source auto # collector, else transcripts
|
|
44
|
+
sigrank submit --source otel --dry-run # signed preview (publishes only with complete coverage)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The Claude collector exposes `/api/pillars` on `http://127.0.0.1:4318` (`SIGRANK_OTEL_URL` may select another loopback HTTP(S) origin). All four windows must validate or the entire `auto` pull falls back to transcripts. Explicit `otel` allows a longer bounded read for a cold collector. Newer collectors also report real `turns`/`sessions`, `provenance` and per-window `coverage` (all optional; absent on older collectors). Normal CLI/MCP reads default to transcripts. The TUI Watch tab may show collector data and labels it separately; its Dashboard and submit preview remain transcript-based. Non-Claude platforms retain their existing readers. A collector pull is publication-eligible per window only when its coverage is complete and self-consistent (no gap days, duplicates or missing requests), it reports real turns > 0, and it cross-checks against this machine's own transcript count: each pillar total within 2% of the transcripts path (collector history beyond the transcripts on disk cannot be verified) and turns within 10% / 5. Submitted turns/sessions are always the local transcript count, never the collector's. With `--window`/`window`, only that window gates; otherwise every window must pass. Otherwise it stays preview-only and the specific reasons are returned. Combined (`multi`) OTEL totals are not enabled, and `watch --submit` still uses transcripts. MCP publishing still requires explicit confirmation. Source, provenance and coverage appear in the tool/CLI response only; no field is added to the signed payload.
|
|
48
|
+
|
|
39
49
|
### Publish your own snapshot
|
|
40
50
|
|
|
41
51
|
1. Sign in at [signalaf.com](https://signalaf.com) and create a connect code in Settings.
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* adapters/otel.mjs — the `otel` pillar source.
|
|
3
|
+
*
|
|
4
|
+
* Reads live Claude Code pillars from the local sigrank-otel collector instead of
|
|
5
|
+
* re-walking ~/.claude/projects transcripts. Contract (owned by the collector):
|
|
6
|
+
*
|
|
7
|
+
* GET http://127.0.0.1:<port>/api/pillars?window=7d|30d|90d|all
|
|
8
|
+
* → 200 { source:"otel-cc", window, sinceMs, total:{input,output,cacheRead,cacheWrite,requests},
|
|
9
|
+
* models:{ <model>: {same fields} },
|
|
10
|
+
* // optional (newer collectors; absent → null, never an error):
|
|
11
|
+
* turns, sessions, turnsSource:"real"|"none", provenance:{reported,logged},
|
|
12
|
+
* coverage:{complete,windowStartMs,firstLiveMs,firstAnyMs,duplicates,gapDays,reasons} }
|
|
13
|
+
*
|
|
14
|
+
* `input` is LOGGED API input tokens (the canonical pillar), never typed input.
|
|
15
|
+
* Platform = claude only. Base URL: opts.otelUrl → SIGRANK_OTEL_URL → http://127.0.0.1:4318.
|
|
16
|
+
*
|
|
17
|
+
* Source modes (`--source` / tool arg `source`):
|
|
18
|
+
* auto probe the collector (≤300 ms); use it when reachable, else transcripts
|
|
19
|
+
* otel collector required — an unreachable/malformed collector is an error
|
|
20
|
+
* transcripts (default) never probe; current behaviour
|
|
21
|
+
*
|
|
22
|
+
* All-or-nothing: if ANY of the four windows fails (timeout, non-200, bad JSON, bad shape)
|
|
23
|
+
* the whole pull falls back, so a result never mixes otel and transcript windows.
|
|
24
|
+
* Token-math is untouched: the collector's totals map 1:1 onto the four pillars
|
|
25
|
+
* (cacheWrite → cacheCreate) and `requests` becomes the window's message count.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { WINDOWS } from "./tokenpull.mjs";
|
|
29
|
+
import { evaluatePublication } from "../submit/publication.mjs";
|
|
30
|
+
|
|
31
|
+
export const OTEL_DEFAULT_URL = "http://127.0.0.1:4318";
|
|
32
|
+
export const OTEL_PROBE_TIMEOUT_MS = 300;
|
|
33
|
+
export const OTEL_FETCH_TIMEOUT_MS = 2000;
|
|
34
|
+
// Explicit collector inspection tolerates cold/large collector windows; auto stays fast.
|
|
35
|
+
export const OTEL_REQUIRED_PROBE_TIMEOUT_MS = 20000;
|
|
36
|
+
export const OTEL_REQUIRED_FETCH_TIMEOUT_MS = 30000;
|
|
37
|
+
export const OTEL_SOURCE_TAG = "otel-cc";
|
|
38
|
+
export const SOURCE_MODES = ["auto", "otel", "transcripts"];
|
|
39
|
+
|
|
40
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
41
|
+
|
|
42
|
+
/** Normalize a --source value. null/'' → 'transcripts'. Throws on anything unknown. */
|
|
43
|
+
export function normalizeSource(s) {
|
|
44
|
+
if (s == null || s === "") return "transcripts";
|
|
45
|
+
const v = String(s).toLowerCase();
|
|
46
|
+
if (!SOURCE_MODES.includes(v))
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Unknown source "${s}". Valid: ${SOURCE_MODES.join(", ")}`,
|
|
49
|
+
);
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Resolve the collector base URL. Loopback http(s) only — the collector is local. */
|
|
54
|
+
export function otelBaseUrl(opts = {}) {
|
|
55
|
+
const raw = (opts.otelUrl || process.env.SIGRANK_OTEL_URL || OTEL_DEFAULT_URL)
|
|
56
|
+
.toString()
|
|
57
|
+
.trim()
|
|
58
|
+
.replace(/\/+$/, "");
|
|
59
|
+
const u = new URL(raw); // throws on garbage → caller treats as unavailable
|
|
60
|
+
if (!/^https?:$/.test(u.protocol) || !LOOPBACK.has(u.hostname) || u.username || u.password || u.pathname !== "/" || u.search || u.hash)
|
|
61
|
+
throw new Error(
|
|
62
|
+
`SIGRANK_OTEL_URL must be a loopback http URL (got ${u.protocol}//${u.hostname})`,
|
|
63
|
+
);
|
|
64
|
+
return u.origin;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const nonNeg = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
68
|
+
|
|
69
|
+
const optCount = (v) => (nonNeg(v) ? v : null);
|
|
70
|
+
const gapDay = (d) => typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Lenient parse of the collector's real-turns / provenance / coverage fields.
|
|
74
|
+
* Every field is optional (older collectors omit them) and a malformed field
|
|
75
|
+
* degrades to null rather than failing the pull; publication treats null as
|
|
76
|
+
* "not verified". Never throws.
|
|
77
|
+
*/
|
|
78
|
+
function _parseExtras(body) {
|
|
79
|
+
const p = body.provenance;
|
|
80
|
+
const provenance =
|
|
81
|
+
p && typeof p === "object" && nonNeg(p.reported) && nonNeg(p.logged)
|
|
82
|
+
? { reported: p.reported, logged: p.logged }
|
|
83
|
+
: null;
|
|
84
|
+
const c = body.coverage;
|
|
85
|
+
const coverage =
|
|
86
|
+
c && typeof c === "object" && typeof c.complete === "boolean"
|
|
87
|
+
? {
|
|
88
|
+
complete: c.complete,
|
|
89
|
+
windowStartMs: optCount(c.windowStartMs),
|
|
90
|
+
firstLiveMs: optCount(c.firstLiveMs),
|
|
91
|
+
firstAnyMs: optCount(c.firstAnyMs),
|
|
92
|
+
duplicates: optCount(c.duplicates) ?? 0,
|
|
93
|
+
missingRequests: optCount(c.missingRequests),
|
|
94
|
+
gapDays: Array.isArray(c.gapDays) ? c.gapDays.filter(gapDay) : [],
|
|
95
|
+
reasons: Array.isArray(c.reasons)
|
|
96
|
+
? c.reasons.filter((r) => typeof r === "string").slice(0, 8)
|
|
97
|
+
: [],
|
|
98
|
+
}
|
|
99
|
+
: null;
|
|
100
|
+
return {
|
|
101
|
+
turns: optCount(body.turns),
|
|
102
|
+
sessions: optCount(body.sessions),
|
|
103
|
+
turnsSource:
|
|
104
|
+
body.turnsSource === "real" || body.turnsSource === "none"
|
|
105
|
+
? body.turnsSource
|
|
106
|
+
: null,
|
|
107
|
+
provenance,
|
|
108
|
+
coverage,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Validate one /api/pillars body → {pillars, messages} or throw with a reason. */
|
|
113
|
+
function _parseWindow(body, windowKey) {
|
|
114
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
115
|
+
throw new Error("malformed body");
|
|
116
|
+
if (body.source !== OTEL_SOURCE_TAG) throw new Error("unexpected collector source");
|
|
117
|
+
if (body.window !== windowKey)
|
|
118
|
+
throw new Error(`window mismatch (${body.window} ≠ ${windowKey})`);
|
|
119
|
+
const t = body.total;
|
|
120
|
+
if (!t || typeof t !== "object") throw new Error("missing total");
|
|
121
|
+
for (const k of ["input", "output", "cacheRead", "cacheWrite"])
|
|
122
|
+
if (!nonNeg(t[k])) throw new Error(`bad total.${k}`);
|
|
123
|
+
const requests = t.requests;
|
|
124
|
+
if (!nonNeg(requests)) throw new Error("bad total.requests");
|
|
125
|
+
return {
|
|
126
|
+
window: windowKey,
|
|
127
|
+
..._parseExtras(body),
|
|
128
|
+
pillars: {
|
|
129
|
+
input: Math.round(t.input),
|
|
130
|
+
output: Math.round(t.output),
|
|
131
|
+
cacheCreate: Math.round(t.cacheWrite),
|
|
132
|
+
cacheRead: Math.round(t.cacheRead),
|
|
133
|
+
},
|
|
134
|
+
messages: Math.round(requests),
|
|
135
|
+
sinceMs: nonNeg(body.sinceMs) ? body.sinceMs : null,
|
|
136
|
+
grade: typeof body.grade === "string" && ["reported", "computed", "logged", "estimated", "native-log", "git-local", "derived", "mixed", "unknown"].includes(body.grade) ? body.grade : null,
|
|
137
|
+
_source: typeof body.source === "string" ? body.source : null,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function _getWindow(base, windowKey, timeoutMs, fetchImpl) {
|
|
142
|
+
const ac = new AbortController();
|
|
143
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
144
|
+
try {
|
|
145
|
+
const res = await fetchImpl(
|
|
146
|
+
`${base}/api/pillars?window=${encodeURIComponent(windowKey)}`,
|
|
147
|
+
{ headers: { accept: "application/json" }, signal: ac.signal, redirect: "error" },
|
|
148
|
+
);
|
|
149
|
+
if (!res || res.status !== 200) throw new Error(`HTTP ${res?.status}`);
|
|
150
|
+
let body;
|
|
151
|
+
try {
|
|
152
|
+
body = JSON.parse(await res.text());
|
|
153
|
+
} catch {
|
|
154
|
+
throw new Error("malformed JSON");
|
|
155
|
+
}
|
|
156
|
+
return _parseWindow(body, windowKey);
|
|
157
|
+
} catch (e) {
|
|
158
|
+
if (e?.name === "AbortError") throw new Error(`timeout after ${timeoutMs}ms`);
|
|
159
|
+
throw e;
|
|
160
|
+
} finally {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Pull the four windows from the collector. Never throws — returns
|
|
167
|
+
* { ok:true, result } (a tokenpull-shaped result tagged source:'otel-cc') or
|
|
168
|
+
* { ok:false, url, reason }.
|
|
169
|
+
*/
|
|
170
|
+
export async function tokenpullOtel(opts = {}) {
|
|
171
|
+
let base;
|
|
172
|
+
try {
|
|
173
|
+
base = otelBaseUrl(opts);
|
|
174
|
+
} catch (e) {
|
|
175
|
+
return { ok: false, url: null, reason: e.message };
|
|
176
|
+
}
|
|
177
|
+
const fetchImpl = opts.otelFetch || fetch;
|
|
178
|
+
const probeMs = opts.otelProbeTimeoutMs ?? OTEL_PROBE_TIMEOUT_MS;
|
|
179
|
+
const fetchMs = opts.otelFetchTimeoutMs ?? OTEL_FETCH_TIMEOUT_MS;
|
|
180
|
+
const keys = WINDOWS.map((w) => w.key);
|
|
181
|
+
try {
|
|
182
|
+
// Probe on the first window with the short timeout; only then pull the rest.
|
|
183
|
+
const first = await _getWindow(base, keys[0], probeMs, fetchImpl);
|
|
184
|
+
const rest = await Promise.all(
|
|
185
|
+
keys.slice(1).map((k) => _getWindow(base, k, fetchMs, fetchImpl)),
|
|
186
|
+
);
|
|
187
|
+
const rows = [first, ...rest];
|
|
188
|
+
if (rows.some((row, i) => i > 0 && Object.keys(row.pillars).some(k => row.pillars[k] < rows[i-1].pillars[k]))) throw new Error("non-monotonic collector windows");
|
|
189
|
+
const nowMs =
|
|
190
|
+
opts.now == null
|
|
191
|
+
? Date.now()
|
|
192
|
+
: typeof opts.now === "number"
|
|
193
|
+
? opts.now
|
|
194
|
+
: Date.parse(opts.now);
|
|
195
|
+
const all = rows.find((r) => r.window === "all");
|
|
196
|
+
return {
|
|
197
|
+
ok: true,
|
|
198
|
+
result: {
|
|
199
|
+
platform: "claude",
|
|
200
|
+
source: OTEL_SOURCE_TAG,
|
|
201
|
+
root: base,
|
|
202
|
+
generatedAt: new Date(nowMs).toISOString(),
|
|
203
|
+
files: 0,
|
|
204
|
+
totalMessages: all ? all.messages : 0,
|
|
205
|
+
excludedTooling: [],
|
|
206
|
+
windows: rows.map(
|
|
207
|
+
({ window, pillars, messages, sinceMs, grade, turns, sessions, turnsSource, provenance, coverage }) => ({
|
|
208
|
+
window,
|
|
209
|
+
pillars,
|
|
210
|
+
messages,
|
|
211
|
+
sinceMs,
|
|
212
|
+
grade,
|
|
213
|
+
turns,
|
|
214
|
+
sessions,
|
|
215
|
+
turnsSource,
|
|
216
|
+
provenance,
|
|
217
|
+
coverage,
|
|
218
|
+
}),
|
|
219
|
+
),
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
} catch (e) {
|
|
223
|
+
return { ok: false, url: base, reason: e?.message || String(e) };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Source-aware pull. `transcriptsPull` is a thunk for the existing adapter path.
|
|
229
|
+
* Only platform 'claude' is otel-backed; every other platform is always transcripts.
|
|
230
|
+
* Returns the pull result with `source` set ('otel-cc' | 'transcripts') and, on an
|
|
231
|
+
* auto-mode fallback, `otelFallback: '<reason>'` so the UI can say why.
|
|
232
|
+
*/
|
|
233
|
+
export async function pullWithSource(platform, opts = {}, transcriptsPull) {
|
|
234
|
+
const mode = normalizeSource(opts.source);
|
|
235
|
+
const tag = (r, extra = {}) =>
|
|
236
|
+
r && typeof r === "object" ? { ...r, source: "transcripts", ...extra } : r;
|
|
237
|
+
// Test injection: a mock adapter means "these are the transcripts" — never probe a
|
|
238
|
+
// real collector that may be running on the dev machine unless a URL is injected too.
|
|
239
|
+
const skipProbe = opts.adapter && !opts.otelUrl;
|
|
240
|
+
if ((platform || "claude") !== "claude") return transcriptsPull();
|
|
241
|
+
if (mode === "transcripts" || (skipProbe && mode === "auto"))
|
|
242
|
+
return tag(await transcriptsPull());
|
|
243
|
+
const o = await tokenpullOtel(mode === "otel" ? {
|
|
244
|
+
...opts,
|
|
245
|
+
otelProbeTimeoutMs: opts.otelProbeTimeoutMs ?? OTEL_REQUIRED_PROBE_TIMEOUT_MS,
|
|
246
|
+
otelFetchTimeoutMs: opts.otelFetchTimeoutMs ?? OTEL_REQUIRED_FETCH_TIMEOUT_MS,
|
|
247
|
+
} : opts);
|
|
248
|
+
if (o.ok) return o.result;
|
|
249
|
+
if (mode === "otel") {
|
|
250
|
+
const error = new Error(`source otel: sigrank-otel collector unavailable (${o.reason}). Start the collector or use --source auto|transcripts.`);
|
|
251
|
+
error.code = "SIGRANK_READ_FAILED";
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
return tag(await transcriptsPull(), { otelFallback: o.reason });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Human marker for watch/TUI rows. */
|
|
258
|
+
export function sourceMarker(pulled) {
|
|
259
|
+
if (!pulled) return null;
|
|
260
|
+
if (pulled.source === OTEL_SOURCE_TAG) {
|
|
261
|
+
const ev = evaluatePublication(pulled);
|
|
262
|
+
return ev.eligible
|
|
263
|
+
? "source: otel (live; complete coverage, real turns)"
|
|
264
|
+
: `source: otel (live; preview only — ${ev.reasons[0] || "coverage not verified"})`;
|
|
265
|
+
}
|
|
266
|
+
if (pulled.source === "transcripts") return "source: transcripts";
|
|
267
|
+
return null;
|
|
268
|
+
}
|
package/adapters/tokenpull.mjs
CHANGED
|
@@ -113,6 +113,40 @@ async function* _walkJsonl(dir, _counter = { n: 0 }) {
|
|
|
113
113
|
for (const p of paths) yield p;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
/**
|
|
117
|
+
* typedPrompt — true when a Claude Code transcript record is a REAL user prompt.
|
|
118
|
+
* Owner definition (2026-12-01): a turn = A+B, one user prompt plus Claude's reply;
|
|
119
|
+
* the prompt (A) is what we count. Not prompts: tool results (also type "user"),
|
|
120
|
+
* meta records, compaction summaries, slash-command / local-command / task-notification /
|
|
121
|
+
* system-reminder wrappers, and any sidechain (subagent) record.
|
|
122
|
+
* Same rules as sigrank-otel src/backfill.mjs typed() + turnStats().
|
|
123
|
+
*/
|
|
124
|
+
const NON_PROMPT_PREFIXES = [
|
|
125
|
+
"<command-",
|
|
126
|
+
"<local-command",
|
|
127
|
+
"<task-notification",
|
|
128
|
+
"<system-reminder",
|
|
129
|
+
"Caveat:",
|
|
130
|
+
"[Request interrupted by user", // Claude Code's synthetic interrupt record, not something the operator typed
|
|
131
|
+
];
|
|
132
|
+
export function typedPrompt(rec) {
|
|
133
|
+
if (!rec || rec.type !== "user" || rec.isSidechain) return false;
|
|
134
|
+
if (rec.isMeta || rec.isCompactSummary) return false;
|
|
135
|
+
const c = rec.message?.content;
|
|
136
|
+
let t;
|
|
137
|
+
if (typeof c === "string") t = c;
|
|
138
|
+
else if (Array.isArray(c)) {
|
|
139
|
+
if (c.some((b) => b?.type === "tool_result")) return false;
|
|
140
|
+
t = c
|
|
141
|
+
.filter((b) => b?.type === "text")
|
|
142
|
+
.map((b) => b.text || "")
|
|
143
|
+
.join(" ");
|
|
144
|
+
} else return false;
|
|
145
|
+
if (!t.trim()) return false;
|
|
146
|
+
const s = t.trimStart();
|
|
147
|
+
return !NON_PROMPT_PREFIXES.some((p) => s.startsWith(p));
|
|
148
|
+
}
|
|
149
|
+
|
|
116
150
|
/**
|
|
117
151
|
* Claude Code adapter. Yields one record per billed assistant message:
|
|
118
152
|
* { id, sid, ts, input, output, cacheCreate, cacheRead, file }. Walks
|
|
@@ -159,6 +193,50 @@ export const claudeAdapter = {
|
|
|
159
193
|
}
|
|
160
194
|
}
|
|
161
195
|
},
|
|
196
|
+
/**
|
|
197
|
+
* prompts(root) — one { uuid, sid, ts } per real user prompt (see typedPrompt).
|
|
198
|
+
* Deduped by record uuid across files (resumed/forked sessions copy earlier
|
|
199
|
+
* records into new transcripts). Subagent transcripts are skipped. Reads
|
|
200
|
+
* counts only — never message text leaves this function. Unreadable files are
|
|
201
|
+
* counted in stats.unreadable (optional). It re-reads the transcripts rather than
|
|
202
|
+
* sharing messages()'s pass: messages() is the cross-adapter contract and
|
|
203
|
+
* changing what it yields would touch every adapter.
|
|
204
|
+
*/
|
|
205
|
+
async *prompts(root, stats) {
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
for await (const path of _walkJsonl(root)) {
|
|
208
|
+
let text;
|
|
209
|
+
try {
|
|
210
|
+
text = await readFile(path, "utf8");
|
|
211
|
+
} catch {
|
|
212
|
+
if (stats) stats.unreadable = (stats.unreadable || 0) + 1; // counted, surfaced by tokenpull()
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const rel = path.startsWith(root) ? path.slice(root.length + 1) : path;
|
|
216
|
+
if (EXCLUDE_TOOLING.test(rel)) continue;
|
|
217
|
+
if (/(^|[/\\])subagents[/\\]/.test(rel)) continue; // subagent transcripts are not prompts
|
|
218
|
+
for (const line of text.split("\n")) {
|
|
219
|
+
const s = line.trim();
|
|
220
|
+
if (!s || !s.includes('"user"')) continue;
|
|
221
|
+
let ev;
|
|
222
|
+
try {
|
|
223
|
+
ev = JSON.parse(s);
|
|
224
|
+
} catch {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (!typedPrompt(ev)) continue;
|
|
228
|
+
if (ev.uuid) {
|
|
229
|
+
if (seen.has(ev.uuid)) continue;
|
|
230
|
+
seen.add(ev.uuid);
|
|
231
|
+
}
|
|
232
|
+
yield {
|
|
233
|
+
uuid: ev.uuid || null,
|
|
234
|
+
sid: ev.sessionId || null,
|
|
235
|
+
ts: ev.timestamp || ev.ts || null,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
},
|
|
162
240
|
};
|
|
163
241
|
|
|
164
242
|
/**
|
|
@@ -191,6 +269,14 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
191
269
|
}
|
|
192
270
|
const msgs = [...seen.values()];
|
|
193
271
|
|
|
272
|
+
// Real turns + sessions (owner 2026-12-01: turn = A+B = one user prompt + the reply).
|
|
273
|
+
// Only adapters that expose prompts() carry them; others keep the message-count proxy.
|
|
274
|
+
const prompts = [];
|
|
275
|
+
const hasPrompts = typeof adapter.prompts === "function";
|
|
276
|
+
const promptStats = { unreadable: 0 };
|
|
277
|
+
if (hasPrompts)
|
|
278
|
+
for await (const p of adapter.prompts(r, promptStats)) prompts.push(p);
|
|
279
|
+
|
|
194
280
|
const windows = WINDOWS.map((w) => {
|
|
195
281
|
const cutoff = w.days === Infinity ? -Infinity : nowMs - w.days * DAY_MS;
|
|
196
282
|
// NULL-TIMESTAMP WINDOW ASYMMETRY: the `all` window returns true unconditionally,
|
|
@@ -215,7 +301,17 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
215
301
|
}),
|
|
216
302
|
{ input: 0, output: 0, cacheCreate: 0, cacheRead: 0 },
|
|
217
303
|
);
|
|
218
|
-
|
|
304
|
+
const win = { window: w.key, pillars, messages: inWin.length };
|
|
305
|
+
if (hasPrompts) {
|
|
306
|
+
const inP = prompts.filter((p) => {
|
|
307
|
+
if (w.days === Infinity) return true;
|
|
308
|
+
const t = p.ts ? Date.parse(p.ts) : NaN;
|
|
309
|
+
return Number.isFinite(t) && t >= cutoff && t <= nowMs;
|
|
310
|
+
});
|
|
311
|
+
win.turns = inP.length;
|
|
312
|
+
win.sessions = new Set(inP.map((p) => p.sid).filter(Boolean)).size;
|
|
313
|
+
}
|
|
314
|
+
return win;
|
|
219
315
|
});
|
|
220
316
|
|
|
221
317
|
// Auto-detect background tooling we excluded → report it (the MCP "asks" by telling).
|
|
@@ -235,6 +331,7 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
235
331
|
generatedAt: new Date(nowMs).toISOString(),
|
|
236
332
|
files: files.size,
|
|
237
333
|
totalMessages: msgs.length,
|
|
334
|
+
...(hasPrompts ? { promptFilesUnreadable: promptStats.unreadable } : {}),
|
|
238
335
|
excludedTooling,
|
|
239
336
|
windows,
|
|
240
337
|
};
|
package/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"$schema": "https://raw.githubusercontent.com/anthropics/mcpb/main/schemas/mcpb-manifest-v0.4.schema.json",
|
|
3
3
|
"manifest_version": "0.4",
|
|
4
4
|
"name": "sigrank",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.53",
|
|
6
6
|
"description": "Ranks AI coding operators by token cascade efficiency (Yield = cache_read \u00d7 output / input\u00b2). 25 tools including SigRank Standard record, yield calculation, local token usage pulls, signed submission, and tokscale-powered analytics (market share, developer profiles, model trends, cost analysis, device profiles, MCP usage, competitive intelligence). Privacy-first: runs locally, only four token counts leave the machine.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "SunrisesIllNeverSee",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sigrank",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.53",
|
|
4
4
|
"author": "SunrisesIllNeverSee (https://github.com/SunrisesIllNeverSee)",
|
|
5
5
|
"description": "SigRank measures observable AI-operator token-cascade efficiency: Yield, Leverage, Velocity, 10xDEV.",
|
|
6
6
|
"mcpName": "io.github.SunrisesIllNeverSee/sigrank-mcp",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
},
|
|
25
25
|
"scripts": {
|
|
26
26
|
"start": "node index.mjs",
|
|
27
|
-
"test": "node test.mjs && node --test __tests__/sign.test.mjs __tests__/cascade.test.mjs __tests__/badges.test.mjs __tests__/tui-input.test.mjs __tests__/standard-record.test.mjs __tests__/standard-cli.test.mjs __tests__/product-architecture.test.mjs __tests__/tteop-delegation.test.mjs __tests__/mcp-stdio.test.mjs __tests__/multi-update-scroll.test.mjs",
|
|
27
|
+
"test": "node test.mjs && node --test __tests__/sign.test.mjs __tests__/cascade.test.mjs __tests__/badges.test.mjs __tests__/tui-input.test.mjs __tests__/standard-record.test.mjs __tests__/standard-cli.test.mjs __tests__/product-architecture.test.mjs __tests__/tteop-delegation.test.mjs __tests__/mcp-stdio.test.mjs __tests__/multi-update-scroll.test.mjs __tests__/real-turns.test.mjs",
|
|
28
28
|
"test:packaged": "node scripts/packed-artifact-smoke.mjs",
|
|
29
29
|
"sync:platforms": "node scripts/sync-platforms.mjs"
|
|
30
30
|
},
|
package/presentation/cli.mjs
CHANGED
|
@@ -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(
|
|
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"
|
|
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();
|
package/presentation/tui.mjs
CHANGED
|
@@ -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";
|
|
@@ -2665,8 +2666,12 @@ async function loadWatchData(platform = "all", win = "all-windows") {
|
|
|
2665
2666
|
const winFilter = win && win !== "all-windows" ? win : null;
|
|
2666
2667
|
// Detect active platforms (any window with input+output > 0), respecting an optional [P] focus.
|
|
2667
2668
|
const candidates = platFilter ? [platFilter] : ALL_PLATFORMS;
|
|
2669
|
+
// source auto: claude reads the live sigrank-otel collector when it answers the
|
|
2670
|
+
// ≤300 ms probe, else the transcripts (same rule as `sigrank watch`).
|
|
2668
2671
|
const settled = await Promise.allSettled(
|
|
2669
|
-
candidates.map((p) =>
|
|
2672
|
+
candidates.map((p) =>
|
|
2673
|
+
pullWithSource(p, { source: "auto" }, () => tokenpullAny(p)),
|
|
2674
|
+
),
|
|
2670
2675
|
);
|
|
2671
2676
|
const active = [];
|
|
2672
2677
|
for (const r of settled) {
|
|
@@ -2722,7 +2727,13 @@ function renderWatchData(data) {
|
|
|
2722
2727
|
const byWin = {};
|
|
2723
2728
|
for (const ww of d.windows || []) byWin[ww.window] = ww;
|
|
2724
2729
|
emit();
|
|
2725
|
-
|
|
2730
|
+
const srcNote =
|
|
2731
|
+
d.source === OTEL_SOURCE_TAG
|
|
2732
|
+
? " " + (evaluatePublication(d).eligible ? green : gold)(sourceMarker(d))
|
|
2733
|
+
: d.platform === "claude"
|
|
2734
|
+
? " " + dim(d.otelFallback ? "source: transcripts (collector fallback)" : "source: transcripts")
|
|
2735
|
+
: "";
|
|
2736
|
+
emit(` ${cyan(d.platform)}${d.estimated ? dim(" (est)") : ""}${srcNote}`);
|
|
2726
2737
|
for (const wk of WINS) {
|
|
2727
2738
|
if (used >= budget - 1) break;
|
|
2728
2739
|
const ww = byWin[wk];
|
|
@@ -3701,7 +3712,13 @@ export async function runTui({
|
|
|
3701
3712
|
multiAbort = null;
|
|
3702
3713
|
for (const p of platforms) {
|
|
3703
3714
|
try {
|
|
3704
|
-
|
|
3715
|
+
// source: transcripts — the preview above was built from the transcript
|
|
3716
|
+
// dashboard; submitting collector numbers would break see→confirm→send.
|
|
3717
|
+
const out = await callTool("submit_verified", {
|
|
3718
|
+
platform: p,
|
|
3719
|
+
confirm: true,
|
|
3720
|
+
source: "transcripts",
|
|
3721
|
+
});
|
|
3705
3722
|
const ws = out.windows || [];
|
|
3706
3723
|
const received = ws.filter((w) => w.status === "received");
|
|
3707
3724
|
const verified = received.filter(
|
|
@@ -3722,6 +3739,7 @@ export async function runTui({
|
|
|
3722
3739
|
const out = await callTool("submit_verified", {
|
|
3723
3740
|
platform: "multi",
|
|
3724
3741
|
confirm: true,
|
|
3742
|
+
source: "transcripts",
|
|
3725
3743
|
});
|
|
3726
3744
|
if (out.status === "error" && out.reason === "platform_read_failed") {
|
|
3727
3745
|
// A platform read failed: the combined total was NOT submitted.
|
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
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
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
|
-
|
|
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(
|
|
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
|
|
@@ -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
package/tools/_helpers.mjs
CHANGED
|
@@ -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") {
|
package/tools/_schemas.mjs
CHANGED
|
@@ -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)",
|
|
@@ -9,6 +9,14 @@ import { SUBMIT_OUTPUT, ANNOTATIONS } from "./_schemas.mjs";
|
|
|
9
9
|
import { collectMultiPlatforms, multiAbortResult } from "./_multi.mjs";
|
|
10
10
|
import { pullByPlatform, WINDOW_TYPE } from "./_helpers.mjs";
|
|
11
11
|
import { _computeReportBlock } from "./_report.mjs";
|
|
12
|
+
import { normalizeSource, OTEL_SOURCE_TAG } from "../adapters/otel.mjs";
|
|
13
|
+
import {
|
|
14
|
+
evaluatePublication,
|
|
15
|
+
measureWindow,
|
|
16
|
+
otelSubmissionMeta,
|
|
17
|
+
publicationFields,
|
|
18
|
+
turnsBasis,
|
|
19
|
+
} from "../submit/publication.mjs";
|
|
12
20
|
|
|
13
21
|
export const TOOL_DEF = {
|
|
14
22
|
name: "submit_verified",
|
|
@@ -34,6 +42,12 @@ export const TOOL_DEF = {
|
|
|
34
42
|
description:
|
|
35
43
|
"source platform (default: claude). 'multi' = combined cascade summed across all locally-detected platforms (needs 2+ active); empty windows are skipped.",
|
|
36
44
|
},
|
|
45
|
+
source: {
|
|
46
|
+
type: "string",
|
|
47
|
+
enum: ["auto", "otel", "transcripts"],
|
|
48
|
+
description:
|
|
49
|
+
"Default transcripts. auto/otel read the local collector (Claude only) and may publish only when every window reports complete coverage and real turns/sessions; otherwise they are dry-run preview only and the blockers are returned.",
|
|
50
|
+
},
|
|
37
51
|
confirm: {
|
|
38
52
|
type: "boolean",
|
|
39
53
|
description:
|
|
@@ -66,6 +80,11 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
66
80
|
};
|
|
67
81
|
}
|
|
68
82
|
const platform = args?.platform || "claude";
|
|
83
|
+
const source = normalizeSource(args?.source ?? ctx.opts.source);
|
|
84
|
+
if (source !== "transcripts" && platform !== "claude") {
|
|
85
|
+
return { status: "error", reason: "otel_preview_only", detail: "The collector source is Claude-only; use source: transcripts for other platforms and multi.", windows: [] };
|
|
86
|
+
}
|
|
87
|
+
const pullOpts = { ...ctx.opts, source };
|
|
69
88
|
|
|
70
89
|
// MULTI: the combined cross-platform cascade. The dashboard already SUMS every
|
|
71
90
|
// active platform's pillars (a "claude+codex" row) but never submitted it — this
|
|
@@ -73,7 +92,7 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
73
92
|
// per window and publish as platform='multi' = the operator's TOTAL usage. Empty
|
|
74
93
|
// windows are skipped so a no-activity window never lands as a degenerate row.
|
|
75
94
|
if (platform === "multi") {
|
|
76
|
-
const { detected, failed } = await collectMultiPlatforms(
|
|
95
|
+
const { detected, failed } = await collectMultiPlatforms(pullOpts);
|
|
77
96
|
if (failed.length) return multiAbortResult(failed, { codename: id.codename, operator_id: id.operator_id });
|
|
78
97
|
if (detected.length < 2) {
|
|
79
98
|
return {
|
|
@@ -93,6 +112,12 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
93
112
|
for (const wk of winKeys) {
|
|
94
113
|
const sum = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
|
|
95
114
|
let msgs = 0;
|
|
115
|
+
// Per platform: real turns/sessions where the reader supplied them, the
|
|
116
|
+
// message proxy (turns = messages, sessions = messages/8) for the rest; summed.
|
|
117
|
+
let turns = 0,
|
|
118
|
+
sessions = 0,
|
|
119
|
+
realN = 0,
|
|
120
|
+
proxyN = 0;
|
|
96
121
|
for (const d of detected) {
|
|
97
122
|
const w = (d.windows || []).find((x) => x.window === wk);
|
|
98
123
|
if (!w) continue;
|
|
@@ -101,6 +126,15 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
101
126
|
sum.cacheCreate += w.pillars.cacheCreate || 0;
|
|
102
127
|
sum.cacheRead += w.pillars.cacheRead || 0;
|
|
103
128
|
msgs += w.messages || 0;
|
|
129
|
+
if (turnsBasis(w) === "real") {
|
|
130
|
+
turns += w.turns;
|
|
131
|
+
sessions += Math.max(1, w.sessions);
|
|
132
|
+
realN++;
|
|
133
|
+
} else if ((w.messages || 0) > 0) {
|
|
134
|
+
turns += w.messages;
|
|
135
|
+
sessions += Math.max(1, Math.round(w.messages / 8));
|
|
136
|
+
proxyN++;
|
|
137
|
+
}
|
|
104
138
|
}
|
|
105
139
|
if (sum.input + sum.output + sum.cacheCreate + sum.cacheRead <= 0)
|
|
106
140
|
continue; // skip empty window
|
|
@@ -113,8 +147,15 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
113
147
|
dryRun: !!args?.dry_run,
|
|
114
148
|
force: !!ctx.opts.force,
|
|
115
149
|
report,
|
|
150
|
+
turns,
|
|
151
|
+
sessions,
|
|
152
|
+
});
|
|
153
|
+
out.push({
|
|
154
|
+
window: wk,
|
|
155
|
+
pillars: sum,
|
|
156
|
+
turns_source: !proxyN ? "real" : realN ? "mixed" : "proxy",
|
|
157
|
+
...r,
|
|
116
158
|
});
|
|
117
|
-
out.push({ window: wk, pillars: sum, ...r });
|
|
118
159
|
}
|
|
119
160
|
return {
|
|
120
161
|
platform: "multi",
|
|
@@ -125,7 +166,24 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
125
166
|
};
|
|
126
167
|
}
|
|
127
168
|
|
|
128
|
-
const pulled = await pullByPlatform(platform,
|
|
169
|
+
const pulled = await pullByPlatform(platform, pullOpts);
|
|
170
|
+
// Collector claims never unlock publishing alone: cross-check against our own
|
|
171
|
+
// transcript count for the same platform (and use it for turns/sessions).
|
|
172
|
+
const local =
|
|
173
|
+
pulled.source === OTEL_SOURCE_TAG
|
|
174
|
+
? await pullByPlatform(platform, { ...pullOpts, source: "transcripts" }).catch(() => null)
|
|
175
|
+
: undefined;
|
|
176
|
+
const pub = evaluatePublication(pulled, local, { window: args?.window });
|
|
177
|
+
if (!pub.eligible && !args?.dry_run) {
|
|
178
|
+
return {
|
|
179
|
+
status: "error",
|
|
180
|
+
reason: "otel_preview_only",
|
|
181
|
+
detail: `Collector data is not publication-verified (blocked: ${pub.blocked.join(", ") || "all"}): ${pub.reasons.join("; ")}. Fix the collector, or publish with source: transcripts.`,
|
|
182
|
+
blockers: pub.reasons,
|
|
183
|
+
source: pulled.source,
|
|
184
|
+
windows: [],
|
|
185
|
+
};
|
|
186
|
+
}
|
|
129
187
|
const targets = args?.window
|
|
130
188
|
? pulled.windows.filter((w) => w.window === args.window)
|
|
131
189
|
: pulled.windows;
|
|
@@ -142,14 +200,24 @@ export async function handleSubmitVerified(args, ctx) {
|
|
|
142
200
|
dryRun: !!args?.dry_run,
|
|
143
201
|
force: !!ctx.opts.force,
|
|
144
202
|
report,
|
|
203
|
+
...measureWindow(w, local),
|
|
204
|
+
});
|
|
205
|
+
out.push({
|
|
206
|
+
window: w.window,
|
|
207
|
+
pillars: w.pillars,
|
|
208
|
+
turns_source: measureWindow(w, local).turns_source,
|
|
209
|
+
...(pulled.source === OTEL_SOURCE_TAG ? { source_meta: otelSubmissionMeta(w) } : {}),
|
|
210
|
+
...r,
|
|
145
211
|
});
|
|
146
|
-
out.push({ window: w.window, pillars: w.pillars, ...r });
|
|
147
212
|
}
|
|
148
213
|
return {
|
|
149
214
|
platform: pulled.platform,
|
|
150
215
|
codename: id.codename,
|
|
151
216
|
operator_id: id.operator_id,
|
|
152
217
|
generatedAt: pulled.generatedAt,
|
|
218
|
+
source: pulled.source,
|
|
219
|
+
...publicationFields(pulled, pub),
|
|
220
|
+
...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
|
|
153
221
|
windows: out,
|
|
154
222
|
};
|
|
155
223
|
}
|
package/tools/tokenpull.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* tools/tokenpull.mjs — tokenpull tool.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { publicationFields } from "../submit/publication.mjs";
|
|
5
6
|
import { cascade } from "../analytics/cascade.mjs";
|
|
6
7
|
import { narrate } from "../presentation/narrate.mjs";
|
|
7
8
|
import { ALL_PLATFORMS } from "../adapters/index.mjs";
|
|
@@ -94,6 +95,9 @@ export async function handleTokenpull(args, ctx) {
|
|
|
94
95
|
estimated: pulled.estimated || false,
|
|
95
96
|
...(pulled.ioRatio ? { ioRatio: pulled.ioRatio } : {}),
|
|
96
97
|
generatedAt: pulled.generatedAt,
|
|
98
|
+
...(pulled.source ? { source: pulled.source } : {}),
|
|
99
|
+
...publicationFields(pulled),
|
|
100
|
+
...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
|
|
97
101
|
files: pulled.files,
|
|
98
102
|
totalMessages: pulled.totalMessages,
|
|
99
103
|
windows,
|
|
@@ -8,6 +8,8 @@ import { ALL_PLATFORMS } from "../adapters/index.mjs";
|
|
|
8
8
|
import { ensureIdentity } from "../identity/keystore.mjs";
|
|
9
9
|
import { submitSignedWindow } from "../submit/index.mjs";
|
|
10
10
|
import { TOKENPULL_OUTPUT, ANNOTATIONS } from "./_schemas.mjs";
|
|
11
|
+
import { normalizeSource, sourceMarker } from "../adapters/otel.mjs";
|
|
12
|
+
import { evaluatePublication, measureWindow, publicationFields } from "../submit/publication.mjs";
|
|
11
13
|
import {
|
|
12
14
|
pullByPlatform,
|
|
13
15
|
WATCH_SUBMIT_COOLDOWN_MS,
|
|
@@ -42,6 +44,12 @@ export const TOOL_DEF = {
|
|
|
42
44
|
description:
|
|
43
45
|
"which window to watch (default: 7d — most sensitive to recent activity)",
|
|
44
46
|
},
|
|
47
|
+
source: {
|
|
48
|
+
type: "string",
|
|
49
|
+
enum: ["auto", "otel", "transcripts"],
|
|
50
|
+
description:
|
|
51
|
+
"Default transcripts. auto = collector if reachable, else transcripts; otel = collector required. Collector sources publish only when coverage is complete and turns are real; otherwise preview-only.",
|
|
52
|
+
},
|
|
45
53
|
submit: {
|
|
46
54
|
type: "boolean",
|
|
47
55
|
description:
|
|
@@ -69,7 +77,8 @@ export async function handleWatchTokenpull(args, ctx) {
|
|
|
69
77
|
const watchWindow = args?.window || "7d";
|
|
70
78
|
const intervalS = Math.max(10, Number(args?.interval_s) || 60);
|
|
71
79
|
|
|
72
|
-
const
|
|
80
|
+
const source = normalizeSource(args?.source ?? ctx.opts.source);
|
|
81
|
+
const pulled = await pullByPlatform(platform, { ...ctx.opts, source });
|
|
73
82
|
const win = pulled.windows.find((w) => w.window === watchWindow);
|
|
74
83
|
if (!win)
|
|
75
84
|
throw new Error(
|
|
@@ -83,12 +92,20 @@ export async function handleWatchTokenpull(args, ctx) {
|
|
|
83
92
|
// watched window to the verified ingest path. Default OFF = preview only. The server
|
|
84
93
|
// dedups identical re-submits (exact snapshot_hash → 422), so re-calling is safe.
|
|
85
94
|
let auth_submit = null;
|
|
95
|
+
// One evaluation for this window; the transcript cross-check runs only when publishing.
|
|
96
|
+
const local =
|
|
97
|
+
args?.submit === true && args?.confirm === true && pulled.source === "otel-cc"
|
|
98
|
+
? await pullByPlatform(platform, { ...ctx.opts, source: "transcripts" }).catch(() => null)
|
|
99
|
+
: undefined;
|
|
100
|
+
const pub = evaluatePublication(pulled, local, { window: watchWindow });
|
|
86
101
|
if (args?.submit === true && args?.confirm !== true) {
|
|
87
102
|
auth_submit = {
|
|
88
103
|
status: "confirmation_required",
|
|
89
104
|
detail:
|
|
90
105
|
"watch_tokenpull with submit:true publishes to the public board. Ask the user for approval, then call again with confirm: true.",
|
|
91
106
|
};
|
|
107
|
+
} else if (args?.submit === true && !pub.eligible) {
|
|
108
|
+
auth_submit = { status: "error", reason: "otel_preview_only", detail: `Collector data is not publication-verified (blocked: ${pub.blocked.join(", ") || watchWindow}): ${pub.reasons.join("; ")}. Fix the collector, or use source: transcripts.`, blockers: pub.reasons };
|
|
92
109
|
} else if (args?.submit === true) {
|
|
93
110
|
const id = ctx.opts.identity || ensureIdentity();
|
|
94
111
|
if (id.codename && id.operator_id && id.private_key_pkcs8_b64) {
|
|
@@ -118,6 +135,7 @@ export async function handleWatchTokenpull(args, ctx) {
|
|
|
118
135
|
fetchImpl: ctx.doFetch,
|
|
119
136
|
platform: pulled.platform,
|
|
120
137
|
now: ctx.opts.now,
|
|
138
|
+
...measureWindow(win, local),
|
|
121
139
|
},
|
|
122
140
|
);
|
|
123
141
|
if (auth_submit?.status !== "error")
|
|
@@ -139,6 +157,10 @@ export async function handleWatchTokenpull(args, ctx) {
|
|
|
139
157
|
card,
|
|
140
158
|
generatedAt: pulled.generatedAt,
|
|
141
159
|
poll_interval_s: intervalS,
|
|
160
|
+
source: pulled.source,
|
|
161
|
+
source_marker: sourceMarker(pulled),
|
|
162
|
+
...(pulled.source === "otel-cc" ? { source_grade: win.grade, ...publicationFields(pulled, pub) } : {}),
|
|
163
|
+
...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
|
|
142
164
|
auth_submit,
|
|
143
165
|
note: "One snapshot per call — re-call at your poll interval to detect changes.",
|
|
144
166
|
};
|