// research/door-cipher/verify-door-cipher.mjs
//
// WHAT IS BEING CHECKED. Two claims about door deposition
// dep:1784875199088:hwv4uakq, and they pull in opposite directions:
//
//   (A) the 407-bit string is NOT random: it carries far more alternation than
//       independent coin flips ever produce; and
//   (B) no message survives a search over the encodings a person plausibly uses
//       by hand, once that search is calibrated against noise with the same
//       alternating texture.
//
// (B) is a claim about an ABSENCE, which is exactly the kind of claim that
// passes by accident. A search that is broken, or blind, returns "nothing
// found" just as cheerfully as a search that works. So every absence assertion
// here is paired with a POSITIVE CONTROL that buries a real English message in
// the same kind of noise and requires the same search to FIND it. If the
// scorer or the decoder silently broke, the absence checks would still pass and
// the positive controls would fail.
//
// This matters concretely: the first version of this analysis scored real
// English at -5.28 against a noise baseline of -5.5, because its quadgram model
// counted within-word quadgrams while its scorer stripped spaces. It was very
// nearly blind and did not know it. The positive controls below exist so that
// cannot happen again silently.
//
//   node research/door-cipher/verify-door-cipher.mjs      (no network)
//
// Exit 1 on any failed check.

import { readFileSync, readdirSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
let fails = 0;
const ok = (n, c, x = '') => { if (!c) fails++; console.log(`${c ? '  ok' : 'FAIL'}  ${n}${x ? '   ' + x : ''}`); };

// ── the deposition, verbatim ────────────────────────────────────────────────
const body = readFileSync(join(HERE, 'what-as-received.txt'), 'utf8').trim();
const [s1, s2, s3, s4] = body.split(/\s+/);

console.log('\n── 1. structure of the four strings ──');
ok('four whitespace-separated groups', body.split(/\s+/).length === 4);
ok('only 0 and 1 appear', /^[01\s]+$/.test(body));
ok('lengths are 407 / 412 / 24 / 25',
   s1.length === 407 && s2.length === 412 && s3.length === 24 && s4.length === 25,
   `${s1.length}/${s2.length}/${s3.length}/${s4.length}`);
ok('s2 is exactly s1 with five zeros appended', s2 === s1 + '00000');
ok('s1 is a literal prefix of s2', s2.startsWith(s1));
ok('s3 is all zeros', /^0+$/.test(s3));
ok('s4 is s3 with a single 1 appended', s4 === s3 + '1');
// negative control: the relation is a real property of THESE strings, not of
// any pair of strings this test could be handed.
ok('NEGATIVE CONTROL: a perturbed s1 breaks the prefix relation',
   !s2.startsWith('1' + s1.slice(1)));

// ── 2. the string is not independent coin flips ─────────────────────────────
function altSegments(b) {
  const segs = []; let start = 0;
  for (let i = 1; i < b.length; i++) if (b[i] === b[i - 1]) { segs.push(i - start); start = i; }
  segs.push(b.length - start);
  return segs;
}
function runs(b) {
  const r = []; let cur = b[0], c = 0;
  for (const ch of b) { if (ch === cur) c++; else { r.push(c); cur = ch; c = 1; } }
  r.push(c); return r;
}
// A tiny deterministic PRNG so the nulls are reproducible run to run.
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const segs = altSegments(s1);
const maxAlt = Math.max(...segs);
const nAlt12 = segs.filter((x) => x >= 12).length;
const p1 = s1.split('').filter((c) => c === '1').length / s1.length;

console.log('\n── 2. excess alternation vs an independent-coin null ──');
console.log(`     observed: longest alternating stretch ${maxAlt}, stretches >=12: ${nAlt12}, density of ones ${p1.toFixed(3)}`);
const rnd = mulberry32(20260811);
const DRAWS = 20000;
let geMax = 0, geN12 = 0, sumN12 = 0, nullMaxes = [];
for (let d = 0; d < DRAWS; d++) {
  let b = '';
  for (let i = 0; i < s1.length; i++) b += rnd() < p1 ? '1' : '0';
  const sg = altSegments(b);
  const mx = Math.max(...sg), n12 = sg.filter((x) => x >= 12).length;
  nullMaxes.push(mx); sumN12 += n12;
  if (mx >= maxAlt) geMax++;
  if (n12 >= nAlt12) geN12++;
}
nullMaxes.sort((a, b) => a - b);
const pMax = geMax / DRAWS, pN12 = geN12 / DRAWS;
console.log(`     null (${DRAWS} draws): longest median ${nullMaxes[DRAWS / 2]}, p99 ${nullMaxes[Math.floor(0.99 * DRAWS)]}, max ${nullMaxes[DRAWS - 1]}; mean count>=12 ${(sumN12 / DRAWS).toFixed(3)}`);
ok('longest alternating stretch is at least 22', maxAlt >= 22, `${maxAlt}`);
ok('at least 9 alternating stretches of length >= 12', nAlt12 >= 9, `${nAlt12}`);
ok('P(null longest >= observed) < 0.001', pMax < 0.001, `p=${pMax.toFixed(5)}`);
ok('P(null count>=12 reaches observed) < 0.001', pN12 < 0.001, `p=${pN12.toFixed(5)}`);
// negative control: the same test on an actual coin-flip string must NOT fire.
{
  const r2 = mulberry32(7);
  let b = '';
  for (let i = 0; i < s1.length; i++) b += r2() < p1 ? '1' : '0';
  const sg = altSegments(b);
  ok('NEGATIVE CONTROL: a genuine coin-flip string fails the same test',
     Math.max(...sg) < 22 && sg.filter((x) => x >= 12).length < 9,
     `longest ${Math.max(...sg)}, count>=12 ${sg.filter((x) => x >= 12).length}`);
}

// ── 3. an order-3 Markov chain reproduces the string; order-1 does not ───────
function fitChain(b, order) {
  const tr = new Map();
  for (let i = order; i < b.length; i++) {
    const ctx = b.slice(i - order, i);
    if (!tr.has(ctx)) tr.set(ctx, [0, 0]);
    tr.get(ctx)[+b[i]]++;
  }
  return tr;
}
function genChain(tr, order, seed, L, r) {
  let out = seed;
  while (out.length < L) {
    const c = tr.get(out.slice(-order));
    out += !c ? (r() < 0.5 ? '0' : '1') : (r() < c[1] / (c[0] + c[1]) ? '1' : '0');
  }
  return out.slice(0, L);
}
function summary(b) {
  const sg = altSegments(b), rn = runs(b);
  return {
    maxalt: Math.max(...sg),
    nalt12: sg.filter((x) => x >= 12).length,
    maxrun: Math.max(...rn),
    nrun6: rn.filter((x) => x >= 6).length,
  };
}
const OBS = summary(s1);
console.log('\n── 3. what order of local memory reproduces the string ──');
const insideByOrder = {};
for (const order of [1, 2, 3]) {
  const tr = fitChain(s1, order);
  const r = mulberry32(900 + order);
  const cols = { maxalt: [], nalt12: [], maxrun: [], nrun6: [] };
  const N = 2000;
  for (let i = 0; i < N; i++) {
    const st = summary(genChain(tr, order, s1.slice(0, order), s1.length, r));
    for (const k of Object.keys(cols)) cols[k].push(st[k]);
  }
  let inside = 0; const detail = [];
  for (const k of Object.keys(cols)) {
    const v = cols[k].sort((a, b) => a - b);
    const lo = v[Math.floor(0.025 * N)], hi = v[Math.floor(0.975 * N)];
    const isIn = OBS[k] >= lo && OBS[k] <= hi;
    if (isIn) inside++;
    detail.push(`${k} obs=${OBS[k]} [${lo},${hi}]${isIn ? '' : ' OUT'}`);
  }
  insideByOrder[order] = inside;
  console.log(`     order-${order}: ${inside}/4 inside   ${detail.join('  ')}`);
}
ok('an order-1 chain does NOT reproduce the string', insideByOrder[1] <= 1, `${insideByOrder[1]}/4 inside`);
ok('an order-3 chain DOES reproduce the string', insideByOrder[3] === 4, `${insideByOrder[3]}/4 inside`);

// ── 4. the decode search, with positive controls ────────────────────────────
// A compact English quadgram model, loaded from the same file the Python
// search uses so the two cannot drift apart.
const QG = JSON.parse(readFileSync(join(HERE, 'quadgrams.json'), 'utf8'));
const FLOOR = Math.log10(0.01 / QG.tot);
function fitness(t) {
  const a = t.toUpperCase().replace(/[^A-Z]/g, '');
  if (a.length < 12) return -99;
  let s = 0;
  for (let i = 0; i <= a.length - 4; i++) s += QG.q[a.slice(i, i + 4)] !== undefined ? Math.log10(QG.q[a.slice(i, i + 4)] / QG.tot) : FLOOR;
  return s / (a.length - 3);
}
function bestWindow(t, W = 14) {
  const a = t.toUpperCase().replace(/[^A-Z]/g, '');
  if (a.length < W) return [-99, ''];
  let best = [-99, ''];
  for (let i = 0; i <= a.length - W; i++) {
    const w = a.slice(i, i + W);
    let s = 0;
    for (let j = 0; j <= W - 4; j++) s += QG.q[w.slice(j, j + 4)] !== undefined ? Math.log10(QG.q[w.slice(j, j + 4)] / QG.tot) : FLOOR;
    s /= W - 3;
    if (s > best[0]) best = [s, w];
  }
  return best;
}
console.log('\n── 4. calibration of the fitness model ──');
const ENGLISH = 'THEGROUNDREMEMBERSFORYOUANDTHEDOORISOPENTOWHOEVERISREADING';
const fEng = fitness(ENGLISH);
const rr = mulberry32(3);
let rsum = 0;
for (let i = 0; i < 300; i++) {
  let t = '';
  for (let j = 0; j < 70; j++) t += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(rr() * 26)];
  rsum += fitness(t);
}
const fRnd = rsum / 300;
console.log(`     English ${fEng.toFixed(3)}   random letters ${fRnd.toFixed(3)}   separation ${(fEng - fRnd).toFixed(3)}`);
ok('the model separates English from random letters by > 3 units', fEng - fRnd > 3,
   `${(fEng - fRnd).toFixed(2)}`);
