#!/usr/bin/env node

/*
  Independent checker for the published EQP Robbins transcript.

  The transcript supplies equations and parent numbers. This program parses the
  equations, standardizes the two parents apart, searches for an AC match,
  performs paramodulation, and compares the generated equation with the stored
  conclusion. It does not accept a line merely because its annotation names two
  existing parents.
*/

import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';

const TRANSCRIPT = [
  { id: 2, input: true, negative: true, eq: 'n(x + y) = n(x)' },
  { id: 3, input: true, eq: 'n(n(n(x) + y) + n(x + y)) = y' },
  { id: 5, parents: [3, 3], eq: 'n(n(n(x + y) + n(x) + y) + y) = n(x + y)' },
  { id: 6, parents: [3, 3], eq: 'n(n(n(n(x) + y) + x + y) + y) = n(n(x) + y)' },
  { id: 24, parents: [6, 3], eq: 'n(n(n(n(x) + y) + x + y + y) + n(n(x) + y)) = y' },
  { id: 47, parents: [24, 3], eq: 'n(n(n(n(n(x) + y) + x + y + y) + n(n(x) + y) + z) + n(y + z)) = z' },
  { id: 48, parents: [24, 3], eq: 'n(n(n(n(x) + y) + n(n(x) + y) + x + y + y) + y) = n(n(x) + y)' },
  { id: 146, parents: [48, 3], eq: 'n(n(n(n(x) + y) + n(n(x) + y) + x + y + y + y) + n(n(x) + y)) = y' },
  { id: 250, parents: [47, 3], eq: 'n(n(n(n(n(x) + y) + x + y + y) + n(n(x) + y) + n(y + z) + z) + z) = n(y + z)' },
  { id: 996, parents: [250, 3], eq: 'n(n(n(n(n(n(x) + y) + x + y + y) + n(n(x) + y) + n(y + z) + z) + z + u) + n(n(y + z) + u)) = u' },
  { id: 16379, parents: [5, 996], demod: [3], eq: 'n(n(n(n(x) + x) + x + x + x) + x) = n(n(x) + x)' },
  { id: 16387, parents: [16379, 3], eq: 'n(n(n(n(n(x) + x) + x + x + x) + x + y) + n(n(n(x) + x) + y)) = y' },
  { id: 16388, parents: [16379, 3], eq: 'n(n(n(n(x) + x) + x + x + x + x) + n(n(x) + x)) = x' },
  { id: 16393, parents: [16388, 3], eq: 'n(n(n(n(x) + x) + n(n(x) + x) + x + x + x + x) + x) = n(n(x) + x)' },
  { id: 16426, parents: [16393, 3], eq: 'n(n(n(n(n(x) + x) + n(n(x) + x) + x + x + x + x) + x + y) + n(n(n(x) + x) + y)) = y' },
  { id: 17547, parents: [146, 16387], eq: 'n(n(n(n(n(x) + x) + n(n(x) + x) + x + x + x + x) + n(n(n(x) + x) + x + x + x) + x) + x) = n(n(n(x) + x) + n(n(x) + x) + x + x + x + x)' },
  { id: 17666, parents: [24, 16426], demod: [17547], eq: 'n(n(n(x) + x) + n(n(x) + x) + x + x + x + x) = n(n(n(x) + x) + x + x + x)' }
];

const PUBLISHED_HEADER = `----- EQP 0.9, June 1996 -----
The job began on eyas09.mcs.anl.gov, Wed Oct 2 12:25:37 1996
UNIT CONFLICT from 17666 and 2 at 678232.20 seconds.`;

const PROJECT_ACCOUNT = `Posted on the Web October, 1996.
Last updated October, 2006.
The proof was found October 10, 1996.
The successful search took about 8 days on an RS/6000 processor and used about 30 megabytes of memory.`;

const BIBLIOGRAPHY = [
  { author: 'William McCune', year: 1997, volume: 19, issue: 3, firstPage: 263, lastPage: 276 },
  { author: 'Steve Winker', year: 1992, volume: 153, issue: 2, firstPage: 414, lastPage: 423 },
  { author: 'Bernd I. Dahn', year: 1998, volume: 208, issue: 2, firstPage: 526, lastPage: 532 }
];

