'use strict';

const fs = require('fs');
const path = require('path');

const chainRoot = path.resolve(__dirname, '..');
const aisforRoot = path.resolve('E:\\aisfor');
const androidRoot = path.resolve('E:\\aisfor-android');

function readUtf8(filePath) {
  return fs.readFileSync(filePath, 'utf8');
}

function hasAll(text, needles) {
  return needles.every(needle => text.includes(needle));
}

function main() {
  const policyPath = path.join(chainRoot, 'config', 'resiliencePermissionlessNodePolicy.example.json');
  const policy = JSON.parse(readUtf8(policyPath));
  const syncRoute = readUtf8(path.join(aisforRoot, 'routes', 'sync.js'));
  const syncClient = readUtf8(path.join(aisforRoot, 'pc-sync-build', 'sync.js'));
  const nodeModel = readUtf8(path.join(aisforRoot, 'models', 'DistributedNode.js'));
  const chunkModel = readUtf8(path.join(aisforRoot, 'models', 'DistributedChunk.js'));
  const replicaPolicy = readUtf8(path.join(aisforRoot, 'services', 'distributedReplicaPolicy.js'));
  const manifestProtocol = readUtf8(path.join(aisforRoot, 'services', 'permissionlessManifestProtocol.js'));
  const replicaRepairProtocol = readUtf8(path.join(aisforRoot, 'services', 'deterministicReplicaRepair.js'));
  const peerReplicaRepairProtocol = readUtf8(path.join(aisforRoot, 'services', 'peerReplicaRepairProtocol.js'));
  const capabilityLeaseProtocol = readUtf8(path.join(aisforRoot, 'services', 'capabilityLeaseProtocol.js'));
  const permissionlessCapabilityAdmission = readUtf8(path.join(aisforRoot, 'services', 'permissionlessCapabilityAdmissionProtocol.js'));
  const permissionlessResourceChallenge = readUtf8(path.join(aisforRoot, 'services', 'permissionlessResourceChallengeProtocol.js'));
  const readOnlyRpcQuorum = readUtf8(path.join(aisforRoot, 'services', 'readOnlyRpcQuorum.js'));
  const rpcBlockAttestationProtocol = readUtf8(path.join(aisforRoot, 'services', 'rpcBlockAttestationProtocol.js'));
  const statelessServiceCapsuleProtocol = readUtf8(path.join(aisforRoot, 'services', 'statelessServiceCapsuleProtocol.js'));
  const clientServiceFailoverProtocol = readUtf8(path.join(aisforRoot, 'services', 'clientServiceFailoverProtocol.js'));
  const signedEventProjectionProtocol = readUtf8(path.join(aisforRoot, 'services', 'signedEventProjectionProtocol.js'));
  const peerSignedEventMailboxProtocol = readUtf8(path.join(aisforRoot, 'services', 'peerSignedEventMailboxProtocol.js'));
  const signedProjectionCheckpointProtocol = readUtf8(path.join(aisforRoot, 'services', 'signedProjectionCheckpointProtocol.js'));
  const signedManifestVoteProtocol = readUtf8(path.join(aisforRoot, 'services', 'signedManifestVoteProtocol.js'));
  const peerServiceDirectoryProtocol = readUtf8(path.join(aisforRoot, 'services', 'peerServiceDirectoryProtocol.js'));
  const webFailoverVerifier = readUtf8(path.join(aisforRoot, 'public', 'js', 'verified-web-service-failover.js'));
  const webFailoverBootstrap = readUtf8(path.join(aisforRoot, 'public', 'js', 'web-service-failover-bootstrap.js'));
  const webServiceWorker = readUtf8(path.join(aisforRoot, 'public', 'sw.js'));
  const webLayout = readUtf8(path.join(aisforRoot, 'views', 'layout.ejs'));
  const webFailoverConfig = readUtf8(path.join(aisforRoot, 'services', 'webServiceFailoverConfig.js'));
  const httpsRelayStagingPlan = readUtf8(path.join(aisforRoot, 'services', 'httpsRelayStagingPlan.js'));
  const stableBootstrapOriginPlan = readUtf8(path.join(aisforRoot, 'services', 'stableBootstrapOriginPlan.js'));
  const stableBootstrapOriginPreparer = readUtf8(path.join(aisforRoot, 'scripts', 'prepare-stable-bootstrap-origins.js'));
  const productionDataReplicaPlan = readUtf8(path.join(chainRoot, 'services', 'productionDataReplicaPlan.js'));
  const syncClientUpdateReleaseService = readUtf8(path.join(aisforRoot, 'services', 'syncClientUpdateReleaseService.js'));
  const liveServiceContinuityCanary = readUtf8(path.join(aisforRoot, 'services', 'liveServiceContinuityCanary.js'));
  const liveServiceContinuityExecutor = readUtf8(path.join(aisforRoot, 'scripts', 'run-upnp-capsule-failover-canary.js'));
  const quickTunnelContinuityExecutor = readUtf8(path.join(aisforRoot, 'scripts', 'run-quick-tunnel-service-canary.js'));
  const androidDirectoryStore = readUtf8(path.join(androidRoot, 'app', 'src', 'main', 'java', 'kr', 'aisfor', 'app', 'VerifiedServiceDirectoryStore.java'));
  const androidBootstrapClient = readUtf8(path.join(androidRoot, 'app', 'src', 'main', 'java', 'kr', 'aisfor', 'app', 'VerifiedServiceBootstrapClient.java'));
  const androidMainActivity = readUtf8(path.join(androidRoot, 'app', 'src', 'main', 'java', 'kr', 'aisfor', 'app', 'MainActivity.java'));
  const androidBuild = readUtf8(path.join(androidRoot, 'app', 'build.gradle'));
  const replicaCanaryEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'multi-replica-canary-redacted.json');
  const replicaCanaryEvidence = fs.existsSync(replicaCanaryEvidencePath)
    ? JSON.parse(readUtf8(replicaCanaryEvidencePath))
    : null;
  const inMemoryOutageEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'main-outage-inmemory-integration-redacted.json');
  const inMemoryOutageEvidence = fs.existsSync(inMemoryOutageEvidencePath)
    ? JSON.parse(readUtf8(inMemoryOutageEvidencePath))
    : null;
  const liveTopologyEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'live-node-topology-preflight-redacted.json');
  const liveTopologyEvidence = fs.existsSync(liveTopologyEvidencePath)
    ? JSON.parse(readUtf8(liveTopologyEvidencePath))
    : null;
  const finiteUpnpEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'finite-upnp-live-canary-result-redacted.json');
  const finiteUpnpEvidence = fs.existsSync(finiteUpnpEvidencePath)
    ? JSON.parse(readUtf8(finiteUpnpEvidencePath))
    : null;
  const outboundOverlayEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'outbound-peer-overlay-stage-redacted.json');
  const outboundOverlayEvidence = fs.existsSync(outboundOverlayEvidencePath)
    ? JSON.parse(readUtf8(outboundOverlayEvidencePath))
    : null;
  const quickTunnelEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'quick-tunnel-discovery-canary-stage-redacted.json');
  const quickTunnelEvidence = fs.existsSync(quickTunnelEvidencePath)
    ? JSON.parse(readUtf8(quickTunnelEvidencePath))
    : null;
  const passiveFleetEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'passive-service-fleet-fence-self-test-redacted.json');
  const passiveFleetEvidence = fs.existsSync(passiveFleetEvidencePath)
    ? JSON.parse(readUtf8(passiveFleetEvidencePath))
    : null;
  const syntheticMongoEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'synthetic-mongo-three-node-failover-redacted.json');
  const syntheticMongoEvidence = fs.existsSync(syntheticMongoEvidencePath)
    ? JSON.parse(readUtf8(syntheticMongoEvidencePath))
    : null;
  const socketMongoAdapterEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'socket-mongo-cluster-adapter-stage-redacted.json');
  const socketMongoAdapterEvidence = fs.existsSync(socketMongoAdapterEvidencePath)
    ? JSON.parse(readUtf8(socketMongoAdapterEvidencePath))
    : null;
  const promotedActiveGateEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'promoted-active-data-plane-gate-redacted.json');
  const promotedActiveGateEvidence = fs.existsSync(promotedActiveGateEvidencePath)
    ? JSON.parse(readUtf8(promotedActiveGateEvidencePath))
    : null;
  const serviceMediaEvidencePath = path.join(chainRoot, 'docs', 'resilience', 'evidence', 'service-media-readonly-inventory-redacted.json');
  const serviceMediaEvidence = fs.existsSync(serviceMediaEvidencePath)
    ? JSON.parse(readUtf8(serviceMediaEvidencePath))
    : null;
  const serviceMediaPolicyPath = path.join(chainRoot, 'config', 'serviceMediaReplication.example.json');
  const serviceMediaPolicy = fs.existsSync(serviceMediaPolicyPath)
    ? JSON.parse(readUtf8(serviceMediaPolicyPath))
    : null;

  const foundations = {
    authenticatedHeartbeat: hasAll(syncRoute, ["router.post('/node/heartbeat'", 'requireSyncToken']),
    dynamicStorageSelection: syncRoute.includes('chooseDistributedNode'),
    unhealthyChunkReassignment: hasAll(syncRoute, ['reassignDistributedChunk', 'rebalanceUnhealthyDistributedChunks']),
    encryptedChunkIntegrity: hasAll(syncRoute, ['encryptNodeChunk', 'chunkHash', 'plainChunkHash']),
    localGateway: hasAll(syncClient, ['/gateway/health', '/gateway/chunks', '/gateway/decentralized-manifest']),
    cachedManifest: hasAll(syncClient, ['refreshDecentralizedManifest', 'decentralized-manifest.json']),
    reliabilityScoring: hasAll(nodeModel, ['reliabilityScore', 'avgResponseMs', 'lastHeartbeatAt']),
    hardwareCapacityInventory: hasAll(nodeModel, ['resilienceLogicalCpuCount', 'resilienceTotalMemoryBytes', 'resilienceNodeVolumeFreeBytes']),
    multiReplicaStorageStaged: hasAll(chunkModel, ['desiredReplicaCount', 'healthyReplicaCount', 'replicationStatus', 'replicas'])
      && hasAll(replicaPolicy, ['chooseDistinctReplicaNodes', 'summarizeReplicaSet'])
      && syncRoute.includes('AISFOR_NODE_MULTI_REPLICA_ENABLED'),
    multiReplicaLiveCanaryProven: replicaCanaryEvidence?.status === 'SYNTHETIC_THREE_REPLICA_REPLENISH_AND_RESTORE_PROVEN'
      && replicaCanaryEvidence.initialReplicaReceipts >= 3
      && replicaCanaryEvidence.replacementReceiptObserved === true
      && replicaCanaryEvidence.nodeRestoreUploadVerified === true
      && replicaCanaryEvidence.plaintextRoundTripVerified === true
      && replicaCanaryEvidence.observedFailureDomains >= 2,
    offlineManifestVerificationStaged: hasAll(manifestProtocol, [
      'canonicalJson',
      'verifyTrustedAnchor',
      'MANIFEST_EXPIRED',
      'MANIFEST_ROLLBACK_REJECTED',
      'selectManifestQuorum'
    ]),
    deterministicReplicaRepairStaged: hasAll(replicaRepairProtocol, [
      'electReplicaRepair',
      'challengePassed',
      'leaseUntil',
      'electionCommitment'
    ]),
    peerReplicaRepairMailboxStaged: hasAll(peerReplicaRepairProtocol, [
      'verifyRepairProposal',
      'signReplicaRepairVote',
      'aggregateReplicaRepairCertificate',
      'PEER_REPAIR_VOTE_QUORUM_NOT_REACHED',
      'PEER_REPAIR_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'PEER_REPAIR_EPOCH_ROLLBACK_REJECTED',
      'fencingToken',
      'verifyReplicaRepairReceipt'
    ]) && hasAll(syncClient, [
      '/gateway/replica-repair/proposal',
      '/gateway/replica-repair/vote',
      '/gateway/replica-repair/certificate',
      '/gateway/replica-repair/execute',
      'peerReplicaRepairEnabled',
      'aggregateEmbeddedReplicaRepairCertificate',
      'executeEmbeddedReplicaRepair',
      'PEER_REPAIR_VOTE_QUORUM_NOT_REACHED',
      'PEER_REPAIR_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'PEER_REPAIR_LOCAL_NODE_NOT_SELECTED',
      'PEER_REPAIR_CIPHERTEXT_PROOF_INVALID'
    ]),
    capabilityLeaseVerificationStaged: hasAll(capabilityLeaseProtocol, [
      'signCapabilityClaim',
      'verifyCapabilityLease',
      'CAPABILITY_FINALIZED_MEMBERSHIP_REQUIRED',
      'CAPABILITY_CHALLENGE_REQUIRED',
      'CAPABILITY_LEASE_EXPIRED'
    ]),
    permissionlessCapabilityAdmissionStaged: hasAll(permissionlessCapabilityAdmission, [
      'createWitnessEligibilitySet',
      'verifyWitnessEligibilitySet',
      'signCapabilityWitnessAttestation',
      'verifyPermissionlessCapabilityAdmission',
      'ADMISSION_WITNESS_QUORUM_NOT_REACHED',
      'ADMISSION_WITNESS_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'ADMISSION_EPOCH_ROLLBACK_REJECTED'
    ]),
    permissionlessResourceChallengeStaged: hasAll(permissionlessResourceChallenge, [
      'createResourceChallenge',
      'executeResourceChallenge',
      'verifyResourceChallengeResponse',
      'RESOURCE_CHALLENGE_STORAGE_PROOF_INVALID',
      'RESOURCE_CHALLENGE_CAPSULE_PROOF_INVALID',
      'RESOURCE_CHALLENGE_RPC_PROOF_INVALID'
    ]) && hasAll(syncClient, [
      '/gateway/capability/resource-challenge',
      '/gateway/capability/witness',
      '/gateway/capability/admission',
      '/gateway/capability/eligibility',
      'executeLocalPermissionlessResourceChallenge',
      'createLocalCapabilityWitnessAttestation',
      'aggregateEmbeddedCapabilityAdmission',
      'resolveEmbeddedWitnessEligibility',
      'permissionlessCapabilityAdmissionEnabled',
      'RESOURCE_CHALLENGE_STORAGE_ROUNDTRIP_FAILED',
      'RESOURCE_CHALLENGE_CAPSULE_RESULT_MISMATCH',
      'RESOURCE_CHALLENGE_RPC_CERTIFICATE_MISMATCH',
      'CAPABILITY_ADMISSION_WITNESS_QUORUM_NOT_REACHED',
      'CAPABILITY_ADMISSION_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'CAPABILITY_ADMISSION_EPOCH_ROLLBACK_REJECTED'
    ]),
    readOnlyRpcQuorumStaged: hasAll(readOnlyRpcQuorum, [
      'RPC_WRITE_OR_UNSAFE_METHOD_REJECTED',
      'readFinalizedBlockQuorum',
      'RPC_BLOCK_HASH_QUORUM_NOT_REACHED'
    ]),
    natSafeRpcAttestationStaged: hasAll(rpcBlockAttestationProtocol, [
      'signRpcBlockAttestation',
      'verifyRpcBlockAttestation',
      'selectRpcBlockQuorum',
      'RPC_ATTESTATION_QUORUM_NOT_REACHED'
    ]),
    finiteUpnpLiveLimitRecorded: finiteUpnpEvidence?.result === 'BLOCKED_BY_NAT_TRAVERSAL_NOT_PROVEN'
      && finiteUpnpEvidence?.selectedPcNodes === 3
      && finiteUpnpEvidence?.revocation?.rolloutPolicyPresent === false
      && finiteUpnpEvidence?.revocation?.canaryMappingsDeleted === true,
    peerSponsoredUpnpStaged: hasAll(syncClient, [
      'reconcileSponsoredUpnpPeerMappings',
      'PLAI finite peer-sponsored relay',
      'sponsoredMappings',
      'PEER_SPONSOR_',
      'finiteUpnpRelay'
    ]),
    outboundPeerOverlayStaged: outboundOverlayEvidence?.status === 'DEFAULT_OFF_SOURCE_AND_SYNTHETIC_PROFILE_STAGED'
      && hasAll(syncClient, [
        'handleOutboundOverlayRegister',
        'handleOutboundOverlayPoll',
        'handleOutboundOverlayResponse',
        'handleOutboundOverlayVirtualRequest',
        'runOutboundPeerOverlayOnce',
        'OUTBOUND_OVERLAY_PATH_REJECTED',
        'OUTBOUND_OVERLAY_SESSION_PROOF_REJECTED'
      ]),
    statelessReadCapsuleProtocolStaged: hasAll(statelessServiceCapsuleProtocol, [
      'verifyCapsuleRelease',
      'executeStatelessCapsule',
      'CAPSULE_UNSAFE_CONTROLS_REJECTED',
      'CAPSULE_FINALIZED_ANCHOR_REQUIRED',
      'verify-rpc-certificate',
      'verify-manifest-quorum'
    ]) && hasAll(syncClient, [
      '/gateway/service-capsule/manifest',
      '/gateway/service-capsule/execute',
      'STATELESS_CAPSULE_OPERATION_REJECTED',
      'executeStatelessServiceCapsuleFenced',
      '--max-old-space-size=32',
      'STATELESS_CAPSULE_WORKER_TIMEOUT'
    ]),
    clientFailoverResolverStaged: hasAll(clientServiceFailoverProtocol, [
      'verifyEndpointDirectoryQuorum',
      'buildFailoverAttemptOrder',
      'FAILOVER_ENDPOINT_POOL_TOO_SMALL',
      'FAILOVER_NO_ELIGIBLE_ENDPOINT'
    ]),
    signedManifestVoteAnchorStaged: hasAll(signedManifestVoteProtocol, [
      'signManifestVote',
      'verifyManifestVote',
      'selectManifestVoteQuorum',
      'MANIFEST_VOTE_RPC_QUORUM_REQUIRED',
      'MANIFEST_VOTE_NODE_NOT_ADMITTED'
    ]),
    peerServiceDirectoryMailboxStaged: hasAll(peerServiceDirectoryProtocol, [
      'validateServiceDirectoryProposal',
      'signServiceDirectoryProposal',
      'assembleVerifiedServiceDirectoryBundle',
      'PEER_DIRECTORY_OWN_ENDPOINT_BINDING_MISMATCH'
    ]) && hasAll(syncClient, [
      '/gateway/service-directory/proposal',
      '/gateway/manifest-vote',
      '/gateway/service-directory',
      'signedManifestVoteExchangeEnabled',
      'PEER_MANIFEST_VOTE_QUORUM_NOT_REACHED',
      'endpoint?.admissionCertificate',
      'PEER_DIRECTORY_DYNAMIC_NODE_ADMISSION_INVALID'
    ]),
    androidVerifiedDirectoryCacheStaged: hasAll(androidDirectoryStore, [
      'plai-rpc-quorum-attested-manifest-anchor/v1',
      'MANIFEST_SEQUENCE_EQUIVOCATION_REJECTED',
      'PREF_HIGHEST_SEQUENCE',
      'FAILOVER_ENDPOINT_POOL_TOO_SMALL',
      'orderForRole',
      'Signature.getInstance("Ed25519")',
      'MANIFEST_VOTE_SIGNATURE_INVALID',
      'MANIFEST_VOTE_ED25519_PROVIDER_UNAVAILABLE'
    ]) && hasAll(androidMainActivity, [
      'tryVerifiedServiceFailoverInBackground',
      'probeVerifiedServiceEndpoint',
      'loadVerifiedServiceFallback'
    ]) && androidBuild.includes('PLAI_SERVICE_FAILOVER_ENABLED\", \"false'),
    androidMultiBootstrapQuorumStaged: hasAll(androidBootstrapClient, [
      'PLAI_SERVICE_BOOTSTRAP_ENABLED',
      'MINIMUM_CONFIGURED_SOURCES = 3',
      'MINIMUM_MATCHING_SOURCES = 2',
      'BOOTSTRAP_SOURCE_ORIGIN_DUPLICATE',
      'BOOTSTRAP_SOURCE_FAILURE_DOMAINS_TOO_FEW',
      'BOOTSTRAP_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'BOOTSTRAP_ANCHOR_KEY_NOT_PINNED',
      'VerifiedServiceDirectoryStore.verifyAndStore'
    ]) && hasAll(androidBuild, [
      'PLAI_SERVICE_BOOTSTRAP_ENABLED\", \"false',
      'PLAI_SERVICE_BOOTSTRAP_SOURCES',
      'PLAI_SERVICE_BOOTSTRAP_ROOT_NODE_KEYS'
    ]) && hasAll(androidMainActivity, [
      'VerifiedServiceBootstrapClient.refreshAndStore',
      'trying durable cache'
    ]),
    androidTwoDomainHttpCanaryBuildStaged: hasAll(androidBootstrapClient, [
      'PLAI_SERVICE_CANARY_HTTP_ENABLED',
      'BOOTSTRAP_HTTP_CANARY_DEBUG_BUILD_REQUIRED',
      'BOOTSTRAP_TRANSPORT_POLICY_MISMATCH',
      'BOOTSTRAP_HTTP_CANARY_PUBLIC_RELAY_REQUIRED',
      'minimumDomains = allowHttpForCanary ? 2 : 3'
    ]) && hasAll(androidBuild, [
      'PLAI_SERVICE_CANARY_HTTP_ENABLED',
      'PLAI_SERVICE_BOOTSTRAP_SOURCES',
      'PLAI_SERVICE_BOOTSTRAP_ROOT_NODE_KEYS',
      'project.findProperty'
    ]),
    webVerifiedServiceFailoverStaged: hasAll(webFailoverVerifier, [
      'WEB_FAILOVER_WEBCRYPTO_UNAVAILABLE',
      'Ed25519',
      'WEB_FAILOVER_SOURCE_QUORUM_NOT_REACHED',
      'WEB_FAILOVER_ANCHOR_SIGNATURE_QUORUM_NOT_REACHED',
      'WEB_FAILOVER_MANIFEST_ROLLBACK_REJECTED',
      'WEB_FAILOVER_MANIFEST_EQUIVOCATION_REJECTED',
      'WEB_FAILOVER_MANIFEST_PREVIOUS_COMMITMENT_MISMATCH',
      'orderEndpoints'
    ]) && hasAll(webServiceWorker, [
      'PLAI_STORE_VERIFIED_WEB_FAILOVER',
      'readVerifiedFailoverProof',
      'storeVerifiedFailoverProof',
      'chooseReachableVerifiedEndpoint',
      'WEB_FAILOVER_NO_REACHABLE_ENDPOINT',
      '/gateway/service-shell',
      "event.request.mode !== 'navigate'"
    ]) && hasAll(webFailoverBootstrap, [
      'sendProofToWorker',
      'previousCache',
      'Fail closed'
    ]) && hasAll(webFailoverConfig, [
      'PLAI_WEB_SERVICE_FAILOVER_ENABLED',
      'PLAI_WEB_SERVICE_BOOTSTRAP_SOURCES',
      'PLAI_WEB_SERVICE_BOOTSTRAP_ROOT_NODE_KEYS',
      'productionDefaultOff: true'
    ]) && hasAll(webLayout, [
      'webServiceFailoverEnabled === true',
      'verified-web-service-failover.js',
      'web-service-failover-bootstrap.js'
    ]) && hasAll(syncClient, [
      '/gateway/service-shell',
      'STATELESS_SERVICE_SHELL_MANIFEST_MISMATCH',
      'STATELESS_SERVICE_SHELL_LOCAL_NODE_NOT_ADMITTED',
      "form-action 'none'"
    ]),
    syntheticMainOutageIntegrationPassed: inMemoryOutageEvidence?.status === 'SYNTHETIC_IN_MEMORY_MAIN_OUTAGE_INTEGRATION_PASSED'
      && inMemoryOutageEvidence.mainServerAvailable === false
      && inMemoryOutageEvidence.databaseConnected === false
      && inMemoryOutageEvidence.networkRequestsMade === false
      && inMemoryOutageEvidence.rpcCheckpoint?.quorumVotes >= 3
      && inMemoryOutageEvidence.manifestAnchor?.nodeVotes >= 3
      && inMemoryOutageEvidence.webFailover?.webCryptoVerified === true
      && inMemoryOutageEvidence.webFailover?.matchingBootstrapSources >= 2
      && inMemoryOutageEvidence.webFailover?.matchingBootstrapFailureDomains >= 2
      && inMemoryOutageEvidence.webFailover?.eligibleServiceEndpoints >= 3
      && inMemoryOutageEvidence.storage?.initialReplicas >= 3
      && inMemoryOutageEvidence.storage?.plaintextHashVerified === true
      && inMemoryOutageEvidence.productionContinuityProven === false,
    liveTopologyPreflightRecorded: liveTopologyEvidence?.status === 'READ_ONLY_LIVE_NODE_TOPOLOGY_PREFLIGHT_COMPLETED'
      && liveTopologyEvidence.databaseReadOnly === true
      && liveTopologyEvidence.productionChanged === false
      && liveTopologyEvidence.identifiersRedacted === true,
    threeDomainContinuityCanaryStaged: hasAll(liveServiceContinuityCanary, [
      'LIVE_CANARY_THREE_INDEPENDENT_RELAYS_REQUIRED',
      'selectRpcBlockQuorum',
      'selectManifestVoteQuorum',
      'verifyEndpointDirectoryQuorum',
      'runSignedServiceContinuityExchange',
      'LIVE_CANARY_THREE_CAPSULE_EXECUTIONS_FAILED',
      'LIVE_CANARY_THREE_SERVICE_SHELLS_FAILED'
    ]) && hasAll(liveServiceContinuityExecutor, [
      'minimumFailureDomains',
      'THREE_INDEPENDENT_PUBLIC_FAILURE_DOMAINS_REQUIRED',
      'findReachablePublicRelays',
      'serviceDirectoryEnabled: true',
      'revokeCanaryPolicyAndMappings',
      'FAILED_CANARY_POLICY_AND_MAPPINGS_REVOKED',
      'REVOCATION_PENDING_UNTIL_FALSE_POLICY_OR_1800_SECOND_LEASE',
      'THREE_DOMAIN_UPNP_RPC_DIRECTORY_CAPSULE_SHELL_PROVEN_AND_REVOKED',
      'writePolicy(buildPolicy(selected, false))'
    ]),
    twoDomainMainHostLossCanaryStaged: hasAll(liveServiceContinuityCanary, [
      'normalizeMinimumFailureDomains',
      'minimum === 2 && allowHttpForCanary === true',
      'LIVE_CANARY_FAILURE_DOMAIN_THRESHOLD_INVALID'
    ]) && hasAll(liveServiceContinuityExecutor, [
      "'failure-domain-loss', 'main-host-loss'",
      'MAIN_HOST_LOSS_ONLY_NOT_WAN_DOMAIN_LOSS',
      'TWO_DOMAIN_THREE_NODE_MAIN_HOST_LOSS_CANARY_PROVEN_AND_REVOKED',
      'upnpExternalPortsByNodeKeyId'
    ]) && hasAll(syncClientUpdateReleaseService, [
      'normalizeUpnpExternalPorts',
      'ROLLOUT_UPNP_EXTERNAL_PORT_INVALID',
      'port < 49152 || port > 65535'
    ]) && hasAll(syncClient, [
      'selectRuntimeUpnpExternalPort',
      'UPNP_EXTERNAL_PORT_NOT_ALLOWLISTED',
      'desiredExternalPort',
      'NewInternalPort: config.gatewayPort'
    ]),
    nodeBoundHttpsRelayPolicyStaged: hasAll(syncClientUpdateReleaseService, [
      'normalizePublicRelayUrls',
      'publicRelayUrlsByNodeKeyId',
      "url.protocol !== 'https:'",
      'origins.has',
      'admitted.has'
    ]) && hasAll(syncRoute, [
      'publicRelayUrlsByNodeKeyId: release.rollout.publicRelayUrlsByNodeKeyId || {}'
    ]) && hasAll(syncClient, [
      'selectRuntimePublicRelayUrl',
      'publicRelayUrlsByNodeKeyId',
      'Sync Client runtime public relay URL is invalid.',
      'ownNodeHttpsRelaySelected'
    ]),
    pcNodeHttps443RelayStaged: hasAll(syncClient, [
      '1.4.110-data-replica-readiness-attestation-default-off-locked',
      'startHttpsRelay',
      'validateHttpsRelayTlsMaterial',
      'httpsRelayRuntimeReady',
      'HTTPS_RELAY_PATH_REJECTED',
      'x-plai-https-relay-observed-address',
      "minVersion: 'TLSv1.2'",
      'authorizationCookieAndGatewayTokenStripped'
    ]) && hasAll(httpsRelayStagingPlan, [
      'plai-https-relay-staging-plan/v1',
      'HTTPS_RELAY_PLAN_SECRET_FIELD_REJECTED',
      'HTTPS_RELAY_PLAN_THREE_INDEPENDENT_RELAYS_REQUIRED',
      'PLAI_WEB_SERVICE_FAILOVER_ENABLED',
      'PLAI_SERVICE_FAILOVER_ENABLED',
      'activationAllowed: false'
    ]),
    stableBootstrapOriginPlanStaged: hasAll(stableBootstrapOriginPlan, [
      'plai-stable-bootstrap-origin-plan/v1',
      '1.4.110-data-replica-readiness-attestation-default-off-locked',
      'STABLE_BOOTSTRAP_SECRET_FIELD_REJECTED',
      'STABLE_BOOTSTRAP_THREE_INDEPENDENT_ORIGINS_REQUIRED',
      "hostname.endsWith('.trycloudflare.com')",
      'certificateAutoRenewalVerified',
      'restartRecoveryVerified',
      'controlPlaneFailureDomainCommitment',
      'activationAllowed: false'
    ]) && hasAll(stableBootstrapOriginPreparer, [
      'OFFLINE_STABLE_BOOTSTRAP_PLAN_VALIDATION',
      'READ_ONLY_STABLE_BOOTSTRAP_LIVE_PREFLIGHT',
      'STABLE_BOOTSTRAP_LIVE_IDENTITY_PROBE_FAILED',
      'operatorSigningUsed: false'
    ]),
    productionDataReplicaPlanStaged: hasAll(productionDataReplicaPlan, [
      'plai-production-data-replica-plan/v1',
      'DATA_REPLICA_SECRET_FIELD_REJECTED',
      'DATA_REPLICA_THREE_INDEPENDENT_NODES_REQUIRED',
      'privateTransportOnly',
      'mutualTlsReady',
      'diskEncryptionVerified',
      'isolatedRestoreWorkspaceReady',
      "writeConcern: 'majority'",
      "readConcern: 'majority'",
      "tlsMode: 'requireTLS'",
      'productionBackupReadAllowed: false',
      'externalCiphertextTransferAllowed: false',
      'applicationWriteSwitchAllowed: false'
    ]),
    finiteQuickTunnelDiscoveryStaged: hasAll(syncClient, [
      '1.4.110-data-replica-readiness-attestation-default-off-locked',
      'QUICK_TUNNEL_BINARY_SHA256',
      'quickTunnelCanaryPolicy',
      'manageQuickTunnelCanary',
      'plai-quick-tunnel-canary-status/v1',
      'QUICK_TUNNEL_PROCESS_CLEANUP_FAILED'
    ]) && hasAll(quickTunnelContinuityExecutor, [
      'EXECUTE_QUICK_TUNNEL_SERVICE_CANARY',
      'THREE_QUICK_TUNNEL_ORIGINS_AND_SIGNATURES_READY',
      'TWO_DOMAIN_THREE_NODE_HTTPS_QUICK_TUNNEL_CONTINUITY_PROVEN_AND_REVOKED',
      'THREE_DOMAIN_THREE_NODE_HTTPS_QUICK_TUNNEL_CONTINUITY_PROVEN_AND_REVOKED',
      'QUICK_TUNNEL_POLICY_AND_LEASES_REVOKED'
    ]),
    liveQuickTunnelReadOnlyContinuityProven: quickTunnelEvidence?.liveProof?.ok === true
      && quickTunnelEvidence.liveProof.readOnlyContinuityProven === true
      && quickTunnelEvidence.liveProof.actualMainServerOutagePerformed === false
      && quickTunnelEvidence.liveRuns?.some(row => row.result
        === 'TWO_DOMAIN_THREE_NODE_HTTPS_QUICK_TUNNEL_CONTINUITY_PROVEN_AND_REVOKED'
        && row.rpcVotes === 3 && row.manifestVotes === 3 && row.directorySources === 3
        && row.capsuleExecutions === 3 && row.serviceShells === 3 && row.revoked === true)
      && quickTunnelEvidence.safety?.allRemoteTunnelProcessesStopped === true
      && quickTunnelEvidence.safety?.allRemoteTunnelUrlsRemoved === true
      && quickTunnelEvidence.safety?.allRpcLeasesExpired === true,
    liveThreeDomainQuickTunnelReadOnlyContinuityProven: quickTunnelEvidence?.liveProof?.ok === true
      && quickTunnelEvidence.liveProof.proofClass === 'THREE_INDEPENDENT_WAN_DOMAIN_READ_ONLY_CONTINUITY'
      && quickTunnelEvidence.liveProof.threeIndependentWanDomainsProven === true
      && quickTunnelEvidence.liveRuns?.some(row => row.result
        === 'THREE_DOMAIN_THREE_NODE_HTTPS_QUICK_TUNNEL_CONTINUITY_PROVEN_AND_REVOKED'
        && row.observedFailureDomains === 3 && row.rpcVotes === 3 && row.manifestVotes === 3
        && row.directorySources === 3 && row.capsuleExecutions === 3
        && row.serviceShells === 3 && row.revoked === true)
      && quickTunnelEvidence.safety?.allRemoteTunnelProcessesStopped === true
      && quickTunnelEvidence.safety?.allRemoteTunnelUrlsRemoved === true
      && quickTunnelEvidence.safety?.allRpcLeasesExpired === true
      && quickTunnelEvidence.safety?.rolloutPolicyPresent === false,
    passiveServiceFleetFenceStaged: passiveFleetEvidence?.serviceCount === 5
      && passiveFleetEvidence.services?.every(row => row.primaryDefaultUnchanged === true
        && row.independentHealthReady === true && row.dynamicReadsFenced === true
        && row.writesFenced === true && row.socketsFenced === true && row.workersFenced === true
        && row.transactionSubmissionFenced === true && row.validatorRuntimeFenced === true)
      && passiveFleetEvidence.loopbackProcessCanary?.allProcessesStopped === true
      && passiveFleetEvidence.loopbackProcessCanary?.allPortsClosed === true,
    syntheticMongoThreeNodeFailoverProven: syntheticMongoEvidence?.status
      === 'SYNTHETIC_MONGO_THREE_NODE_MAJORITY_FAILOVER_PROVEN_AND_CLEANED'
      && syntheticMongoEvidence.replicaNodes === 3
      && syntheticMongoEvidence.majorityWriteBeforeFailure === true
      && syntheticMongoEvidence.differentPrimaryElected === true
      && syntheticMongoEvidence.majorityWriteAfterFailure === true
      && syntheticMongoEvidence.preFailureRecordPreserved === true
      && syntheticMongoEvidence.allMongodProcessesStopped === true
      && syntheticMongoEvidence.temporaryDataDeleted === true
      && syntheticMongoEvidence.productionMongoChanged === false,
    socketMongoClusterAdapterStaged: socketMongoAdapterEvidence?.adapter?.version === '0.4.0'
      && socketMongoAdapterEvidence.policy?.activationDefaultOff === true
      && socketMongoAdapterEvidence.policy?.standaloneMongoRejected === true
      && socketMongoAdapterEvidence.policy?.silentDowngradeAllowedWhenRequested === false
      && socketMongoAdapterEvidence.syntheticFailover?.broadcastBeforePrimaryFailure === true
      && socketMongoAdapterEvidence.syntheticFailover?.differentPrimaryElected === true
      && socketMongoAdapterEvidence.syntheticFailover?.broadcastAfterPrimaryFailure === true
      && socketMongoAdapterEvidence.productionAdapterActivated === false,
    promotedActiveDataPlaneGateStaged: promotedActiveGateEvidence?.status
      === 'FIVE_SERVICE_PROMOTED_ACTIVE_GATE_STAGED_DEFAULT_OFF'
      && promotedActiveGateEvidence.serviceCount === 5
      && promotedActiveGateEvidence.policy?.trafficClosedBeforeVerification === true
      && promotedActiveGateEvidence.policy?.mongoReplicaSetRequired === true
      && promotedActiveGateEvidence.policy?.standaloneMongoRejected === true
      && promotedActiveGateEvidence.aismallSessionPolicy?.promotedActiveUsesMongoReplicaSessionStoreWhenRedisUnavailable === true
      && promotedActiveGateEvidence.syntheticFailover?.gatesOpenedBeforePrimaryFailure === 5
      && promotedActiveGateEvidence.syntheticFailover?.gatesOpenedAfterPrimaryFailure === 5
      && promotedActiveGateEvidence.productionModeActivated === false,
    serviceMediaCiphertextReplicationPreflightStaged: serviceMediaEvidence?.status
      === 'FIVE_SERVICE_MEDIA_READ_ONLY_CONTENT_INVENTORY_COMPLETE'
      && serviceMediaEvidence.services?.length === 5
      && serviceMediaEvidence.totalFiles === 1060
      && serviceMediaEvidence.totalBytes === 10244305915
      && serviceMediaEvidence.pathsDisclosed === false
      && serviceMediaEvidence.externalTransfersMade === false
      && serviceMediaEvidence.syntheticCiphertextProof?.initialCiphertextReplicas === 3
      && serviceMediaEvidence.syntheticCiphertextProof?.initialFailureDomains === 3
      && serviceMediaEvidence.syntheticCiphertextProof?.ciphertextOnlyRepairToFourthDomain === true
      && serviceMediaEvidence.syntheticCiphertextProof?.restoredPlaintextHashVerified === true
      && serviceMediaEvidence.syntheticCiphertextProof?.tamperedCiphertextRejected === true
      && serviceMediaEvidence.syntheticCiphertextProof?.temporaryDataDeleted === true
      && serviceMediaPolicy?.activationAllowed === false
      && serviceMediaPolicy?.encryption?.storageNodeReceivesPlaintext === false
      && serviceMediaPolicy?.encryption?.storageNodeReceivesDecryptionKey === false
      && serviceMediaPolicy?.placement?.minimumCiphertextReplicas >= 3
      && serviceMediaPolicy?.placement?.minimumIndependentFailureDomains >= 3
      && serviceMediaPolicy?.repair?.minimumPeerVotes >= 3,
    signedEventProjectionStaged: hasAll(signedEventProjectionProtocol, [
      'signProjectionEvent',
      'verifyProjectionEvent',
      'rebuildProjection',
      'SIGNED_EVENT_FINALITY_REQUIRED',
      'SIGNED_EVENT_IDEMPOTENCY_CONFLICT',
      'projectionCommitment',
      'getTrustedIdentity',
      'lastVersions'
    ]),
    peerSignedRecoveryEventMailboxStaged: hasAll(peerSignedEventMailboxProtocol, [
      'signPeerEventVote',
      'aggregatePeerEventFinality',
      'rebuildPeerFinalizedProjection',
      'allowHistoricalFinality',
      'PEER_EVENT_VOTE_QUORUM_NOT_REACHED',
      'PEER_EVENT_FAILURE_DOMAIN_QUORUM_NOT_REACHED'
    ]) && hasAll(syncClient, [
      '/gateway/recovery-event/sign',
      '/gateway/recovery-event/proposal',
      '/gateway/recovery-event/vote',
      '/gateway/recovery-event/projection',
      'peerSignedEventMailboxEnabled',
      'rebuildEmbeddedRecoveryProjection',
      'RECOVERY_EVENT_PENDING_EQUIVOCATION_REJECTED',
      'RECOVERY_EVENT_STREAM_CAPACITY_REACHED'
    ]),
    signedRecoveryCheckpointStaged: hasAll(signedProjectionCheckpointProtocol, [
      'createProjectionCheckpoint',
      'signCheckpointVote',
      'aggregateCheckpointCertificate',
      'verifyCheckpointCertificate',
      'rebuildProjectionFromCheckpoint',
      'CHECKPOINT_EPOCH_ROLLBACK_REJECTED',
      'CHECKPOINT_EPOCH_EQUIVOCATION_REJECTED',
      'CHECKPOINT_PREVIOUS_COMMITMENT_MISMATCH',
      'versionFloors'
    ]) && hasAll(syncClient, [
      '/gateway/recovery-event/checkpoint/create',
      '/gateway/recovery-event/checkpoint/proposal',
      '/gateway/recovery-event/checkpoint/vote',
      '/gateway/recovery-event/checkpoint',
      'aggregateEmbeddedRecoveryCheckpointCertificate',
      'verifyEmbeddedRecoveryCheckpointCertificate',
      'RECOVERY_CHECKPOINT_VOTE_QUORUM_NOT_REACHED',
      'RECOVERY_CHECKPOINT_FAILURE_DOMAIN_QUORUM_NOT_REACHED',
      'RECOVERY_CHECKPOINT_EPOCH_ROLLBACK_REJECTED',
      'RECOVERY_CHECKPOINT_EPOCH_EQUIVOCATION_REJECTED',
      'checkpointStateCompacted',
      'checkpointTailContinuationVerified'
    ])
  };

  const gaps = [
    {
      id: 'CENTRAL_MANIFEST_ORIGIN',
      blocks: ['MAIN_SERVER_INDEPENDENT_DISCOVERY'],
      evidence: 'The approved candidate 1.4.109 live canary obtained three distinct public HTTPS origins across three independent WAN failure domains and verified three RPC votes, three manifest votes, three directory sources, three stateless capsule executions and three read-only service shells. Every temporary tunnel, lease and rollout policy was then revoked. Quick Tunnel origins are ephemeral and are not active production bootstrap origins.',
      required: 'Replace the development-only temporary origins with at least three stable publicly trusted HTTPS 443 relay/bootstrap origins, bind them to admitted node keys, and distribute the signed directory through main-independent bootstrap paths.'
    },
    {
      id: 'CENTRAL_REPLICA_CONTROL_PLANE',
      blocks: ['MAIN_INDEPENDENT_REPLICA_SELF_HEAL'],
      evidence: 'Three-node ciphertext storage, fourth-node replenishment and cache-withheld restore are live-proven. A default-OFF PC mailbox now validates admission-backed storage candidates, deterministically elects repair nodes, requires 3 peer votes across at least 2 failure domains, and emits an expiring fencing token. Pure protocol receipts reject unselected nodes and ciphertext tampering. Live ciphertext repair without the main server remains unproven.',
      required: 'With explicit public-PC approval, exchange the signed repair proposal/votes/certificate, transfer ciphertext only to selected nodes under the fencing lease, and prove the repaired manifest from peer state while the main server is unavailable.'
    },
    {
      id: 'NO_PUBLIC_KEY_OFFLINE_MANIFEST_VERIFICATION',
      blocks: ['UNTRUSTED_PEER_DISCOVERY'],
      evidence: 'The live Quick Tunnel canary exchanged admitted-node Ed25519 manifest votes bound to a three-node RPC quorum and read the same verified directory from all three PCs. Android compiles direct SPKI/nodeKeyId/canonical-claim/signature verification and fails closed when Ed25519 is unavailable, but physical-device consumption remains unproven.',
      required: 'Run the verifier on a physical Android device and attach the accepted live bundle to the peer-cached endpoint manifest through stable authenticated bootstrap paths.'
    },
    {
      id: 'NO_CAPABILITY_ROLE_LEASE',
      blocks: ['DYNAMIC_SERVICE_AND_RPC_ASSIGNMENT'],
      evidence: 'Node-self-signed short leases, isolated encrypted storage challenge, real HTTP endpoint probing, a default-OFF witness mailbox, 3-witness/2-failure-domain admission aggregation, eligibility certificate exchange, and next-epoch witness rotation are staged and self-tested in the PC candidate. Same-epoch circular admission and 2-witness quorum are rejected. A fixed three-node canary consumed a verified service directory live, but dynamic public-PC admission exchange remains unproven.',
      required: 'Exchange challenge/witness/admission/eligibility certificates through authenticated outbound sessions, publish only unexpired dynamically admitted endpoints, and prove lease-expiry removal.'
    },
    {
      id: 'CENTRAL_MUTABLE_DATA_AND_SECRETS',
      blocks: ['PERMISSIONLESS_WRITES'],
      evidence: 'The signed recovery projection and checkpoint protocols remain default-off. Five services now have passive and promoted-active fail-closed gates. A synthetic 3-node Mongo replica set proved majority writes, Socket.IO broadcasts, five promotion gates, and AISMALL shared Mongo sessions before and after primary loss. A read-only live inventory found four storage-and-supervisor eligible PCs across three independent network failure domains. The default-off production data plan requires private mTLS transport, disk encryption and isolated restore workspaces, but authenticated evidence for those controls is not provisioned. Production application writes and uploads have not been migrated.',
      required: 'Provision mTLS, disk-encryption evidence and isolated restore workspaces on three eligible independent PCs, prove a production backup restore in isolation, execute and verify ciphertext media replication, then run a separately approved non-secret write canary under fencing before any production migration.'
    },
    {
      id: 'CLIENT_SINGLE_ENDPOINT_DEPENDENCY',
      blocks: ['MAIN_SERVER_OUTAGE_CONTINUITY'],
      evidence: 'Android has a compiled default-OFF native verified-directory cache, main-frame failure hook, and three-source HTTPS bootstrap client. Web/TWA retains HTTPS-only WebCrypto verification, rollback protection, service-worker proof revalidation and PC shell failover. Three temporary HTTPS PC origins and service shells were live-proven, but stable independent URLs are absent and no physical Android or browser exchange is proven.',
      required: 'Provision three independent HTTPS bootstrap origins and pinned root keys under an approved canary, verify the same 2-of-3 signed bundle on physical Android and Web/TWA, then prove both clients reach admitted PC service shells without the main domain.'
    },
    {
      id: 'PC_RPC_NAT_REACHABILITY',
      blocks: ['DIRECT_MULTI_PC_RPC_ACCESS'],
      evidence: 'The approved candidate 1.4.109 canary proved three outbound HTTPS origins, node-bound RPC certificates, signed directory exchange, three capsule executions and three service shells across three independent WAN failure domains. All tunnel processes, URLs, leases and rollout policy were revoked. This proves NAT-safe finite three-domain read-only reachability but not continuously available production ingress.',
      required: 'For production, replace Quick Tunnel with at least three stable multi-provider or independently controlled HTTPS origins and keep their failure domains independent.'
    }
  ];

  const policyValid = policy.schemaVersion === 'plai-permissionless-node-policy/v1'
    && policy.fixedNodeAllowlistAllowed === false
    && policy.productionActivationAllowed === false
    && policy.roles.storage.minimumReplicaCount >= 3
    && policy.discovery.mainServerRequiredAfterBootstrap === false
    && policy.dataPlane.arbitraryNodeDirectMongoAccessAllowed === false
    && policy.roles.validator.automaticPromotionAllowed === false;

  const output = {
    ok: policyValid && Object.values(foundations).every(Boolean),
    mode: 'READ_ONLY_SOURCE_CAPABILITY_GAP_ANALYSIS',
    target: policy.goal,
    policyValid,
    foundations,
    currentContinuity: false,
    hostnamePinnedProductionTarget: false,
    liveTopology: liveTopologyEvidence ? {
      freshNodes: liveTopologyEvidence.freshNodes,
      runtimeReadyNodes: liveTopologyEvidence.runtimeReadyNodes,
      runtimeReadyFailureDomains: liveTopologyEvidence.runtimeReadyFailureDomains,
      mainHostLossCanaryTopologyReady: liveTopologyEvidence.mainHostLossCanaryTopologyReady,
      mainHostLossCanaryReachabilityReady: quickTunnelEvidence?.liveProof?.readOnlyContinuityProven === true,
      threeIndependentFailureDomainsReady: liveTopologyEvidence.threeIndependentFailureDomainsReady,
      threeIndependentWanCanaryProven: quickTunnelEvidence?.liveProof?.threeIndependentWanDomainsProven === true,
      currentBlocker: 'STABLE_THREE_DOMAIN_HTTPS_ORIGINS_CLIENT_BOOTSTRAP_AND_PRODUCTION_DATA_HA_REQUIRED'
    } : null,
    gapCount: gaps.length,
    gaps,
    nextSafeSlice: [
      'Provision stable independent publicly trusted HTTPS 443 relay/bootstrap origins without changing production DNS traffic.',
      'Distribute the live verified directory to Android through at least three authenticated bootstrap/peer paths.',
      'Provision authenticated Mongo replica candidates on independent PCs and rehearse a production backup restore without switching application writes.',
      'Use the staged promoted-active gate with shared Mongo sessions and the Mongo Socket adapter only after authenticated replica-set rehearsal.',
      'Replicate upload/media ciphertext and verify hashes from passive PCs before enabling dynamic routes.',
      'Run a controlled main-unavailable isolation canary only under an explicit outage window.',
      'Do not activate service writes, public traffic, validator promotion, or operator signing.'
    ],
    safety: {
      environmentRead: false,
      databaseConnected: false,
      networkRequestsMade: false,
      filesWritten: false,
      productionChanged: false
    },
    checkedAt: new Date().toISOString()
  };

  process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
  if (!output.ok) process.exitCode = 1;
}

main();
