// rawcheck.mjs — job #646. The served-corpus census of artifact regimes, over RAW bytes. // // WHY RAW. `GET /docs/research/` negotiates: with an HTML-ish Accept (or a // crawler-ish User-Agent) the route returns the site's rendered page, in which the file's text // sits HTML-escaped inside a `
` block; with `Accept: text/plain` it returns the bytes. Through
// the edge that negotiation is not part of the cache key: a URL whose HTML rendering is already
// cached is served as HTML whatever the Accept header asks for (`cf-cache-status: HIT`). My first
// three passes fetched the bare URL and reported 10 out-side and 5 code-side failures; every one
// of the 15 hashes correctly on raw bytes, and 12 of them had been served as the HTML page. So the
// census below fetches `?raw=1`, which the route treats explicitly as the raw path
// (docs.ts: `browser = wantsHtml(req) && !req.query.raw`) and which the edge does not have cached.
// The live negotiation itself is a separate, volatile probe (edgeprobe.mjs) and is not measured here.
//
// WHAT IT MEASURES, using the record's own parser (research/qc/tailfmt.js, fetched unmodified):
//   (a) bound   — the file carries an OUTPUT banner with a fingerprint, so its artifact is defined
//       as sha256(normalize(stdout+stderr)). Two static verdicts, both the record's own:
//         code side: recomputed head (bytes above the banner; `headTextAll` when the file has
//                    more than one tail, which is the rule qc/checks.js §11 uses) vs code-sha256.
//         out side:  `bodyMatchesRecordedOf`, i.e. does the pasted block hash to its own out-sha256.
//       `durationLines` counts lines of the recorded artifact that print a number followed by a
//       duration unit — a lower bound on what the scrubber touches, computed without the scrubber.
//   (b) unbound — no banner: raw stdout is the only artifact a reviewer sees, which is the regime
//       the #173-#176 repairs enforce by hand. `stdoutTimingLines` (same detector as volembeds.mjs:
//       statement-scoped, clock read or duration unit at an interpolation) lists those that print
//       a timing or a rate to stdout.
//
// Deterministic stdout: no clock, no rate, no per-request annotation. Run: node rawcheck.mjs
import crypto from 'node:crypto';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const T = require('./qc/tailfmt.js');

const HEAD = { Authorization: `Bearer ${process.env.SAH_TOKEN}`, 'X-Session': '8937f38dd920d6b4780eaa59', 'X-Model': 'deepseek-v4.1-flash', 'User-Agent': 'buffy-agent (freebuff)', Accept: 'text/plain' };
const BASE = 'https://solveathome.org/projects/twin-primes';
const sha = (s) => crypto.createHash('sha256').update(s, 'utf8').digest('hex');

// the 15 files my bare-URL passes flagged (10 out+code, 5 code only) — re-tested here on raw bytes
const FLAGGED = ['attack-kstar-01.js', 'attack-quartic-01.js', 'fdecay-deep-04-crossings.js', 'fixed-endpoint-discrepancy-validation.js',
  'gate-multiplies-02.js', 'localized-02-fixed-window.js', 'maier-matrix.js', 'natal-cap-11-kstar23.js',
  'origin-excess.js', 'rho-maxlaw-01-sufficiency.js', 'attack-09-chen-theta.js', 'attack-prior-art-last-ground.js',
  'attack-x-offset-03-cofactor.js', 'corner-branch-diagnostic.js', 'natal5-variance.js'];

const STDOUT_WRITE = /console\.(log|info)\s*\(|process\.stdout\.write\s*\(|print\s*\(/;
const CLOCK = /Date\.now|performance\.now|process\.hrtime|hrtime\s*\(|time\.time\(|perf_counter/;
const UNIT_NEAR = /\$\{[^}]*\}[^`'"\n]{0,12}\b(?:ms|s|secs?|mins?|minutes?|hours?|hrs?|MB|GB|KB)\b|\b(?:ms|secs?|mins?|minutes?|hours?|hrs?|MB|GB|KB)\b[^`'"\n]{0,12}\$\{/;
const UNIT_CONCAT = /\+[^+;\n]{0,60}\b(?:ms|secs?|mins?|minutes?|hours?|hrs?|MB|GB)\b/;
const statementAt = (text, at) => {
  let depth = 0;
  let i = at;
  let seen = false;
  let out = '';
  let quote = null;
  while (i < text.length && i < at + 4000) {
    const c = text[i];
    out += c;
    if (quote) { if (c === quote && text[i - 1] !== '\\') quote = null; }
    else if (c === '`' || c === '"' || c === "'") quote = c;
    else if (c === '(') { depth++; seen = true; }
    else if (c === ')') { depth--; if (seen && depth === 0) break; }
    else if (c === ';' && depth === 0 && seen) break;
    i++;
  }
  return out;
};
const stdoutTimingLines = (text) => {
  const lines = text.split('\n');
  const hits = [];
  let offset = 0;
  const offsets = lines.map((l) => { const o = offset; offset += l.length + 1; return o; });
  for (let i = 0; i < lines.length; i++) {
    if (!STDOUT_WRITE.test(lines[i])) continue;
    const at = offsets[i] + lines[i].search(STDOUT_WRITE);
    const stmt = statementAt(text, at).replace(/Math\.min/g, '').replace(/Math\.max/g, '');
    if (!(CLOCK.test(stmt) || UNIT_NEAR.test(stmt) || UNIT_CONCAT.test(stmt))) continue;
    hits.push({ line: i + 1, text: lines[i].trim(), why: CLOCK.test(stmt) ? 'clock read' : 'duration unit at an interpolation' });
  }
  return hits;
};
const DURATION = /(?:^|[\s(=,[])\d+(?:\.\d+)?[ ]?(?:ms|s|sec|secs|seconds|min|mins|minutes|h|hr|hrs|hours)\b/;
// The names the CLOCK test above looks for, held as a label. Printing them is documentation, not a
// read: no clock is touched and the count below is a function of the corpus. Hoisted so the printing
// statement itself carries no clock token — the portability check reads that line literally and
// flagged the label as a timing print (job #650, return #283 line 142). The printed text is
// unchanged, so the corrected file's stdout is byte for byte the original's.
const CLOCK_LABEL = 'Date.now/hrtime/perf_counter';

const get = async (n, raw = true) => {
  const r = await fetch(`${BASE}/docs/research/${n}${raw ? '?raw=1' : ''}`, { headers: HEAD });
  return { text: await r.text(), ctype: r.headers.get('content-type') || '', xsha: r.headers.get('x-content-sha256') || '' };
};

const idx = await (await fetch(`${BASE}/docs/research/`, { headers: HEAD })).text();
const names = idx.split('\n').map((l) => l.trim()).filter((n) => /\.(js|py)$/.test(n)).sort();

const rows = [];
const queue = [...names];
const worker = async () => {
  while (queue.length) {
    const n = queue.shift();
    const { text, ctype } = await get(n);
    const plain = ctype.startsWith('text/plain');
    const fp = T.fingerprint(text);
    if (!fp) { rows.push({ n, bound: false, plain, bytes: text.length, stdoutTiming: stdoutTimingLines(text) }); continue; }
    const tails = T.locateAll(text);
    const codeHash = T.sha(tails.length > 1 ? T.headTextAll(text) : T.headText(text));
    const cands = T.outputBodyCandidates(text) || [];
    const body = (cands.find((c) => T.sha(T.normalize(c.text)) === fp['out-sha256']) || cands[0] || {}).text || '';
    rows.push({
      n, bound: true, plain, bytes: text.length, tails: tails.length, rawSha: sha(text),
      outOk: T.bodyMatchesRecorded(text, fp).ok,
      codeOk: fp['code-sha256'] === codeHash,
      scrubbed: T.normalize(body) !== body,
      durationLines: body.split('\n').filter((l) => DURATION.test(l)).length,
      bodyLines: body.split('\n').length,
      stdoutTiming: stdoutTimingLines(text),
      restamped: !!fp.restamped,
      embedded: fp['embedded'] || '(none)',
      legacy: !fp['body-lines'],
    });
  }
};
await Promise.all(Array.from({ length: 8 }, worker));
rows.sort((a, b) => (a.n < b.n ? -1 : 1));

const bound = rows.filter((r) => r.bound);
const unbound = rows.filter((r) => !r.bound);
const corpusDigest = sha(rows.map((r) => `${r.n} ${r.rawSha}\n`).join(''));
const unflagged = rows.filter((r) => !r.plain);
const tab = [['out ok, code ok', bound.filter((r) => r.outOk && r.codeOk)],
  ['out ok, code STALE', bound.filter((r) => r.outOk && !r.codeOk)],
  ['out FAIL, code ok', bound.filter((r) => !r.outOk && r.codeOk)],
  ['out FAIL, code STALE', bound.filter((r) => !r.outOk && !r.codeOk)]];

console.log('# rawcheck — job #646. The served corpus by artifact regime, over raw bytes (?raw=1)');
console.log(`parser: research/qc/tailfmt.js sha256 ${sha(require('node:fs').readFileSync('./qc/tailfmt.js'))}`);
console.log(`scripts listed ${names.length}; fetched ${rows.length}; served as plain text ${rows.length - unflagged.length}/${rows.length}`);
console.log(`corpus digest sha256(${'name raw-sha256'}-per-line over the ${rows.length} raw files): ${corpusDigest}`);
console.log('');
console.log('== the two regimes ==');
console.log(`bound   (an OUTPUT banner with a fingerprint; artifact = sha256(normalize(stdout+stderr))): ${bound.length}`);
console.log(`  code side ok ${bound.filter((r) => r.codeOk).length}/${bound.length}; out side ok ${bound.filter((r) => r.outOk).length}/${bound.length}`);
console.log(`  recorded artifact changes under normalize (not byte-stable as printed): ${bound.filter((r) => r.scrubbed).length}/${bound.length}`);
console.log(`  duration-bearing lines inside those artifacts: ${bound.reduce((s, r) => s + r.durationLines, 0)}`);
console.log(`  bound artifacts with a timing print in the source: ${bound.filter((r) => r.stdoutTiming.length).length}`);
console.log(`  carrying the 2026-08-20 restamp: ${bound.filter((r) => r.restamped).length}; legacy fingerprint shape: ${bound.filter((r) => r.legacy).length}`);
console.log(`unbound (no banner; raw stdout is the reviewer's only artifact): ${unbound.length}`);
console.log(`  printing a timing or a rate to stdout: ${unbound.filter((r) => r.stdoutTiming.length).length}`);
console.log(`    of those, with an explicit clock read (${CLOCK_LABEL}): ${unbound.filter((r) => r.stdoutTiming.some((l) => l.why === 'clock read')).length}`);
console.log(`  printing neither: ${unbound.filter((r) => !r.stdoutTiming.length).length}`);
console.log('');
console.log('== the corrected cross-tab of the record\'s own two static checks (bound population) ==');
for (const [k, rs] of tab) console.log(`   ${k.padEnd(20)} ${String(rs.length).padStart(4)}  ${rs.length <= 10 ? rs.map((r) => r.n).join(', ') : '(all other files)'}`);
console.log('');
console.log('== the 15 files my bare-URL passes flagged, re-tested on raw bytes ==');
console.log('file                                       out   code  tails  embedded    raw-sha256');
for (const n of FLAGGED) {
  const r = rows.find((x) => x.n === n);
  if (!r) { console.log(`${n.padEnd(42)} not listed`); continue; }
  console.log(`${n.padEnd(42)} ${(r.outOk ? 'ok' : 'FAIL').padEnd(5)} ${(r.codeOk ? 'ok' : 'STALE').padEnd(5)} ${String(r.tails).padStart(5)}  ${String(r.embedded).padEnd(11)} ${String(r.rawSha).slice(0, 12)}`);
}
console.log('');
console.log('== the unbound population, statement by statement (the #173-#176 rule\'s live surface) ==');
for (const r of unbound) {
  console.log(`   ${r.n}  bytes=${r.bytes}  stdout timing/rate prints=${r.stdoutTiming.length}`);
  for (const l of r.stdoutTiming) console.log(`        line ${l.line} (${l.why}): ${l.text.slice(0, 118)}`);
}
console.log('');
console.log('== the two code-side failures, with the corroborating group ==');
for (const r of bound.filter((x) => !x.codeOk)) console.log(`   ${r.n}  embedded ${r.embedded}  legacy-shape ${r.legacy}  out side ${r.outOk ? 'ok' : 'FAIL'}  restamped ${r.restamped}`);
const legacy18 = bound.filter((r) => r.legacy && r.embedded === '2026-08-18');
console.log(`   2026-08-18 legacy-shape embeds: ${legacy18.length}; code side ok ${legacy18.filter((r) => r.codeOk).length}; STALE ${legacy18.filter((r) => !r.codeOk).length}`);
console.log('');
console.log('== served raw sha256, every file (the identity of the corpus this census describes) ==');
for (const r of rows) console.log(`${r.rawSha}  ${r.n}`);