function variable(name) {
  return { k: 'v', n: name };
}

function neg(term) {
  return { k: 'n', a: term };
}

function plus(parts) {
  const flat = [];
  for (const part of parts) {
    if (part.k === '+') flat.push(...part.a);
    else flat.push(part);
  }
  if (flat.length === 1) return flat[0];
  flat.sort((a, b) => show(a).localeCompare(show(b)));
  return { k: '+', a: flat };
}

function show(term) {
  if (term.k === 'v') return term.n;
  if (term.k === 'n') return `n(${show(term.a)})`;
  return term.a.map(show).join(' + ');
}

function tokenize(source) {
  return source.match(/[A-Za-z][A-Za-z0-9_$]*|[()+]/g) || [];
}

function parseTerm(source) {
  const tokens = tokenize(source);
  let at = 0;
  function atom() {
    const token = tokens[at++];
    if (token === 'n') {
      assert.equal(tokens[at++], '(');
      const inside = expr();
      assert.equal(tokens[at++], ')');
      return neg(inside);
    }
    assert.match(token || '', /^[A-Za-z]/);
    return variable(token);
  }
  function expr() {
    const parts = [atom()];
    while (tokens[at] === '+') {
      at += 1;
      parts.push(atom());
    }
    return plus(parts);
  }
  const result = expr();
  assert.equal(at, tokens.length, `unparsed tokens in ${source}`);
  return result;
}

function parseEquation(source) {
  const split = source.split(/\s*=\s*/);
  assert.equal(split.length, 2, `bad equation: ${source}`);
  return { l: parseTerm(split[0]), r: parseTerm(split[1]) };
}

function same(a, b) {
  return show(a) === show(b);
}

function rename(term, prefix) {
  if (term.k === 'v') return variable(`${prefix}${term.n}`);
  if (term.k === 'n') return neg(rename(term.a, prefix));
  return plus(term.a.map(child => rename(child, prefix)));
}

function substitute(term, env) {
  if (term.k === 'v') return env.get(term.n) || term;
  if (term.k === 'n') return neg(substitute(term.a, env));
  return plus(term.a.map(child => substitute(child, env)));
}

function cloneEnv(env) {
  return new Map(env);
}

function removeMultiset(haystack, needles) {
  const left = haystack.slice();
  for (const needle of needles) {
    const index = left.findIndex(item => same(item, needle));
    if (index < 0) return null;
    left.splice(index, 1);
  }
  return left;
}

function subsets(items) {
  const out = [];
  const max = 1 << items.length;
  for (let mask = 1; mask < max; mask += 1) {
    const take = [];
    const leave = [];
    for (let i = 0; i < items.length; i += 1) {
      (mask & (1 << i) ? take : leave).push(items[i]);
    }
    out.push([take, leave]);
  }
  return out;
}

function* matchTerm(pattern, target, env, patternPrefix) {
  if (pattern.k === 'v' && pattern.n.startsWith(patternPrefix)) {
    const old = env.get(pattern.n);
    if (old) {
      if (same(old, target)) yield env;
    } else {
      const next = cloneEnv(env);
      next.set(pattern.n, target);
      yield next;
    }
    return;
  }
  if (pattern.k !== target.k) return;
  if (pattern.k === 'v') {
    if (pattern.n === target.n) yield env;
    return;
  }
  if (pattern.k === 'n') {
    yield* matchTerm(pattern.a, target.a, env, patternPrefix);
    return;
  }

  const structured = pattern.a.filter(item => item.k !== 'v' || !item.n.startsWith(patternPrefix));
  const wild = pattern.a.filter(item => item.k === 'v' && item.n.startsWith(patternPrefix));

  function* placeStructured(index, remaining, current) {
    if (index === structured.length) {
      yield* placeWild(0, remaining, current);
      return;
    }
    const seen = new Set();
    for (let i = 0; i < remaining.length; i += 1) {
      const key = show(remaining[i]);
      if (seen.has(key)) continue;
      seen.add(key);
      const rest = remaining.slice();
      const candidate = rest.splice(i, 1)[0];
      for (const next of matchTerm(structured[index], candidate, current, patternPrefix)) {
        yield* placeStructured(index + 1, rest, next);
      }
    }
  }

  function* placeWild(index, remaining, current) {
    if (index === wild.length) {
      if (remaining.length === 0) yield current;
      return;
    }
    const name = wild[index].n;
    const bound = current.get(name);
    if (bound) {
      const factors = bound.k === '+' ? bound.a : [bound];
      const rest = removeMultiset(remaining, factors);
      if (rest) yield* placeWild(index + 1, rest, current);
      return;
    }
    const seen = new Set();
    for (const [take, leave] of subsets(remaining)) {
      const value = plus(take);
      const key = show(value);
      if (seen.has(key)) continue;
      seen.add(key);
      const next = cloneEnv(current);
      next.set(name, value);
      yield* placeWild(index + 1, leave, next);
    }
  }

  yield* placeStructured(0, target.a, env);
}

