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.
- package/CHANGELOG.md +7 -1
- package/README.md +11 -1
- package/adapters/otel.mjs +268 -0
- package/adapters/tokenpull.mjs +98 -1
- package/lib/integrity-worker.mjs +42 -0
- package/lib/integrity.mjs +402 -0
- package/lib/vendor/tokenpull-integrity/humanlike.mjs +257 -0
- package/lib/vendor/tokenpull-integrity/integrity.mjs +467 -0
- package/lib/vendor/tokenpull-integrity/model/human-v1.json +127 -0
- package/manifest.json +2 -2
- package/package.json +2 -2
- package/presentation/cli.mjs +76 -7
- package/presentation/tui.mjs +47 -4
- package/proxy.mjs +7 -4
- package/submit/index.mjs +33 -7
- package/submit/publication.mjs +140 -0
- package/tokenpull.mjs +1 -0
- package/tools/_helpers.mjs +13 -0
- package/tools/_schemas.mjs +53 -0
- package/tools/check-integrity.mjs +54 -0
- package/tools/index.mjs +4 -0
- package/tools/submit-verified.mjs +117 -5
- package/tools/tokenpull.mjs +4 -0
- package/tools/watch-tokenpull.mjs +23 -1
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tokenpull Integrity: checks 1 (record integrity), 2 (source agreement), 3 (human likelihood, humanlike.mjs), 4 (cache pumping),
|
|
3
|
+
// 5 (cross-adapter, crossadapter.mjs), 6 (double counting).
|
|
4
|
+
// Read-only. Reads Claude Code transcripts and Tokenpull's stored OTel rows; writes one JSON report per window.
|
|
5
|
+
// Reports carry counts, scores and flags with a file ordinal and a 1-based line number. Never prompt text, paths, session ids or user ids.
|
|
6
|
+
// A flag means "worth a look", not "cheating". See ../DESIGN.md.
|
|
7
|
+
//
|
|
8
|
+
// node integrity.mjs run [--roots a:b] [--data DIR] [--out DIR] [--now ISO] [--max-flags N]
|
|
9
|
+
// node integrity.mjs where <ordinal> --report FILE [--roots a:b] prints the local path for a file ordinal (this machine only; never written to a report)
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
|
|
16
|
+
export const TOOL = 'tokenpull-integrity';
|
|
17
|
+
export const VERSION = '0.1.0';
|
|
18
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
19
|
+
const DAY = 864e5, GRACE_MS = 10 * 60e3;
|
|
20
|
+
export const WINDOWS = { '7d': 7, '30d': 30, '90d': 90, all: 0 };
|
|
21
|
+
|
|
22
|
+
// ---- thresholds (every one is reported in the output so a run can be reproduced) ----
|
|
23
|
+
export const T = {
|
|
24
|
+
backwardsMs: 60e3, // check 1: a record more than this earlier than the latest record before it in the same file
|
|
25
|
+
futureMs: 10 * 60e3, // check 1: a record dated more than this after the run
|
|
26
|
+
maxContext: 1_000_000, // check 1: input + cache_read + cache_creation above this is impossible for any current model
|
|
27
|
+
maxOutput: 128_000, // check 1: output above this is impossible
|
|
28
|
+
driftAbs: 100, driftRel: 0.01, // check 2: a matched request whose token fields differ by more than both of these
|
|
29
|
+
unverifiedShare: 0.10, // check 2: transcript-only requests or tokens above this share of the live-covered window
|
|
30
|
+
gapShare: 0.02, // check 2: tokens in sessions with no telemetry at all (receiver off) above this share of the window
|
|
31
|
+
otelOnlyShare: 0.02, // check 2: tokens in stored OTel rows no transcript shows, above this share of the window
|
|
32
|
+
robustZ: 3.5, // check 4: robust z (median/MAD of log values) far outside the operator's own range
|
|
33
|
+
madFloor: 0.05, // check 4: minimum spread (log10 units) for the robust z
|
|
34
|
+
minUnits: 8, // check 4: fewer sessions or days than this: no outlier test (too little of the operator's own range)
|
|
35
|
+
minSessionReqs: 20, // check 4: sessions with fewer requests are pooled per UTC day
|
|
36
|
+
resendRun: 5, // check 4: this many consecutive requests re-sending the same context (within resendTol) with output <= resendMaxOut
|
|
37
|
+
resendTol: 0.01,
|
|
38
|
+
resendMaxOut: 50,
|
|
39
|
+
loopShare: 0.02, // check 4: tokens in cross-session re-send loops above this share of the window
|
|
40
|
+
replayMinReqs: 10, // check 6: sessions with at least this many requests are compared by their token sequence
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// ---- same population rules as Tokenpull (sigrank-otel src/transcripts.mjs) ----
|
|
44
|
+
const EXCLUDE_TOOLING = /(^|[/-])(claude-mem|mem0|claude-self-reflect|basic-memory|memento|cipher-mem|memory-keeper)\b|observer-(sessions|archive)/i;
|
|
45
|
+
const isSubagentPath = (rel) => /(^|[/\\])subagents[/\\]/.test(rel);
|
|
46
|
+
// Any Claude model id: first-party, dated 2024 ids, Bedrock (anthropic.claude-…-v2:0), Vertex (…@date), gateway prefixes. Other models are context.
|
|
47
|
+
const CLAUDE_MODEL = /claude-[a-z0-9]/i;
|
|
48
|
+
const idShape = (id) => String(id).replace(/[A-Za-z0-9]+/g, 'x');
|
|
49
|
+
const sourceOf = (q = '') => (!q || q === 'main' || q === 'sdk' || q.startsWith('repl_main')) ? 'you'
|
|
50
|
+
: (q.startsWith('agent:') || q.includes('subagent')) ? 'subagents' : q.includes('compact') ? 'compaction' : 'harness';
|
|
51
|
+
|
|
52
|
+
const home = (p) => path.resolve(p.replace(/^~(?=\/|$)/, os.homedir()));
|
|
53
|
+
function defaultData() {
|
|
54
|
+
try { const c = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/sigrank-otel/config.json'), 'utf8')); if (c.dataDir) return home(c.dataDir); } catch {}
|
|
55
|
+
return path.join(os.homedir(), '.local/share/sigrank-otel');
|
|
56
|
+
}
|
|
57
|
+
// Same walk as Tokenpull's walkSync: real directories are walked, symlinked directories are not, and a symlinked .jsonl file is read.
|
|
58
|
+
export function listTranscripts(roots) {
|
|
59
|
+
const out = [];
|
|
60
|
+
const walk = (d, root) => {
|
|
61
|
+
let ents; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
62
|
+
for (const e of ents) {
|
|
63
|
+
const p = path.join(d, e.name);
|
|
64
|
+
if (e.isDirectory()) walk(p, root); else if (e.name.endsWith('.jsonl')) out.push([p, p.slice(root.length + 1), e.isSymbolicLink()]);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
for (const r of roots) walk(r, r);
|
|
68
|
+
out.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
|
69
|
+
return out.filter(([, rel]) => !EXCLUDE_TOOLING.test(rel));
|
|
70
|
+
}
|
|
71
|
+
export const fileListHash = (files) => sha(files.map(([p]) => p).join('\n')).slice(0, 16);
|
|
72
|
+
|
|
73
|
+
// JSONL lines split on "\n" only, like Tokenpull. (node:readline also breaks on U+2028/U+2029, which are legal inside JSON strings.)
|
|
74
|
+
export async function* jsonlLines(file) {
|
|
75
|
+
let carry = '';
|
|
76
|
+
for await (const chunk of fs.createReadStream(file, { encoding: 'utf8', highWaterMark: 1 << 20 })) {
|
|
77
|
+
const parts = (carry + chunk).split('\n'); carry = parts.pop();
|
|
78
|
+
yield* parts;
|
|
79
|
+
}
|
|
80
|
+
if (carry) yield carry;
|
|
81
|
+
}
|
|
82
|
+
const num = (v) => (typeof v === 'number' ? v : v == null ? 0 : Number(v));
|
|
83
|
+
const isCount = (v) => v == null || (Number.isInteger(v) && v >= 0);
|
|
84
|
+
const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
85
|
+
const tok = (q) => q.in + q.out + q.cr + q.cc;
|
|
86
|
+
const limitCodes = (q) => { const c = [], ctx = q.in + q.cr + q.cc; if (ctx > T.maxContext) c.push('context_over_limit'); if (q.out > T.maxOutput) c.push('output_over_limit'); if (q.out > 0 && ctx === 0) c.push('output_without_input'); return c; };
|
|
87
|
+
|
|
88
|
+
// ---------------- pass A: transcripts ----------------
|
|
89
|
+
export async function readTranscripts(files, { onFile, now = Date.now() } = {}) {
|
|
90
|
+
const reqs = new Map(); // requestId -> { ms, model, in, out, cr, cc, done, f, l, sid, mid, sub, n, nf }
|
|
91
|
+
const recs = []; // check 1 flags: [check, code, f, l, ms]
|
|
92
|
+
const msgToReq = new Map(); let zeroCopies = 0, nonClaude = 0, noTimeOrModel = 0, symlinked = 0;
|
|
93
|
+
const stats = { files: files.length, lines: 0, records: 0, malformed: 0, subagentFiles: 0, sessions: new Set() };
|
|
94
|
+
for (let f = 0; f < files.length; f++) {
|
|
95
|
+
const [file, rel, link] = files[f]; const sub = isSubagentPath(rel); if (sub) stats.subagentFiles++; if (link) symlinked++;
|
|
96
|
+
const uuids = new Map(); let maxMs = 0, lastMs = 0, l = 0; const pendingParents = [], ids = [];
|
|
97
|
+
for await (const line of jsonlLines(file)) {
|
|
98
|
+
l++; if (!line.trim()) continue; stats.lines++;
|
|
99
|
+
let r; try { r = JSON.parse(line); } catch { stats.malformed++; recs.push(['record', 'malformed_json', f, l, lastMs || -1]); continue; }
|
|
100
|
+
if (!r || typeof r !== 'object') continue;
|
|
101
|
+
stats.records++;
|
|
102
|
+
const ms = Date.parse(r.timestamp || '') || 0;
|
|
103
|
+
if (r.sessionId) stats.sessions.add(r.sessionId);
|
|
104
|
+
if (ms) {
|
|
105
|
+
lastMs = ms;
|
|
106
|
+
if (ms > now + T.futureMs) recs.push(['record', 'time_in_future', f, l, now]);
|
|
107
|
+
// Attachments carry the time of the thing attached, not of the record, so they are not held to file order.
|
|
108
|
+
else if (maxMs && ms < maxMs - T.backwardsMs && r.type !== 'attachment') recs.push(['record', 'time_backwards', f, l, ms]);
|
|
109
|
+
if (ms > maxMs && ms <= now + T.futureMs) maxMs = ms;
|
|
110
|
+
}
|
|
111
|
+
if (r.uuid) {
|
|
112
|
+
const h = sha(line).slice(0, 16), o = uuids.get(r.uuid);
|
|
113
|
+
if (o && o !== h) recs.push(['record', 'uuid_conflict', f, l, ms]);
|
|
114
|
+
if (!o) uuids.set(r.uuid, h);
|
|
115
|
+
}
|
|
116
|
+
if (r.parentUuid) pendingParents.push([r.parentUuid, l, ms]);
|
|
117
|
+
if (r.type !== 'assistant' || !r.message?.usage) continue;
|
|
118
|
+
const m = r.message, u = m.usage, id = r.requestId;
|
|
119
|
+
if (m.model === '<synthetic>') continue;
|
|
120
|
+
if (!id || !m.id) { recs.push(['record', 'usage_without_ids', f, l, ms]); continue; }
|
|
121
|
+
// Tokenpull's requestOf() drops records without a time or a model: they are never scored, so they are counted, not checked.
|
|
122
|
+
if (!ms || !m.model) { noTimeOrModel++; continue; }
|
|
123
|
+
ids.push([idShape(id), idShape(m.id), l, ms]);
|
|
124
|
+
if (!CLAUDE_MODEL.test(m.model)) nonClaude++;
|
|
125
|
+
if (![u.input_tokens, u.output_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].every(isCount)) recs.push(['record', 'bad_token_value', f, l, ms]);
|
|
126
|
+
const q = { ms, model: m.model, in: num(u.input_tokens), out: num(u.output_tokens), cr: num(u.cache_read_input_tokens), cc: num(u.cache_creation_input_tokens),
|
|
127
|
+
done: m.stop_reason != null, f, l, sid: r.sessionId || '', mid: m.id, sub, n: 1, nf: 1, lastF: f };
|
|
128
|
+
for (const c of limitCodes(q)) recs.push(['record', c, f, l, ms]);
|
|
129
|
+
const om = msgToReq.get(m.id); if (om && om !== id) recs.push(['record', 'message_id_reused', f, l, ms]); else if (!om) msgToReq.set(m.id, id);
|
|
130
|
+
const o = reqs.get(id), zero = tok(q) === 0;
|
|
131
|
+
if (!o) { q.zero = zero; reqs.set(id, q); continue; }
|
|
132
|
+
o.n++; if (o.lastF !== f) { o.nf++; o.lastF = f; }
|
|
133
|
+
if (q.ms < o.ms) o.ms = q.ms; // the earliest copy dates the request, as in Tokenpull
|
|
134
|
+
if (o.mid !== q.mid) recs.push(['record', 'request_id_reused', f, l, ms]);
|
|
135
|
+
// Copies of one request (one record per content block, resumed/forked/rewound sessions): finished copies must agree on usage.
|
|
136
|
+
// Copies written with all-zero usage (seen in forked and rewound files) are counted, not compared, and never replace real numbers.
|
|
137
|
+
if (zero) { zeroCopies++; continue; }
|
|
138
|
+
if (o.zero) { Object.assign(o, { in: q.in, out: q.out, cr: q.cr, cc: q.cc, done: q.done, zero: false }); continue; }
|
|
139
|
+
if (o.done && q.done && (o.in !== q.in || o.out !== q.out || o.cr !== q.cr || o.cc !== q.cc)) recs.push(['record', 'usage_conflict', f, l, ms]);
|
|
140
|
+
if (q.done && (!o.done || q.out > o.out)) Object.assign(o, { in: q.in, out: q.out, cr: q.cr, cc: q.cc, done: true });
|
|
141
|
+
}
|
|
142
|
+
// A parent that never appears in the file. Compaction and session starts use parentUuid null, so they are not counted here.
|
|
143
|
+
for (const [p, pl, pms] of pendingParents) if (!uuids.has(p)) recs.push(['record', 'broken_parent_chain', f, pl, pms || maxMs]);
|
|
144
|
+
// Ids are checked against the shape the rest of the same file uses (first-party, Bedrock, Vertex and gateways differ).
|
|
145
|
+
if (ids.length >= 3) for (const k of [0, 1]) {
|
|
146
|
+
const cnt = new Map(); for (const x of ids) cnt.set(x[k], (cnt.get(x[k]) || 0) + 1);
|
|
147
|
+
const major = [...cnt].sort((a, b) => b[1] - a[1])[0][0];
|
|
148
|
+
for (const x of ids) if (x[k] !== major) recs.push(['record', k ? 'odd_message_id' : 'odd_request_id', f, x[2], x[3]]);
|
|
149
|
+
}
|
|
150
|
+
for (const r of recs) if (r[4] === -1) r[4] = maxMs;
|
|
151
|
+
onFile?.(f);
|
|
152
|
+
}
|
|
153
|
+
return { reqs, recs, files: files.length, stats: { ...stats, sessions: stats.sessions.size, zeroUsageCopies: zeroCopies, nonClaudeModelRequests: nonClaude, droppedNoTimeOrModel: noTimeOrModel, symlinkedFiles: symlinked } };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------------- pass B: stored OTel rows ----------------
|
|
157
|
+
export function otelFiles(dataDir) {
|
|
158
|
+
let names = []; try { names = fs.readdirSync(dataDir); } catch {}
|
|
159
|
+
const months = names.filter((n) => /^otel-\d{4}-\d{2}\.jsonl$/.test(n)).sort();
|
|
160
|
+
return ['backfill.jsonl', ...months, 'otel.jsonl'].map((n) => path.join(dataDir, n)).filter((p) => fs.existsSync(p));
|
|
161
|
+
}
|
|
162
|
+
export async function readOtel(paths) {
|
|
163
|
+
const rows = new Map(); // request_id -> { ms, in, out, cr, cc, live, src, sid, copies, liveCopies, disagree }
|
|
164
|
+
let firstLive = Infinity; const liveMinutes = new Set(); const st = { files: paths.length, apiRows: 0, liveRows: 0, backfillRows: 0 };
|
|
165
|
+
for (const p of paths) {
|
|
166
|
+
for await (const line of jsonlLines(p)) {
|
|
167
|
+
if (!line.trim()) continue;
|
|
168
|
+
const isApi = line.includes('"claude_code.api_request"');
|
|
169
|
+
if (!isApi && !line.includes('"kind":"logs"')) continue;
|
|
170
|
+
let r; try { r = JSON.parse(line); } catch { continue; }
|
|
171
|
+
const a = r?.attrs; if (!a) continue;
|
|
172
|
+
let ms = 0; try { ms = Number(BigInt(r.time || r.end || 0) / 1000000n); } catch {} if (!ms) ms = Date.parse(a['event.timestamp'] || '') || 0;
|
|
173
|
+
const live = !a.backfill;
|
|
174
|
+
if (live && ms) { if (ms < firstLive) firstLive = ms; liveMinutes.add(Math.floor(ms / 60e3)); }
|
|
175
|
+
if (!isApi || !a.request_id) continue;
|
|
176
|
+
st.apiRows++; live ? st.liveRows++ : st.backfillRows++;
|
|
177
|
+
const q = { ms, in: num(a.input_tokens), out: num(a.output_tokens), cr: num(a.cache_read_tokens), cc: num(a.cache_creation_tokens), live, src: sourceOf(a.query_source), sid: a['session.id'] || '' };
|
|
178
|
+
const o = rows.get(a.request_id);
|
|
179
|
+
if (!o) { rows.set(a.request_id, { ...q, copies: 1, liveCopies: live ? 1 : 0, disagree: false }); continue; }
|
|
180
|
+
o.copies++;
|
|
181
|
+
if (live) {
|
|
182
|
+
if (o.live && (o.in !== q.in || o.out !== q.out || o.cr !== q.cr || o.cc !== q.cc)) o.disagree = true;
|
|
183
|
+
o.liveCopies++; if (!o.live) Object.assign(o, q);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return { rows, firstLive: isFinite(firstLive) ? firstLive : null, liveMinutes, stats: st };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ---------------- robust outliers ----------------
|
|
191
|
+
const median = (a) => { if (!a.length) return NaN; const s = [...a].sort((x, y) => x - y), m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
|
|
192
|
+
export function robustZ(values) {
|
|
193
|
+
const med = median(values), mad = median(values.map((v) => Math.abs(v - med)));
|
|
194
|
+
const m = Math.max(mad, T.madFloor); // identical units give MAD 0; the floor keeps the test alive
|
|
195
|
+
return { med, mad, n: values.length, z: (v) => (values.length >= T.minUnits ? (0.6745 * (v - med)) / m : 0) };
|
|
196
|
+
}
|
|
197
|
+
export const yieldOf = (t) => (t.in > 0 ? (t.cr * t.out) / (t.in * t.in) : null);
|
|
198
|
+
const near = (a, b) => Math.abs(a - b) <= T.resendTol * Math.max(a, b);
|
|
199
|
+
|
|
200
|
+
// ---------------- checks for one window ----------------
|
|
201
|
+
export function evaluate({ tx, otel, windowName, now, maxFlags = 200, human = null, crossAdapter = null }) {
|
|
202
|
+
const days = WINDOWS[windowName], since = days ? now - days * DAY : 0;
|
|
203
|
+
const inWin = (ms) => ms && ms >= since && ms <= now;
|
|
204
|
+
const winReqs = [...tx.reqs].filter(([, q]) => inWin(q.ms));
|
|
205
|
+
const cap = (arr) => arr.slice(0, maxFlags).map(([code, f, l, extra]) => ({ code, file: f, line: l, ...(extra || {}) }));
|
|
206
|
+
const ratio = (a, b) => (b ? +(a / b).toFixed(4) : null);
|
|
207
|
+
|
|
208
|
+
// The scored set: what Tokenpull's stored rows count. Every transcript request, with the live OTel numbers where the transcript only
|
|
209
|
+
// has a streaming-start copy, plus stored OTel rows no transcript shows (harness calls are not scored by Tokenpull, so not here either).
|
|
210
|
+
const scored = new Map();
|
|
211
|
+
for (const [id, q] of winReqs) {
|
|
212
|
+
const o = otel?.rows.get(id), useOtel = o && !q.done;
|
|
213
|
+
scored.set(id, { ms: q.ms, sid: q.sid, f: q.f, l: q.l, in: useOtel ? o.in : q.in, out: useOtel ? o.out : q.out, cr: useOtel ? o.cr : q.cr, cc: useOtel ? o.cc : q.cc, from: 'transcript' });
|
|
214
|
+
}
|
|
215
|
+
const otelOnly = [];
|
|
216
|
+
if (otel) for (const [id, o] of otel.rows) {
|
|
217
|
+
if (o.src === 'harness' || !inWin(o.ms) || tx.reqs.has(id)) continue;
|
|
218
|
+
const s = { ms: o.ms, sid: o.sid, f: null, l: null, in: o.in, out: o.out, cr: o.cr, cc: o.cc, from: 'otel', src: o.src };
|
|
219
|
+
scored.set(id, s); otelOnly.push(s);
|
|
220
|
+
}
|
|
221
|
+
const S = [...scored.values()], totalTok = S.reduce((a, q) => a + tok(q), 0);
|
|
222
|
+
|
|
223
|
+
// ---- check 1: record integrity ----
|
|
224
|
+
// File-level codes (one flag per file, with the record count and first line); request-level codes are one flag per record.
|
|
225
|
+
const FILE_LEVEL = new Set(['malformed_json', 'time_backwards', 'broken_parent_chain', 'odd_request_id', 'odd_message_id']);
|
|
226
|
+
const c1raw = tx.recs.filter(([, , , , ms]) => inWin(ms)), c1records = {}, grouped = new Map(), c1 = [];
|
|
227
|
+
for (const [, code, f, l] of c1raw) {
|
|
228
|
+
c1records[code] = (c1records[code] || 0) + 1;
|
|
229
|
+
if (!FILE_LEVEL.has(code)) { c1.push([code, f, l]); continue; }
|
|
230
|
+
const k = code + ':' + f, g = grouped.get(k); if (g) g[3].records++; else { const e = [code, f, l, { records: 1 }]; grouped.set(k, e); c1.push(e); }
|
|
231
|
+
}
|
|
232
|
+
// Stored rows with no transcript get the same impossible-number limits (no file or line to point at).
|
|
233
|
+
for (const q of otelOnly) for (const c of limitCodes(q)) { c1.push(['stored_' + c, null, null]); c1records['stored_' + c] = (c1records['stored_' + c] || 0) + 1; }
|
|
234
|
+
const c1codes = {}; for (const [c] of c1) c1codes[c] = (c1codes[c] || 0) + 1;
|
|
235
|
+
const filesInWin = new Set(winReqs.map(([, q]) => q.f)), flaggedFiles = new Set(c1.map(([, f]) => f).filter((f) => f != null));
|
|
236
|
+
|
|
237
|
+
// ---- check 2: source agreement (only where live telemetry was running) ----
|
|
238
|
+
const c2 = [], c2codes = {}; const add2 = (code, f, l, extra) => { c2codes[code] = (c2codes[code] || 0) + 1; c2.push([code, f, l, extra]); };
|
|
239
|
+
const info2 = {}; const note2 = (k, n = 1) => { info2[k] = (info2[k] || 0) + n; };
|
|
240
|
+
const live = { compared: 0, matched: 0, exact: 0, unmatched: 0, unmatchedTok: 0, comparedTok: 0, gapTok: 0, downtimeMinutes: new Set(), txOnlyDowntime: 0, units: 0 };
|
|
241
|
+
const sums = { tx: { in: 0, out: 0, cr: 0, cc: 0 }, otel: { in: 0, out: 0, cr: 0, cc: 0 } };
|
|
242
|
+
let c2result = { status: 'not_run', reason: 'no live OTel rows found: nothing to compare transcripts with. A report without this check must not earn an "integrity checked" mark.' };
|
|
243
|
+
if (otel && otel.firstLive) {
|
|
244
|
+
const from = Math.max(since, otel.firstLive), to = now - GRACE_MS;
|
|
245
|
+
const liveNear = (ms) => { const m = Math.floor(ms / 60e3); for (let d = -5; d <= 5; d++) if (otel.liveMinutes.has(m + d)) return true; return false; };
|
|
246
|
+
// Units: each session id AND each file (the cheater picks session ids, not how many files they write).
|
|
247
|
+
const units = new Map(); const acc = (key, q, ok, nearLive) => { const u = units.get(key) || units.set(key, { m: 0, u: 0, near: 0, tok: 0, f: q.f, l: q.l }).get(key); if (ok) u.m++; else { u.u++; u.tok += tok(q); if (nearLive) u.near++; } };
|
|
248
|
+
for (const [id, q] of winReqs) {
|
|
249
|
+
if (q.ms < from || q.ms > to) continue;
|
|
250
|
+
const sq = scored.get(id);
|
|
251
|
+
live.compared++; live.comparedTok += tok(sq);
|
|
252
|
+
const o = otel.rows.get(id);
|
|
253
|
+
if (!o || !o.liveCopies) {
|
|
254
|
+
const nl = liveNear(q.ms);
|
|
255
|
+
acc('s:' + q.sid, q, false, nl); acc('f:' + q.f, q, false, nl);
|
|
256
|
+
live.unmatched++; live.unmatchedTok += tok(sq);
|
|
257
|
+
if (!nl) { live.txOnlyDowntime++; live.downtimeMinutes.add(Math.floor(q.ms / 60e3)); }
|
|
258
|
+
else note2(o ? 'request_transcript_only_backfilled' : 'request_transcript_only');
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
live.matched++; acc('s:' + q.sid, q, true); acc('f:' + q.f, q, true);
|
|
262
|
+
if (o.disagree) add2('stored_copies_disagree', q.f, q.l);
|
|
263
|
+
const diffs = ['in', 'out', 'cr', 'cc'].filter((k) => { const d = Math.abs(q[k] - o[k]); return d > T.driftAbs && d > T.driftRel * Math.max(q[k], o[k]); });
|
|
264
|
+
if (q.done) for (const k of ['in', 'out', 'cr', 'cc']) { sums.tx[k] += q[k]; sums.otel[k] += o[k]; }
|
|
265
|
+
if (!diffs.length) { if (q.in === o.in && q.out === o.out && q.cr === o.cr && q.cc === o.cc) live.exact++; continue; }
|
|
266
|
+
if (q.done) { add2('token_mismatch', q.f, q.l, { fields: diffs }); continue; }
|
|
267
|
+
// A streaming-start copy undercounts output (a known transcript limit, context). One that claims MORE than telemetry is not that.
|
|
268
|
+
if (['in', 'out', 'cr', 'cc'].some((k) => q[k] > o[k] && diffs.includes(k))) add2('unfinished_exceeds_otel', q.f, q.l, { fields: diffs });
|
|
269
|
+
else note2('unfinished_in_transcript');
|
|
270
|
+
}
|
|
271
|
+
// Unit level: a fabricated or replayed session (or file) has no live telemetry at all; a receiver that drops a batch leaves a few unmatched.
|
|
272
|
+
const seen = new Set();
|
|
273
|
+
for (const [key, u] of units) {
|
|
274
|
+
live.units += key.startsWith('s:') ? 1 : 0;
|
|
275
|
+
const tag = `${u.f}:${u.l}`; if (seen.has(tag)) continue;
|
|
276
|
+
if (u.m === 0 && u.u >= 3) {
|
|
277
|
+
if (u.near) { add2('session_without_otel', u.f, u.l, { requests: u.u }); seen.add(tag); }
|
|
278
|
+
else { note2('sessions_in_receiver_gap'); live.gapTok += u.tok; }
|
|
279
|
+
} else if (u.u >= 5 && u.u / (u.m + u.u) > 0.25 && u.near >= 5) { add2('session_mostly_transcript_only', u.f, u.l, { matched: u.m, unmatched: u.u }); seen.add(tag); }
|
|
280
|
+
}
|
|
281
|
+
// Window level: many small fabrications stay under the unit rules, so the unverified share of the window is limited too.
|
|
282
|
+
const reqShare = ratio(live.unmatched, live.compared), tokShare = ratio(live.unmatchedTok, live.comparedTok), gapShare = ratio(live.gapTok, totalTok);
|
|
283
|
+
if (reqShare > T.unverifiedShare || tokShare > T.unverifiedShare) add2('window_unverified_share', null, null, { requests: reqShare, tokens: tokShare });
|
|
284
|
+
if (gapShare > T.gapShare) add2('window_receiver_gap_share', null, null, { tokens: gapShare, minutes: live.downtimeMinutes.size });
|
|
285
|
+
// Stored rows no transcript shows. Headless runs that write no transcript are normal, but they carry few tokens.
|
|
286
|
+
const ooFrom = otelOnly.filter((q) => q.ms >= from && q.ms <= to && q.src !== 'compaction'), ooTok = ooFrom.reduce((a, q) => a + tok(q), 0);
|
|
287
|
+
note2('stored_rows_without_transcript', ooFrom.length);
|
|
288
|
+
const ooShare = ratio(ooTok, totalTok);
|
|
289
|
+
if (ooShare > T.otelOnlyShare) add2('stored_only_token_share', null, null, { tokens: ooShare, requests: ooFrom.length });
|
|
290
|
+
const c2div = {}; for (const k of ['in', 'out', 'cr', 'cc']) c2div[k] = sums.otel[k] ? +((sums.tx[k] - sums.otel[k]) / sums.otel[k]).toFixed(5) : null;
|
|
291
|
+
c2result = {
|
|
292
|
+
flags: c2.length, unit: 'session or file', unitsCompared: live.units, score: live.units ? +Math.max(0, 1 - c2.length / live.units).toFixed(4) : null, codes: c2codes,
|
|
293
|
+
requestAgreement: ratio(live.matched, live.compared), unverifiedShare: { requests: reqShare, tokens: tokShare }, receiverGapTokenShare: gapShare, storedOnlyTokenShare: ooShare,
|
|
294
|
+
liveFrom: new Date(otel.firstLive).toISOString().slice(0, 10), compared: live.compared, matched: live.matched, exactMatch: live.exact,
|
|
295
|
+
receiverDowntime: { minutes: live.downtimeMinutes.size, requests: live.txOnlyDowntime }, context: info2, totalDivergenceMatchedFinished: c2div, sample: cap(c2),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ---- check 4: cache pumping (over the scored set: transcripts, unfinished copies with telemetry numbers, stored-only rows) ----
|
|
300
|
+
const c4 = [], c4codes = {}; const add4 = (code, f, l, extra) => { c4codes[code] = (c4codes[code] || 0) + 1; c4.push([code, f, l, extra]); };
|
|
301
|
+
const bySess = new Map(), byDay = new Map();
|
|
302
|
+
for (const q of S) {
|
|
303
|
+
(bySess.get(q.sid) || bySess.set(q.sid, []).get(q.sid)).push(q);
|
|
304
|
+
const d = new Date(q.ms).toISOString().slice(0, 10), t = byDay.get(d) || byDay.set(d, { in: 0, out: 0, cr: 0, n: 0 }).get(d);
|
|
305
|
+
t.in += q.in; t.out += q.out; t.cr += q.cr; t.n++;
|
|
306
|
+
}
|
|
307
|
+
const resent = (a, b) => b.cr > 0 && near(a.in, b.in) && near(a.cr, b.cr) && near(a.cc, b.cc) && a.out <= T.resendMaxOut && b.out <= T.resendMaxOut;
|
|
308
|
+
// (a) the same context re-sent in a session: consecutive requests with the same context (within 1 %) and almost no output
|
|
309
|
+
for (const list of bySess.values()) {
|
|
310
|
+
list.sort((a, b) => a.ms - b.ms);
|
|
311
|
+
let run = 1;
|
|
312
|
+
for (let i = 1; i <= list.length; i++) {
|
|
313
|
+
if (list[i] && resent(list[i - 1], list[i])) run++; else { if (run >= T.resendRun) { const s = list[i - run]; add4('context_resent', s.f, s.l, { run }); } run = 1; }
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// (b) the same across sessions: a loop of one-request runs re-sending one context. Headless loops are normal (hooks, tools) and small;
|
|
317
|
+
// the flag is on their share of the window's tokens, the runs themselves are context.
|
|
318
|
+
const loops = { runs: 0, requests: 0, tokens: 0 };
|
|
319
|
+
{
|
|
320
|
+
const all = [...S].sort((a, b) => a.ms - b.ms); let run = 1, sids = new Set(), t = 0;
|
|
321
|
+
for (let i = 1; i <= all.length; i++) {
|
|
322
|
+
if (all[i] && resent(all[i - 1], all[i])) { if (run === 1) t = tok(all[i - 1]); run++; t += tok(all[i]); sids.add(all[i - 1].sid); sids.add(all[i].sid); }
|
|
323
|
+
else { if (run >= T.resendRun && sids.size > 1) { loops.runs++; loops.requests += run; loops.tokens += t; } run = 1; sids = new Set(); t = 0; }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const loopShare = totalTok ? +(loops.tokens / totalTok).toFixed(4) : 0;
|
|
327
|
+
if (loopShare > T.loopShare) add4('context_resent_across_sessions', null, null, { tokens: loopShare, runs: loops.runs, requests: loops.requests });
|
|
328
|
+
// (c) sessions (short ones pooled per UTC day) far outside the operator's own: cache read per output, and Yield (input's lever)
|
|
329
|
+
const units = []; const shortByDay = new Map();
|
|
330
|
+
for (const list of bySess.values()) {
|
|
331
|
+
if (list.length >= T.minSessionReqs) units.push(list);
|
|
332
|
+
else for (const q of list) { const d = new Date(q.ms).toISOString().slice(0, 10); (shortByDay.get(d) || shortByDay.set(d, []).get(d)).push(q); }
|
|
333
|
+
}
|
|
334
|
+
for (const list of shortByDay.values()) if (list.length >= T.minSessionReqs) units.push(list);
|
|
335
|
+
const U = units.map((l) => { const t = l.reduce((s, q) => ({ in: s.in + q.in, cr: s.cr + q.cr, out: s.out + q.out }), { in: 0, cr: 0, out: 0 }); const first = l.find((q) => q.f != null) || l[0]; return { first, n: l.length, r: Math.log10((t.cr + 1) / (t.out + 1)), y: Math.log10((yieldOf(t) ?? 0) + 1) }; });
|
|
336
|
+
const zr = robustZ(U.map((u) => u.r)), zy = robustZ(U.map((u) => u.y));
|
|
337
|
+
for (const u of U) {
|
|
338
|
+
const a = zr.z(u.r), b = zy.z(u.y);
|
|
339
|
+
if (a > T.robustZ) add4('session_cache_ratio_outlier', u.first.f, u.first.l, { z: +a.toFixed(2), requests: u.n });
|
|
340
|
+
else if (b > T.robustZ) add4('session_yield_outlier', u.first.f, u.first.l, { z: +b.toFixed(2), requests: u.n });
|
|
341
|
+
}
|
|
342
|
+
// (d) days whose pooled Yield is far outside the operator's own days (logged input)
|
|
343
|
+
const dayY = [...byDay].map(([d, t]) => [d, yieldOf(t), t.n]).filter(([, y, n]) => y && n >= T.minSessionReqs);
|
|
344
|
+
const dz = robustZ(dayY.map(([, y]) => Math.log10(y)));
|
|
345
|
+
const dayOutliers = dayY.map(([d, y, n]) => ({ day: d, z: +dz.z(Math.log10(y)).toFixed(2), requests: n })).filter((x) => x.z > T.robustZ);
|
|
346
|
+
if (dayOutliers.length) c4codes.day_yield_outlier = dayOutliers.length;
|
|
347
|
+
|
|
348
|
+
// ---- check 6: double counting ----
|
|
349
|
+
const c6 = [], c6codes = {}; const add6 = (code, f, l, extra) => { c6codes[code] = (c6codes[code] || 0) + 1; c6.push([code, f, l, extra]); };
|
|
350
|
+
let storedDup = 0;
|
|
351
|
+
if (otel) for (const [, o] of otel.rows) if (inWin(o.ms) && o.copies > 1) storedDup++; // any request id stored more than once, live or backfill
|
|
352
|
+
if (storedDup) add6('stored_more_than_once', null, null, { requests: storedDup });
|
|
353
|
+
// Replays with fresh ids: two sessions with the same sequence of token numbers. Forks share request ids and are already one request.
|
|
354
|
+
const seqs = new Map();
|
|
355
|
+
for (const list of bySess.values()) {
|
|
356
|
+
if (list.length < T.replayMinReqs) continue;
|
|
357
|
+
const key = sha(list.map((q) => `${q.in},${q.out},${q.cr},${q.cc}`).join(';')), first = list.find((q) => q.f != null) || list[0];
|
|
358
|
+
if (seqs.has(key)) add6('session_replayed', first.f, first.l, { requests: list.length }); else seqs.set(key, true);
|
|
359
|
+
}
|
|
360
|
+
const copied = winReqs.filter(([, q]) => q.nf > 1).length;
|
|
361
|
+
// Per-UTC-day fingerprints of the scored request set: a server (or a later run) can find overlapping windows and requests sent from two devices.
|
|
362
|
+
const perDay = new Map(); for (const [id, q] of scored) { const d = new Date(q.ms).toISOString().slice(0, 10); (perDay.get(d) || perDay.set(d, []).get(d)).push(id); }
|
|
363
|
+
const dayPrints = Object.fromEntries([...perDay].sort().map(([d, ids]) => [d, { requests: ids.length, sha256: sha(ids.sort().join('\n')).slice(0, 32) }]));
|
|
364
|
+
|
|
365
|
+
// ---- check 3: human-operator likelihood (phase 2; humanlike.mjs) ----
|
|
366
|
+
let c3 = { status: 'not_run', reason: 'no calibrated model (node humanlike.mjs calibrate)' };
|
|
367
|
+
if (human) {
|
|
368
|
+
const ws = human.sessions.filter((x) => inWin(x.lastMs) && x.prompts > 0), sc = ws.filter((x) => x.p != null);
|
|
369
|
+
const prompts = ws.reduce((a, x) => a + x.prompts, 0), scoredPrompts = sc.reduce((a, x) => a + x.prompts, 0);
|
|
370
|
+
const flagged = sc.filter((x) => x.p < human.model.flagBelow).sort((a, b) => a.p - b.p);
|
|
371
|
+
const humanPrompts = sc.filter((x) => x.p >= human.model.threshold).reduce((a, x) => a + x.prompts, 0);
|
|
372
|
+
c3 = {
|
|
373
|
+
flags: flagged.length, unit: 'session', model: human.model.model, sessionsScored: sc.length,
|
|
374
|
+
score: scoredPrompts ? +(humanPrompts / scoredPrompts).toFixed(4) : null,
|
|
375
|
+
coverage: { typedPrompts: prompts, inScoredSessions: scoredPrompts, note: `sessions with fewer than ${human.minPrompts} typed prompts are not scored` },
|
|
376
|
+
distribution: { below02: flagged.length, from02to05: sc.filter((x) => x.p >= human.model.flagBelow && x.p < human.model.threshold).length, atOrAbove05: sc.filter((x) => x.p >= human.model.threshold).length },
|
|
377
|
+
codes: flagged.length ? { likely_scripted_session: flagged.length } : {},
|
|
378
|
+
calibration: { ...human.model.calibration.cv5, note: 'calibrated on one operator; false-alarm rate on other operators not yet measured' },
|
|
379
|
+
sample: flagged.slice(0, maxFlags).map((x) => ({ code: 'likely_scripted_session', file: x.ordinal, line: x.firstLine, p: +x.p.toFixed(3), prompts: x.prompts })),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
const n4 = c4.length + dayOutliers.length, units4 = U.length + dayY.length;
|
|
383
|
+
return {
|
|
384
|
+
tool: TOOL, version: VERSION, hash: TOOL_HASH, window: windowName, from: since ? new Date(since).toISOString() : null, to: new Date(now).toISOString(),
|
|
385
|
+
population: { requests: scored.size, fromTranscripts: winReqs.length, storedOnly: otelOnly.length, sessions: bySess.size, transcriptFiles: filesInWin.size },
|
|
386
|
+
checks: {
|
|
387
|
+
record_integrity: { flags: c1.length, unit: 'file (request-level codes count per record)', score: filesInWin.size ? +Math.max(0, 1 - flaggedFiles.size / filesInWin.size).toFixed(4) : null, codes: c1codes, records: c1records, sample: cap(c1) },
|
|
388
|
+
source_agreement: c2result,
|
|
389
|
+
cache_pumping: {
|
|
390
|
+
flags: n4, unit: 'session, pooled day or day', unitsScored: units4, score: units4 ? +Math.max(0, 1 - n4 / units4).toFixed(4) : null, codes: c4codes,
|
|
391
|
+
operatorRange: { log10CacheReadPerOutput: { median: +(zr.med || 0).toFixed(3), mad: +(zr.mad || 0).toFixed(3), units: zr.n }, dayLog10Yield: { median: +(dz.med || 0).toFixed(3), mad: +(dz.mad || 0).toFixed(3), days: dz.n } },
|
|
392
|
+
note: 'compares the operator with their own range only; uniform inflation needs a reference range across operators (phase 4)',
|
|
393
|
+
crossSessionLoops: { ...loops, tokenShare: loopShare }, dayOutliers, sample: cap(c4),
|
|
394
|
+
},
|
|
395
|
+
human_likelihood: c3,
|
|
396
|
+
...(crossAdapter ? { cross_adapter: crossAdapter } : {}),
|
|
397
|
+
double_counting: { flags: c6.length, unit: 'request set or session', score: scored.size ? +Math.max(0, 1 - (storedDup + c6.length) / scored.size).toFixed(4) : null, codes: c6codes, requestsCopiedAcrossTranscripts: copied, dayFingerprints: dayPrints, sample: cap(c6) },
|
|
398
|
+
},
|
|
399
|
+
thresholds: T,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// The tool hash covers everything that decides a result: this file, the check-3 code and its model (when present).
|
|
404
|
+
export function toolHash(dir = HERE) {
|
|
405
|
+
const h = crypto.createHash('sha256');
|
|
406
|
+
for (const f of ['integrity.mjs', 'humanlike.mjs', path.join('model', 'human-v1.json')]) {
|
|
407
|
+
const p = path.join(dir, f); h.update(f + '\0'); h.update(fs.existsSync(p) ? fs.readFileSync(p) : Buffer.alloc(0)); h.update('\0');
|
|
408
|
+
}
|
|
409
|
+
return h.digest('hex').slice(0, 16);
|
|
410
|
+
}
|
|
411
|
+
let TOOL_HASH = toolHash();
|
|
412
|
+
const flagsLine = (r) => Object.entries(r.checks).map(([k, c]) => `${k} ${c.flags ?? c.status}`).join(' · ');
|
|
413
|
+
|
|
414
|
+
async function main(argv) {
|
|
415
|
+
const [cmd, ...rest] = argv; const opt = {};
|
|
416
|
+
for (let i = 0; i < rest.length; i++) if (rest[i].startsWith('--')) opt[rest[i].slice(2)] = rest[i + 1]?.startsWith('--') || rest[i + 1] == null ? true : rest[++i]; else (opt._ ||= []).push(rest[i]);
|
|
417
|
+
const roots = (opt.roots ? String(opt.roots).split(path.delimiter) : ['~/.claude/projects']).map(home);
|
|
418
|
+
if (cmd === 'where') {
|
|
419
|
+
// Ordinals are positions in the sorted transcript list at run time: refuse when the list has changed since the report was written.
|
|
420
|
+
const files = listTranscripts(roots), want = opt.report ? JSON.parse(fs.readFileSync(home(String(opt.report)), 'utf8')).input?.fileListHash : null;
|
|
421
|
+
if (!want) { console.error('pass --report <report.json> so the file list can be checked'); return 2; }
|
|
422
|
+
if (want !== fileListHash(files)) { console.error('the transcript list changed since this report was written: run the checks again'); return 2; }
|
|
423
|
+
const f = files[Number(opt._?.[0])]; if (!f) { console.error('no such ordinal'); return 2; }
|
|
424
|
+
console.log(f[0]); return 0;
|
|
425
|
+
}
|
|
426
|
+
if (cmd !== 'run') { console.error('usage: node integrity.mjs run [--roots a:b] [--data DIR] [--out DIR] [--now ISO] [--max-flags N] | where <ordinal>'); return 2; }
|
|
427
|
+
const now = opt.now ? Date.parse(opt.now) : Date.now();
|
|
428
|
+
const dataDir = opt.data ? home(String(opt.data)) : defaultData();
|
|
429
|
+
const outDir = opt.out ? home(String(opt.out)) : path.join(HERE, 'reports');
|
|
430
|
+
const files = listTranscripts(roots);
|
|
431
|
+
const t0 = Date.now();
|
|
432
|
+
process.stderr.write(`transcripts: ${files.length} files\n`);
|
|
433
|
+
const tx = await readTranscripts(files, { now, onFile: (f) => { if (f % 250 === 0) process.stderr.write(` ${f}/${files.length} ${((Date.now() - t0) / 1e3).toFixed(0)}s\n`); } });
|
|
434
|
+
const op = otelFiles(dataDir);
|
|
435
|
+
process.stderr.write(`otel: ${op.length} files\n`);
|
|
436
|
+
const otel = op.length ? await readOtel(op) : null;
|
|
437
|
+
// Check 3: score main-session files when a calibrated model exists.
|
|
438
|
+
let human = null;
|
|
439
|
+
const { MODEL_PATH, MIN_PROMPTS, scoreSessions } = await import('./humanlike.mjs');
|
|
440
|
+
const modelPath = opt.model ? home(String(opt.model)) : MODEL_PATH;
|
|
441
|
+
if (fs.existsSync(modelPath)) {
|
|
442
|
+
const model = JSON.parse(fs.readFileSync(modelPath, 'utf8')), ord = new Map(files.map(([p], i) => [p, i]));
|
|
443
|
+
const sessions = (await scoreSessions(roots, model)).map((x) => ({ ...x, ordinal: ord.get(x.path) ?? null, path: undefined }));
|
|
444
|
+
human = { model, minPrompts: MIN_PROMPTS, sessions };
|
|
445
|
+
process.stderr.write(`human likelihood: ${sessions.filter((x) => x.p != null).length} sessions scored\n`);
|
|
446
|
+
}
|
|
447
|
+
// Check 5: cross-adapter conformance when crossadapter.mjs is present (phase 3).
|
|
448
|
+
let crossAdapter = null;
|
|
449
|
+
if (fs.existsSync(path.join(HERE, 'crossadapter.mjs')) && !opt['no-cross-adapter']) {
|
|
450
|
+
try { const ca = await import('./crossadapter.mjs'); if (typeof ca.checkCrossAdapter === 'function') crossAdapter = await ca.checkCrossAdapter({}); }
|
|
451
|
+
catch (e) { crossAdapter = { status: 'not_run', reason: `cross-adapter check failed: ${e.message}` }; }
|
|
452
|
+
}
|
|
453
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
454
|
+
const stamp = new Date(now).toISOString().slice(0, 16).replace(/[:T]/g, '-');
|
|
455
|
+
const listHash = fileListHash(files);
|
|
456
|
+
for (const w of Object.keys(WINDOWS)) {
|
|
457
|
+
const rep = evaluate({ tx, otel, windowName: w, now, maxFlags: Number(opt['max-flags'] || 200), human, crossAdapter });
|
|
458
|
+
rep.input = { transcripts: { ...tx.stats }, fileListHash: listHash, otel: otel?.stats || null };
|
|
459
|
+
const out = path.join(outDir, `${stamp}_${w}.json`);
|
|
460
|
+
fs.writeFileSync(out, JSON.stringify(rep, null, 2) + '\n');
|
|
461
|
+
console.log(`${w.padEnd(4)} requests ${String(rep.population.requests).padStart(7)} · ${flagsLine(rep)} → ${path.relative(process.cwd(), out)}`);
|
|
462
|
+
}
|
|
463
|
+
process.stderr.write(`done in ${((Date.now() - t0) / 1e3).toFixed(0)}s\n`);
|
|
464
|
+
return 0;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv.slice(2)).then((c) => { process.exitCode = c; }, (e) => { console.error(e.stack || e.message); process.exitCode = 2; });
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
{
|
|
2
|
+
"model": "human-v1",
|
|
3
|
+
"features": [
|
|
4
|
+
"latency_median_log10s",
|
|
5
|
+
"latency_iqr_log10",
|
|
6
|
+
"latency_under_3s",
|
|
7
|
+
"latency_length_spearman",
|
|
8
|
+
"gaps_over_5min",
|
|
9
|
+
"interrupts_per_prompt",
|
|
10
|
+
"queued_per_prompt",
|
|
11
|
+
"away_per_prompt",
|
|
12
|
+
"own_permission_decisions_per_prompt",
|
|
13
|
+
"rewinds_per_prompt",
|
|
14
|
+
"duplicate_prompt_share",
|
|
15
|
+
"template_prompt_share",
|
|
16
|
+
"fragment_share",
|
|
17
|
+
"lowercase_start_share",
|
|
18
|
+
"no_end_punct_share",
|
|
19
|
+
"backref_share",
|
|
20
|
+
"median_length_log10",
|
|
21
|
+
"typing_over_20cps_share"
|
|
22
|
+
],
|
|
23
|
+
"mu": [
|
|
24
|
+
1.5295736954486723,
|
|
25
|
+
0.7091583359113096,
|
|
26
|
+
0.21862034925160384,
|
|
27
|
+
-0.0010672633441997283,
|
|
28
|
+
0.21853558468810408,
|
|
29
|
+
0.0018089087929376736,
|
|
30
|
+
0.07807093364201445,
|
|
31
|
+
0.08582325934869225,
|
|
32
|
+
0.0076814799100825525,
|
|
33
|
+
8.140008140008139e-05,
|
|
34
|
+
0.040148450360832644,
|
|
35
|
+
0.6088431503258778,
|
|
36
|
+
0.039483593383698085,
|
|
37
|
+
0.3401522197946143,
|
|
38
|
+
0.8942183127597851,
|
|
39
|
+
0.8369956638766749,
|
|
40
|
+
3.4459216804918262,
|
|
41
|
+
0.7205475742446125
|
|
42
|
+
],
|
|
43
|
+
"sd": [
|
|
44
|
+
0.8834033638197755,
|
|
45
|
+
0.5315098200392586,
|
|
46
|
+
0.39166259403465903,
|
|
47
|
+
0.35327949030764766,
|
|
48
|
+
0.28141795686895743,
|
|
49
|
+
0.01115865799224182,
|
|
50
|
+
0.3137797300713188,
|
|
51
|
+
0.20581580213522832,
|
|
52
|
+
0.04622657681852749,
|
|
53
|
+
0.0017344139806807091,
|
|
54
|
+
0.16658471130337763,
|
|
55
|
+
0.47756412307932794,
|
|
56
|
+
0.08071820502939067,
|
|
57
|
+
0.4339757775102294,
|
|
58
|
+
0.17673716567323958,
|
|
59
|
+
0.22351113783197354,
|
|
60
|
+
1.1346416678129385,
|
|
61
|
+
0.3805163499172338
|
|
62
|
+
],
|
|
63
|
+
"w": [
|
|
64
|
+
0.39146064126501107,
|
|
65
|
+
0.19813682604782584,
|
|
66
|
+
-0.44877286563337365,
|
|
67
|
+
0.008864933526564053,
|
|
68
|
+
0.3100213547268302,
|
|
69
|
+
0.11019385916531567,
|
|
70
|
+
0.3197325203302428,
|
|
71
|
+
0.6221343789508392,
|
|
72
|
+
-0.030722811755335724,
|
|
73
|
+
0.054759978304806466,
|
|
74
|
+
-0.3633331526227579,
|
|
75
|
+
-0.39327564650246744,
|
|
76
|
+
0.07238966660375157,
|
|
77
|
+
0.41779452904646325,
|
|
78
|
+
-0.28743739992772377,
|
|
79
|
+
-0.27124772459716145,
|
|
80
|
+
-0.3311392854665862,
|
|
81
|
+
-0.6557597893922426
|
|
82
|
+
],
|
|
83
|
+
"b": -2.0947310335848957,
|
|
84
|
+
"threshold": 0.5,
|
|
85
|
+
"flagBelow": 0.2,
|
|
86
|
+
"calibration": {
|
|
87
|
+
"at": "2026-12-04T12:02:53.061Z",
|
|
88
|
+
"sessions": {
|
|
89
|
+
"human": 88,
|
|
90
|
+
"scripted": 279,
|
|
91
|
+
"fastbotReplays": 88
|
|
92
|
+
},
|
|
93
|
+
"labels": "entrypoint cli = human; sdk-cli, sdk-ts = scripted (labels only, never features). Scripted multi-prompt sessions are rare locally, so consecutive headless runs of one project are chained 10 at a time (275 pseudo-sessions). Each human session is also replayed by a fast bot (1-3 s replies, no interrupts/queue/away/own-permission/rewind events) as a scripted example, in the same CV fold as its source.",
|
|
94
|
+
"cv5": {
|
|
95
|
+
"auc_humanVsScripted": 0.9997,
|
|
96
|
+
"falseAlarm_humanBelow05": 0.0114,
|
|
97
|
+
"falseAlarm_humanBelow02": 0,
|
|
98
|
+
"scriptedPassedAbove05": 0.0072,
|
|
99
|
+
"fastbotCaughtBelow05": 1
|
|
100
|
+
},
|
|
101
|
+
"ablationAuc_humanVsScripted": {
|
|
102
|
+
"timing": 0.9585,
|
|
103
|
+
"behaviour": 0.9963,
|
|
104
|
+
"texture": 0.9995
|
|
105
|
+
},
|
|
106
|
+
"weights": {
|
|
107
|
+
"latency_median_log10s": 0.391,
|
|
108
|
+
"latency_iqr_log10": 0.198,
|
|
109
|
+
"latency_under_3s": -0.449,
|
|
110
|
+
"latency_length_spearman": 0.009,
|
|
111
|
+
"gaps_over_5min": 0.31,
|
|
112
|
+
"interrupts_per_prompt": 0.11,
|
|
113
|
+
"queued_per_prompt": 0.32,
|
|
114
|
+
"away_per_prompt": 0.622,
|
|
115
|
+
"own_permission_decisions_per_prompt": -0.031,
|
|
116
|
+
"rewinds_per_prompt": 0.055,
|
|
117
|
+
"duplicate_prompt_share": -0.363,
|
|
118
|
+
"template_prompt_share": -0.393,
|
|
119
|
+
"fragment_share": 0.072,
|
|
120
|
+
"lowercase_start_share": 0.418,
|
|
121
|
+
"no_end_punct_share": -0.287,
|
|
122
|
+
"backref_share": -0.271,
|
|
123
|
+
"median_length_log10": -0.331,
|
|
124
|
+
"typing_over_20cps_share": -0.656
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
package/manifest.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
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.
|
|
6
|
-
"description": "Ranks AI coding operators by token cascade efficiency (Yield = cache_read \u00d7 output / input\u00b2).
|
|
5
|
+
"version": "1.0.54",
|
|
6
|
+
"description": "Ranks AI coding operators by token cascade efficiency (Yield = cache_read \u00d7 output / input\u00b2). 26 tools including SigRank Standard record, Tokenpull Integrity checks (check_integrity), 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",
|
|
9
9
|
"url": "https://github.com/SunrisesIllNeverSee"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sigrank",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.54",
|
|
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 __tests__/integrity.test.mjs",
|
|
28
28
|
"test:packaged": "node scripts/packed-artifact-smoke.mjs",
|
|
29
29
|
"sync:platforms": "node scripts/sync-platforms.mjs"
|
|
30
30
|
},
|