import {
  assertCatalog,
  catalogs,
  classes,
  evidenceStates,
  inquiryDomains,
  keySpecs,
  materialModes,
  polarities,
  slug,
} from './catalog.mjs';
import { sourceById, sources } from './source-registry.mjs';
import { assertAuthoredCandidateRegistry, buildCandidateLonglist, candidateQualityMetrics } from './candidate-registry.mjs';

const RELEASE = Object.freeze({
  number: '1.0.0',
  status: 'canonical-core',
  dated: '2026-08-24',
  schema: 'sf-oracle-card/1.0',
});

const CLASS_BY_ID = Object.fromEntries(classes.map((item) => [item.id, item]));
const DOMAIN_BY_ID = Object.fromEntries(inquiryDomains.map((item) => [item.id, item]));
const VALID_MODES = new Set(materialModes);
const VALID_EVIDENCE = new Set(evidenceStates);
const VALID_SOURCES = new Set(sources.map((source) => source.id));

function hash(value) {
  let output = 2166136261;
  for (const character of String(value)) {
    output ^= character.charCodeAt(0);
    output = Math.imul(output, 16777619);
  }
  return output >>> 0;
}

function pick(seed, values, offset = 0) {
  return values[(hash(`${seed}:${offset}`) + offset) % values.length];
}

function uniq(values) {
  return [...new Set(values.filter(Boolean))];
}

function clamp(value, minimum, maximum) {
  return Math.max(minimum, Math.min(maximum, value));
}

function sentence(value) {
  return /[.!?]$/.test(value) ? value : `${value}.`;
}

function phrase(value) {
  return String(value).replace(/[.!?]+$/, '');
}

const aliasesBySlug = {
  '15-minute-city': ['15-minute city', 'complete neighborhood', 'proximity city'],
  '20-and-back': ['20 & Back', 'twenty-and-back'],
  'artificial-general-intelligence': ['AGI'],
  'brain-computer-interface': ['BCI', 'neural interface'],
  'central-bank-digital-currency': ['CBDC'],
  'controlled-remote-viewing': ['CRV'],
  'deep-underground-military-base': ['DUMB'],
  'déjà-vu': ['deja vu'],
  'dmt-entity': ['psychedelic entity'],
  'extraterrestrial-hypothesis': ['ETH'],
  'grey': ['Gray', 'small Grey'],
  'many-worlds': ['many-worlds interpretation'],
  'military-industrial-complex': ['MIC'],
  'mkultra': ['MK-ULTRA', 'Project MKULTRA'],
  'near-death-experience': ['NDE'],
  'out-of-body-experience': ['OBE'],
  'quantified-self': ['self-tracking'],
  'special-access-program': ['SAP'],
  'the-matrix': ['Matrix'],
  'tic-tac-craft': ['Tic Tac UAP'],
  'unidentified-anomalous-phenomena': ['UAP', 'UFO'],
  'united-federation-of-planets': ['Federation'],
  'zero-point-energy': ['ZPE', 'vacuum energy'],
};

const classModels = {
  forces: {
    noun: 'a recurrent pressure or organizing dynamic',
    origin: 'observations of change, relation, and constraint across natural and cultural systems',
    history: 'has been named differently by scientific, philosophical, spiritual, and narrative traditions whenever people tried to explain recurring change',
    action: 'changes the conditions under which every actor chooses',
    social: 'becomes visible in norms, incentives, contagion, and collective attention',
    spiritual: 'asks how a person relates to powers larger than intention',
    technological: 'appears as an operating condition, feedback signal, or design constraint',
    political: 'reveals who can shape the field and who must adapt to it',
    image: 'an abstract field of directional lines, pressure waves, and one unmistakable central gesture',
  },
  cosmologies: {
    noun: 'a whole-world model for reality and its hidden architecture',
    origin: 'human attempts to place experience inside a comprehensible total order',
    history: 'belongs to a long lineage of cosmograms, religious world-models, scientific universes, and speculative metaphysics',
    action: 'changes what counts as possible before any local decision is made',
    social: 'organizes communities around a shared map of what is ultimately real',
    spiritual: 'locates purpose, suffering, and transcendence within a larger order',
    technological: 'invites tools that reveal, model, navigate, or alter hidden layers',
    political: 'can justify authority by claiming privileged access to the structure of reality',
    image: 'nested horizons and celestial registration rings arranged around a legible world-model',
  },
  beings: {
    noun: 'an agent, intelligence, identity, or recurring role',
    origin: 'encounter narratives and stories about agency beyond the familiar human self',
    history: 'accumulated through folklore, testimony, speculative fiction, spiritual identity, and technological imagination',
    action: 'introduces intention, perspective, and the possibility of reciprocal encounter',
    social: 'tests the boundary between person, role, outsider, and collective identity',
    spiritual: 'can become messenger, mirror, ancestor, guide, adversary, or projected ideal',
    technological: 'asks which capacities make an entity legible as intelligent or alive',
    political: 'raises questions of rights, representation, consent, and classification',
    image: 'a non-portrait emblem built from silhouette, gaze, gesture, or role rather than a literal face',
  },
  worlds: {
    noun: 'a place, environment, frontier, or constructed reality',
    origin: 'geography, exploration, memory-place, and speculative worldbuilding',
    history: 'became meaningful as maps, institutions, stories, and communities layered different uses onto a location',
    action: 'sets the affordances, dangers, distances, and resources of action',
    social: 'gathers identities around belonging, exclusion, migration, and shared place',
    spiritual: 'acts as sanctuary, exile, underworld, promised land, or threshold',
    technological: 'depends on infrastructure for access, survival, sensing, and maintenance',
    political: 'makes borders, jurisdiction, ownership, and environmental burden visible',
    image: 'a navigable horizon, gateway, or terrain mark with clear depth and no scenic illustration clutter',
  },
  technologies: {
    noun: 'a repeatable capability for sensing, transforming, connecting, or constructing',
    origin: 'technical practice joined to dreams about extending human and nonhuman capability',
    history: 'developed through real engineering, speculative extrapolation, fictional prototypes, or contested claims depending on the evidence layer',
    action: 'turns an intention into a repeatable intervention',
    social: 'redistributes skill, dependency, access, and the meaning of expertise',
    spiritual: 'can function as sacrament, prosthesis, forbidden shortcut, or mirror of transformation',
    technological: 'must be evaluated through mechanism, constraints, failure modes, and reproducibility',
    political: 'concentrates or distributes power according to who owns, governs, and can refuse it',
    image: 'a precise instrument diagram reduced to one luminous capability and a readable input-output path',
  },
  artifacts: {
    noun: 'an object-like carrier of evidence, memory, power, or exchange',
    origin: 'material culture and stories in which an object outlasts or exceeds its maker',
    history: 'gathered meaning through use, provenance, circulation, imitation, and retelling',
    action: 'anchors an otherwise abstract claim in something that can be found, held, traded, or decoded',
    social: 'organizes attention around custody, authenticity, value, and access',
    spiritual: 'may operate as relic, talisman, revelation, test, or burden',
    technological: 'invites inspection of material, function, interface, and chain of custody',
    political: 'creates conflict over possession, classification, ownership, and public knowledge',
    image: 'a single centered relic in a registered reliquary with enough empty field for immediate recognition',
  },
  factions: {
    noun: 'a coordinated collective actor with durable membership and aims',
    origin: 'the human need to coordinate at scales larger than one person',
    history: 'draws from orders, states, movements, companies, networks, and fictional polities',
    action: 'turns shared identity into strategy, allocation, and collective consequence',
    social: 'creates belonging while distinguishing members, outsiders, rivals, and dependents',
    spiritual: 'can embody covenant, mission, orthodoxy, or collective shadow',
    technological: 'relies on communication, logistics, records, and enforcement infrastructure',
    political: 'makes legitimacy, sovereignty, hierarchy, and consent unavoidable',
    image: 'interlocking heraldic forms showing membership, center, boundary, and relation without copying a franchise insignia',
  },
  programs: {
    noun: 'a deliberate mission, project, protocol, or coordinated operation',
    origin: 'institutional attempts to produce a defined outcome under constraints',
    history: 'combines documented operations, remembered programs, alleged projects, and fictional mission structures',
    action: 'sequences resources, secrecy, roles, and milestones toward an objective',
    social: 'assigns participants different knowledge, risk, and responsibility',
    spiritual: 'can become initiation, ordeal, rescue mission, or counterfeit salvation',
    technological: 'depends on procedures, interfaces, verification, and operational feedback',
    political: 'must answer who authorized it, who is accountable, and who bears its costs',
    image: 'a segmented mission track with one active objective, one clearance mark, and one visible exit',
  },
  systems: {
    noun: 'a persistent rule environment coordinating access, behavior, and value',
    origin: 'repeated interactions that become infrastructure, institution, or regime',
    history: 'evolved through governance, markets, bureaucracy, networks, and fictional control systems',
    action: 'shapes outcomes even when no participant intends the whole pattern',
    social: 'distributes opportunity, visibility, obligation, and risk across positions',
    spiritual: 'can appear as fate, karmic enclosure, false world, or field of interdependence',
    technological: 'is legible through protocols, data flows, interfaces, and feedback loops',
    political: 'embeds rules about who can know, decide, benefit, appeal, or leave',
    image: 'a governance lattice with visible gates, circulation paths, and one pressure point',
  },
  events: {
    noun: 'a threshold that produces a meaningful before and after',
    origin: 'collective memory and stories organized around irreversible change',
    history: 'takes shape as eyewitness report, public record, prophecy, rumor, or narrative turning point',
    action: 'reorders priorities by making an old equilibrium impossible to maintain',
    social: 'synchronizes attention while communities dispute causes and consequences',
    spiritual: 'may be read as revelation, judgment, initiation, return, or rebirth',
    technological: 'tests detection, resilience, coordination, and recovery capacity',
    political: 'opens exceptional powers while exposing who controls the official account',
    image: 'a broken ring crossed by a bright threshold line, with before and after remaining visually distinct',
  },
  states: {
    noun: 'a condition of mind, body, identity, or society that can be inhabited',
    origin: 'reports of lived experience and the vocabularies used to make those reports shareable',
    history: 'has moved among clinical, spiritual, artistic, political, and subcultural frames',
    action: 'changes perception and choice without necessarily proving an external explanation',
    social: 'affects testimony, belonging, stigma, care, and the ability to coordinate reality',
    spiritual: 'can be interpreted as opening, ordeal, initiation, illusion, or integration',
    technological: 'may be measured, induced, mediated, recorded, or misclassified by tools',
    political: 'raises questions about credibility, autonomy, accommodation, and coercive interpretation',
    image: 'a layered interior halo expressing a condition without diagnosing or literalizing a person',
  },
  myths: {
    noun: 'a durable story-pattern through which communities organize possibility and fear',
    origin: 'storytelling, ritual, memory, propaganda, entertainment, and participatory culture',
    history: 'changes as each medium and community selects different heroes, causes, enemies, and promised endings',
    action: 'provides roles and causal shapes before evidence has settled the world',
    social: 'creates shared meaning, identity, warning, permission, and sometimes scapegoats',
    spiritual: 'offers a symbolic path through transformation without requiring literal belief',
    technological: 'travels through media systems that amplify, remix, and personalize it',
    political: 'can legitimize solidarity or manipulation depending on who defines the story and its enemy',
    image: 'a story-knot, ancestral mark, or mythic object expressed without proprietary characters or emblems',
  },
  hypotheses: {
    noun: 'an explanatory lens applied to ambiguous observations',
    origin: 'the disciplined and undisciplined effort to compare explanations for incomplete evidence',
    history: 'developed as observations accumulated faster than consensus about their interpretation',
    action: 'selects what evidence to seek and what counterevidence could matter',
    social: 'organizes camps around competing standards of explanation and trust',
    spiritual: 'may preserve mystery or close it prematurely by naming an unseen cause',
    technological: 'suggests different instruments, tests, and information architectures',
    political: 'can redirect blame, authority, funding, and disclosure demands',
    image: 'a split lens comparing two or more models around the same unresolved observation',
  },
};

const domainFallback = {
  forces: ['reality-ontology', 'power-control', 'liberation-transcendence'],
  cosmologies: ['reality-ontology', 'origin-lineage', 'time-causality'],
  beings: ['intelligence-otherness', 'contact-communication', 'memory-identity'],
  worlds: ['civilization-ecology', 'origin-lineage', 'technology-infrastructure'],
  technologies: ['technology-infrastructure', 'body-evolution', 'power-control'],
  artifacts: ['memory-identity', 'technology-infrastructure', 'origin-lineage'],
  factions: ['power-control', 'civilization-ecology', 'contact-communication'],
  programs: ['power-control', 'technology-infrastructure', 'contact-communication'],
  systems: ['power-control', 'civilization-ecology', 'technology-infrastructure'],
  events: ['time-causality', 'contact-communication', 'liberation-transcendence'],
  states: ['mind-consciousness', 'memory-identity', 'body-evolution'],
  myths: ['origin-lineage', 'memory-identity', 'power-control'],
  hypotheses: ['reality-ontology', 'intelligence-otherness', 'mind-consciousness'],
};

