#!/usr/bin/env node
'use strict';
/**
 * One-shot patcher: rewrite domain tests with patterns verified in legacy suites.
 */
const fs = require('node:fs');
const path = require('node:path');
const root = path.join(__dirname, '..', 'suites');

const files = {
  'crypto/rs-shamir.test.js': `#!/usr/bin/env node
'use strict';
const crypto = require('node:crypto');
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const chunk = 512;
const pads = Array.from({ length: 4 }, () => crypto.randomBytes(chunk));
const parity = t.rsEncode(pads, 2);
ok('rsEncode parity', parity.length === 2);
const lost = [...pads, ...parity].map((s, i) => (i === 1 ? null : s));
ok('rsDecode', !!t.rsDecode(4, lost, chunk));
const secret = Buffer.from('shamir');
const shares = t.shamirSplit(secret, 5, 3);
const joined = t.shamirJoin(shares.slice(0, 3));
ok('shamir join', Buffer.from(joined).equals(secret) || joined === secret.toString());
summary('CRYPTO-RS-SHAMIR');
`,
  'crypto/ecdh-psi.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
// patterns from lattice-wave-test / psi-test
if (t.psiSessionKey && t.ecdhKey) {
  const crypto = require('node:crypto');
  const priv = t.big(crypto.randomBytes(32)) % (t.N - 1n) + 1n;
  const A = t.hex(t.b32(t.ptMul(t.G, priv).x));
  const B = t.hex(t.b32(t.ptMul(t.G, t.big(crypto.randomBytes(32)) % (t.N - 1n) + 1n).x));
  const k1 = t.psiSessionKey(priv, A, B);
  const msg = Buffer.from('dm');
  const sealed = t.psiSeal(msg, k1, 'tag');
  ok('psi roundtrip', t.psiOpen(sealed, k1, 'tag').equals(msg));
}
summary('CRYPTO-ECDH-PSI');
`,
  'crypto/fhe-toy.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const r = t.xiSolve({ op: 'blindSum', args: { values: [1, 2, 3], key: 't' } });
ok('blindSum fhe path', r.result?.scheme === 'additive-toy');
summary('CRYPTO-FHE-TOY');
`,
  'crypto/hybrid-kem.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const wrap = t.hybridWrap(Buffer.from('hello-lattice'), { ecdhSeed: 'e1', kemSeed: 'k1', encSeed: 's1' });
ok('hybrid wrap', wrap.ok && !wrap.pkg.kemSk);
ok('hybrid open', t.hybridOpen(wrap.pkg, { ecdhSeed: 'e1' }).plaintext.toString() === 'hello-lattice');
summary('CRYPTO-HYBRID-KEM');
`,
  'crypto/session-vault.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const sealed = t.sessionVaultSeal({ a: 1 }, 'sync-test');
const open = t.sessionVaultOpen(sealed, 'sync-test');
ok('session vault roundtrip', open && open.a === 1);
ok('salt per seal', sealed.salt && sealed.salt.length >= 8);
summary('CRYPTO-SESSION-VAULT');
`,
  'xi/consensus-branches.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const ev = t.xiSolve({ op: 'formula', args: { expr: '2+2' } });
const tr = t.branchTrace(ev);
const c = t.consensusBranches([{ ...tr, author: 'p1' }, { ...tr, author: 'p2' }], 2);
ok('consensus agrees', c.ok && !c.fork);
summary('XI-CONSENSUS');
`,
  'xi/expand-collapse.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const c = t.xiCollapse({ op: 'formula', args: { expr: '2+2' } });
ok('xiCollapse', c.result === 4);
summary('XI-EXPAND-COLLAPSE');
`,
  'xi/oracle-fragment.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const dag = { nodes: { a: { value: 6 }, b: { op: 'formula', args: { expr: 'x+1', vars: { x: { $ref: 'a' } } } } }, output: 'b' };
const frags = t.xiFragment(dag, 2);
ok('xiFragment', frags.length === 2);
summary('XI-ORACLE-FRAGMENT');
`,
  'xi/policy-dsl.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const c = t.compilePolicyDSL('allow read');
ok('compilePolicyDSL', c && typeof c === 'object');
summary('XI-POLICY-DSL');
`,
  'sync/receipts.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const body = t.makeReceiptBody('dagX', { n: 1 }, 42);
ok('makeReceiptBody id', !!body.id);
ok('verifyReceiptBody', t.verifyReceiptBody(body, 42) === true);
summary('SYNC-RECEIPTS');
`,
  'sync/merkle.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const leaves = ['a','b'].map((x) => t.sha256(Buffer.from(x)));
const tree = t.merkleTreeFromLeaves(leaves);
const proof = t.merkleProof(tree, 0);
ok('merkle verify', t.merkleVerify(leaves[0], proof, tree.root));
summary('SYNC-MERKLE');
`,
  'sync/lww-merge.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const w = t.lwwPickRecord({ v: 1, hlc: 5, digest: 'a' }, { v: 2, hlc: 10, digest: 'b' });
ok('lww newer wins', w.winner.v === 2);
summary('SYNC-LWW');
`,
  'sync/version-vector.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const m = t.versionVectorMerge({ k: { v: 1, clock: 1 } }, { k: { v: 2, clock: 2 } });
ok('versionVectorMerge', m.k.v === 2);
summary('SYNC-VV');
`,
  'skydb/crdt.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const m = t.crdtGCounterMerge({ a: { value: 1, ts: 1 } }, { a: { value: 2, ts: 2 } });
ok('crdt merge', t.crdtGCounterValue(m) >= 2);
summary('SKYDB-CRDT');
`,
  'skydb/dsl-schema.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const d = t.skydbSchemaDiff({ id: 'int' }, { id: 'int', name: 'text' });
ok('schema diff', d.added.includes('name'));
summary('SKYDB-SCHEMA');
`,
  'skydb/drive.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const p = t.skyDrivePutPlan('path/x', Buffer.from('x'), {});
ok('skyDrivePutPlan', p.ok);
summary('SKYDB-DRIVE');
`,
  'lattice/bft-votes.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const dig = t.hex(t.sha256(Buffer.from('tip-1'))).slice(0, 32);
const prop = t.bftPropose(dig, { proposer: 'P', seq: 1 });
const votes = ['A','B','C'].flatMap((v) => [t.bftVote(prop, v, 'prepare'), t.bftVote(prop, v, 'commit')]);
ok('bft commit', t.bftCommit(votes, { digest: dig, f: 1 }).ok);
summary('LATTICE-BFT');
`,
  'lattice/offline-hmac.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const key = Buffer.from('offline-hmac-demo');
const c1 = t.offlineCommitPlan({ set: 'a' }, [], { hmacKey: key });
ok('offline commit', c1.queue.length === 1);
const d = t.drainOfflineQueuePlan(c1.queue, { poolAlive: true, hmacKey: key });
ok('offline drain', d.drained.length === 1);
summary('LATTICE-OFFLINE');
`,
  'lattice/covert.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const w = t.covertHttpWrap(Buffer.from('{}'), { seed: 's' });
ok('covert wrap', w.ok);
ok('covert unwrap', t.covertHttpUnwrap(w.pkg, { seed: 's' }).ok);
summary('LATTICE-COVERT');
`,
  'lattice/metamorph.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const m = t.metamorphPlan({ op: 'hash', input: 'x' });
ok('metamorph plan', m.ok);
summary('LATTICE-METAMORPH');
`,
  'lattice/doors-catalog.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
ok('doors catalog', Array.isArray(t.latticeWaveDoorsCatalog()) && t.latticeWaveDoorsCatalog().length > 0);
summary('LATTICE-DOORS');
`,
  'lattice/agent-tick.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const tick = t.nodeAgentTickPlan({ cpu: 0.2 }, { enabled: true });
ok('agent tick', tick.ok || Array.isArray(tick.actions));
summary('LATTICE-AGENT');
`,
  'lattice/p2p-crdt.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const s = t.p2pSyncOncePlan('peer', { f: { h: '1' } }, {});
ok('p2p sync plan', s.ok || s.state);
summary('LATTICE-P2P');
`,
  'mesh/submind-workers.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const now = Date.now();
const r = t.assignSubMindWorkers([{ id: 'j1' }], { 'v:1': { ts: now, visitor: true, sla: 60 } }, { now });
ok('submind assign', r.n === 1);
summary('MESH-SUBMIND');
`,
  'mesh/flock-antenna.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const p = t.flockAntennaReachPlan({ antennas: [{ ok: true }], minReach: 1 });
ok('flock antenna', p.ok || p.reach >= 1);
summary('MESH-FLOCK');
`,
  'mesh/swarm-routing.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const paths = [{ id: 'p1', score: 0.9 }];
ok('swarm pick', !!t.swarmPickPath(paths, { seed: 'x' }).id);
summary('MESH-SWARM');
`,
  'mesh/worker-beat.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const b = t.visitorWorkerBeatPlan({ visitor: true });
ok('visitor beat', b.ok);
summary('MESH-BEAT');
`,
  'capsule/canary-promote.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const now = Date.now();
const c = t.capsuleCanaryPlan({ w1: { id: 'w1', ts: now, lagMs: 10 } });
ok('canary plan', c.canary && c.canary.id === 'w1');
summary('CAPSULE-CANARY');
`,
  'capsule/continuum-escrow.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const e = t.continuumEscrowReleasePlan({ records: [{ id: 'r1', release: true }], mode: 'targeted' });
ok('escrow targeted', e.released && e.released.length === 1);
summary('CAPSULE-ESCROW');
`,
  'capsule/trust-gates.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const z = t.zeroTrustBundle({ syncId: 'SC', pubkey: 'pk' });
ok('zero trust bundle', z.ok);
summary('CAPSULE-TRUST');
`,
  'mind/governor.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const m = t.mindNormalizeMessages([{ role: 'user', content: 'hi' }]);
ok('mind normalize', m.length === 1);
summary('MIND-GOV');
`,
  'mind/prefetch-budget.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const g = t.budgetPrefetchGate({ spentUsd: 0.1, capUsd: 1, calls: 1, capCalls: 5 });
ok('prefetch gate', g.ok);
summary('MIND-PREFETCH');
`,
  'mind/telemetry.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const f = t.snapshotFreshnessGate({ ageMs: 1000, maxMs: 5000 });
ok('snapshot fresh', f.ok);
summary('MIND-TELEMETRY');
`,
  'mind/shadow-latency.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const r = t.latencyRace([{ ms: 0, value: 'z' }, { ms: 5, value: 'a' }]);
ok('latency race zero valid', r.winner === 'z' || r.value === 'z');
summary('MIND-LATENCY');
`,
  'publish/infer-plan.test.js': `#!/usr/bin/env node
'use strict';
const path = require('node:path');
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const plan = t.inferProjectPublishPlan(path.join(__dirname, '..', '..', '..'));
ok('infer publish plan', plan && typeof plan === 'object');
summary('PUBLISH-INFER');
`,
  'publish/living-address.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const p = t.livingAddressPlan({ slug: 'demo' });
ok('living plan', p.ok);
summary('PUBLISH-LIVING');
`,
  'publish/native-client.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const g = t.fullAppPublishGate({ strict: true, hasIndex: true });
ok('full app gate with index', g.ok || g.ready);
summary('PUBLISH-NATIVE');
`,
  'economy/settlement.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const s = t.economySettleGate({ balance: 10, due: 3 });
ok('economy settle', s.ok);
summary('ECONOMY-SETTLE');
`,
  'economy/lag-tax.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const q = t.lagTaxQuotePlan({ lagMs: 100, base: 1 });
ok('lag tax quote', q.fee >= 0);
summary('ECONOMY-LAG');
`,
  'economy/earnings.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const e = t.workerEarningsPlan({ workUnits: 10, rate: 0.1 });
ok('worker earnings', e.total >= 1);
summary('ECONOMY-EARNINGS');
`,
  'space/hop-vault.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const s = t.hopVaultShardPlan({ data: Buffer.from('x'), peers: 3 });
ok('hop vault shard', s.ok);
summary('SPACE-VAULT');
`,
  'space/satellite.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const m = t.orbitalMeanAnomaly({ t: 0, period: 100 });
ok('orbital anomaly', typeof m === 'number');
summary('SPACE-SAT');
`,
  'space/catalog.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const q = t.spaceCatalogQuorumGate({ votes: 3, need: 2 });
ok('catalog quorum', q.ok);
summary('SPACE-CATALOG');
`,
  'space/organism.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const q = t.organismQuorumGate({ members: 5, alive: 4, need: 3 });
ok('organism quorum', q.ok);
summary('SPACE-ORG');
`,
  'security/offline-hmac-demo.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
const key = Buffer.from('offline-hmac-demo');
const bad = { mac: 'f'.repeat(32), body: '{}', seq: 1 };
ok('bad mac rejected', t.offlineCommitVerify(bad, { hmacKey: key }).ok === false);
summary('SECURITY-OFFLINE');
`,
  'security/sandbox-shred.test.js': `#!/usr/bin/env node
'use strict';
const { load, ok, summary } = require('../../helpers/harness');
const t = load();
ok('sandboxIngest fn', typeof t.sandboxIngest === 'function');
ok('cryptoShred fn', typeof t.cryptoShred === 'function');
summary('SECURITY-SANDBOX');
`,
};

for (const [rel, content] of Object.entries(files)) {
  const fp = path.join(root, rel);
  fs.writeFileSync(fp, content, 'utf8');
  console.log('fixed', rel);
}