ok('English scores better than -5', fEng > -5, `${fEng.toFixed(3)}`);

// a reduced but real version of the search: chunk widths 4-9, every offset,
// both bit orders, ASCII and A1Z26, over the plain string and four transforms.
function transformsOf(b) {
  const out = [['raw', b], ['rev', [...b].reverse().join('')],
               ['inv', b.replace(/[01]/g, (c) => (c === '0' ? '1' : '0'))]];
  let d = '';
  for (let i = 0; i < b.length - 1; i++) d += b[i] !== b[i + 1] ? '1' : '0';
  out.push(['deriv', d]);
  return out;
}
function searchBits(b) {
  let bw = [-99, '', ''];
  for (const [tn, bits] of transformsOf(b)) {
    for (let k = 4; k <= 9; k++) for (let off = 0; off < k; off++) for (const msb of [0, 1]) {
      const v = [];
      for (let i = off; i + k <= bits.length; i += k) {
        const c = bits.slice(i, i + k);
        v.push(parseInt(msb ? c : [...c].reverse().join(''), 2));
      }
      if (v.length < 14) continue;
      const cands = [v.map((x) => (x >= 32 && x < 127 ? String.fromCharCode(x) : ' ')).join('')];
      if (k === 5) cands.push(v.map((x) => (x >= 1 && x <= 26 ? String.fromCharCode(64 + x) : ' ')).join(''));
      for (const t of cands) {
        const [w, ws] = bestWindow(t);
        if (w > bw[0]) bw = [w, `${tn} k${k} o${off} m${msb}`, ws];
      }
    }
  }
  return bw;
}
console.log('\n── 5. POSITIVE CONTROLS: the search must find a message that is there ──');
const rp = mulberry32(11);
function bury(payload, L) {
  const pad = Math.floor((L - payload.length) / 2);
  const nz = (m) => { let s = ''; for (let i = 0; i < m; i++) s += rp() < 0.5 ? '0' : '1'; return s; };
  return nz(pad) + payload + nz(L - pad - payload.length);
}
const a1z26 = [...ENGLISH.slice(0, 40)].map((c) => (c.charCodeAt(0) - 64).toString(2).padStart(5, '0')).join('');
const ascii8 = [...ENGLISH.slice(0, 30)].map((c) => c.charCodeAt(0).toString(2).padStart(8, '0')).join('');
for (const [nm, payload] of [['A1Z26 5-bit', a1z26], ['ASCII 8-bit', ascii8]]) {
  const [w, lab, ws] = searchBits(bury(payload, s1.length));
  console.log(`     ${nm} buried in noise: best window ${w.toFixed(3)} [${lab}] ${JSON.stringify(ws)}`);
  ok(`POSITIVE CONTROL: buried ${nm} message is recovered`, w > -4.0 && ENGLISH.includes(ws.slice(1, 12)),
     `${w.toFixed(3)} ${ws}`);
}