const domainRules = [
  [/walkability|neighborhood access|local services/i, 'civilization-ecology'],
  [/origin|ancient|ancestor|bloodline|dynasty|source|first|founding|seed|birth|past/i, 'origin-lineage'],
  [/reality|simulation|cosmos|universe|dimension|ontology|hologra|matrix|world|source/i, 'reality-ontology'],
  [/alien|grey|reptil|mantis|insect|intelligence|android|robot|synthetic|borg|other/i, 'intelligence-otherness'],
  [/contact|communication|signal|translator|disclosure|encounter|federation|alliance/i, 'contact-communication'],
  [/mind|conscious|dream|psych|viewing|precognition|attention|wonder|noosphere/i, 'mind-consciousness'],
  [/memory|identity|amnesia|forget|implant|archive|codex|clone|continuity/i, 'memory-identity'],
  [/body|gene|dna|bio|evolution|health|med bed|water|cyborg|longevity|cryo/i, 'body-evolution'],
  [/technology|energy|drive|computer|infrastructure|station|habitat|portal|stargate|smart/i, 'technology-infrastructure'],
  [/time|timeline|causal|loop|future|precognition|mandela|event horizon|etern/i, 'time-causality'],
  [/civilization|ecology|planet|earth|mars|city|colony|econom|resource|community|environment/i, 'civilization-ecology'],
  [/control|government|empire|secret|program|war|prison|panopticon|surveillance|military|scarcity/i, 'power-control'],
  [/liber|ascen|transcend|resist|abundance|awakening|return|exodus|breakthrough/i, 'liberation-transcendence'],
];

function domainsFor(title, classId, index) {
  const matched = domainRules.filter(([pattern]) => pattern.test(title)).map(([, id]) => id);
  const fallback = domainFallback[classId];
  const rotated = [fallback[index % fallback.length], fallback[(index + 1) % fallback.length], fallback[(index + 2) % fallback.length]];
  return uniq([...matched, ...rotated]).slice(0, 3);
}

const scientificTerms = /chaos|emergence|complexity|entropy|evolution|selection pressure|feedback|recursion|nonlinearity|butterfly effect|strange attractor|contagion|many-worlds|block universe|heat death|big bounce|earth$|mars$|moon$|ceres$|asteroid belt|space station|orbital habitat|walkability|neighborhood access|quantum entanglement|zero-point energy|vacuum energy|casimir|gene editing|crispr|synthetic biology|quantified self|wearables|nanotechnology|metamaterial|time crystal|dark matter|event horizon|antikythera mechanism/i;
const emergingTerms = /artificial general intelligence|superintelligence|ai agent|alignment|brain-computer|organ regeneration|longevity|terraform|quantum computer|synthetic biology|gene editing|great filter|fusion|solar sail/i;
const fictionTerms = /dune|arrakis|solaris|ringworld|spice|monolith|galactic empire|rebel alliance|bene gesserit|spacing guild|jedi|sith|starfleet|united federation|borg|three laws|replicant|holodeck|transporter|warp drive|replicator|the matrix/i;
const mythologyTerms = /anunnaki|watcher|atlantis|lemuria|agartha|shambhala|ancient builders|hidden heir|bloodline|dynasty|royal house|chosen one|prophecy|trickster/i;
const esotericTerms = /akashi|gnostic|astral|etheric|source|reincarnation|soul school|remote viewing|starseed|light body|crystalline|ascension|morphic|collective unconscious|synchronicity/i;
const experienceTerms = /experience|projection|dream|déjà|precognition|missing time|life review|witness|experiencer|psychedelic|dmt entity|walk-in/i;
const ufoTerms = /grey|reptilian|mantis|insectoid|pleiadian|sirian|arcturian|andromedan|avian|tall white|uap|saucer|tic-tac|black triangle|mothership|crash|area 51|secret space|disclosure|contactee|hybrid/i;
const conspiracyTerms = /qanon|cabal|deep state|shadow government|illuminati|montauk|philadelphia experiment|blue beam|predictive programming|loosh|prison planet|control grid|limited hangout|false disclosure|the storm|great reset|2027|suppressed technology/i;
const politicalTerms = /empire|federation|government|technocracy|feudalism|digital id|social credit|cbdc|governance|warfare|psyop|propaganda|disinformation|surveillance|panopticon|military/i;
const documentedTerms = /^(earth|mars|moon|ceres|asteroid belt|antarctica|area 51|camp hero|space station|mkultra|project stargate|operation highjump|antikythera mechanism|15-minute city|maha movement|anti-vaccine movement)$/i;
const contestedTerms = /structured water|free energy|anti-gravity|med bed|dna activation|morphic resonance|remote viewing|age regression|black goo|grey goo|quantum consciousness/i;
const currentPoliticalTerms = /qanon|maha movement|anti-vaccine movement|great reset|deep state|digital id|social credit|central bank digital currency/i;

const defaultModesByClass = {
  forces: [],
  cosmologies: ['speculative-science'],
  beings: ['experiential-report'],
  worlds: ['science-fiction'],
  technologies: ['speculative-science'],
  artifacts: ['science-fiction'],
  factions: [],
  programs: [],
  systems: [],
  events: [],
  states: ['experiential-report'],
  myths: ['mythology'],
  hypotheses: ['speculative-science'],
};

function modesFor(title, classId) {
  const modes = [];
  if (/15-minute city/i.test(title)) modes.push('established-science', 'political-mythology', 'internet-folklore');
  if (/walkability|neighborhood access/i.test(title)) modes.push('established-science');
  if (/structured water/i.test(title)) modes.push('established-science', 'speculative-science');
  if (/zero-point energy/i.test(title)) modes.push('established-science', 'speculative-science', 'conspiracy-mythology');
  if (scientificTerms.test(title)) modes.push('established-science');
  if (emergingTerms.test(title)) modes.push('emerging-science');
  if (fictionTerms.test(title)) modes.push('science-fiction');
  if (mythologyTerms.test(title)) modes.push('mythology');
  if (esotericTerms.test(title)) modes.push('esoteric-tradition', 'spiritual-cosmology');
  if (experienceTerms.test(title)) modes.push('experiential-report');
  if (ufoTerms.test(title)) {
    modes.push('ufology-disclosure-lore');
    if (classId === 'beings') modes.push('experiential-report');
  }
  if (conspiracyTerms.test(title)) modes.push('conspiracy-mythology', 'internet-folklore');
  if (politicalTerms.test(title)) modes.push('political-mythology');
  if (/mkultra|project stargate|operation highjump|patent secrecy|special access program|waived sap/i.test(title)) modes.push('political-mythology');
  if (currentPoliticalTerms.test(title)) modes.push('political-mythology');
  if (/anti-vaccine movement|qanon/i.test(title)) modes.push('internet-folklore');
  if (documentedTerms.test(title) && /earth|mars|moon|ceres|asteroid|antarctica|space station|antikythera/i.test(title)) modes.push('established-science');
  if (!modes.length) modes.push(...defaultModesByClass[classId]);
  if (modes.includes('established-science') && (classId === 'technologies' || classId === 'cosmologies')) modes.push('speculative-science');
  modes.push('original-synthesis');
  return uniq(modes).filter((mode) => VALID_MODES.has(mode)).slice(0, 5);
}

const sourceRules = [
  [/chaos|emergence|complexity|feedback|nonlinearity|butterfly effect|strange attractor/i, ['sfi-complexity']],
  [/entropy|heat death/i, ['openstax-thermodynamics']],
  [/^earth$/i, ['nasa-earth']],
  [/^mars$|mars colony/i, ['nasa-mars', 'nasa-astrobiology']],
  [/^moon$|lunar base|dark side of the moon/i, ['nasa-moon']],
  [/ceres|asteroid belt/i, ['nasa-solar-system']],
  [/space station|orbital habitat/i, ['nasa-space-station']],
  [/dark matter|galactic ecology/i, ['nasa-dark-matter', 'cern-dark-matter']],
  [/black hole|event horizon|wormhole/i, ['nasa-black-holes']],
  [/antimatter drive/i, ['cern-antimatter', 'sf-encyclopedia']],
  [/wormhole/i, ['caltech-wormholes', 'ibm-quantum']],
  [/quantum entanglement/i, ['ibm-quantum', 'nist-quantum']],
  [/quantum computer/i, ['nist-quantum']],
  [/fusion/i, ['doe-fusion']],
  [/exoplanet|technosignature|dyson|great filter|dark forest|fermi/i, ['nasa-technosignatures', 'seti-fermi']],
  [/terraform|ocean world|garden world/i, ['nasa-exoplanets', 'nasa-astrobiology']],
  [/grey|reptilian|mantis|uap|saucer|tic-tac|black triangle|mothership|crash retrieval|disclosure/i, ['nasa-uap-2023', 'aaro-fy23', 'aaro-historical']],
  [/remote viewing|project stargate/i, ['cia-stargate', 'cia-stargate-review']],
  [/mkultra/i, ['senate-mkultra', 'archives-mkultra']],
  [/mkultra|project stargate|black project|special access program|waived sap/i, ['cia-crest']],
  [/area 51/i, ['smithsonian-area51', 'aaro-historical']],
  [/camp hero|montauk/i, ['nps-camp-hero']],
  [/brain-computer|neural lace/i, ['nih-bci']],
  [/gene editing|crispr|designer child|synthetic biology|dna activation|epigenetic/i, ['nsf-crispr']],
  [/near-death|life review|out-of-body/i, ['nih-nde', 'nih-nde-scoping']],
  [/psychedelic|dmt entity|machine elf/i, ['nih-psychedelics']],
  [/artificial general intelligence|superintelligence|rogue ai|ai agent|alignment|three laws|algorithmic/i, ['nist-ai-rmf', 'unesco-ai-ethics']],
  [/fifteen-minute|15-minute|walkability|neighborhood access/i, ['who-urban', 'c40-urban-planning']],
  [/smart city/i, ['who-urban', 'c40-urban-planning']],
  [/structured water/i, ['water-exclusion-zone-review', 'water-structure-review']],
  [/zero-point energy|vacuum energy|casimir|free energy/i, ['nasa-vacuum-energy', 'aps-casimir']],
  [/anti-vaccine movement/i, ['cdc-vaccine-safety', 'cdc-vaers', 'nih-antivaccine-review', 'pubmed-antivaccine-taxonomy']],
  [/maha movement/i, ['hhs-maha', 'hhs-maha-assessment']],
  [/qanon/i, ['adl-qanon', 'qanon-fictioning', 'psych-conspiracy', 'rand-truth-decay', 'un-disinformation']],
  [/cabal|deep state|shadow government|illuminati|conspiracy|true-believer|rabbit hole|red-pill/i, ['psych-conspiracy', 'rand-truth-decay']],
  [/great reset/i, ['wef-great-reset', 'rand-truth-decay']],
  [/med bed/i, ['ap-med-bed']],
  [/disinformation|misinformation|propaganda|true-believer|institutional distrust/i, ['un-disinformation', 'rand-truth-decay']],
  [/cognitive warfare|narrative warfare/i, ['nato-cognitive']],
  [/galactic empire|rebel alliance|jedi|sith|the force/i, ['starwars-empire', 'starwars-force']],
  [/starfleet|united federation|prime directive/i, ['startrek-prime-directive']],
  [/borg/i, ['startrek-borg']],
  [/post-scarcity|replicator/i, ['startrek-post-scarcity']],
  [/holodeck|hologram/i, ['startrek-holodeck']],
  [/arrakis|spice|bene gesserit|spacing guild|great houses|dune/i, ['dune-publisher']],
  [/monolith|2001/i, ['clarke-2001', 'sf-encyclopedia']],
  [/solaris/i, ['solaris-publisher', 'sf-encyclopedia']],
  [/loosh/i, ['monroe-far-journeys', 'monroe-books']],
  [/gnostic|archon|prison planet/i, ['nag-hammadi-archons', 'nag-hammadi-john']],
  [/akashi/i, ['theosophy-akasha']],
  [/collective unconscious|synchronicity|archetype/i, ['iep-jung']],
  [/dream|lucid/i, ['iep-dreaming']],
  [/noosphere|omega point/i, ['teilhard-noosphere']],
  [/morphic resonance|cosmic memory field|space memory network/i, ['sheldrake-morphic']],
  [/simulation/i, ['bostrom-simulation']],
  [/anunnaki|ancient astronaut hypothesis/i, ['met-anunnaki']],
  [/antikythera|out-of-place artifact/i, ['nature-antikythera']],
  [/frankenstein|clone|synthetic person|android|robot/i, ['loc-frankenstein']],
  [/alien invasion|war of the worlds/i, ['gutenberg-war-worlds', 'loc-war-worlds']],
];