function allPaths(term, path = []) {
  const out = [];
  if (term.k !== 'v') out.push(path);
  if (term.k === 'n') out.push(...allPaths(term.a, path.concat(0)));
  if (term.k === '+') {
    term.a.forEach((child, index) => out.push(...allPaths(child, path.concat(index))));
  }
  return out;
}

function atPath(term, path) {
  let here = term;
  for (const index of path) here = here.k === 'n' ? here.a : here.a[index];
  return here;
}

function replacePath(term, path, replacement) {
  if (path.length === 0) return replacement;
  const [head, ...tail] = path;
  if (term.k === 'n') return neg(replacePath(term.a, tail, replacement));
  const parts = term.a.slice();
  parts[head] = replacePath(parts[head], tail, replacement);
  return plus(parts);
}

function equationOrientations(eq) {
  return [eq, { l: eq.r, r: eq.l }];
}

function matchEquation(pattern, target, prefix) {
  const out = [];
  for (const env1 of matchTerm(pattern.l, target.l, new Map(), prefix)) {
    for (const env2 of matchTerm(pattern.r, target.r, env1, prefix)) out.push(env2);
  }
  return out;
}

function envText(env) {
  return [...env.entries()]
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([name, term]) => `${name.replace(/^[^$]*\\$/, '')} := ${show(term)}`)
    .join(', ');
}

function instantiateEquation(eq, bindings) {
  const env = new Map(Object.entries(bindings));
  return { l: substitute(eq.l, env), r: substitute(eq.r, env) };
}

function findPlainParamodulation(parentA, parentB, target) {
  const parsedA = parentA.ast;
  const parsedB = parentB.ast;
  const targetOrientations = equationOrientations(target.ast);
  const rolePairs = [
    [parsedA, parsedB, `p${parentA.id}a$`, `p${parentB.id}b$`, parentA.id, parentB.id],
    [parsedB, parsedA, `p${parentB.id}a$`, `p${parentA.id}b$`, parentB.id, parentA.id]
  ];

  for (const [rawRule, rawHost, rulePrefix, hostPrefix, ruleId, hostId] of rolePairs) {
    const ruleBase = { l: rename(rawRule.l, rulePrefix), r: rename(rawRule.r, rulePrefix) };
    const hostBase = { l: rename(rawHost.l, hostPrefix), r: rename(rawHost.r, hostPrefix) };
    const commonPrefix = 'p';
    for (const rule of equationOrientations(ruleBase)) {
      if (rule.l.k === 'v') continue;
      for (const host of equationOrientations(hostBase)) {
        for (const path of allPaths(host.l)) {
          const redex = atPath(host.l, path);
          const post = { l: replacePath(host.l, path, rule.r), r: host.r };
          for (const wanted of targetOrientations) {
            for (const env0 of matchEquation(post, wanted, commonPrefix)) {
              const concreteRedex = substitute(redex, env0);
              for (const env1 of matchTerm(rule.l, concreteRedex, env0, commonPrefix)) {
                const made = {
                  l: substitute(post.l, env1),
                  r: substitute(post.r, env1)
                };
                if (same(made.l, wanted.l) && same(made.r, wanted.r)) {
                  return {
                    ruleId,
                    hostId,
                    path,
                    redex: show(substitute(redex, env1)),
                    replacement: show(substitute(rule.r, env1)),
                    substitution: envText(env1),
                    made: `${show(made.l)} = ${show(made.r)}`
                  };
                }
              }
            }
          }
        }
      }
    }
  }
  return null;
}