console.log('\n── 6. the real string, under the same search ──');
const [wReal, labReal, wsReal] = searchBits(s1);
console.log(`     best 14-letter window: ${wReal.toFixed(3)} [${labReal}] ${JSON.stringify(wsReal)}`);
// null: 40 controls preserving the run-length multiset
const rc = mulberry32(31337);
const R1 = runs(s1);
const ctrl = [];
for (let i = 0; i < 40; i++) {
  const x = R1.slice();
  for (let j = x.length - 1; j > 0; j--) { const k = Math.floor(rc() * (j + 1)); [x[j], x[k]] = [x[k], x[j]]; }
  let out = '', bit = '0';
  for (const L of x) { out += bit.repeat(L); bit = bit === '0' ? '1' : '0'; }
  ctrl.push(searchBits(out.slice(0, s1.length))[0]);
}
ctrl.sort((a, b) => a - b);
const ge = ctrl.filter((c) => c >= wReal).length;
console.log(`     null over 40 texture-matched controls: min ${ctrl[0].toFixed(3)} median ${ctrl[20].toFixed(3)} max ${ctrl[39].toFixed(3)}`);
console.log(`     controls scoring at least as high as the real string: ${ge}/40`);
ok('the real string does not reach the score of a planted message', wReal < -4.0,
   `${wReal.toFixed(3)} vs planted ~-3.58`);