const contextualFallbackByClass = {
  forces: 'sf-encyclopedia',
  cosmologies: 'sf-encyclopedia',
  beings: 'sf-encyclopedia',
  worlds: 'sf-encyclopedia',
  technologies: 'sf-encyclopedia',
  artifacts: 'sf-encyclopedia',
  factions: 'sf-encyclopedia',
  programs: 'aaro-historical',
  systems: 'rand-truth-decay',
  events: 'sf-encyclopedia',
  states: 'iep-jung',
  myths: 'sf-encyclopedia',
  hypotheses: 'nasa-astrobiology',
};

function sourcesFor(title, classId, modes) {
  const ids = [];
  for (const [pattern, matches] of sourceRules) if (pattern.test(title)) ids.push(...matches);
  if (!ids.length && modes.includes('science-fiction')) ids.push('sf-encyclopedia', 'isfdb');
  const conceptSpecificSourceIds = uniq(ids).filter((id) => id !== 'original-synthesis' && VALID_SOURCES.has(id)).slice(0, 3);
  const contextualSourceId = /walkability|neighborhood access/i.test(title) ? 'c40-urban-planning' : contextualFallbackByClass[classId];
  const external = uniq([...conceptSpecificSourceIds, contextualSourceId]).filter((id) => VALID_SOURCES.has(id)).slice(0, 4);
  return { sourceIds: [...external, 'original-synthesis'], conceptSpecificSourceIds, contextualSourceId };
}

function evidenceFor(title, modes, sourceIds, conceptSpecificSourceIds) {
  const claims = [];
  const documented = documentedTerms.test(title) || currentPoliticalTerms.test(title) || /panopticon|outer space treaty/i.test(title);
  const contested = contestedTerms.test(title);
  const externalSources = sourceIds.filter((id) => id !== 'original-synthesis');
  const claimSources = conceptSpecificSourceIds.filter((id) => id !== 'original-synthesis');
  const contradicted = /med bed/i.test(title);
  const literal = contradicted
    ? 'contradicted-by-evidence'
    : documented
    ? 'documented-historical'
    : contested
      ? 'contested'
      : modes.includes('established-science')
    ? 'well-established'
    : modes.includes('emerging-science')
      ? 'active-research'
      : modes.includes('science-fiction')
        ? 'fictional'
        : modes.includes('conspiracy-mythology') || modes.includes('ufology-disclosure-lore')
          ? 'unverified'
        : modes.includes('experiential-report')
          ? 'experiential-only'
          : modes.includes('mythology') || modes.includes('esoteric-tradition') || modes.includes('spiritual-cosmology')
            ? 'not-applicable'
            : modes.includes('speculative-science')
              ? 'plausible-speculation'
              : 'not-applicable';
  const literalArticle = /^[aeiou]/i.test(literal) ? 'an' : 'a';
  const literalStatement = /structured water/i.test(title)
    ? 'Water has measurable short-range and interfacial structure, while durable bulk “structured water,” exclusion-zone mechanisms, commercial device performance, and claimed health benefits require separate evaluation. The cited reviews describe active findings and disputes; they do not establish a general medical benefit.'
    : /zero-point energy/i.test(title)
      ? 'Zero-point energy is a real feature of quantum descriptions and vacuum-related effects such as the Casimir force are experimentally studied. Those facts do not demonstrate a practical device that extracts unlimited net usable energy from the vacuum.'
      : /15-minute city/i.test(title)
        ? 'The 15-minute city is a documented proximity-planning model for access to daily needs by walking, cycling, and public transport. Its existence as an urban-planning approach does not validate claims that the model inherently requires confinement, surveillance, or movement restrictions.'
        : literal === 'not-applicable'
          ? `${title} is not assigned a blanket literal truth claim; its historical, community, or symbolic meanings are evaluated on their own layers.`
          : `${title} has ${literalArticle} ${literal} literal or empirical layer. That designation applies only to the bounded claims supported by the listed sources.`;
  claims.push({
    id: `${slug(title)}-literal`,
    layer: 'literal-and-empirical',
    materialModes: modes.filter((mode) => mode !== 'original-synthesis'),
    status: literal,
    statement: literalStatement,
    sourceIds: claimSources,
  });
  if (modes.some((mode) => ['conspiracy-mythology', 'political-mythology', 'internet-folklore', 'ufology-disclosure-lore'].includes(mode))) {
    const contradictedNarrative = /qanon|anti-vaccine movement|med bed/i.test(title);
    claims.push({
      id: `${slug(title)}-extraordinary-claims`,
      layer: 'extraordinary-and-contested-claims',
      materialModes: modes.filter((mode) => ['conspiracy-mythology', 'political-mythology', 'internet-folklore', 'ufology-disclosure-lore'].includes(mode)),
      status: contradictedNarrative ? 'contradicted-by-evidence' : 'unverified',
      statement: contradictedNarrative
        ? `Documented circulation of ${title} does not validate its sweeping causal or extraordinary claims; the cited evidence contradicts central factual assertions or shows that they remain unsupported.`
        : `The extraordinary or hidden-causal claims associated with ${title} remain unverified. Cultural importance, testimony, secrecy, and narrative repetition do not substitute for reproducible evidence.`,
      sourceIds: externalSources,
    });
  }
  if (/zero-point energy|free energy/i.test(title)) {
    claims.push({
      id: `${slug(title)}-energy-extraction-claim`,
      layer: 'energy-extraction-and-device-claims',
      materialModes: uniq(modes.filter((mode) => ['established-science', 'speculative-science', 'conspiracy-mythology'].includes(mode))),
      status: 'unverified',
      statement: `Quantum vacuum phenomena do not establish the ${title} claim as a working source of unlimited net usable power. Treat proposed extraction devices, suppression narratives, and promised commercial systems as separate claims requiring public mechanism, independent replication, full energy accounting, and ordinary safety review.`,
      sourceIds: claimSources,
    });
  }
  claims.push({
    id: `${slug(title)}-cultural`,
    layer: 'cultural-and-historical',
    materialModes: modes,
    status: claimSources.length ? 'documented-historical' : 'unverified',
    statement: claimSources.length
      ? `The cited cultural record documents at least one lineage, use, or reception context for ${title}; it does not certify every later claim.`
      : `${title} has a class-level contextual source but still lacks a concept-specific external source in this release. Its cultural history is an editorial research lead, not a completed provenance claim.`,
      sourceIds: claimSources,
  });
  claims.push({
    id: `${slug(title)}-symbolic`,
    layer: 'symbolic-and-divinatory',
    materialModes: ['original-synthesis'],
    status: 'symbolic',
    statement: `The Oracle uses ${title} as a reflective symbol, never as proof that its literal or causal claims are true.`,
    sourceIds: ['original-synthesis'],
  });
  return claims.filter((claim) => VALID_EVIDENCE.has(claim.status));
}

const curatedOrigins = {
  'mkultra': 'The card begins with the documented CIA behavior-modification program and its surviving Senate and archival record; later internet mythology is labeled separately.',
  'project-stargate': 'The card begins with the documented U.S. government remote-viewing program and the released STARGATE archive, then separates program history from claims of psychic efficacy.',
  'montauk-project': 'The card begins with Camp Hero as a documented military site and treats the Montauk Project narrative as later conspiracy mythology and cultural production.',
  'philadelphia-experiment': 'The card begins with the twentieth-century legend rather than treating invisibility or teleportation claims as documented naval history.',
  'qanon': 'The card begins with QAnon as a documented participatory conspiracy movement whose false claims produced real harassment, radicalization, and political effects.',
  'area-51': 'The card begins with the documented Nevada test site and tracks its transformation into a global emblem of secrecy and extraterrestrial technology.',
  'gnostic-cosmos': 'The card begins with historical Gnostic texts and avoids presenting modern prison-planet synthesis as identical to the diverse ancient traditions.',
  'loosh-farm': 'The card traces “loosh” to Robert Monroe’s published cosmology before examining later extraction narratives and contemporary remixing.',
  'starseed': 'The card treats Starseed as a modern spiritual identity with multiple lineages, not as a biological category or hierarchy of human worth.',
  '15-minute-city': 'The card separates the documented urban-planning model from contemporary claims that it necessarily creates digitally enforced confinement.',
  'med-bed': 'The card identifies the healing chamber as speculative technology and contemporary miracle-cure lore, not an available medical device.',
  'structured-water': 'The card distinguishes ordinary water chemistry, active biophysical research, wellness marketing, and spiritual symbolism claim by claim.',
};

function safetyFor(title, modes) {
  const medical = /med bed|structured water|dna activation|vaccine|health|healing|age regression|organ regeneration|nootropic|psychedelic|cryonics|longevity|biohack|gene|crispr/i.test(title);
  const mental = /dissociation|false memory|implanted memory|hypervigilance|ontological shock|chapel perilous|rabbit hole|true-believer|red-pill|existential dread|psychedelic|dmt/i.test(title);
  const harmfulMyth = /qanon|cabal|deep state|illuminati|bloodline|eugenic|great reset|the storm|shadow government|reptilian/i.test(title);
  const identity = /nordic|bloodline|designer child|starseed|lyran|pleiadian|reptilian|anunnaki/i.test(title);
  const flags = [];
  if (medical) flags.push('health-claim');
  if (mental) flags.push('mental-health-and-reality-testing');
  if (harmfulMyth) flags.push('conspiracy-harm-and-scapegoating');
  if (identity) flags.push('identity-hierarchy-and-dehumanization');
  if (modes.includes('experiential-report')) flags.push('lived-experience-without-causal-certification');
  return {
    level: flags.length >= 2 ? 'high-attention' : flags.length ? 'reviewed' : 'standard',
    flags,
    boundaries: uniq([
      medical ? 'Not medical advice; do not delay or replace qualified care because of this card.' : null,
      mental ? 'Validate distress and agency without confirming a frightening external explanation; encourage grounded support when needed.' : null,
      harmfulMyth ? 'Do not turn coded elites, religions, ethnicities, migrants, or political opponents into a hidden inhuman enemy.' : null,
      identity ? 'Never use this symbol to rank ancestry, race, blood, disability, or human worth.' : null,
      'Keep documented fact, testimony, community belief, fiction, and symbolic interpretation visibly separated.',
    ]),
    use: 'Invite reflection and source comparison; do not diagnose, recruit, threaten, harass, or certify extraordinary claims.',
  };
}