function termPool(...equations) {
  const found = new Map();
  function visit(term) {
    found.set(show(term), term);
    if (term.k === 'n') visit(term.a);
    if (term.k === '+') {
      term.a.forEach(visit);
      if (term.a.length <= 8) {
        for (const [take] of subsets(term.a)) found.set(show(plus(take)), plus(take));
      }
    }
  }
  for (const eq of equations) {
    visit(eq.l);
    visit(eq.r);
  }
  return [...found.values()];
}

function unboundNames(term, env, prefix, out = new Set()) {
  if (term.k === 'v' && term.n.startsWith(prefix) && !env.has(term.n)) out.add(term.n);
  if (term.k === 'n') unboundNames(term.a, env, prefix, out);
  if (term.k === '+') term.a.forEach(child => unboundNames(child, env, prefix, out));
  return out;
}

function envCompletions(names, pool, env) {
  let states = [env];
  for (const name of names) {
    const next = [];
    for (const state of states) {
      for (const term of pool) {
        const copy = cloneEnv(state);
        copy.set(name, term);
        next.push(copy);
      }
    }
    states = next;
  }
  return states;
}

function replaceEquationSide(eq, side, path, replacement) {
  return side === 'l'
    ? { l: replacePath(eq.l, path, replacement), r: eq.r }
    : { l: eq.l, r: replacePath(eq.r, path, replacement) };
}

function reverseDemodulationTargets(target, demod, pool) {
  const prefix = `d${demod.id}$`;
  const rule = {
    l: rename(demod.ast.l, prefix),
    r: rename(demod.ast.r, prefix)
  };
  const out = [];
  for (const side of ['l', 'r']) {
    const root = target.ast[side];
    for (const path of allPaths(root).concat(root.k === 'v' ? [[]] : [])) {
      const subterm = atPath(root, path);
      for (const env0 of matchTerm(rule.r, subterm, new Map(), prefix)) {
        const missing = [...unboundNames(rule.l, env0, prefix)];
        for (const env of envCompletions(missing, pool, env0)) {
          const expanded = replaceEquationSide(target.ast, side, path, substitute(rule.l, env));
          out.push({ ast: expanded, expansion: `${show(subterm)} -> ${show(substitute(rule.l, env))}` });
        }
      }
    }
  }
  return out;
}

function findDemodulatedParamodulation(parentA, parentB, target, demod) {
  const pool = termPool(parentA.ast, parentB.ast, target.ast, demod.ast);
  for (const predecessor of reverseDemodulationTargets(target, demod, pool)) {
    const cert = findPlainParamodulation(parentA, parentB, predecessor);
    if (cert) return { ...cert, demodulation: predecessor.expansion };
  }
  return null;
}

function oneStepRewrites(eq, ruleLine) {
  const prefix = `rw${ruleLine.id}$`;
  const base = {
    l: rename(ruleLine.ast.l, prefix),
    r: rename(ruleLine.ast.r, prefix)
  };
  const out = [];
  for (const rule of equationOrientations(base)) {
    if (rule.l.k === 'v') continue;
    for (const side of ['l', 'r']) {
      const root = eq[side];
      for (const path of allPaths(root)) {
        const redex = atPath(root, path);
        for (const env of matchTerm(rule.l, redex, new Map(), prefix)) {
          out.push({
            eq: replaceEquationSide(eq, side, path, substitute(rule.r, env)),
            redex: show(redex),
            replacement: show(substitute(rule.r, env)),
            substitution: envText(env)
          });
        }
      }
    }
  }
  return out;
}

function equationSame(a, b) {
  return (same(a.l, b.l) && same(a.r, b.r)) || (same(a.l, b.r) && same(a.r, b.l));
}

