sigrank 1.0.53 → 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 +1 -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/tui.mjs +25 -0
- package/proxy.mjs +7 -4
- package/submit/index.mjs +7 -0
- package/tools/_schemas.mjs +28 -0
- package/tools/check-integrity.mjs +54 -0
- package/tools/index.mjs +4 -0
- package/tools/submit-verified.mjs +45 -1
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tokenpull Integrity, phase 2: check 3, human-operator likelihood.
|
|
3
|
+
// A probability per session that its typed turns were operated by a person, from behaviour only: response latency against prompt length,
|
|
4
|
+
// rhythm and breaks, interruptions, prompts queued while the agent works, the operator's own permission decisions, rewinds, repeated or
|
|
5
|
+
// templated prompts, and writing texture (fragments, lowercase starts, missing end punctuation, back-references).
|
|
6
|
+
// Self-declared fields (entrypoint, promptSource, turnOrigin) are never features: they are trivially faked. They are used only as
|
|
7
|
+
// calibration labels: entrypoint "cli" = human set, "sdk-cli"/"sdk-ts" = scripted set.
|
|
8
|
+
// Prompt text is read in memory to compute counts; it is never written anywhere.
|
|
9
|
+
//
|
|
10
|
+
// node humanlike.mjs calibrate [--roots a:b] [--model FILE] fit on local sessions, 5-fold CV, write the model (weights + metrics only)
|
|
11
|
+
// node humanlike.mjs score [--roots a:b] [--model FILE] score local sessions, print the distribution
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
import { jsonlLines } from './integrity.mjs';
|
|
18
|
+
|
|
19
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
export const MODEL_PATH = path.join(HERE, 'model', 'human-v1.json');
|
|
21
|
+
export const MIN_PROMPTS = 3;
|
|
22
|
+
const TOOLING = /(^|[/-])(claude-mem|mem0|claude-self-reflect|basic-memory|memento|cipher-mem|memory-keeper)\b|observer-(sessions|archive)/i;
|
|
23
|
+
const SUBAGENT = /(^|[/\\])subagents[/\\]/;
|
|
24
|
+
|
|
25
|
+
// Same rule as Tokenpull's typedText() (sigrank-otel src/transcripts.mjs), plus a flag for interrupt markers.
|
|
26
|
+
const NON_PROMPT = ['<command-', '<local-command', '<task-notification', '<system-reminder', 'Caveat:', '[Request interrupted by user'];
|
|
27
|
+
function userText(rec) {
|
|
28
|
+
const c = rec.message?.content; let t;
|
|
29
|
+
if (typeof c === 'string') t = c;
|
|
30
|
+
else if (Array.isArray(c)) { if (c.some((b) => b?.type === 'tool_result')) return null; t = c.filter((b) => b?.type === 'text').map((b) => b.text || '').join(' '); }
|
|
31
|
+
else return null;
|
|
32
|
+
return t;
|
|
33
|
+
}
|
|
34
|
+
export function typedText(rec) {
|
|
35
|
+
if (!rec || rec.type !== 'user' || rec.isSidechain || rec.isMeta || rec.isCompactSummary) return null;
|
|
36
|
+
const t = userText(rec); if (t == null || !t.trim()) return null;
|
|
37
|
+
const s = t.trimStart(); return NON_PROMPT.some((p) => s.startsWith(p)) ? null : t;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const FEATURES = [
|
|
41
|
+
'latency_median_log10s', 'latency_iqr_log10', 'latency_under_3s', 'latency_length_spearman', 'gaps_over_5min',
|
|
42
|
+
'interrupts_per_prompt', 'queued_per_prompt', 'away_per_prompt', 'own_permission_decisions_per_prompt', 'rewinds_per_prompt',
|
|
43
|
+
'duplicate_prompt_share', 'template_prompt_share', 'fragment_share', 'lowercase_start_share', 'no_end_punct_share',
|
|
44
|
+
'backref_share', 'median_length_log10', 'typing_over_20cps_share',
|
|
45
|
+
];
|
|
46
|
+
const BACKREF = /\b(that|this|it|those|these|above|again|same|earlier|before|you said|as i said|like i said)\b/i;
|
|
47
|
+
|
|
48
|
+
const quant = (s, q) => { if (!s.length) return 0; const i = (s.length - 1) * q, lo = Math.floor(i), hi = Math.ceil(i); return s[lo] + (s[hi] - s[lo]) * (i - lo); };
|
|
49
|
+
function ranks(a) { const idx = a.map((v, i) => [v, i]).sort((x, y) => x[0] - y[0]), r = new Array(a.length); for (let i = 0; i < idx.length;) { let j = i; while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++; for (let k = i; k <= j; k++) r[idx[k][1]] = (i + j) / 2; i = j + 1; } return r; }
|
|
50
|
+
function spearman(x, y) {
|
|
51
|
+
if (x.length < 3) return 0; const rx = ranks(x), ry = ranks(y), n = x.length, mx = (n - 1) / 2;
|
|
52
|
+
let sxy = 0, sxx = 0, syy = 0; for (let i = 0; i < n; i++) { sxy += (rx[i] - mx) * (ry[i] - mx); sxx += (rx[i] - mx) ** 2; syy += (ry[i] - mx) ** 2; }
|
|
53
|
+
return sxx && syy ? sxy / Math.sqrt(sxx * syy) : 0;
|
|
54
|
+
}
|
|
55
|
+
const h = (s) => crypto.createHash('sha1').update(s).digest('base64').slice(0, 12);
|
|
56
|
+
|
|
57
|
+
// One transcript file -> one session summary (prompt-level numbers only).
|
|
58
|
+
export async function readSession(file) {
|
|
59
|
+
const prompts = []; let lastAgentMs = 0, interrupts = 0, queued = 0, away = 0, ownPerm = 0, entry = null, firstLine = 0, l = 0;
|
|
60
|
+
const childTyped = new Map();
|
|
61
|
+
for await (const line of jsonlLines(file)) {
|
|
62
|
+
l++; if (!line) continue;
|
|
63
|
+
let r; try { r = JSON.parse(line); } catch { continue; }
|
|
64
|
+
const ms = Date.parse(r.timestamp || '') || 0;
|
|
65
|
+
if (r.entrypoint && !entry) entry = r.entrypoint;
|
|
66
|
+
if (r.type === 'assistant') { if (ms) lastAgentMs = ms; continue; }
|
|
67
|
+
if (r.type === 'attachment') { if (r.attachment?.type === 'queued_command') queued++; continue; }
|
|
68
|
+
if (r.type === 'system') { if (r.subtype === 'away_summary') away++; continue; }
|
|
69
|
+
if (r.type !== 'user') continue;
|
|
70
|
+
const src = r.permissionDecision?.source; if (typeof src === 'string' && src.startsWith('user')) ownPerm++;
|
|
71
|
+
if (r.isSidechain) continue;
|
|
72
|
+
const raw = userText(r); if (raw && raw.trimStart().startsWith('[Request interrupted by user')) { interrupts++; continue; }
|
|
73
|
+
const t = typedText(r); if (!t) continue;
|
|
74
|
+
if (!firstLine) firstLine = l;
|
|
75
|
+
if (r.parentUuid) childTyped.set(r.parentUuid, (childTyped.get(r.parentUuid) || 0) + 1);
|
|
76
|
+
const s = t.trim(), words = s.split(/\s+/).filter(Boolean).length;
|
|
77
|
+
prompts.push({ ms, len: s.length, latency: lastAgentMs && ms > lastAgentMs ? (ms - lastAgentMs) / 1e3 : null,
|
|
78
|
+
frag: words < 6, lower: /^[a-z]/.test(s), noEnd: !/[.?!)"'`]$/.test(s), back: BACKREF.test(s), full: h(s), pre: s.length >= 40 ? h(s.slice(0, 40)) : null });
|
|
79
|
+
}
|
|
80
|
+
let rewinds = 0; for (const n of childTyped.values()) if (n > 1) rewinds += n - 1;
|
|
81
|
+
return { entry, firstLine, prompts, interrupts, queued, away, ownPerm, rewinds, lastMs: prompts.length ? prompts[prompts.length - 1].ms : 0, lastAgentMs };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function featuresOf(s) {
|
|
85
|
+
const P = s.prompts, n = P.length; if (n < MIN_PROMPTS) return null;
|
|
86
|
+
const lat = P.filter((p) => p.latency != null && p.latency > 0);
|
|
87
|
+
const ll = lat.map((p) => Math.log10(p.latency)).sort((a, b) => a - b);
|
|
88
|
+
const gaps = []; for (let i = 1; i < n; i++) if (P[i].ms && P[i - 1].ms) gaps.push(P[i].ms - P[i - 1].ms);
|
|
89
|
+
const cnt = (k) => { const m = new Map(); for (const p of P) if (p[k]) m.set(p[k], (m.get(p[k]) || 0) + 1); return P.filter((p) => p[k] && m.get(p[k]) > 1).length / n; };
|
|
90
|
+
const share = (f) => P.filter(f).length / n;
|
|
91
|
+
const lens = P.map((p) => p.len).sort((a, b) => a - b);
|
|
92
|
+
return [
|
|
93
|
+
ll.length ? quant(ll, 0.5) : 0, ll.length ? quant(ll, 0.75) - quant(ll, 0.25) : 0, lat.length ? lat.filter((p) => p.latency < 3).length / lat.length : 0,
|
|
94
|
+
spearman(lat.map((p) => p.latency), lat.map((p) => p.len)), gaps.length ? gaps.filter((g) => g > 300e3).length / gaps.length : 0,
|
|
95
|
+
s.interrupts / n, s.queued / n, s.away / n, s.ownPerm / n, s.rewinds / n,
|
|
96
|
+
cnt('full'), cnt('pre'), share((p) => p.frag), share((p) => p.lower), share((p) => p.noEnd),
|
|
97
|
+
share((p) => p.back), Math.log10(quant(lens, 0.5) + 1), lat.length ? lat.filter((p) => p.len / p.latency > 20).length / lat.length : 0,
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---------- logistic regression (standardized, L2), AUC ----------
|
|
102
|
+
const sig = (z) => 1 / (1 + Math.exp(-z));
|
|
103
|
+
export function fit(X, y, { l2 = 0.05, iters = 3000, lr = 0.2 } = {}) {
|
|
104
|
+
const d = X[0].length, mu = new Array(d).fill(0), sd = new Array(d).fill(0);
|
|
105
|
+
for (const x of X) for (let j = 0; j < d; j++) mu[j] += x[j] / X.length;
|
|
106
|
+
for (const x of X) for (let j = 0; j < d; j++) sd[j] += (x[j] - mu[j]) ** 2 / X.length;
|
|
107
|
+
for (let j = 0; j < d; j++) sd[j] = Math.sqrt(sd[j]) || 1;
|
|
108
|
+
const Z = X.map((x) => x.map((v, j) => (v - mu[j]) / sd[j]));
|
|
109
|
+
// Class-balanced weights so the larger set does not dominate.
|
|
110
|
+
const pos = y.filter(Boolean).length, wPos = y.length / (2 * pos), wNeg = y.length / (2 * (y.length - pos));
|
|
111
|
+
const w = new Array(d).fill(0); let b = 0;
|
|
112
|
+
for (let it = 0; it < iters; it++) {
|
|
113
|
+
const gw = new Array(d).fill(0); let gb = 0, W = 0;
|
|
114
|
+
for (let i = 0; i < Z.length; i++) { const wi = y[i] ? wPos : wNeg, e = (sig(b + Z[i].reduce((s, v, j) => s + v * w[j], 0)) - y[i]) * wi; W += wi; gb += e; for (let j = 0; j < d; j++) gw[j] += e * Z[i][j]; }
|
|
115
|
+
b -= lr * gb / W; for (let j = 0; j < d; j++) w[j] -= lr * (gw[j] / W + l2 * w[j]);
|
|
116
|
+
}
|
|
117
|
+
return { mu, sd, w, b };
|
|
118
|
+
}
|
|
119
|
+
export const predict = (m, x) => sig(m.b + x.reduce((s, v, j) => s + ((v - m.mu[j]) / m.sd[j]) * m.w[j], 0));
|
|
120
|
+
export function auc(scores, y) {
|
|
121
|
+
const r = ranks(scores); let sp = 0, np = 0; for (let i = 0; i < y.length; i++) if (y[i]) { sp += r[i] + 1; np++; }
|
|
122
|
+
const nn = y.length - np; return np && nn ? (sp - np * (np + 1) / 2) / (np * nn) : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---------- corpus ----------
|
|
126
|
+
export function listSessionFiles(roots) {
|
|
127
|
+
const out = [];
|
|
128
|
+
const walk = (d, root) => { let es; try { es = fs.readdirSync(d, { withFileTypes: true }); } catch { return; } for (const e of es) { const p = path.join(d, e.name); if (e.isSymbolicLink()) continue; if (e.isDirectory()) walk(p, root); else if (e.name.endsWith('.jsonl')) { const rel = p.slice(root.length + 1); if (!SUBAGENT.test(rel)) out.push([p, rel, TOOLING.test(rel)]); } } };
|
|
129
|
+
for (const r of roots) walk(r, r);
|
|
130
|
+
return out.sort((a, b) => (a[0] < b[0] ? -1 : 1));
|
|
131
|
+
}
|
|
132
|
+
export const labelOf = (entry) => (entry === 'cli' ? 1 : entry === 'sdk-cli' || entry === 'sdk-ts' ? 0 : null);
|
|
133
|
+
|
|
134
|
+
// Headless runs here are one prompt each. A script driving many runs in a row is the scripted case that matters, so consecutive
|
|
135
|
+
// headless runs of one project are chained into pseudo-sessions of CHAIN runs: real prompts, real gaps between runs.
|
|
136
|
+
export const CHAIN = 10;
|
|
137
|
+
export function chainRuns(runs) {
|
|
138
|
+
const byProj = new Map();
|
|
139
|
+
for (const r of runs) if (r.s.prompts.length) (byProj.get(r.proj) || byProj.set(r.proj, []).get(r.proj)).push(r.s);
|
|
140
|
+
const out = [];
|
|
141
|
+
for (const list of byProj.values()) {
|
|
142
|
+
list.sort((a, b) => a.prompts[0].ms - b.prompts[0].ms);
|
|
143
|
+
for (let i = 0; i + CHAIN <= list.length; i += CHAIN) {
|
|
144
|
+
const part = list.slice(i, i + CHAIN), P = []; let prevEnd = 0;
|
|
145
|
+
const sum = (k) => part.reduce((a, s) => a + s[k], 0);
|
|
146
|
+
for (const s of part) { for (const q of s.prompts) P.push({ ...q, latency: q.latency ?? (prevEnd && q.ms > prevEnd ? (q.ms - prevEnd) / 1e3 : null) }); prevEnd = s.lastAgentMs || prevEnd; }
|
|
147
|
+
out.push({ prompts: P, interrupts: sum('interrupts'), queued: sum('queued'), away: sum('away'), ownPerm: sum('ownPerm'), rewinds: sum('rewinds') });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function folds(n, k, seed = 7) { const idx = [...Array(n).keys()]; let s = seed; for (let i = n - 1; i > 0; i--) { s = (s * 1103515245 + 12345) % 2147483648; const j = s % (i + 1); [idx[i], idx[j]] = [idx[j], idx[i]]; } return idx.map((i, p) => [i, p % k]); }
|
|
154
|
+
// groups: rows derived from the same source session share a group and always land in the same fold (no leakage).
|
|
155
|
+
export function crossValidate(X, y, k = 5, cols = null, groups = null) {
|
|
156
|
+
const sel = (x) => (cols ? cols.map((c) => x[c]) : x); const pred = new Array(y.length);
|
|
157
|
+
const g = groups || y.map((_, i) => i), ng = Math.max(...g) + 1, gf = new Map(folds(ng, k));
|
|
158
|
+
const f = y.map((_, i) => [i, gf.get(g[i])]);
|
|
159
|
+
for (let fold = 0; fold < k; fold++) {
|
|
160
|
+
const tr = f.filter(([, p]) => p !== fold).map(([i]) => i), te = f.filter(([, p]) => p === fold).map(([i]) => i);
|
|
161
|
+
const m = fit(tr.map((i) => sel(X[i])), tr.map((i) => y[i]));
|
|
162
|
+
for (const i of te) pred[i] = predict(m, sel(X[i]));
|
|
163
|
+
}
|
|
164
|
+
return pred;
|
|
165
|
+
}
|
|
166
|
+
const rate = (pred, y, cls, thr) => { const idx = y.map((v, i) => [v, i]).filter(([v]) => v === cls).map(([, i]) => i); return idx.length ? idx.filter((i) => pred[i] < thr).length / idx.length : null; };
|
|
167
|
+
|
|
168
|
+
// Synthetic adversaries built from real sessions: human prompts replayed with scripted timing, scripted prompts given human-like timing.
|
|
169
|
+
// fastbot: 1-3 s after the agent stops. mimic: a bot that fakes typing (4 s + length / 3-6 cps, occasional long pause). human: same as mimic.
|
|
170
|
+
// Events a timing script does not produce (interrupts, queued prompts, away summaries, own permission decisions, rewinds) are dropped for bots.
|
|
171
|
+
export function withTiming(s, mode, seed) {
|
|
172
|
+
let r = seed; const rnd = () => ((r = (r * 1103515245 + 12345) % 2147483648) / 2147483648);
|
|
173
|
+
let t = s.prompts[0]?.ms || 0; const P = [];
|
|
174
|
+
const bot = mode !== 'human', base = bot ? { ...s, interrupts: 0, queued: 0, away: 0, ownPerm: 0, rewinds: 0 } : s;
|
|
175
|
+
for (const p of s.prompts) {
|
|
176
|
+
const lat = mode === 'fastbot' ? 1 + rnd() * 2 : 4 + p.len / (3 + rnd() * 3) + (rnd() < 0.1 ? 600 * rnd() : 0) + rnd() * 20;
|
|
177
|
+
t += (lat + 30) * 1e3; P.push({ ...p, ms: t, latency: lat });
|
|
178
|
+
}
|
|
179
|
+
return { ...base, prompts: P };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function main(argv) {
|
|
183
|
+
const [cmd, ...rest] = argv; const opt = {}; for (let i = 0; i < rest.length; i++) if (rest[i].startsWith('--')) opt[rest[i].slice(2)] = rest[++i];
|
|
184
|
+
const roots = (opt.roots ? opt.roots.split(':') : ['~/.claude/projects']).map((p) => path.resolve(p.replace(/^~(?=\/|$)/, os.homedir())));
|
|
185
|
+
const modelPath = opt.model || MODEL_PATH;
|
|
186
|
+
const files = listSessionFiles(roots); const t0 = Date.now();
|
|
187
|
+
const rows = [], runs = [];
|
|
188
|
+
for (const [p, rel, tool] of files) {
|
|
189
|
+
const s = await readSession(p); const y = labelOf(s.entry);
|
|
190
|
+
if (y === 0 && s.prompts.length < MIN_PROMPTS) { runs.push({ s, proj: rel.split(/[/\\]/)[0] + (tool ? ':tool' : '') }); continue; }
|
|
191
|
+
const x = featuresOf(s); if (x) rows.push({ s, x, y, tool });
|
|
192
|
+
}
|
|
193
|
+
const chains = chainRuns(runs);
|
|
194
|
+
for (const s of chains) { const x = featuresOf(s); if (x) rows.push({ s, x, y: 0, tool: false, chain: true }); }
|
|
195
|
+
process.stderr.write(`${files.length} session files, ${rows.length} scored sessions (${chains.length} chained headless pseudo-sessions), ${((Date.now() - t0) / 1e3).toFixed(0)}s\n`);
|
|
196
|
+
if (cmd === 'calibrate') {
|
|
197
|
+
const L = rows.filter((r) => r.y != null);
|
|
198
|
+
const nH = L.filter((r) => r.y === 1).length, nS = L.length - nH;
|
|
199
|
+
if (nH < 20 || nS < 20) { console.error(`not enough labelled sessions (human ${nH}, scripted ${nS})`); return 2; }
|
|
200
|
+
// Training set: real human, real scripted (chained headless runs), and each human session replayed by a fast bot (same group as its source).
|
|
201
|
+
const T_ = []; L.forEach((r, i) => { T_.push({ x: r.x, y: r.y, g: i, kind: r.y ? 'human' : 'scripted' }); if (r.y === 1) T_.push({ x: featuresOf(withTiming(r.s, 'fastbot', i + 1)), y: 0, g: i, kind: 'fastbot' }); });
|
|
202
|
+
// Held-out adversaries (never trained on): a typing-mimic bot replaying human prompts, and scripted prompts given human timing.
|
|
203
|
+
const X = T_.map((r) => r.x), y = T_.map((r) => r.y), g = T_.map((r) => r.g);
|
|
204
|
+
const pred = crossValidate(X, y, 5, null, g);
|
|
205
|
+
const pick = (kind) => T_.map((r, i) => [r.kind, i]).filter(([k]) => k === kind).map(([, i]) => i);
|
|
206
|
+
const realIdx = [...pick('human'), ...pick('scripted')];
|
|
207
|
+
const share = (idx, f) => +(idx.filter((i) => f(pred[i])).length / idx.length).toFixed(4);
|
|
208
|
+
const timing = [0, 1, 2, 3, 4, 17], behaviour = [5, 6, 7, 8, 9], texture = [10, 11, 12, 13, 14, 15, 16];
|
|
209
|
+
const ablation = Object.fromEntries([['timing', timing], ['behaviour', behaviour], ['texture', texture]].map(([k, c]) => { const pp = crossValidate(X, y, 5, c, g); return [k, +auc(realIdx.map((i) => pp[i]), realIdx.map((i) => y[i])).toFixed(4)]; }));
|
|
210
|
+
const model = fit(X, y);
|
|
211
|
+
const H = L.filter((r) => r.y === 1), S = L.filter((r) => r.y === 0);
|
|
212
|
+
// Held-out adversaries are scored by a model trained without their source session's fold is not needed: they are never in training.
|
|
213
|
+
const mimic = H.map((r, i) => predict(model, featuresOf(withTiming(r.s, 'mimic', 1000 + i)))), sHuman = S.map((r, i) => predict(model, featuresOf(withTiming(r.s, 'human', 2000 + i))));
|
|
214
|
+
const out = {
|
|
215
|
+
model: 'human-v1', features: FEATURES, mu: model.mu, sd: model.sd, w: model.w, b: model.b, threshold: 0.5, flagBelow: 0.2,
|
|
216
|
+
calibration: {
|
|
217
|
+
at: new Date().toISOString(), sessions: { human: nH, scripted: nS, fastbotReplays: H.length }, 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 ${CHAIN} at a time (${rows.filter((r) => r.chain).length} 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.`,
|
|
218
|
+
cv5: {
|
|
219
|
+
auc_humanVsScripted: +auc(realIdx.map((i) => pred[i]), realIdx.map((i) => y[i])).toFixed(4),
|
|
220
|
+
falseAlarm_humanBelow05: share(pick('human'), (p) => p < 0.5), falseAlarm_humanBelow02: share(pick('human'), (p) => p < 0.2),
|
|
221
|
+
scriptedPassedAbove05: share(pick('scripted'), (p) => p >= 0.5), fastbotCaughtBelow05: share(pick('fastbot'), (p) => p < 0.5),
|
|
222
|
+
},
|
|
223
|
+
ablationAuc_humanVsScripted: ablation,
|
|
224
|
+
heldOutAdversaries: {
|
|
225
|
+
typingMimicBot_humanPrompts_caughtBelow05: +(mimic.filter((p) => p < 0.5).length / mimic.length).toFixed(4),
|
|
226
|
+
scriptedPrompts_humanTiming_passedAbove05: +(sHuman.filter((p) => p >= 0.5).length / sHuman.length).toFixed(4),
|
|
227
|
+
},
|
|
228
|
+
weights: Object.fromEntries(FEATURES.map((f, j) => [f, +model.w[j].toFixed(3)])),
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
// Adversary results stay in a lab-only sidecar: the shipped model carries weights and CV metrics, not a recipe for passing the check.
|
|
232
|
+
const lab = { model: out.model, at: out.calibration.at, heldOutAdversaries: out.calibration.heldOutAdversaries };
|
|
233
|
+
delete out.calibration.heldOutAdversaries;
|
|
234
|
+
fs.mkdirSync(path.dirname(modelPath), { recursive: true }); fs.writeFileSync(modelPath, JSON.stringify(out, null, 2) + '\n');
|
|
235
|
+
fs.writeFileSync(modelPath.replace(/\.json$/, '.lab.json'), JSON.stringify(lab, null, 2) + '\n');
|
|
236
|
+
console.log(JSON.stringify(out.calibration, null, 2)); return 0;
|
|
237
|
+
}
|
|
238
|
+
if (cmd === 'score') {
|
|
239
|
+
const m = JSON.parse(fs.readFileSync(modelPath, 'utf8')); const by = {};
|
|
240
|
+
for (const r of rows) { const k = r.chain ? 'chained-headless' : r.tool ? 'tooling' : r.s.entry || 'unknown', p = predict(m, r.x), b = by[k] ||= { n: 0, below05: 0 }; b.n++; if (p < 0.5) b.below05++; }
|
|
241
|
+
console.log(by); return 0;
|
|
242
|
+
}
|
|
243
|
+
console.error('usage: node humanlike.mjs calibrate|score [--roots a:b] [--model FILE]'); return 2;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// For integrity.mjs: score the main-session files of the population (no tooling, no subagents) for one window.
|
|
247
|
+
export async function scoreSessions(roots, model, { onlyFiles = null } = {}) {
|
|
248
|
+
const files = listSessionFiles(roots).filter(([, , tool]) => !tool), out = [];
|
|
249
|
+
for (const [p] of files) {
|
|
250
|
+
if (onlyFiles && !onlyFiles.has(p)) continue;
|
|
251
|
+
const s = await readSession(p); const x = featuresOf(s);
|
|
252
|
+
out.push({ path: p, lastMs: s.lastMs, firstLine: s.firstLine, prompts: s.prompts.length, p: x ? predict(model, x) : null });
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
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; });
|