const conceptAtoms = {
  chaos: 'unsettled possibility', pattern: 'recurring order', meaning: 'interpretive coherence', emergence: 'novel order arising from interaction', complexity: 'many interdependent causes', scarcity: 'a binding limit', abundance: 'surplus and access', entropy: 'irreversible dispersal', evolution: 'change across generations', selection: 'differential survival', feedback: 'an outcome returning as an input', recursion: 'a process acting upon itself', nonlinearity: 'effects disproportionate to causes', synchronicity: 'meaningful coincidence', apophenia: 'pattern perceived beyond support', trust: 'willing reliance under uncertainty', doubt: 'productive suspension', certainty: 'closure around a model', discernment: 'layered judgment', wonder: 'openness before the unknown', fear: 'threat-shaped attention', memory: 'continuity through retained traces', forgetting: 'loss that also permits renewal', extraction: 'value removed from a host', harvest: 'collection at a threshold', assimilation: 'difference absorbed into a whole', resistance: 'refusal that preserves agency', control: 'constrained possibility', liberation: 'released agency', transcendence: 'movement beyond a prior limit', interconnection: 'mutual dependence', dark: 'the unseen or unmeasured', filter: 'a bottleneck between potential and survival', simulation: 'reality mediated by executable rules', prison: 'enclosure maintained by asymmetrical power', gnostic: 'truth divided from lesser authority', holographic: 'a whole encoded through distributed parts', multiverse: 'coexisting possible worlds', time: 'ordered consequence', universe: 'the total field of reality', cosmos: 'a world made intelligible as order', reincarnation: 'identity returning through successive lives', soul: 'continuity of personhood beyond one frame', source: 'an originating ground', grey: 'clinical otherness', starseed: 'cosmic belonging and mission', synthetic: 'agency constructed rather than born', intelligence: 'capacity to model and choose', witness: 'presence that preserves an account', trickster: 'category-breaking intelligence', earth: 'the inhabited home world', mars: 'the red frontier', moon: 'the near other world', antarctica: 'a remote preserved frontier', area: 'a bounded site of access', colony: 'settlement under inherited authority', city: 'dense shared infrastructure', habitat: 'a maintained envelope for life', walkability: 'safe human-scale movement through the built environment', neighborhood: 'daily life organized at a local place scale', access: 'practical ability to reach, use, and benefit from a resource', energy: 'capacity to produce change', quantum: 'physical behavior at fundamental scales', portal: 'a threshold joining separated contexts', stargate: 'an addressable passage between worlds', neural: 'signal exchange with nervous systems', gene: 'heritable biological instruction', cloning: 'copied biological identity', med: 'promised total repair', water: 'the medium of living systems', alignment: 'capability constrained by chosen values', black: 'an opaque adaptive substrate', artifact: 'material evidence outlasting its maker', signal: 'information arriving from elsewhere', beacon: 'a deliberate call across distance', spice: 'perception made scarce and valuable', monolith: 'an external catalyst for discontinuous growth', federation: 'unity negotiated across difference', empire: 'centralized order across distance', alliance: 'cooperation without complete merger', cabal: 'secret coordination as explanatory enemy', technocracy: 'expertise converted into rule', disclosure: 'hidden knowledge crossing into public consequence', program: 'sequenced action toward an objective', project: 'bounded coordinated work', secret: 'knowledge controlled through access', cognitive: 'attention and interpretation as terrain', narrative: 'causal meaning carried by story', panopticon: 'behavior shaped by possible observation', digital: 'identity or value mediated by computation', surveillance: 'observation converted into power', economy: 'rules for allocating value and obligation', loosh: 'emotion imagined as harvestable energy', matrix: 'a reality-maintaining control environment', event: 'an irreversible threshold', contact: 'reciprocal encounter across difference', collapse: 'loss of a sustaining order', reset: 'renewal that may also erase continuity', ascension: 'transformation toward a higher state', experience: 'lived perception before causal settlement', dream: 'imaginal experience during altered awareness', shock: 'a world-model failing under new information', rabbit: 'inquiry descending beyond its first frame', chapel: 'uncertainty where revelation and destabilization meet', identity: 'continuity claimed across change', mythic: 'the past organized as destiny', future: 'possibility organized as aspiration', bloodline: 'inheritance used to authorize identity', prophecy: 'a future claim shaping present behavior', awakening: 'a changed account of what is real', hypothesis: 'a model exposed to comparison', extraterrestrial: 'origin beyond Earth', interdimensional: 'adjacency beyond ordinary distance', psychosocial: 'experience shaped by mind, culture, and context', morphic: 'form imagined as retaining prior habit', qanon: 'participatory conspiracy organized as revelation', vaccine: 'collective prevention interpreted through trust and risk', maha: 'public health reform organized as a political movement', dune: 'ecology, prophecy, resource, and empire in one storyworld', directive: 'a rule limiting intervention', borg: 'collective capability joined to compulsory assimilation', akashic: 'universal memory imagined as an archive', records: 'durable traces available for retrieval', structure: 'ordered relation among parts', system: 'rules persisting beyond one actor', state: 'a condition temporarily inhabited', movement: 'collective identity becoming coordinated action', world: 'a bounded environment of possibility', reality: 'the field treated as actually existing', civilization: 'large-scale continuity of shared life', technology: 'repeatable capability embodied in method', consciousness: 'subjective awareness and experience', body: 'embodied capacity and limit', ancient: 'deep time used to authorize an origin', astronaut: 'a traveler beyond the home world', alien: 'radical otherness', machine: 'repeatable operation embodied in mechanism', mind: 'attention, interpretation, and subjective continuity', life: 'self-maintaining embodied process', review: 'retrospective integration of a life', zero: 'potential at an apparent minimum', free: 'abundance claimed without ordinary cost', structured: 'order asserted within a medium', remote: 'perception or action across separation', viewing: 'observation made into a practice', near: 'a threshold approached but not completed', death: 'the end of embodied continuity', great: 'civilizational scale', prime: 'a rule treated as foundational', technological: 'capability expressed through engineered systems', singularity: 'a threshold beyond reliable extrapolation', hidden: 'withheld from ordinary access', heir: 'inheritance awaiting recognition', first: 'the initiating encounter', collective: 'agency distributed across many members', unconscious: 'mental process outside direct awareness', antimatter: 'matter with opposite conserved charges', drive: 'propulsion converting energy into motion', antikythera: 'ancient mechanism revealing unexpected technical skill', mkultra: 'documented covert behavioral experimentation', solaris: 'an unknowable living world confronting human projection', wormhole: 'topology imagined as a shortcut through spacetime', entanglement: 'correlation irreducible to classical separation', matter: 'physical substance and mass-energy', resonance: 'pattern reinforced through sympathetic response', anunnaki: 'Mesopotamian deities later remixed in ancient-astronaut lore', horizon: 'a boundary beyond which information changes',
};

const insignificantWords = new Set(['the', 'and', 'of', 'to', 'in', 'for', 'a', 'an', 'program', 'project', 'system', 'hypothesis', 'cosmos', 'state', 'movement']);
const archetypeRole = {
  forces: 'field-reader', cosmologies: 'cosmographer', beings: 'emissary', worlds: 'wayfinder', technologies: 'artificer', artifacts: 'reliquary-keeper', factions: 'convener', programs: 'mission-keeper', systems: 'rule-reader', events: 'herald', states: 'inner witness', myths: 'story-bearer', hypotheses: 'examiner',
};
const domainGifts = {
  'origin-lineage': 'trace inheritance without confusing age with truth', 'reality-ontology': 'compare world-models without premature closure', 'intelligence-otherness': 'meet difference without erasing or dehumanizing it', 'contact-communication': 'build reciprocal contact with consent and translation', 'mind-consciousness': 'observe experience without forcing one explanation', 'memory-identity': 'preserve continuity while allowing revision', 'body-evolution': 'honor embodiment while examining transformation', 'technology-infrastructure': 'make capability, mechanism, cost, and failure visible', 'time-causality': 'separate sequence, cause, memory, and prediction', 'civilization-ecology': 'see interdependence across people, place, and resource', 'power-control': 'locate authority, access, accountability, and exit', 'liberation-transcendence': 'increase agency without promising escape from every limit',
};

function semanticKernel(title, classId, domainIds) {
  const words = slug(title).split('-').filter((word) => !insignificantWords.has(word));
  const atoms = uniq(words.map((word) => conceptAtoms[word] ?? `the ${word} motif`).filter(Boolean)).slice(0, 3);
  if (!atoms.length) return `an unnamed tension considered as ${classModels[classId].noun}`;
  if (atoms.length === 1) return `${atoms[0]} placed within ${DOMAIN_BY_ID[domainIds[0]].name.toLowerCase()}`;
  if (atoms.length === 2) return `${atoms[0]} meeting ${atoms[1]}`;
  return `${atoms[0]}, ${atoms[1]}, and ${atoms[2]} acting together`;
}

const domainFacets = {
  'origin-lineage': {
    lens: 'inheritance, transmission, rupture, and the authority claimed by beginnings',
    test: 'trace the earliest attested form, each handoff, and what later tellers added',
    stake: 'an origin story can preserve obligation or turn age into unearned authority',
    practice: 'draw a three-generation lineage: source, transformation, and present claimant',
    completion: 'the inheritance is visible without making ancestry destiny',
  },
  'reality-ontology': {
    lens: 'world-models, observer limits, and the boundary between appearance and claim',
    test: 'state what this model explains, what could count against it, and what remains outside its scope',
    stake: 'a model can enlarge possibility or quietly make itself impossible to question',
    practice: 'compare two rival maps of the same observation and mark their different blind spots',
    completion: 'the model can be used without being mistaken for the whole of reality',
  },
  'intelligence-otherness': {
    lens: 'agency, difference, recognition, and the ethics of meeting a mind unlike one’s own',
    test: 'look for learning, intention, reciprocal response, refusal, and alternatives to human resemblance',
    stake: 'misrecognition can erase a subject or invent an agent where none has been shown',
    practice: 'write the encounter twice, once from each side, preserving what neither side can translate',
    completion: 'difference remains legible without becoming inferiority, divinity, or projection',
  },
  'contact-communication': {
    lens: 'signal, translation, reciprocity, consent, and the repair of misunderstanding',
    test: 'separate transmission from interpretation and require a return signal that could expose error',
    stake: 'contact can create relationship, contamination, domination, or a false sense of mutual understanding',
    practice: 'design a contact protocol with greeting, confirmation, refusal, pause, and safe exit',
    completion: 'a message can be exchanged without pretending that every ambiguity has vanished',
  },
  'mind-consciousness': {
    lens: 'attention, perception, interior experience, and the models used to explain awareness',
    test: 'describe the experience before choosing among neurological, psychological, social, or metaphysical causes',
    stake: 'an intense experience can deepen agency or become captive to one total explanation',
    practice: 'record observation, felt meaning, interpretation, and confidence in four separate columns',
    completion: 'the experience is honored while causal certainty remains proportionate to evidence',
  },
  'memory-identity': {
    lens: 'continuity, forgetting, archives, testimony, and the stories that hold a self together',
    test: 'compare recollection with records, other witnesses, missing intervals, and the cost of revision',
    stake: 'memory can preserve personhood while also being edited, inherited, contested, or supplied by others',
    practice: 'make a continuity map of what is remembered, documented, inferred, and still absent',
    completion: 'identity can continue without forcing every gap into a finished story',
  },
  'body-evolution': {
    lens: 'embodiment, care, inheritance, adaptation, disability, and the politics of transformation',
    test: 'name the mechanism, affected body, evidence, risks, alternatives, consent, and follow-up',
    stake: 'transformation can expand capacity or rank bodies against an imagined ideal',
    practice: 'translate the promise into mechanism, benefit, burden, access, and care obligations',
    completion: 'change is assessed by lived wellbeing and agency rather than purity or perfection',
  },
  'technology-infrastructure': {
    lens: 'mechanism, dependency, maintenance, access, failure, and the labor beneath capability',
    test: 'trace inputs, transformation, outputs, energy, operators, error states, ownership, and shutdown',
    stake: 'a capability redistributes power long before its interface appears neutral',
    practice: 'sketch the full stack from material supply through maintenance and decommissioning',
    completion: 'the capability is understood together with its costs, keepers, and failure paths',
  },
  'time-causality': {
    lens: 'sequence, recurrence, prediction, counterfactuals, and the difference between order and cause',
    test: 'build a dated chain and ask which link is observation, inference, memory, or forecast',
    stake: 'retrospective coherence can turn coincidence into destiny and warning into inevitability',
    practice: 'write one timeline, one plausible alternative, and the evidence that distinguishes them',
    completion: 'the sequence informs action without pretending the future has already happened',
  },
  'civilization-ecology': {
    lens: 'shared survival, place, stewardship, access, feedback, and unequal exposure to risk',
    test: 'follow resources, waste, care, mobility, governance, and nonhuman dependencies across scales',
    stake: 'a durable world can hide extraction by moving its costs beyond the visible center',
    practice: 'map one need from source to use, repair, replenishment, and the people carrying each burden',
    completion: 'collective continuity includes ecology, access, and those previously treated as external costs',
  },
  'power-control': {
    lens: 'authority, secrecy, classification, benefit, coercion, appeal, and the practical right to leave',
    test: 'identify who can decide, inspect, refuse, revise, profit, and obtain remedy',
    stake: 'coordination becomes domination when accountability and exit exist only for the powerful',
    practice: 'build an authority table with mandate, evidence access, affected parties, appeal, and sunset',
    completion: 'power is named precisely enough to be challenged, bounded, or made answerable',
  },
  'liberation-transcendence': {
    lens: 'agency, release, transformation, integration, and the limits that freedom must still honor',
    test: 'ask what becomes possible, what material condition changes, and who might be abandoned by escape',
    stake: 'a promise of transcendence can release an old enclosure or bypass repair in the world at hand',
    practice: 'name one constraint to resist, one responsibility to keep, and one capacity to practice now',
    completion: 'greater freedom arrives with more relationship and responsibility, not less reality',
  },
};