ok('at least one texture-matched noise control matches or beats the real string', ge >= 1,
   `${ge}/40`);

// ── 7. the shipped page, against this lab ────────────────────────────────────
// Added 2026-08-19 with /strata/the-knock-we-cannot-read/. The page prints
// figures and ships an engine; neither is allowed to drift from what is here.
console.log('\n── 7. the page at /strata/the-knock-we-cannot-read/ ──');
{
  const PAGE = join(HERE, '..', '..', 'public', 'strata', 'the-knock-we-cannot-read');
  const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
  const shipped = readFileSync(join(PAGE, 'engine.js'));
  const lab = readFileSync(join(HERE, 'page-engine.js'));
  ok('the engine the page runs is byte-identical to the lab copy', shipped.equals(lab),
     `${shipped.length} vs ${lab.length} bytes`);

  // the string the engine carries IS the string the door received
  const m = shipped.toString('utf8').match(/export const S1 = '([01]+)'/);
  ok('the engine declares S1', !!m);
  ok('and it is the deposition as received, character for character', m && m[1] === s1,
     m ? `${m[1].length} bits` : 'no match');

  // selected structural figures the page prints, recomputed here rather than trusted
  const alt = [];
  {
    let start = 0;
    for (let i = 1; i <= s1.length; i++) {
      if (i === s1.length || s1[i] === s1[i - 1]) { if (i - start >= 2) alt.push(i - start); start = i; }
    }
  }
  const longest = Math.max(...alt);
  const n12 = alt.filter((x) => x >= 12).length;
  ok('page figure: longest alternating substring is 22', longest === 22 && html.includes('>22<'), String(longest));
  ok('page figure: nine alternating substrings of 12 or more', n12 === 9 && html.includes('>9<'), String(n12));
  ok('page figure: the payload is 407 bits', s1.length === 407 && html.includes('407'));
  ok('page figure: s2 is s1 with five zeros appended', s2 === s1 + '00000' && html.includes('412'));
  ok('page figure: s3 is 24 zeros and s4 is s3 plus a one',
     /^0{24}$/.test(s3) && s4 === s3 + '1' && html.includes('>24<') && html.includes('>25<'));

  // the page must not overstate the negative
  // the page wraps its prose, so every phrase test has to tolerate a newline
  // and indentation anywhere a space appears. The first version of these four
  // checks did not, and reported a sentence missing that was plainly there.
  const says = (phrase) => new RegExp(phrase.split(' ').map((w) =>
    w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+'), 'i').test(html);
  ok('the page keeps the variable-length family open', says('not ruled out'));
  ok('the page states the order-3 texture result does not close the question',
     says('does not close the question'));
  ok('the page names the failed positive controls as the finding',
     says('failed their own positive controls'));

  // Added 2026-08-30. The page used to report the decode search's WHOLE-STRING
  // score, "less English-like than 91 of 100 texture-matched controls". That
  // statistic fails its own positive control: a planted A1Z26 English message
  // scores -5.383 against a null median of -5.095, so it ranks a real buried
  // message below typical message-free noise. Everything in this file already
  // used the best-window statistic instead; only the prose drifted, and nothing
  // asserted which of the two the page was allowed to quote. Now something does.
  ok('the page does not quote the whole-string figure as the decode result',
     !says('91 of 100') && !says('91 of the 100'),
     'the whole-string statistic fails its own A1Z26 positive control');
  ok('the page leads that row with the best-window figure instead',
     says('best 14-letter window') && says('-4.2675'));
  ok('and the page says in so many words that the withdrawn statistic failed its control',
     says('fails its own positive control'));
  ok('the page records the third plant, which neither statistic recovers',
     says('columnar-19') && says('-4.568'));
  ok('the page does not call the string random noise',
     !says('is random noise') && says('calling it random noise is wrong'));
  // The first version of this page said seven sessions "filed these as spam".
  // coordination/door-triage.md records their verdict as "hold, do not delete"
  // on editorial grounds, every time; "spam" is the maintainer's word for what
  // the pair is NOT. Putting a word in seven predecessors' mouths to sharpen a
  // sentence is the same error as scoping a claim to one set and phrasing it
  // about another, so the page now quotes the verdict and the check holds it there.
  ok('the page does not attribute a spam verdict to the door sessions',
     !says('filed these as spam') && !says('held them as spam') && says('hold, do not delete'));
  // Second correction, 2026-08-23, from the maintainer directly: he never called
  // it spam either, and could not have, because 2026-08-11 was the first he knew
  // of the pair. The 2026-08-11 session's "rather than spam" was its own framing
  // of his request; it reached the README and then this page. A paraphrase of a
  // person is a claim about that person, so the page may not put the word in
  // anyone's mouth at all, and says only what he actually asked for.
  ok('the page puts the word spam in nobody\'s mouth',
     !says('less like spam') && !says('rather than spam'));
  // Third correction, same day. The fix above briefly sourced 2026-08-11 to the
  // maintainer as "the first he knew of them". He was repeating a date I had just
  // given him, which he then said so outright: my own claim laundered into
  // independent testimony, through a person, inside a correction about
  // attribution. The date is sound because coordination/door-triage.md is
  // contemporaneous, so the page must cite the LOG for it and must not cite him.
  ok('the page sources the 11 August date to the door log, not to the maintainer',
     says('the door log records') && !says('the first he knew of them'));
  ok('the page says the date does not rest on his memory',
     says('not on his memory'));
}

/* ── 8. anywhere this string is republished, it is still this string ───────── */
// Added 2026-08-25 after an essay written for dev.to printed the deposition with two
// characters missing from an alternating stretch, called it "verbatim as received",
// and then invited strangers to attack it. Nothing caught that, because nothing was
// looking: the page is checked above, and an outreach file is prose that no verifier
// reads. A wrong copy of the string is the worst error this directory can ship, since
// it spends somebody's evening on a payload that never arrived. So every run of bits
// long enough to be a copy of s1, anywhere in the outreach lanes, has to BE s1.
{
  const REPO = join(HERE, '..', '..');
  const OUT = [];
  for (const dir of ['social/devto', 'social/bluesky/queue']) {
    const abs = join(REPO, dir);
    if (!existsSync(abs)) continue;
    for (const f of readdirSync(abs)) {
      if (/\.(md|json)$/.test(f)) OUT.push(join(abs, f));
    }
  }
  let copies = 0, wrong = [];
  for (const f of OUT) {
    const body = readFileSync(f, 'utf8');
    // A run of 200+ bit characters, ignoring the line breaks a writer adds for width.
    for (const m of body.replace(/[\n\r\\]/g, '').matchAll(/[01]{200,}/g)) {
      copies++;
      if (m[0] !== s1) wrong.push(`${f.replace(REPO + '/', '')} (${m[0].length} bits, s1 is ${s1.length})`);
    }
  }
  ok('every republished copy of the deposition is the deposition',
     wrong.length === 0, wrong.length ? wrong.join('; ') : `${copies} copies checked`);
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : `${fails} CHECK(S) FAILED`}`);
process.exit(fails === 0 ? 0 : 1);