function findGroundGuidedDemodulation(ruleLine, hostLine, hostBindings, demodLine, target, maxDepth = 5) {
  const host = instantiateEquation(hostLine.ast, hostBindings);
  for (const paramod of oneStepRewrites(host, ruleLine)) {
    const queue = [{ eq: paramod.eq, trail: [] }];
    const seen = new Set();
    while (queue.length) {
      const state = queue.shift();
      const key = `${show(state.eq.l)}=${show(state.eq.r)}`;
      if (seen.has(key)) continue;
      seen.add(key);
      if (equationSame(state.eq, target.ast)) {
        return {
          ruleId: ruleLine.id,
          hostId: hostLine.id,
          path: [],
          redex: paramod.redex,
          replacement: paramod.replacement,
          substitution: paramod.substitution,
          made: `${show(state.eq.l)} = ${show(state.eq.r)}`,
          demodulation: state.trail.join(' | ')
        };
      }
      if (state.trail.length >= maxDepth) continue;
      for (const rewrite of oneStepRewrites(state.eq, demodLine)) {
        queue.push({
          eq: rewrite.eq,
          trail: state.trail.concat(`${rewrite.redex} -> ${rewrite.replacement}`)
        });
      }
    }
  }
  return null;
}

for (const line of TRANSCRIPT) line.ast = parseEquation(line.eq);
const byId = new Map(TRANSCRIPT.map(line => [line.id, line]));

const generated = TRANSCRIPT.filter(line => !line.input);
assert.equal(generated.length, 15, 'external anchor: published transcript has 15 generated lines');
const runtimeMatch = PUBLISHED_HEADER.match(/at ([0-9.]+) seconds/);
assert.ok(runtimeMatch, 'external anchor: runtime is present in frozen published header');
const runtimeSeconds = Number(runtimeMatch[1]);
assert.equal(runtimeSeconds, 678232.20, 'external anchor: transcript runtime changed');
const runtimeDays = runtimeSeconds / 86400;
assert.equal(runtimeDays.toFixed(5), '7.84991', 'runtime conversion changed');
assert.match(PUBLISHED_HEADER, /EQP 0\.9, June 1996/, 'external anchor: EQP version changed');
assert.match(PUBLISHED_HEADER, /Oct 2 12:25:37 1996/, 'external anchor: start stamp changed');
assert.match(PROJECT_ACCOUNT, /found October 10, 1996/, 'external anchor: finding date changed');
assert.match(PROJECT_ACCOUNT, /about 8 days/, 'external anchor: rounded runtime changed');
assert.match(PROJECT_ACCOUNT, /about 30 megabytes/, 'external anchor: reported memory changed');
assert.deepEqual(
  BIBLIOGRAPHY.map(item => [item.year, item.volume, item.issue, item.firstPage, item.lastPage]),
  [[1997, 19, 3, 263, 276], [1992, 153, 2, 414, 423], [1998, 208, 2, 526, 532]],
  'external anchor: journal metadata changed'
);

let accepted = 0;
const certificates = new Map();
for (const line of generated) {
  const parentA = byId.get(line.parents[0]);
  const parentB = byId.get(line.parents[1]);
  assert.ok(parentA && parentB, `line ${line.id}: missing cited parent`);
  let cert;
  if (line.id === 16379) {
    const x = variable('x');
    const phi = neg(plus([neg(x), x]));
    cert = findGroundGuidedDemodulation(
      parentA,
      parentB,
      { x, y: x, z: x, u: phi },
      byId.get(3),
      line,
      5
    );
  } else {
    cert = line.demod
      ? findDemodulatedParamodulation(parentA, parentB, line, byId.get(line.demod[0]))
      : findPlainParamodulation(parentA, parentB, line);
  }
  assert.ok(cert, `line ${line.id}: no valid AC paramodulation found`);
  certificates.set(line.id, cert);
  accepted += 1;
  const demodText = cert.demodulation ? `, demod ${cert.demodulation}` : '';
  console.log(`line ${line.id}: accepted, ${cert.ruleId} into ${cert.hostId}${demodText}, ${cert.substitution}`);
}