const modeFacets = {
  'established-science': { lens: 'a bounded empirical record', discipline: 'mechanism, measurement, uncertainty, and replication', boundary: 'established findings do not automatically support later extraordinary extensions' },
  'emerging-science': { lens: 'an active research frontier', discipline: 'current evidence, competing models, and unresolved limitations', boundary: 'promising work is not yet mature consensus or a guaranteed application' },
  'speculative-science': { lens: 'a physically or conceptually motivated extrapolation', discipline: 'assumptions, feasibility constraints, and discriminating tests', boundary: 'coherence is not the same as demonstration' },
  'science-fiction': { lens: 'a traceable fictional or speculative story lineage', discipline: 'work, creator, reception, and symbolic reuse', boundary: 'narrative truth does not establish literal availability' },
  mythology: { lens: 'a mythic lineage carried through story and ritual', discipline: 'historical context, community meaning, and difference among traditions', boundary: 'motif comparison must not erase provenance or living authority' },
  'esoteric-tradition': { lens: 'an esoteric teaching or practice lineage', discipline: 'community vocabulary, historical sources, and claims stated at their own layer', boundary: 'spiritual use is not blanket empirical verification' },
  'experiential-report': { lens: 'lived and reported experience', discipline: 'phenomenology, context, care, and multiple possible explanations', boundary: 'respect for testimony does not require certifying one external cause' },
  'ufology-disclosure-lore': { lens: 'ufology and disclosure culture', discipline: 'dated claims, witness context, documents, counterevidence, and media mutation', boundary: 'secrecy and repetition do not independently prove extraordinary causation' },
  'conspiracy-mythology': { lens: 'a conspiracy narrative with real social effects', discipline: 'claim-level sourcing, incentive analysis, falsifiability, and harm review', boundary: 'documenting a narrative does not validate its hidden-cause allegations' },
  'political-mythology': { lens: 'a political story that organizes identity and threat', discipline: 'institutions, material interests, rhetoric, and affected communities', boundary: 'symbolic force must remain separate from unsupported accusations' },
  'internet-folklore': { lens: 'networked participatory folklore', discipline: 'platform history, remix paths, community practice, and virality', boundary: 'engagement and recurrence are evidence of circulation, not factual truth' },
  'spiritual-cosmology': { lens: 'a spiritual model of reality and purpose', discipline: 'tradition, practice, community interpretation, and ethical consequence', boundary: 'meaning can be real to practitioners without becoming universal ontology' },
  'original-synthesis': { lens: 'an explicit Oracle synthesis', discipline: 'transparent analogy, declared invention, and practical usefulness', boundary: 'the synthesis must never masquerade as inherited doctrine or discovered fact' },
};

function modeFacetFor(modes) {
  const priority = ['established-science', 'emerging-science', 'science-fiction', 'mythology', 'esoteric-tradition', 'experiential-report', 'conspiracy-mythology', 'political-mythology', 'ufology-disclosure-lore', 'internet-folklore', 'spiritual-cosmology', 'speculative-science', 'original-synthesis'];
  return modeFacets[priority.find((mode) => modes.includes(mode)) ?? 'original-synthesis'];
}

function render(seed, patterns, context, offset = 0) {
  return pick(seed, patterns, offset)(context);
}

const essencePatterns = [
  (c) => `${c.title} brings ${c.kernel} into focus. It operates as ${c.model.noun} and asks how ${c.facet.lens} alter practical choice.`,
  (c) => `At the center of ${c.title} is ${c.kernel}. The card treats that tension as ${c.model.noun}, bounded by ${c.mode.boundary}.`,
  (c) => `${c.kernel} gives ${c.title} its distinctive charge. Read it through ${c.facet.lens}, with ${c.mode.discipline} kept visible.`,
  (c) => `${c.title} is a way of encountering ${c.kernel}. Its Oracle use joins ${c.model.noun} to the question of ${c.facet.lens}.`,
  (c) => `The working core of ${c.title} is ${c.kernel}: a pattern that can reorganize attention, relation, and action. ${c.mode.boundary}.`,
  (c) => `${c.title} concentrates ${c.kernel} into ${c.model.noun}. Its value lies in examining ${c.facet.lens} without exceeding the evidence layer.`,
  (c) => `Read ${c.title} as ${c.model.noun} shaped by ${c.kernel}. The useful inquiry is not belief alone, but what ${c.facet.test}.`,
  (c) => `${c.title} names a threshold where ${c.kernel} changes what participants can notice or do. The card keeps ${c.mode.lens} distinct from symbolic use.`,
  (c) => `Within the Oracle, ${c.title} holds together ${c.kernel} and ${c.facet.lens}. That combination creates both an interpretive tool and a responsibility.`,
  (c) => `${c.kernel} is the engine beneath ${c.title}. As ${c.model.noun}, it reveals how a local image can carry system-scale consequences.`,
  (c) => `${c.title} frames ${c.kernel} as a decision environment rather than a finished answer. Its evidence discipline is ${c.mode.discipline}.`,
  (c) => `What makes ${c.title} consequential is the meeting of ${c.kernel} with ${c.facet.lens}. The card preserves that meeting without universalizing it.`,
  (c) => `${c.title} offers an instrument for reading ${c.kernel}. It becomes useful when interpretation remains answerable to ${c.facet.test}.`,
  (c) => `The Oracle places ${c.title} where ${c.kernel} affects agency. It is neither mere decoration nor automatic proof, but ${c.model.noun} with a declared evidence boundary.`,
  (c) => `${c.title} gathers a field around ${c.kernel}. Its deeper subject is ${c.facet.stake}.`,
  (c) => `Seen closely, ${c.title} is about ${c.kernel} under conditions of ${c.facet.lens}. That frame makes its gift, shadow, and limits readable together.`,
];

function genericSpec(title, classId, index, domainIds, modes) {
  const model = classModels[classId];
  const kernel = semanticKernel(title, classId, domainIds);
  const facet = domainFacets[domainIds[0]];
  const mode = modeFacetFor(modes);
  const label = title.replace(/\b(Hypothesis|Program|System|Cosmos|Movement|Project|Mission)\b/gi, '').replace(/^the\s+/i, '').replace(/\s+/g, ' ').trim() || title.replace(/^the\s+/i, '');
  const context = { title, classId, index, domainIds, modes, model, kernel, facet, mode };
  const giftPatterns = [
    (c) => `${domainGifts[c.domainIds[0]]} by making ${c.kernel} available for careful comparison`,
    (c) => `turn ${c.kernel} into a question that can be shared, tested, and revised`,
    (c) => `notice how ${c.facet.lens} change the choices that appeared available`,
    (c) => `use ${c.kernel} to reveal a dependency, relationship, or neglected point of agency`,
    (c) => `hold ${c.mode.lens} and symbolic meaning together without collapsing their standards`,
    (c) => `translate ${c.kernel} into a bounded practice of observation and accountable response`,
    (c) => `recognize the opportunity concealed inside ${c.facet.stake}`,
    (c) => `make room for revision while preserving what ${c.title} can genuinely illuminate`,
    (c) => `connect individual perception with the wider conditions expressed by ${c.kernel}`,
    (c) => `clarify what can be known, what can be chosen, and what must remain open`,
    (c) => `find a proportionate action through ${c.facet.test}`,
    (c) => `restore context where ${c.kernel} had become isolated or absolute`,
  ];
  const shadowPatterns = [
    (c) => `letting ${c.kernel} harden into a total explanation that no contrary evidence can revise`,
    (c) => `using ${c.title} to bypass consent, context, or the people who carry its consequences`,
    (c) => `confusing ${c.mode.lens} with permission to claim more than its evidence supports`,
    (c) => `turning ${c.facet.stake} into inevitability instead of a condition open to response`,
    (c) => `protecting the preferred interpretation by moving every test beyond reach`,
    (c) => `treating a vivid symbol as a mechanism, diagnosis, mandate, or historical fact`,
    (c) => `using technical or sacred language to conceal ordinary power and dependency`,
    (c) => `reducing a plural history to one secret lineage that explains every difference`,
    (c) => `mistaking intensity, repetition, or belonging for independent verification`,
    (c) => `pursuing the promise carried by ${c.kernel} while externalizing its costs`,
    (c) => `making uncertainty frightening enough that premature certainty feels like safety`,
    (c) => `preserving the map after it has begun to erase the territory and its witnesses`,
  ];
  const questionPatterns = [
    (c) => `Where is ${c.kernel} shaping the situation, and what would make the response more accountable?`,
    (c) => `What changes when ${c.facet.test}, rather than assuming the preferred interpretation?`,
    (c) => `Which part of ${c.title} is observation, inherited story, active claim, or chosen symbol?`,
    (c) => `Who gains agency through ${c.kernel}, who carries risk, and who can revise the arrangement?`,
    (c) => `What remains useful in ${c.title} if its strongest literal claim proves false?`,
    (c) => `Which boundary from ${c.mode.boundary.toLowerCase()} matters most in this decision?`,
    (c) => `What evidence, relationship, or material condition would distinguish insight from projection here?`,
    (c) => `How could ${c.facet.stake} be met without feeding the card’s shadow?`,
    (c) => `What is the smallest reversible action that could clarify ${c.kernel}?`,
    (c) => `Which voice, dependency, or counterexample is missing from the current reading of ${c.title}?`,
    (c) => `What permission or obligation changes if ${c.kernel} becomes decisive?`,
    (c) => `How can the gift of ${c.title} be practiced while its evidence status remains explicit?`,
  ];
  return {
    essence: render(`${title}:essence`, essencePatterns, context, index),
    archetype: `the ${label} ${archetypeRole[classId]}`.toLowerCase(),
    gift: render(`${title}:gift`, giftPatterns, context, index),
    shadow: render(`${title}:shadow`, shadowPatterns, context, index),
    question: `${render(`${title}:question`, questionPatterns, context, index)} ${contextSentence(context, 'question')}`,
  };
}

function cardSpec(title, classId, index, domainIds, modes) {
  const cardSlug = slug(title);
  const curated = keySpecs[cardSlug]
    ?? (cardSlug === 'akashic-cosmos' ? keySpecs['akasha-cosmos'] : null)
    ?? (cardSlug === '15-minute-city' ? keySpecs['fifteen-minute-city'] : null);
  if (!curated) return genericSpec(title, classId, index, domainIds, modes);
  const [essence, archetype, gift, shadow, question] = curated;
  return {
    essence: sentence(essence),
    archetype,
    gift,
    shadow: shadow.replace(/\bundefined dimension\b/gi, 'ill-defined dimension'),
    question: sentence(question),
  };
}

function polaritiesFor(title, index) {
  const lower = title.toLowerCase();
  const matches = polarities.filter((polarity) => lower.includes(polarity.left) || lower.includes(polarity.right));
  const fallback = [polarities[index % polarities.length], polarities[(index + 3) % polarities.length]];
  return uniq([...matches, ...fallback].map((item) => item.id)).slice(0, 2);
}

const gameRolesByClass = {
  forces: ['pressure', 'modifier', 'turning-condition'],
  cosmologies: ['world-model', 'hidden-rule', 'stakes-frame'],
  beings: ['agent', 'witness', 'relationship-node'],
  worlds: ['setting', 'route-node', 'resource-environment'],
  technologies: ['capability', 'cost-bearing-tool', 'escalation'],
  artifacts: ['key-object', 'evidence', 'contested-resource'],
  factions: ['collective-actor', 'agenda', 'opposition-or-ally'],
  programs: ['mission', 'clock', 'secret-objective'],
  systems: ['rule-set', 'constraint', 'economy'],
  events: ['threshold', 'reversal', 'countdown'],
  states: ['condition', 'perception-filter', 'consequence'],
  myths: ['story-frame', 'role-offer', 'narrative-hazard'],
  hypotheses: ['explanatory-model', 'investigation-path', 'rival-theory'],
};

const signalConditionsByClass = {
  forces: 'a diffuse pressure changes the choices available to every participant',
  cosmologies: 'a world-model changes what the group treats as possible, real, or inevitable',
  beings: 'an unfamiliar agent introduces intention, perspective, and reciprocal obligation',
  worlds: 'an environment sets the routes, resources, distances, and risks of action',
  technologies: 'a proposed capability turns intention into an intervention with dependencies and failure modes',
  artifacts: 'an object anchors a disputed claim in custody, provenance, function, or exchange',
  factions: 'collective identity becomes coordinated strategy and distinguishes members from outsiders',
  programs: 'a mission sequences authority, resources, secrecy, roles, and milestones toward an objective',
  systems: 'persistent rules shape outcomes beyond the intention of any one participant',
  events: 'a threshold makes the previous equilibrium impossible to maintain',
  states: 'perception or identity changes before its causal explanation has settled',
  myths: 'a durable story assigns roles and causes before the evidence has settled',
  hypotheses: 'an explanatory lens determines which observations, tests, and counterexamples can matter',
};

