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,402 @@
|
|
|
1
|
+
// lib/integrity.mjs — Tokenpull Integrity wrapper for sigrank-mcp (check_integrity,
|
|
2
|
+
// submit_verified's optional integrity block, and the TUI status line).
|
|
3
|
+
//
|
|
4
|
+
// Vendored, not forked: ./vendor/tokenpull-integrity/ holds byte-identical copies of
|
|
5
|
+
// source repo : _7_labs/tokenpull-integrity (integrity/), commit 69360a7
|
|
6
|
+
// integrity.mjs sha256 13fbbc5111ceee707f300999c41af17e335993122cca77e7e7dfcae6608ba713
|
|
7
|
+
// humanlike.mjs sha256 fc86829f1d506d778d1c9a3b5a85da0061783afa95f8cda23a36cd38e5e954c6
|
|
8
|
+
// model/human-v1.json sha256 cb6492329bb5719e6b746bdf7e3b16795627ae863679a383e3bf6215a5006c0e
|
|
9
|
+
// (original filenames and layout kept: humanlike.mjs imports ./integrity.mjs and reads
|
|
10
|
+
// model/ next to itself). crossadapter.mjs and model/human-v1.lab.json (lab-only adversary
|
|
11
|
+
// results) are not vendored and must not ship. A test pins
|
|
12
|
+
// the sha256s. To upgrade, re-copy the files and update the pins here and in the test.
|
|
13
|
+
// The logic lives only in the vendored files. This module adds nothing to it: it iterates
|
|
14
|
+
// `report.checks` and never lists check names, so checks added later flow through.
|
|
15
|
+
//
|
|
16
|
+
// Local-only. Nothing here touches the network or writes outside the cache helpers below.
|
|
17
|
+
|
|
18
|
+
import { readFileSync, existsSync, writeFileSync, mkdirSync, unlinkSync } from "node:fs";
|
|
19
|
+
import { spawn } from "node:child_process";
|
|
20
|
+
import { homedir } from "node:os";
|
|
21
|
+
import { join, dirname } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import {
|
|
24
|
+
listTranscripts,
|
|
25
|
+
readTranscripts,
|
|
26
|
+
otelFiles,
|
|
27
|
+
readOtel,
|
|
28
|
+
evaluate,
|
|
29
|
+
toolHash,
|
|
30
|
+
WINDOWS,
|
|
31
|
+
TOOL,
|
|
32
|
+
VERSION,
|
|
33
|
+
} from "./vendor/tokenpull-integrity/integrity.mjs";
|
|
34
|
+
import { MIN_PROMPTS, scoreSessions } from "./vendor/tokenpull-integrity/humanlike.mjs";
|
|
35
|
+
|
|
36
|
+
export const VENDORED_SHA256 = {
|
|
37
|
+
"integrity.mjs": "13fbbc5111ceee707f300999c41af17e335993122cca77e7e7dfcae6608ba713",
|
|
38
|
+
"humanlike.mjs": "fc86829f1d506d778d1c9a3b5a85da0061783afa95f8cda23a36cd38e5e954c6",
|
|
39
|
+
"model/human-v1.json": "cb6492329bb5719e6b746bdf7e3b16795627ae863679a383e3bf6215a5006c0e",
|
|
40
|
+
};
|
|
41
|
+
export const VENDORED_COMMIT = "69360a7";
|
|
42
|
+
export const INTEGRITY_WINDOWS = Object.keys(WINDOWS); // 7d, 30d, 90d, all
|
|
43
|
+
export { TOOL as INTEGRITY_TOOL, VERSION as INTEGRITY_VERSION };
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The board's snapshot schema is strict (unknown fields are rejected). sigrank-app #521
|
|
47
|
+
* accepts the optional signed `integrity` block, so a real publish with integrity:true
|
|
48
|
+
* is allowed. Set false to refuse client-side again (dry_run always shows the block).
|
|
49
|
+
*/
|
|
50
|
+
export const INTEGRITY_SERVER_ACCEPTS = true;
|
|
51
|
+
|
|
52
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
53
|
+
const VENDOR_DIR = join(here, "vendor", "tokenpull-integrity");
|
|
54
|
+
const MODEL_FILE = join(VENDOR_DIR, "model", "human-v1.json");
|
|
55
|
+
// Same convention as the tool itself: first 16 hex of the sha256 of the file.
|
|
56
|
+
// The vendored toolHash(): sha256[:16] over integrity.mjs + humanlike.mjs + model/human-v1.json.
|
|
57
|
+
export const INTEGRITY_HASH = toolHash(VENDOR_DIR);
|
|
58
|
+
|
|
59
|
+
const SAMPLE_LIMIT = 5;
|
|
60
|
+
|
|
61
|
+
function defaultDataDir() {
|
|
62
|
+
try {
|
|
63
|
+
const c = JSON.parse(
|
|
64
|
+
readFileSync(join(homedir(), ".config", "sigrank-otel", "config.json"), "utf8"),
|
|
65
|
+
);
|
|
66
|
+
if (c && typeof c.dataDir === "string" && c.dataDir) {
|
|
67
|
+
return c.dataDir.replace(/^~(?=\/|$)/, homedir());
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
/* no collector config */
|
|
71
|
+
}
|
|
72
|
+
return join(homedir(), ".local", "share", "sigrank-otel");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Run the checks. Reads transcripts + stored OTel rows once, evaluates each requested
|
|
77
|
+
* window. opts: { windows?: string[], roots?: string[], dataDir?: string, now?: number }.
|
|
78
|
+
* Returns { tool, version, hash, reports: { <window>: report } } with the vendored
|
|
79
|
+
* report objects untouched (the vendored evaluate() sets `hash` from toolHash()).
|
|
80
|
+
*/
|
|
81
|
+
export async function runIntegrity(opts = {}) {
|
|
82
|
+
const windows = (opts.windows && opts.windows.length ? opts.windows : INTEGRITY_WINDOWS).filter(
|
|
83
|
+
(w) => w in WINDOWS,
|
|
84
|
+
);
|
|
85
|
+
const roots = opts.roots || [join(homedir(), ".claude", "projects")];
|
|
86
|
+
const now = opts.now ?? Date.now();
|
|
87
|
+
const files = listTranscripts(roots);
|
|
88
|
+
const tx = await readTranscripts(files, { now });
|
|
89
|
+
const op = otelFiles(opts.dataDir || defaultDataDir());
|
|
90
|
+
const otel = op.length ? await readOtel(op) : null;
|
|
91
|
+
// Check 3 (human likelihood), mirroring integrity.mjs main(): session scores carry the
|
|
92
|
+
// transcript ordinal; the path is dropped.
|
|
93
|
+
let human = null;
|
|
94
|
+
if (existsSync(MODEL_FILE)) {
|
|
95
|
+
const model = JSON.parse(readFileSync(MODEL_FILE, "utf8"));
|
|
96
|
+
const ord = new Map(files.map(([p], i) => [p, i]));
|
|
97
|
+
const sessions = (await scoreSessions(roots, model)).map((x) => ({ ...x, ordinal: ord.get(x.path) ?? null, path: undefined }));
|
|
98
|
+
human = { model, minPrompts: MIN_PROMPTS, sessions };
|
|
99
|
+
}
|
|
100
|
+
const reports = {};
|
|
101
|
+
for (const w of windows) {
|
|
102
|
+
const rep = evaluate({ tx, otel, windowName: w, now, human });
|
|
103
|
+
reports[w] = rep;
|
|
104
|
+
}
|
|
105
|
+
return { tool: TOOL, version: VERSION, hash: INTEGRITY_HASH, reports };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Total flags across every check in a report (checks without a flag count add 0). */
|
|
109
|
+
export function flagCount(report) {
|
|
110
|
+
let n = 0;
|
|
111
|
+
for (const c of Object.values(report?.checks || {})) {
|
|
112
|
+
if (c && Number.isFinite(c.flags)) n += c.flags;
|
|
113
|
+
}
|
|
114
|
+
return n;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** One-line overall summary for a window. */
|
|
118
|
+
export function overallLine(report) {
|
|
119
|
+
const checks = Object.entries(report?.checks || {});
|
|
120
|
+
const ran = checks.filter(([, c]) => c && Number.isFinite(c.flags));
|
|
121
|
+
const skipped = checks.length - ran.length;
|
|
122
|
+
const n = flagCount(report);
|
|
123
|
+
return (
|
|
124
|
+
`${report.window}: ${n} flag${n === 1 ? "" : "s"} across ${ran.length} check${ran.length === 1 ? "" : "s"}` +
|
|
125
|
+
(skipped ? ` (${skipped} not run)` : "") +
|
|
126
|
+
` · ${report.tool} v${report.version} (${report.hash}) · a flag means worth a look, not cheating · local only, nothing sent`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Per-check view for check_integrity: flags, score, codes, a few samples (ordinal + line). */
|
|
131
|
+
export function checkView(check) {
|
|
132
|
+
const c = check || {};
|
|
133
|
+
if (!Number.isFinite(c.flags)) {
|
|
134
|
+
return { status: c.status || "not_run", ...(c.reason ? { reason: c.reason } : {}) };
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
flags: c.flags,
|
|
138
|
+
score: c.score ?? null,
|
|
139
|
+
codes: { ...(c.codes || {}) },
|
|
140
|
+
// e.g. human_likelihood: "calibrated on one operator ..." so a flag is not read as an accusation
|
|
141
|
+
...(typeof c.calibration?.note === "string" ? { note: c.calibration.note } : {}),
|
|
142
|
+
sample: (c.sample || []).slice(0, SAMPLE_LIMIT).map((s) => ({
|
|
143
|
+
code: s.code,
|
|
144
|
+
file: s.file, // ordinal in the sorted transcript list, not a path
|
|
145
|
+
line: s.line,
|
|
146
|
+
})),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** check_integrity result for one window. */
|
|
151
|
+
export function windowView(report) {
|
|
152
|
+
const checks = {};
|
|
153
|
+
for (const [name, c] of Object.entries(report.checks || {})) checks[name] = checkView(c);
|
|
154
|
+
return {
|
|
155
|
+
window: report.window,
|
|
156
|
+
from: report.from,
|
|
157
|
+
to: report.to,
|
|
158
|
+
population: report.population,
|
|
159
|
+
flags: flagCount(report),
|
|
160
|
+
checks,
|
|
161
|
+
overall: overallLine(report),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The block added to a signed snapshot when integrity is on. Scores and counts only:
|
|
167
|
+
* no samples, file ordinals, line numbers, text, paths or session ids. Check names and
|
|
168
|
+
* code names are the vendored tool's own fixed vocabulary; a check that did not run
|
|
169
|
+
* carries flags: null.
|
|
170
|
+
*/
|
|
171
|
+
export function integrityBlock(report) {
|
|
172
|
+
const checks = {};
|
|
173
|
+
for (const [name, c] of Object.entries(report.checks || {})) {
|
|
174
|
+
const ran = c && Number.isFinite(c.flags);
|
|
175
|
+
const codes = {};
|
|
176
|
+
if (ran) {
|
|
177
|
+
for (const [k, v] of Object.entries(c.codes || {})) {
|
|
178
|
+
if (Number.isFinite(v)) codes[k] = v;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
checks[name] = {
|
|
182
|
+
flags: ran ? c.flags : null,
|
|
183
|
+
score: ran && Number.isFinite(c.score) ? c.score : null,
|
|
184
|
+
codes,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
tool: report.tool,
|
|
189
|
+
version: report.version,
|
|
190
|
+
hash: report.hash,
|
|
191
|
+
window: report.window,
|
|
192
|
+
checks,
|
|
193
|
+
flagCount: flagCount(report),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ── TUI cache: last result per window, written by a background worker ───────────
|
|
198
|
+
export const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
|
199
|
+
export const integrityCachePath = (dir = process.env.SIGRANK_INTEGRITY_DIR || join(homedir(), ".sigrank-mcp")) =>
|
|
200
|
+
join(dir, "integrity-last.json");
|
|
201
|
+
|
|
202
|
+
/** Compact cache shape: counts only. */
|
|
203
|
+
export function cacheEntry(report) {
|
|
204
|
+
// checks: name -> flag count, or null when that check did not run (generic: no name list).
|
|
205
|
+
const checks = {};
|
|
206
|
+
for (const [name, c] of Object.entries(report.checks || {})) checks[name] = c && Number.isFinite(c.flags) ? c.flags : null;
|
|
207
|
+
return { flags: flagCount(report), version: report.version, hash: report.hash, checks };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Read the cache synchronously. Returns { at, windows: { <w>: {flags,version,hash} } } or null. */
|
|
211
|
+
export function readIntegrityCache(dir) {
|
|
212
|
+
try {
|
|
213
|
+
const c = JSON.parse(readFileSync(integrityCachePath(dir), "utf8"));
|
|
214
|
+
if (c && typeof c.at === "number" && c.windows && typeof c.windows === "object") return c;
|
|
215
|
+
} catch {
|
|
216
|
+
/* none yet */
|
|
217
|
+
}
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** One status line for a window; "not checked" until a cached result exists. */
|
|
222
|
+
export function statusLine(cache, window) {
|
|
223
|
+
const e = cache?.windows?.[window];
|
|
224
|
+
if (!e || !Number.isFinite(e.flags)) return `integrity: not checked · ${window}`;
|
|
225
|
+
return `integrity: ${e.flags} flag${e.flags === 1 ? "" : "s"} · checked ${window} · v${e.version}`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ── Single-worker lock: integrity-worker.lock = { pid, at }. A lock is live while its pid
|
|
229
|
+
// runs and it is younger than LOCK_MAX_AGE_MS; otherwise it is stale and is taken over.
|
|
230
|
+
export const LOCK_MAX_AGE_MS = 15 * 60 * 1000;
|
|
231
|
+
export const integrityLockPath = (dir) => join(dir || process.env.SIGRANK_INTEGRITY_DIR || join(homedir(), ".sigrank-mcp"), "integrity-worker.lock");
|
|
232
|
+
const pidAlive = (pid) => {
|
|
233
|
+
try {
|
|
234
|
+
process.kill(pid, 0);
|
|
235
|
+
return true;
|
|
236
|
+
} catch (e) {
|
|
237
|
+
return e.code === "EPERM";
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
/** True when another worker holds a live lock. */
|
|
241
|
+
export function integrityLockHeld(dir, { now = Date.now(), alive = pidAlive } = {}) {
|
|
242
|
+
try {
|
|
243
|
+
const l = JSON.parse(readFileSync(integrityLockPath(dir), "utf8"));
|
|
244
|
+
return Number.isInteger(l.pid) && now - l.at < LOCK_MAX_AGE_MS && alive(l.pid);
|
|
245
|
+
} catch {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** Take the lock; false if a live one exists. Atomic create. A stale lock is removed only
|
|
250
|
+
* if its content is still what we read (two takeovers cannot both succeed: whoever loses the
|
|
251
|
+
* re-check, or the following exclusive create, backs off). */
|
|
252
|
+
export function acquireIntegrityLock(dir, { now = Date.now(), pid = process.pid, alive = pidAlive } = {}) {
|
|
253
|
+
const file = integrityLockPath(dir);
|
|
254
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
255
|
+
for (let i = 0; i < 3; i++) {
|
|
256
|
+
try {
|
|
257
|
+
writeFileSync(file, JSON.stringify({ pid, at: now }), { flag: "wx", mode: 0o600 });
|
|
258
|
+
return true;
|
|
259
|
+
} catch (e) {
|
|
260
|
+
if (e.code !== "EEXIST") return false;
|
|
261
|
+
let seen;
|
|
262
|
+
try { seen = readFileSync(file, "utf8"); } catch { continue; } // vanished: retry the create
|
|
263
|
+
if (integrityLockHeld(dir, { now, alive })) return false;
|
|
264
|
+
try {
|
|
265
|
+
if (readFileSync(file, "utf8") === seen) unlinkSync(file); // still the stale one we judged
|
|
266
|
+
} catch { /* someone else took it over */ }
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
export function releaseIntegrityLock(dir, pid = process.pid) {
|
|
272
|
+
try {
|
|
273
|
+
const l = JSON.parse(readFileSync(integrityLockPath(dir), "utf8"));
|
|
274
|
+
if (l.pid === pid) unlinkSync(integrityLockPath(dir));
|
|
275
|
+
} catch { /* gone */ }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ── Attempt marker: integrity-attempt.json = { at, ok }. A failed or unfinished attempt blocks
|
|
279
|
+
// respawning for RETRY_MS, so a broken worker cannot be restarted on every TUI launch.
|
|
280
|
+
export const RETRY_MS = 30 * 60 * 1000;
|
|
281
|
+
export const integrityAttemptPath = (dir) => join(dir || process.env.SIGRANK_INTEGRITY_DIR || join(homedir(), ".sigrank-mcp"), "integrity-attempt.json");
|
|
282
|
+
export function writeIntegrityAttempt(dir, ok, now = Date.now()) {
|
|
283
|
+
try {
|
|
284
|
+
const f = integrityAttemptPath(dir);
|
|
285
|
+
mkdirSync(dirname(f), { recursive: true, mode: 0o700 });
|
|
286
|
+
writeFileSync(f, JSON.stringify({ at: now, ok }), { mode: 0o600 });
|
|
287
|
+
} catch { /* best effort */ }
|
|
288
|
+
}
|
|
289
|
+
export function readIntegrityAttempt(dir) {
|
|
290
|
+
try {
|
|
291
|
+
const a = JSON.parse(readFileSync(integrityAttemptPath(dir), "utf8"));
|
|
292
|
+
return a && typeof a.at === "number" ? a : null;
|
|
293
|
+
} catch { return null; }
|
|
294
|
+
}
|
|
295
|
+
/** Minutes until a retry is allowed after a failed/unfinished attempt, else 0. */
|
|
296
|
+
export function retryInMinutes(dir, now = Date.now()) {
|
|
297
|
+
const a = readIntegrityAttempt(dir);
|
|
298
|
+
if (!a || a.ok === true) return 0;
|
|
299
|
+
const left = RETRY_MS - (now - a.at);
|
|
300
|
+
return left > 0 ? Math.ceil(left / 60000) : 0;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const truthy = (v) => v != null && v !== "" && v !== "0" && v !== "false";
|
|
304
|
+
|
|
305
|
+
/** Opt out of the TUI's background check: SIGRANK_NO_INTEGRITY=1 (also set in CI). */
|
|
306
|
+
export function integrityBackgroundDisabled(env = process.env) {
|
|
307
|
+
return truthy(env.SIGRANK_NO_INTEGRITY) || truthy(env.CI);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Refresh the cache in a separate process when it is missing or older than CACHE_TTL_MS.
|
|
312
|
+
* Never blocks and never throws: returns null when nothing was started, else the child
|
|
313
|
+
* (unref'd, stdio ignored). onDone fires when the worker exits, so the caller can re-read
|
|
314
|
+
* the cache and redraw. opts: { dir, env, now, spawnFn }.
|
|
315
|
+
*/
|
|
316
|
+
export function refreshIntegrityInBackground(onDone, opts = {}) {
|
|
317
|
+
try {
|
|
318
|
+
if (integrityBackgroundDisabled(opts.env)) return null;
|
|
319
|
+
const cache = readIntegrityCache(opts.dir);
|
|
320
|
+
const now = opts.now ?? Date.now();
|
|
321
|
+
if (cache && now - cache.at < CACHE_TTL_MS) return null;
|
|
322
|
+
if (retryInMinutes(opts.dir, now) > 0) return null; // backing off after a failed attempt
|
|
323
|
+
if (integrityLockHeld(opts.dir, { now, ...(opts.alive ? { alive: opts.alive } : {}) })) return null; // one worker at a time
|
|
324
|
+
writeIntegrityAttempt(opts.dir, null, now); // unfinished until the worker reports ok
|
|
325
|
+
const child = (opts.spawnFn || spawn)(
|
|
326
|
+
process.execPath,
|
|
327
|
+
[join(here, "integrity-worker.mjs")],
|
|
328
|
+
{ stdio: "ignore", detached: true, windowsHide: true, env: { ...process.env, ...(opts.dir ? { SIGRANK_INTEGRITY_DIR: opts.dir } : {}) } },
|
|
329
|
+
);
|
|
330
|
+
child.on?.("exit", () => {
|
|
331
|
+
try {
|
|
332
|
+
onDone?.();
|
|
333
|
+
} catch {
|
|
334
|
+
/* ignore */
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
child.on?.("error", () => {});
|
|
338
|
+
child.unref?.();
|
|
339
|
+
return child;
|
|
340
|
+
} catch {
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ── TUI block: checks × windows matrix (same design as the site's matrix) ──────────
|
|
346
|
+
// ✓ clean (green) · N flags (amber, never red: a flag is "worth a look") · – not run (dim).
|
|
347
|
+
const SHORT = {
|
|
348
|
+
record_integrity: "records",
|
|
349
|
+
source_agreement: "sources",
|
|
350
|
+
cache_pumping: "cache",
|
|
351
|
+
human_likelihood: "human",
|
|
352
|
+
double_counting: "double",
|
|
353
|
+
cross_adapter: "adapters",
|
|
354
|
+
};
|
|
355
|
+
/** Short row label; an unknown check falls back to its key, shortened. */
|
|
356
|
+
export const checkLabel = (name) => SHORT[name] || String(name).replace(/_/g, " ").slice(0, 8);
|
|
357
|
+
|
|
358
|
+
export function ageLabel(ms) {
|
|
359
|
+
if (!Number.isFinite(ms) || ms < 0) return "just now";
|
|
360
|
+
const m = Math.floor(ms / 60000);
|
|
361
|
+
if (m < 1) return "just now";
|
|
362
|
+
if (m < 60) return `${m}m ago`;
|
|
363
|
+
const h = Math.floor(m / 60);
|
|
364
|
+
return h < 48 ? `${h}h ago` : `${Math.floor(h / 24)}d ago`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const PLAIN = { ok: (s) => s, flag: (s) => s, off: (s) => s, head: (s) => s };
|
|
368
|
+
const MATRIX_MIN_WIDTH = 44;
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Lines for the Dashboard (no leading indent). opts: { width, rows (spare lines),
|
|
372
|
+
* color: {ok, flag, off, head} painters or null for plain, now }.
|
|
373
|
+
* Matrix when it fits; else one line (statusLine for 7d); "not checked" until a cache exists.
|
|
374
|
+
*/
|
|
375
|
+
export function renderIntegrityBlock(cache, { width = 80, rows = 99, color = null, now = Date.now(), retryIn = 0 } = {}) {
|
|
376
|
+
const P = color || PLAIN;
|
|
377
|
+
if (!cache || !cache.windows) {
|
|
378
|
+
if (rows < 1) return [];
|
|
379
|
+
return [`${P.head("INTEGRITY")} ${P.off(retryIn > 0 ? `integrity: check failed · retry in ${retryIn}m` : "not checked")}`];
|
|
380
|
+
}
|
|
381
|
+
const wins = INTEGRITY_WINDOWS.filter((w) => cache.windows[w]);
|
|
382
|
+
const names = [];
|
|
383
|
+
for (const w of wins) for (const n of Object.keys(cache.windows[w].checks || {})) if (!names.includes(n)) names.push(n);
|
|
384
|
+
const first = cache.windows[wins[0]] || {};
|
|
385
|
+
const need = 2 + names.length;
|
|
386
|
+
if (!names.length || rows < need || width < MATRIX_MIN_WIDTH) {
|
|
387
|
+
return rows >= 1 ? [P.off(statusLine(cache, "7d"))] : [];
|
|
388
|
+
}
|
|
389
|
+
const LW = Math.max(7, ...names.map((n) => checkLabel(n).length)) + 2, CW = 6;
|
|
390
|
+
const cell = (v) => {
|
|
391
|
+
if (v == null) return P.off("–".padStart(Math.ceil((CW + 1) / 2)).padEnd(CW));
|
|
392
|
+
if (v === 0) return P.ok("✓".padStart(Math.ceil((CW + 1) / 2)).padEnd(CW));
|
|
393
|
+
const t = v > 99 ? "99+" : String(v);
|
|
394
|
+
return P.flag(t.padStart(Math.ceil((CW + t.length) / 2)).padEnd(CW));
|
|
395
|
+
};
|
|
396
|
+
const out = [`${P.head("INTEGRITY")} ${P.off(`v${first.version} · ${String(first.hash || "").slice(0, 8)} · checked ${ageLabel(now - cache.at)}`)}`];
|
|
397
|
+
out.push(" ".repeat(LW) + wins.map((w) => P.off(w.padStart(Math.ceil((CW + w.length) / 2)).padEnd(CW))).join(""));
|
|
398
|
+
for (const n of names) {
|
|
399
|
+
out.push(checkLabel(n).padEnd(LW) + wins.map((w) => cell(cache.windows[w].checks?.[n])).join(""));
|
|
400
|
+
}
|
|
401
|
+
return out;
|
|
402
|
+
}
|
|
@@ -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; });
|