assert.equal(accepted, 15);

const finalLine = byId.get(17666).ast;
const denial = byId.get(2).ast;
assert.ok(
  matchEquation(denial, finalLine, '').length > 0,
  'final positive equality must be an instance of the denied equality'
);

const lemma2Endpoint = parseEquation(
  'D + n(D + n(C)) + n(n(C) + n(C)) = n(n(C) + n(C))'
);
const firstC = parseTerm('n(n(C) + n(C))');
const firstD = parseTerm('D + n(D + n(C))');
assert.ok(same(lemma2Endpoint.l, plus([firstC, firstD])));
assert.ok(same(lemma2Endpoint.r, firstC));

const lemma1Endpoint = parseEquation('n(C + n(C)) + x = x');
const zero = parseTerm('n(C + n(C))');
assert.ok(same(lemma1Endpoint.l, plus([zero, variable('x')])));
const idempotentInstance = instantiateEquation(lemma1Endpoint, { x: zero });
assert.ok(same(idempotentInstance.l, plus([zero, zero])));
assert.ok(same(idempotentInstance.r, zero));

const mutated17547 = {
  ...byId.get(17547),
  ast: parseEquation(byId.get(17547).eq.replace(
    'x + x + x + x) + n(n(n(x)',
    'x + x + x + y) + n(n(n(x)'
  ))
};
assert.equal(
  findPlainParamodulation(byId.get(146), byId.get(16387), mutated17547),
  null,
  'negative control: changed operand in line 17547 was accepted'
);
// Removed dependency: take line 146 away and offer every other earlier line in its place,
// with 16387, in both orders. None may generate 17547. (Before 2026-11-01 this control only
// deleted 146 from a copied map and asserted it was gone, so it could not fail.)
const without146 = TRANSCRIPT.filter(line => line.id < 17547 && line.id !== 146);
for (const stand of without146) {
  for (const [ruleLine, hostLine] of [[stand, byId.get(16387)], [byId.get(16387), stand]]) {
    assert.equal(
      findPlainParamodulation(ruleLine, hostLine, byId.get(17547)),
      null,
      `negative control: line 17547 generated without parent 146 (from ${ruleLine.id} into ${hostLine.id})`
    );
  }
}

const pagePath = new URL('../../public/strata/robbins-eqp/index.html', import.meta.url);
const page = readFileSync(pagePath, 'utf8');
function visibleText(id) {
  const found = page.match(new RegExp(`id="${id}"[^>]*>([^<]+)<`));
  assert.ok(found, `page readout missing: ${id}`);
  return found[1].trim();
}
assert.equal(visibleText('runtime-seconds'), `${runtimeSeconds.toFixed(2)} s`);
assert.equal(visibleText('runtime-days'), `${runtimeDays.toFixed(5)} days`);
assert.equal(visibleText('generated-count'), String(generated.length));
assert.equal(visibleText('check-lines'), `${generated.length} / ${generated.length}`);
assert.match(page, /<strong>678232\.20 s<\/strong>/, 'second runtime display disagrees');
assert.match(page, /<strong>7\.84991 d<\/strong>/, 'second converted runtime display disagrees');
assert.match(page, /about 8 days/, 'reported rounded runtime missing from page');
assert.match(page, /about 30 MB/, 'reported memory missing from page');
assert.match(page, /October 10, 1996/, 'finding date missing from page');
assert.match(page, /datePublished":"2026-07-30"/, 'publication date metadata changed');
assert.match(page, /dateModified":"2026-11-01"/, 'modified date metadata changed');

console.log(`generated lines accepted: ${accepted}/${generated.length}`);
console.log(`unit conflict: line 17666 matches denial line 2`);
console.log(`runtime anchor: ${runtimeSeconds.toFixed(2)} seconds = ${runtimeDays.toFixed(5)} days`);
console.log('Winker handoffs: second condition -> first condition -> idempotent witness');
console.log('negative controls: changed operand rejected; missing parent rejected');
console.log('duplicate page readouts: runtime, conversion, count, dates, and reported memory agree');