const originPatterns = [
  (c) => `${c.title} enters the archive through ${c.model.origin}. The first task is to ${c.facet.test}.`,
  (c) => `The starting point for ${c.title} is ${c.mode.lens}, read alongside ${c.model.origin}. Later symbolic use is registered as a separate editorial layer.`,
  (c) => `Before it became an Oracle card, ${c.title} arose from ${c.model.origin}. Its provenance turns on ${c.facet.lens}.`,
  (c) => `${c.title} has no single timeless beginning in this record. It is approached through ${c.mode.discipline}, then followed into later reinterpretation.`,
  (c) => `The origin file for ${c.title} begins where ${c.kernel} first becomes legible in ${c.mode.lens}. It does not backdate later language into earlier sources.`,
  (c) => `To locate ${c.title}, the Oracle separates the originating record, the name now used for it, and the synthesis made for this deck. ${c.mode.boundary}.`,
  (c) => `${c.title} is rooted in ${c.model.origin}, but the card’s present form is editorial rather than primordial. Source order and later mutation remain visible.`,
  (c) => `The earliest usable context for ${c.title} is sought through ${c.mode.discipline}. Where the record breaks, the gap is marked rather than repaired with invention.`,
  (c) => `${c.title} reaches the Oracle by way of ${c.mode.lens}. Its origin question is not merely when it appeared, but how ${c.facet.stake}.`,
  (c) => `The card begins with a bounded origin claim: ${c.model.origin}. Community usage, popular remix, and divinatory meaning are added only after that boundary.`,
  (c) => `Provenance for ${c.title} is built outward from the earliest attributable context. ${c.facet.test.charAt(0).toUpperCase()}${c.facet.test.slice(1)} before proposing continuity.`,
  (c) => `${c.title} emerged where ${c.kernel} became nameable. The archive distinguishes a traceable source lineage from resemblance discovered after the fact.`,
  (c) => `Rather than assign ${c.title} an impressive ancient pedigree, the record begins with ${c.mode.lens}. It then asks which inheritances are demonstrated and which are interpretive.`,
  (c) => `The Oracle receives ${c.title} from ${c.model.origin}. That receipt includes a duty to preserve creators, communities, dates, and disagreement.`,
  (c) => `${c.title} begins as a situated answer to ${c.facet.lens}. Its later uses may travel far, but they do not erase the conditions of first appearance.`,
  (c) => `Origin is treated as a chain of custody for ${c.title}: initial context, transmission, alteration, reception, and explicit Oracle synthesis.`,
];

const historyPatterns = [
  (c) => `${c.title} ${c.model.history}. Its history is most legible when changes in audience, medium, and authority are recorded separately.`,
  (c) => `The cultural life of ${c.title} follows ${c.kernel} across institutions and communities. Each reuse changes what the symbol permits people to notice or ignore.`,
  (c) => `Across time, ${c.title} moved through ${c.mode.lens}. The Oracle preserves disagreement rather than compressing those contexts into a secret universal genealogy.`,
  (c) => `${c.title} did not keep one meaning while its setting changed. Its reception shows how ${c.facet.stake}.`,
  (c) => `The historical record of ${c.title} is a sequence of translations: source context, public circulation, community interpretation, and later symbolic use.`,
  (c) => `Different communities recruited ${c.title} to solve different problems. The record compares those uses through ${c.facet.lens} instead of declaring one timeless essence.`,
  (c) => `${c.title} became culturally durable because ${c.kernel} could be re-read under new pressures. Durability here demonstrates adaptability, not literal proof.`,
  (c) => `Media form matters to the history of ${c.title}: testimony, archive, ritual, fiction, journalism, and networked remix authorize claims differently.`,
  (c) => `As ${c.title} circulated, some tellers emphasized its gift while others intensified its threat. The cultural file records both selection and omission.`,
  (c) => `The usable history of ${c.title} includes advocates, critics, witnesses, creators, institutions, and people affected by its claims. No one group stands in for the whole record.`,
  (c) => `${c.title} acquired authority through repetition, affiliation, evidence, or ritual in different proportions. Those routes are not treated as interchangeable.`,
  (c) => `The card tracks when ${c.title} crossed from specialist context into common imagination. That crossing altered both vocabulary and stakes.`,
  (c) => `Historical comparison places ${c.title} beside its precursors without assuming identity. Similar motifs may reveal transmission, convergence, or only a useful analogy.`,
  (c) => `${c.title} carries residues of earlier conflicts over ${c.facet.lens}. Reading it well requires noticing which older argument has returned in new clothing.`,
  (c) => `The cultural archive treats ${c.title} as a changing relation rather than a fixed object. Custody, platform, genre, and power all shape the version now encountered.`,
  (c) => `What survives of ${c.title} is not neutral. Preservation choices determine which witnesses, failures, and counter-readings remain available.`,
];

const meaningPatterns = {
  psychological: [
    (c) => `Psychologically, ${c.title} directs attention toward ${c.kernel}. It can organize uncertainty, but its preferred explanation should remain revisable.`,
    (c) => `${c.title} may function inwardly as a lens for ${c.kernel}. Its gift supports ${c.gift}; its shadow begins when that lens excludes disconfirming experience.`,
    (c) => `In personal reflection, ${c.title} asks what feeling, memory, or expectation is selecting the current pattern. ${c.facet.test.charAt(0).toUpperCase()}${c.facet.test.slice(1)} before choosing certainty.`,
    (c) => `The inner movement of ${c.title} runs between orientation and enclosure. ${c.kernel} can give experience shape without becoming the only shape allowed.`,
    (c) => `${c.title} reveals how attention behaves around ${c.facet.stake}. The psychological work is to regain choice without dismissing what feels consequential.`,
    (c) => `As an interior archetype, ${c.archetype} gathers ${c.kernel} into a role a person may inhabit. Integration requires entering and leaving that role consciously.`,
    (c) => `The card may surface when a person needs language for ${c.kernel}. Useful language increases agency; harmful language makes every experience confirm itself.`,
    (c) => `${c.title} tests the difference between intuition, memory, fear, desire, and observation within ${c.facet.lens}. None must be shamed, and none should silently impersonate the others while the pattern ${c.model.action}.`,
    (c) => `The psychological question in ${c.title} is not whether the symbol feels true, but what it does to attention, relationship, and available action.`,
    (c) => `${c.kernel} can become a container for experience through ${c.title}. The container is healthy when it holds complexity without sealing inquiry.`,
    (c) => `Encountering ${c.title} may expose a need for coherence, protection, belonging, mastery, or transformation. Name the need before granting the story causal authority.`,
    (c) => `${c.title} offers a rehearsal for meeting ${c.kernel}. The rehearsal is complete when the person can choose a grounded response rather than merely repeat the script.`,
  ],
  social: [
    (c) => `Socially, ${c.title} ${c.model.social}. The key question is whose account becomes legible and who can contest the arrangement.`,
    (c) => `${c.title} coordinates people around ${c.kernel}. That coordination can create care and shared purpose, or punish those who do not accept the same map.`,
    (c) => `In groups, ${c.title} distributes roles: witness, expert, outsider, beneficiary, skeptic, keeper, or threat. Those assignments deserve explicit review.`,
    (c) => `The social life of ${c.title} appears in how communities share evidence, status, obligation, and belonging. ${c.facet.stake.charAt(0).toUpperCase()}${c.facet.stake.slice(1)}.`,
    (c) => `${c.title} can make a dispersed experience discussable. It becomes dangerous when shared vocabulary closes the door on revision or exit.`,
    (c) => `A community may use ${c.title} to preserve memory, coordinate action, or mark identity. The Oracle also asks who bears the costs of that cohesion.`,
    (c) => `${c.kernel} becomes institutional when repeated through norms, records, rituals, platforms, or procedures. ${c.title} makes that passage visible.`,
    (c) => `Read socially, ${c.title} is less a private belief than a pattern of relationship. Notice trust, imitation, silence, conflict, care, and unequal consequence.`,
    (c) => `${c.title} can bridge strangers through a common symbol, yet common language does not guarantee common interests or equal voice.`,
    (c) => `The collective question is whether ${c.title} expands the group’s capacity to learn. A healthy form preserves dissent, source access, correction, and belonging.`,
    (c) => `${c.title} reveals which experiences a culture rewards, doubts, medicalizes, celebrates, or hides. Those responses shape the phenomenon’s lived reality.`,
    (c) => `Around ${c.title}, social proof can become support or substitute for evidence. Separate the value of community from the truth status of every shared claim.`,
  ],
  spiritual: [
    (c) => `Spiritually, ${c.title} ${c.model.spiritual}. Symbolic depth is invited without requiring universal metaphysical agreement.`,
    (c) => `${c.title} may orient a person toward purpose through ${c.kernel}. The practice is sound when humility and relationship grow with meaning.`,
    (c) => `As sacred metaphor, ${c.title} asks how ${c.facet.stake}. It should not erase living tradition while its symbolic role ${c.model.action}.`,
    (c) => `The spiritual register of ${c.title} can hold mystery, grief, initiation, belonging, or vocation. None of these meanings alone proves a literal mechanism.`,
    (c) => `${c.title} becomes spiritually useful when it changes conduct, care, and attention rather than merely conferring special status.`,
    (c) => `Through ${c.archetype}, the card offers a relationship to ${c.kernel}. The reader is asked to receive that relationship without demanding possession of the unknown.`,
    (c) => `The contemplative work in ${c.title} is to distinguish revelation, interpretation, inheritance, and desire through ${c.facet.lens}, allowing each an honest place.`,
    (c) => `${c.title} can become a threshold symbol: something is released, encountered, remembered, or promised. Integration returns the threshold to ordinary responsibility.`,
    (c) => `A spiritual reading of ${c.title} measures fruit rather than spectacle. Does it deepen compassion, courage, discernment, reciprocity, and grounded agency?`,
    (c) => `${c.kernel} may be held as mystery through ${c.title}. Mystery remains open; it does not require an enemy, hierarchy, or exemption from care.`,
    (c) => `The card permits devotion to meaning while protecting freedom of belief. ${c.mode.boundary.charAt(0).toUpperCase()}${c.mode.boundary.slice(1)}.`,
    (c) => `${c.title} may echo several traditions, but resemblance is not ownership or proof of one hidden source. Context and community authority come first.`,
  ],
  technological: [
    (c) => `Technologically, ${c.title} ${c.model.technological}. Analysis begins with mechanism, input, dependency, constraint, operator, and failure.`,
    (c) => `${c.title} can be read as an interface around ${c.kernel}. Ask what enters, what changes, what exits, and who can interrupt the process.`,
    (c) => `The technical layer of ${c.title} is bounded by ${c.mode.discipline}. Vocabulary borrowed from science cannot substitute for a working account.`,
    (c) => `As infrastructure, ${c.title} would require materials, energy, labor, maintenance, governance, and disposal. The imagined capability must carry those dependencies.`,
    (c) => `${c.title} changes more than efficiency when it makes ${c.kernel} repeatable. It also changes expertise, access, liability, and refusal wherever ${c.facet.lens} are at stake.`,
    (c) => `A credible implementation of ${c.title} needs an observable mechanism and graceful failure path. Otherwise the card remains story, hypothesis, or symbolic instrument.`,
    (c) => `The technological question is who gets capability without inheriting equal risk. ${c.facet.test.charAt(0).toUpperCase()}${c.facet.test.slice(1)}.`,
    (c) => `${c.title} invites a full-stack reading from source material to interface and decommissioning. Hidden labor is part of the mechanism.`,
    (c) => `When ${c.kernel} is rendered as technology, metaphors can quietly become specifications. Mark which functions are demonstrated, proposed, fictional, or impossible.`,
    (c) => `${c.title} may be valuable as a design fiction even when unavailable as engineering. Its role then is to expose values, assumptions, and second-order effects.`,
    (c) => `Technical authority around ${c.title} should be auditable. Require test conditions, negative results, uncertainty, ownership, and a route to stop harm.`,
    (c) => `The card’s machine-level inquiry asks whether ${c.title} expands capability while preserving agency, maintenance, accessibility, and repair.`,
  ],
  political: [
    (c) => `Politically, ${c.title} ${c.model.political}. Follow authority, benefit, exposure to harm, refusal, remedy, and control of the official record.`,
    (c) => `${c.title} makes ${c.kernel} governable, scarce, secret, compulsory, or contestable. Ask who acquires jurisdiction through that move.`,
    (c) => `The political stakes of ${c.title} appear where ${c.facet.stake}. Legitimacy requires more than effective control.`,
    (c) => `Power enters ${c.title} through classification: who is expert, witness, member, patient, believer, threat, or owner. Each label changes available rights.`,
    (c) => `${c.title} may justify exceptional action by promising safety, destiny, abundance, or revelation where ${c.facet.lens} are contested. Examine mandate, evidence, proportionality, and sunset as the pattern ${c.model.action}.`,
    (c) => `In public life, ${c.title} can reveal a real asymmetry while offering an exaggerated hidden cause. Preserve the critique and test the allegation separately.`,
    (c) => `The governance question is whether people affected by ${c.title} can inspect, challenge, revise, and leave the arrangement without catastrophic loss.`,
    (c) => `${c.kernel} becomes political when institutions allocate its costs and benefits. The Oracle traces those allocations instead of treating power as atmosphere.`,
    (c) => `${c.title} can mobilize solidarity or scapegoating. The difference lies in evidence, target, method, accountability, and whether opponents remain human.`,
    (c) => `A political reading of ${c.title} asks which material interest is hidden by cosmic, technical, therapeutic, or mythic language.`,
    (c) => `${c.title} tests the boundary between necessary coordination and domination. Record consent, appeal, oversight, and the people excluded from decision.`,
    (c) => `Where ${c.title} promises order, ask whose uncertainty is being reduced and whose freedom is being converted into someone else’s assurance.`,
  ],
};

const signalPatterns = [
  (c) => `${c.title} becomes relevant when ${c.signalCondition}. The immediate signal is a change in ${c.facet.lens}.`,
  (c) => `Draw ${c.title} when ${c.kernel} begins to organize choices before participants have named it. Separate the event, interpretation, and response.`,
  (c) => `${c.title} signals that ${c.facet.stake}. Look for the practical site where that tension ${c.model.action} and produces consequence.`,
  (c) => `This card appears when the situation needs ${c.facet.test}. It does not demand belief; it demands a more precise map.`,
  (c) => `${c.title} enters a reading when ${c.mode.lens} is being asked to carry more certainty than it can support. Restore the proper evidence boundary.`,
  (c) => `The divinatory signal is ${c.kernel} moving from background condition to active decision. Notice who recognizes the shift first.`,
  (c) => `${c.title} marks a threshold between the role already inherited and the response that can still be chosen. ${c.facet.lens.charAt(0).toUpperCase()}${c.facet.lens.slice(1)} are in play.`,
  (c) => `When ${c.title} surfaces, an image, system, or claim may be concentrating too much meaning. Widen the frame before acting.`,
  (c) => `${c.title} points to an unintegrated relation among ${c.kernel}. The reading asks for distinction without disconnection.`,
  (c) => `This is a signal to examine the keeper, witness, outsider, beneficiary, and cost hidden inside ${c.title}, especially around ${c.facet.lens}.`,
  (c) => `${c.title} may indicate that a vivid possibility is being dismissed too quickly or believed too completely. Test both reactions.`,
  (c) => `The card becomes timely when ${c.kernel} can no longer remain symbolic alone because it is shaping real permissions, risks, or relationships.`,
];

const uprightPatterns = [
  (c) => `In its generative position, ${c.title} offers ${c.gift}. Let that capacity widen the map before selecting an action.`,
  (c) => `Upright, ${c.title} asks you to practice ${c.gift}. Begin with ${c.facet.practice}.`,
  (c) => `Receive the card as permission to engage ${c.kernel} with curiosity and proportion. The gift becomes real through accountable action.`,
  (c) => `${c.title} upright restores context around ${c.facet.lens}. Use the larger view to find a neglected point of agency.`,
  (c) => `The constructive movement is toward ${c.gift}. Keep the evidence layer visible so wonder and discernment can work together.`,
  (c) => `Upright, ${c.archetype} reveals a capacity already present but not yet coordinated. Give it a bounded role.`,
  (c) => `${c.title} can now become an instrument rather than an identity. Use it to compare, clarify, connect, or repair.`,
  (c) => `The gift of ${c.title} is not certainty but a better question about ${c.kernel}. Let the question improve the next decision.`,
  (c) => `In the upright position, the card favors a reversible experiment, a clearer source trail, and a wider circle of affected voices.`,
  (c) => `${c.title} supports movement when ${c.facet.test}. Let insight earn trust through method and consequence.`,
  (c) => `Take the generative path: preserve ${c.kernel} as a source of possibility while refusing to make it absolute.`,
  (c) => `Upright, ${c.title} makes hidden structure visible without declaring every unknown solved. Act on what is clear and protect what remains open.`,
];

const shadowPatterns = [
  (c) => `In shadow, ${c.title} becomes ${c.shadow}. Pause before the preferred explanation hardens into identity or mandate.`,
  (c) => `The shadow position warns that ${c.kernel} is being used to erase context, consent, or counterevidence. Restore those missing constraints.`,
  (c) => `${c.title} darkens when ${c.mode.boundary.toLowerCase()}. Acknowledge the symbolic charge while reducing the factual claim to what sources support.`,
  (c) => `Watch for ${c.shadow}. The remedy is not ridicule, but a safer distinction among observation, interpretation, need, and story.`,
  (c) => `The card’s hazard is enclosure: every new detail may be recruited to protect the same conclusion. Name what could genuinely change the reading.`,
  (c) => `In shadow, ${c.archetype} claims special exemption from ordinary care, evidence, or reciprocity. Return authority to shared review.`,
  (c) => `${c.title} may be concentrating hidden costs in people who did not choose the promise. Follow burden before celebrating capability.`,
  (c) => `The warning is premature closure around ${c.kernel}. Keep at least one rival explanation and one exit route alive.`,
  (c) => `${c.title} in shadow confuses intensity with truth and belonging with proof. Separate the value of the experience from the reach of the claim.`,
  (c) => `A shadow reading asks whether ${c.facet.stake}. Find the material mechanism beneath the dramatic account as the pattern ${c.model.action}.`,
  (c) => `The danger is that the card becomes a role no one may question. Let witnesses revise, refuse, and remain more than the assigned archetype.`,
  (c) => `When ${c.title} contracts the field, reduce scale: one claim, one source, one affected relationship, and one repairable action.`,
];

const guidancePatterns = [
  (c) => `Stay with the distinction around ${c.kernel}. Begin by ${c.facet.practice}.`,
  (c) => `Slow the conclusion and widen the source base for ${c.title}. Prefer the smallest reversible step that could teach something real about ${c.facet.lens}.`,
  (c) => `Name the evidence layer before naming the meaning of ${c.kernel}. Let affected people help define what accountability requires.`,
  (c) => `Protect both wonder and agency while reading ${c.title}. Choose a response that remains useful even if the strongest interpretation changes.`,
  (c) => `Compare the story of ${c.title} with the system carrying it. Trace one dependency from ${c.kernel} to consequence.`,
  (c) => `Do not ask ${c.title} to solve every scale at once within ${c.facet.lens}. Work at the nearest point where consent and feedback are possible while the pattern ${c.model.action}.`,
  (c) => `Turn ${c.title} into a careful experiment concerning ${c.kernel}. State what result would support, weaken, or leave the claim unresolved.`,
  (c) => `Bring in the missing witness to ${c.title} through ${c.facet.lens}. Record whose knowledge, labor, risk, or refusal the current map omits while the pattern ${c.model.action}.`,
  (c) => `Separate the need from the explanation serving ${c.title}. Meet that need through ${c.facet.practice} without granting unsupported certainty.`,
  (c) => `Make the hidden rule inside ${c.title} explicit through ${c.facet.lens}. Add a reviewer, appeal, pause, or exit wherever power currently has none.`,
  (c) => `Return from the scale of ${c.title} to one lived consequence of ${c.kernel}. Repair that relationship before expanding the theory.`,
  (c) => `Use ${c.title} as a lens on ${c.facet.lens}, not a verdict. Stop when the lens begins to erase evidence or personhood.`,
];

const integrationPatterns = [
  (c) => `Write four accounts of ${c.title}: observation, interpretation, cultural story, and symbolic meaning. Underline where ${c.kernel} changes category.`,
  (c) => `Choose one claim linked to ${c.title}. List what supports it, weakens it, remains unknown, and still matters if it proves false.`,
  (c) => `Map who acts, knows, benefits, bears risk, may refuse, and can appeal in the situation evoked by ${c.title}.`,
  (c) => `Pair ${c.title} with its strongest polarity. Design one action that preserves ${c.gift} without feeding ${c.shadow}.`,
  (c) => `${c.facet.practice.charAt(0).toUpperCase()}${c.facet.practice.slice(1)}. Add one source and one affected witness before interpreting the result.`,
  (c) => `Retell ${c.title} from the viewpoint of the person or system carrying its hidden cost. Then revise the original reading.`,
  (c) => `Build a claim ladder for ${c.title}: documented, probable, possible, contested, fictional, symbolic. Place each statement on only one rung.`,
  (c) => `Create a failure rehearsal for ${c.title}. Name the earliest warning, a safe stop, a repair keeper, and evidence that recovery has begun.`,
  (c) => `Spend ten minutes describing ${c.kernel} without using the card’s familiar explanation. Notice which alternatives become available.`,
  (c) => `Identify one institution, relationship, body, and landscape touched by ${c.title}. Trace the consequence across all four.`,
  (c) => `Draft a consent protocol for engaging ${c.title}: scope, information, refusal, review, revocation, and care after participation.`,
  (c) => `Find the earliest source and newest remix of ${c.title}. Mark what changed in vocabulary, audience, evidence, and political effect.`,
];

const completionPatterns = [
  (c) => `Integration is present when ${c.facet.completion}.`,
  (c) => `The practice is complete when ${c.title} can carry meaning without demanding unsupported factual certainty.`,
  (c) => `Completion means you can state the claim, evidence level, symbolic value, risk, and next action without confusing them.`,
  (c) => `${c.title} is integrated when its gift remains available after the total explanation has been released.`,
  (c) => `A finished cycle leaves more grounded agency, more source clarity, and less need to force agreement.`,
  (c) => `The card has done its work when ${c.kernel} can be discussed with curiosity, boundaries, and a practical route to repair.`,
  (c) => `Completion arrives when the people affected can revise the account and still recognize their own experience within it.`,
  (c) => `You are complete when a changed interpretation would alter the theory without destroying identity or relationship.`,
  (c) => `The integration signal is a proportionate response: neither dismissal nor total surrender to the symbol.`,
  (c) => `${c.title} has settled when its origin, present use, and Oracle synthesis remain distinct and usable together.`,
  (c) => `The cycle closes when evidence can update belief, meaning can survive revision, and consent remains active.`,
  (c) => `Completion is demonstrated by one accountable action and one uncertainty that no longer needs to be hidden.`,
];

const storyPatterns = [
  (c) => `Introduce ${c.title} when ${c.kernel} offers a real advantage but transfers an unseen cost. The protagonist must decide which witness can revise the plan.`,
  (c) => `A community organizes around ${c.title}, then discovers that ${c.facet.stake}. The decisive conflict is over repair after the pattern ${c.model.action}, not possession.`,
  (c) => `The evidence for ${c.title} is genuine but supports less than either faction claims. Force the investigator to protect truth without abandoning meaning.`,
  (c) => `${c.title} becomes an interface everyone depends on and no one fully understands. A failure reveals the keeper hidden beneath the myth.`,
  (c) => `Two cultures encounter ${c.title} through incompatible evidence layers. Their survival depends on a protocol that preserves disagreement.`,
  (c) => `A protagonist inherits the role of ${c.archetype} and learns that its gift was built on an unacknowledged burden. They must redesign the role.`,
  (c) => `Someone uses ${c.title} to explain a private wound, while an institution uses it to justify public control. One source can disrupt both stories.`,
  (c) => `The promised liberation within ${c.title} works, but only for those able to leave. Make access, obligation, and return the center of the plot.`,
  (c) => `An archive proves the origin of ${c.title} and disproves its most famous legend. The new truth creates a more difficult responsibility.`,
  (c) => `${c.title} begins as harmless symbolic play, then acquires material authority. The characters must decide when imagination became governance.`,
  (c) => `A rival explanation for ${c.title} predicts the same event for a different reason. The story turns on a test neither side can control.`,
  (c) => `After ${c.title} changes the world, the first emergency is over but the old hierarchy remains. The protagonists must choose what not to rebuild.`,
];

function contextSentence(context, field) {
  const { model, facet, kernel } = context;
  const variants = {
    origin: `Because ${kernel} ${model.action}, provenance work must ${facet.test}.`,
    history: `At collective scale, ${kernel} ${model.social}; this matters because ${facet.stake}.`,
    psychological: `A grounded check for ${kernel} is to ${facet.test}, especially where the pattern ${model.action}.`,
    social: `In shared life, ${kernel} ${model.social}. Test that specific ${kernel} pattern by asking people to ${facet.test}.`,
    spiritual: `In symbolic practice, ${kernel} ${model.spiritual}; keep in view that ${facet.stake}.`,
    technological: `When ${kernel} becomes a capability, it ${model.technological}. Verify the implementation of ${kernel} by asking participants to ${facet.test}.`,
    political: `When ${kernel} becomes governance, it ${model.political}. Make authority over ${kernel} answerable by requiring decision-makers to ${facet.test}.`,
    signal: `Operationally, ${kernel} ${model.action}; the reader should ${facet.test}.`,
    upright: `The capacity within ${kernel} is strongest when ${facet.completion}, even as the pattern ${model.action}.`,
    shadow: `To keep ${kernel} from escalating, ${facet.test}, because the pattern ${model.action}.`,
    guidance: `Use this guidance where ${kernel} ${model.action}; keep visible that ${facet.stake}.`,
    practice: `Review ${kernel} through ${facet.lens}, remembering that the card ${model.action}.`,
    completion: `At that point, ${kernel} reaches a different relation to ${facet.completion}; its class-specific dynamic still ${model.action}, but no longer without recognition.`,
    story: `The world of the story must show how ${kernel} ${model.action} and why ${facet.stake}.`,
    question: `Answer by testing how ${kernel} ${model.action} against ${facet.lens}.`,
  };
  return variants[field];
}

function buildCard(title, classId, index, globalIndex) {
  const classInfo = CLASS_BY_ID[classId];
  const model = classModels[classId];
  const cardSlug = slug(title);
  const cardId = `sfoc-${classId}-${cardSlug}`;
  const domainIds = domainsFor(title, classId, index);
  const modes = modesFor(title, classId);
  const sourceSelection = sourcesFor(title, classId, modes);
  const sourceIds = sourceSelection.sourceIds;
  const spec = cardSpec(title, classId, index, domainIds, modes);
  const kernel = semanticKernel(title, classId, domainIds);
  const safety = safetyFor(title, modes);
  const facet = domainFacets[domainIds[0]];
  const mode = modeFacetFor(modes);
  const context = {
    title,
    cardId,
    classId,
    domainIds,
    modes,
    model,
    kernel,
    facet,
    mode,
    spec,
    archetype: spec.archetype,
    gift: phrase(spec.gift),
    shadow: phrase(spec.shadow),
    question: phrase(spec.question),
    signalCondition: signalConditionsByClass[classId],
  };
  const originSummary = curatedOrigins[cardSlug] ?? `${render(`${cardId}:origin`, originPatterns, context, index)} ${contextSentence(context, 'origin')}`;
  const externalSourceCount = sourceIds.filter((id) => id !== 'original-synthesis').length;
  const conceptSpecificSourceCount = sourceSelection.conceptSpecificSourceIds.length;
  return {
    id: cardId,
    ordinal: globalIndex + 1,
    title,
    aliases: aliasesBySlug[cardSlug] ?? [],
    class: classId,
    className: classInfo.name,
    domains: domainIds,
    primaryDomain: domainIds[0],
    secondaryDomains: domainIds.slice(1),
    domainNames: domainIds.map((id) => DOMAIN_BY_ID[id].name),
    materialModes: modes,
    epistemicLayers: evidenceFor(title, modes, sourceIds, sourceSelection.conceptSpecificSourceIds),
    sources: sourceIds,
    origin: {
      summary: originSummary,
      provenanceRule: 'Earliest documented use, later cultural mutation, community self-description, and Oracle synthesis remain separate records.',
      traditionCare: modes.includes('mythology') || modes.includes('esoteric-tradition') ? 'Describe traditions in their own context before drawing cross-tradition analogies.' : 'Do not invent an ancient origin to make a modern idea feel authoritative.',
    },
    culturalHistory: `${render(`${cardId}:history`, historyPatterns, context, index)} ${contextSentence(context, 'history')}`,
    essence: spec.essence,
    archetype: spec.archetype,
    gift: sentence(spec.gift),
    shadow: sentence(spec.shadow),
    meanings: {
      psychological: `${render(`${cardId}:psychological`, meaningPatterns.psychological, context, index)} ${contextSentence(context, 'psychological')}`,
      social: `${render(`${cardId}:social`, meaningPatterns.social, context, index + 1)} ${contextSentence(context, 'social')}`,
      spiritual: `${render(`${cardId}:spiritual`, meaningPatterns.spiritual, context, index + 2)} ${contextSentence(context, 'spiritual')}`,
      technological: `${render(`${cardId}:technological`, meaningPatterns.technological, context, index + 3)} ${contextSentence(context, 'technological')}`,
      political: `${render(`${cardId}:political`, meaningPatterns.political, context, index + 4)} ${contextSentence(context, 'political')}`,
    },
    divination: {
      signal: `${render(`${cardId}:signal`, signalPatterns, context, index)} ${contextSentence(context, 'signal')}`,
      upright: `${render(`${cardId}:upright`, uprightPatterns, context, index + 1)} ${contextSentence(context, 'upright')}`,
      shadow: `${render(`${cardId}:shadow-reading`, shadowPatterns, context, index + 2)} ${contextSentence(context, 'shadow')}`,
      positionPrompts: {
        origin: `Which inherited account of ${title} first made ${kernel} meaningful here?`,
        present: `Where is ${title} active now, on which evidence layer, and who is affected?`,
        threshold: `What permission, cost, or relationship changes if ${kernel} becomes decisive?`,
        integration: `How can ${phrase(spec.gift)} be kept without reproducing ${phrase(spec.shadow)}?`,
      },
    },
    guidance: `${render(`${cardId}:guidance`, guidancePatterns, context, index)} ${contextSentence(context, 'guidance')}`,
    integration: {
      practice: `${render(`${cardId}:practice`, integrationPatterns, context, index)} ${contextSentence(context, 'practice')}`,
      boundary: safety.boundaries[0],
      completionSignal: `${render(`${cardId}:completion`, completionPatterns, context, index)} ${contextSentence(context, 'completion')}`,
    },
    question: spec.question,
    storySeed: `${render(`${cardId}:story`, storyPatterns, context, index)} ${contextSentence(context, 'story')}`,
    gameRoles: gameRolesByClass[classId],
    polarities: polaritiesFor(title, globalIndex),
    relationships: [],
    relationshipRequirements: {
      minimumDegree: 4,
      minimumEdgeFamilies: 3,
      requireCrossDomain: true,
      requireSourcedEdge: false,
      requireOriginalSynthesisEdge: true,
      status: 'requirements-declared',
    },
    visual: {
      alt: `${title}: an original rounded-square enamel oracle tile for the ${classInfo.name} class.`,
      centralMotif: `${title} visualized as ${kernel}: ${model.image}.`,
      borderGrammar: classInfo.border,
      accent: classInfo.accent,
      material: 'deep midnight vitreous enamel, warm metallic registration, restrained luminous accents',
      typography: 'No words baked into the art; all labels remain accessible live text.',
      prohibited: ['franchise logos', 'celebrity likenesses', 'sacred imagery stripped of context', 'diagnostic or hate symbolism'],
    },
    safety,
    research: {
      confidence: modes.includes('established-science') ? 'high-for-established-layer' : modes.includes('science-fiction') ? 'high-for-cultural-layer' : 'layer-dependent',
      editorialStatus: 'core-reviewed',
      sourceCoverage: conceptSpecificSourceCount,
      contextualSourceCoverage: externalSourceCount - conceptSpecificSourceCount,
      contextualSourceId: sourceSelection.contextualSourceId,
      unsourced: conceptSpecificSourceCount === 0,
      sourceGap: conceptSpecificSourceCount === 0 ? `${title} has class-level external context but no concept-specific external source in this release; its non-symbolic provenance remains an explicit research gap.` : null,
      openQuestions: [
        `Which earliest reliable source fixes the modern meaning of ${title}?`,
        `Which communities use ${title} differently, and what changes across those contexts?`,
        `What evidence would distinguish the leading literal explanations associated with ${title}?`,
      ],
      nextReview: '2027-02-24',
    },
    version: { ...RELEASE, contentHash: hash(`${cardId}:${spec.essence}:${sourceIds.join(',')}`).toString(16).padStart(8, '0') },
  };
}

export function buildCards() {
  assertCatalog();
  let globalIndex = 0;
  const result = [];
  for (const classInfo of classes) {
    catalogs[classInfo.id].forEach((title, classIndex) => {
      result.push(buildCard(title, classInfo.id, classIndex, globalIndex));
      globalIndex += 1;
    });
  }
  return result;
}

export function buildLonglist(cards = buildCards()) {
  return buildCandidateLonglist(cards);
}

export function assertContent(cards = buildCards(), longlist = buildLonglist(cards)) {
  const failures = [];
  if (cards.length !== 480) failures.push(`expected 480 cards, found ${cards.length}`);
  if (longlist.length < 1500) failures.push(`expected at least 1,500 evaluated candidates, found ${longlist.length}`);
  if (new Set(cards.map((card) => card.id)).size !== cards.length) failures.push('card IDs are not unique');
  if (new Set(longlist.map((item) => item.id)).size !== longlist.length) failures.push('candidate IDs are not unique');
  const normalizedTitles = longlist.map((item) => item.title.normalize('NFKC').toLocaleLowerCase('en'));
  if (new Set(normalizedTitles).size !== normalizedTitles.length) failures.push('candidate titles are not unique after Unicode casefolding');
  const decisions = Object.fromEntries(['core', 'expansion-ready', 'research-reserve', 'merged', 'deferred', 'excluded'].map((decision) => [decision, longlist.filter((item) => item.decision === decision).length]));
  if (decisions.core !== 480) failures.push(`core: expected 480, found ${decisions.core}`);
  if (longlist.length - decisions.core < 1020) failures.push(`expected at least 1,020 independent non-core candidates, found ${longlist.length - decisions.core}`);
  for (const card of cards) {
    if (!card.title || !card.essence || !card.culturalHistory || !card.question) failures.push(`${card.id}: missing core prose`);
    if (card.domains.length < 1 || card.materialModes.length < 1 || card.epistemicLayers.length < 3 || card.sources.length < 1) failures.push(`${card.id}: incomplete classification or provenance`);
    if (!card.sources.includes('original-synthesis')) failures.push(`${card.id}: missing original-synthesis provenance`);
    if (card.sources.some((sourceId) => !sourceById[sourceId])) failures.push(`${card.id}: unknown source ID`);
    if (card.epistemicLayers.some((layer) => !VALID_EVIDENCE.has(layer.status))) failures.push(`${card.id}: invalid evidence status`);
    if (card.epistemicLayers.some((layer) => layer.sourceIds.some((sourceId) => !sourceById[sourceId]))) failures.push(`${card.id}: evidence layer has unknown source ID`);
    const externalCount = card.sources.filter((sourceId) => sourceId !== 'original-synthesis').length;
    if (externalCount === 0) failures.push(`${card.id}: missing external contextual source`);
    if (card.research.unsourced !== (card.research.sourceCoverage === 0)) failures.push(`${card.id}: concept-specific unsourced flag does not match source coverage`);
    const prose = [card.culturalHistory, card.essence, ...Object.values(card.meanings), ...Object.values(card.divination).filter((value) => typeof value === 'string')].join(' ');
    if (/\[object Object\]|through clearer distinctions through|is plural:\s+(has|belongs|accumulated|became|developed|gathered|draws|combines|evolved|takes|changes)/i.test(prose)) failures.push(`${card.id}: generated prose defect`);
  }
  if (new Set(cards.map((card) => card.archetype)).size < 430) failures.push('archetypes are insufficiently differentiated');
  for (const item of longlist) {
    const dimensions=Object.values(item.scoring?.dimensions ?? {});
    const criterionNotes=Object.values(item.scoring?.criterionNotes ?? {});
    if (dimensions.length !== 8 || dimensions.some((value) => !Number.isFinite(value)) || criterionNotes.length !== 8 || criterionNotes.some((value) => typeof value !== 'string' || value.length < 40) || !Number.isFinite(item.scoring?.weightedScore)) failures.push(`${item.id}: incomplete eight-criterion evaluation`);
    if ((item.definition ?? item.essence ?? '').length < 35 || (item.originContext ?? item.origin?.summary ?? '').length < 80 || item.rationale.length < 120) failures.push(`${item.id}: definition, origin context, or rationale is not substantive`);
    if (item.decision !== 'core' && 'parentCardId' in item) failures.push(`${item.id}: non-core candidate is mechanically derived from a core parent`);
  }
  try {
    assertAuthoredCandidateRegistry(longlist.filter((item) => item.decision !== 'core'), { coreTitles: cards.map((card) => card.title) });
  } catch (error) {
    failures.push(`authored candidate registry: ${error.message}`);
  }
  if (failures.length) throw new Error(failures.slice(0, 25).join('\n'));
  return { cards: cards.length, candidates: longlist.length, decisions, candidateQuality: candidateQualityMetrics(longlist) };
}

export const cards = buildCards();
export const longlist = buildLonglist(cards);
export const contentValidation = assertContent(cards, longlist);
