#!/usr/bin/env node

import {
  createHash,
  createPublicKey,
  randomBytes,
  verify as verifyEd25519,
} from "node:crypto";
import {
  closeSync,
  constants as fsConstants,
  existsSync,
  fstatSync,
  fsyncSync,
  lstatSync,
  mkdirSync,
  openSync,
  readFileSync,
  readSync,
  realpathSync,
  renameSync,
  rmdirSync,
  unlinkSync,
  writeFileSync,
} from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";

const EMBEDDED_RELEASE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAkWWjt3wneNm/PquRK+EFfKmZ0cO2fAUno+AdlbUwFR0=
-----END PUBLIC KEY-----
`;
const EMBEDDED_RELEASE_KEY_ID = "marketingos-release-ed25519:7a86d8252d6eca79bc287e974040a538";
const EMBEDDED_RELEASE_SPKI_SHA256 = "7a86d8252d6eca79bc287e974040a538d91c902d01ef9fab5a98cc0e8fe4757e";
const REVIEWED_ENTITLEMENT_KEY_ID = "marketingos-license-ed25519:6bc532ff47868c3fe1046d3b5355dfb7";
const REVIEWED_ENTITLEMENT_SPKI_SHA256 = "6bc532ff47868c3fe1046d3b5355dfb7c5960f834d56efcdea018af91cdc4072";
const REVIEWED_REVOCATION_KEY_ID = "marketingos-revocation-ed25519:94f1adca2df84a9e647a499cdbe16682";
const REVIEWED_REVOCATION_SPKI_SHA256 = "94f1adca2df84a9e647a499cdbe1668221c9f117a4691e12e1b5ebc97554bdc1";
const BOOTSTRAP_NAME = "marketingos-release-verify.mjs";
const MINIMUM_NODE_VERSION = "22.19.0";
const RELEASE_SIGNATURE_SCHEMA = "marketingos.releaseSignature.v1";
const CHANNEL_SCHEMA = "marketingos.releaseChannel.v1";
const CHANNEL_SIGNATURE_SCHEMA = "marketingos.releaseChannelSignature.v1";
const CHANNEL_STATE_SCHEMA = "marketingos.releaseChannelState.v1";
const EXTERNAL_BOOTSTRAP_RECEIPT_SCHEMA =
  "marketingos.externalBootstrapReceipt.v1";
const PIN_SCHEMA = "marketingos.trustPinPublication.v1";
const MAX_JSON_BYTES = 4 * 1024 * 1024;
const MAX_VALIDITY_MS = 45 * 24 * 60 * 60 * 1000;
const CLOCK_SKEW_MS = 5 * 60 * 1000;
const WEBSITE_PIN_URL = "https://marketingos.scilipoti.de/trust/marketingos-trust-pins.v1.json";
const DNS_PIN_NAME = "_marketingos-trust.marketingos.scilipoti.de";
const ACQUISITION_NAME = "marketingos-release-acquire.mjs";
const VERIFICATION_BOUNDARY = "Compare the verifier SHA256 through an independent MarketingOS channel before running it. The verifier cannot establish trust in its own bytes.";
const reparseChecks = new Set();

function main() {
  assertVersionAtLeast(process.versions.node, MINIMUM_NODE_VERSION, "Node.js");
  const args = parseArguments(process.argv.slice(2));
  if (args.help) {
    process.stdout.write(helpText());
    return;
  }

  const artifactPath = path.resolve(args.artifact);
  const pinPath = path.resolve(args.pin);
  const selfPath = path.resolve(process.argv[1]);
  const pin = readSecureJson(pinPath, "trust pin publication");
  validateTrustPin(pin, { requirePublished: args.requirePublished === true });
  const selfDigest = secureDigestFile(selfPath, "verifier");
  if (path.basename(selfPath) !== pin.bootstrap.name
    || selfDigest.bytes !== pin.bootstrap.bytes
    || selfDigest.sha256 !== pin.bootstrap.sha256) {
    throw new Error("Verifier bytes do not match the independently published pin");
  }
  if (pin.bootstrap.minimumNodeVersion !== MINIMUM_NODE_VERSION) {
    throw new Error("Trust pin Node.js minimum does not match the reviewed verifier");
  }

  const publicKey = validateEmbeddedReleaseKey(pin.releaseKey);
  const releaseFiles = expectedReleaseFiles(artifactPath);
  const manifest = readSecureJson(releaseFiles.channelManifest, "release channel manifest");
  const channelSignature = readSecureJson(releaseFiles.channelSignature, "release channel signature");
  validateChannelManifest(manifest, releaseFiles, pin);
  validateChannelSignature(channelSignature, manifest, releaseFiles, publicKey);
  validateChannelTime(manifest);
  const statePath = args.state ? path.resolve(args.state) : null;
  if (statePath && existsSync(statePath)) {
    assertPrivateStateFileBoundary(statePath, "release channel state");
  }
  const stateLock = statePath ? acquireSequenceStateLock(statePath) : null;
  try {
    runBootstrapTestPauseAfterStateLock();
    validateSequence(manifest, pin, statePath, releaseFiles.channelManifest);
    assertVersionAtLeast(process.versions.node, manifest.minimumVersions.node, "Node.js");

    const channelRecords = new Map([
      ["artifact", manifest.artifact],
      ...manifest.sidecars.map((record) => [record.kind, record]),
    ]);
    const actualDigests = new Map();
    for (const [kind, record] of channelRecords) {
      const target = releaseFiles.byKind[kind];
      const digest = secureDigestFile(target, `release ${kind}`);
      if (digest.bytes !== record.bytes || digest.sha256 !== record.sha256) {
        throw new Error(`Release channel digest mismatch for ${record.name}`);
      }
      actualDigests.set(kind, digest);
    }
    const checksumText = secureReadFile(releaseFiles.byKind.checksum, "checksum", 1024).toString("utf8");
    const expectedChecksum = `${manifest.artifact.sha256}  ${manifest.artifact.name}\n`;
    if (checksumText !== expectedChecksum) throw new Error("Checksum sidecar content is not canonical");

    const releaseEnvelope = readSecureJson(releaseFiles.byKind["release-signature"], "release signature");
    validateReleaseSignature(releaseEnvelope, manifest, releaseFiles, actualDigests, publicKey);

    const manifestDigest = secureDigestFile(releaseFiles.channelManifest, "release channel manifest");
    if (statePath) recordSequenceState(statePath, manifest, manifestDigest.sha256, stateLock);
    const receipt = args.receipt
      ? writeExternalBootstrapReceipt({
          receiptPath: path.resolve(args.receipt),
          artifactPath,
          pinPath,
          selfPath,
          selfDigest,
          manifest,
          manifestDigest,
          channelSignature,
          releaseFiles,
          actualDigests,
        })
      : null;
    process.stdout.write(`${JSON.stringify({
      ok: true,
      product: "MarketingOS",
      channel: manifest.channel,
      sequence: manifest.sequence,
      version: manifest.version,
      platform: manifest.platform,
      architecture: manifest.architecture,
      artifact: manifest.artifact.name,
      artifactSha256: manifest.artifact.sha256,
      releaseKeyId: EMBEDDED_RELEASE_KEY_ID,
      minimumVersions: manifest.minimumVersions,
      expiresAt: manifest.expiresAt,
      sequenceState: statePath,
      externalBootstrapReceipt: receipt?.path || null,
      externalBootstrapReceiptSha256: receipt?.sha256 || null,
    }, null, 2)}\n`);
  } finally {
    if (stateLock) releaseSequenceStateLock(stateLock);
  }
}

function parseArguments(values) {
  const result = Object.create(null);
  for (let index = 0; index < values.length; index += 1) {
    const value = values[index];
    if (value === "--help" || value === "-h") {
      result.help = true;
      continue;
    }
    if (value === "--require-published") {
      if (result.requirePublished)
        throw new Error("--require-published may only be supplied once");
      result.requirePublished = true;
      continue;
    }
    if (!["--artifact", "--pin", "--state", "--receipt"].includes(value)) throw new Error(`Unknown argument: ${value}`);
    const next = values[index + 1];
    if (!next || next.startsWith("--")) throw new Error(`${value} requires a value`);
    const key = value.slice(2);
    if (result[key]) throw new Error(`${value} may only be supplied once`);
    result[key] = next;
    index += 1;
  }
  if (!result.help && (!result.artifact || !result.pin)) throw new Error("--artifact and --pin are required");
  return result;
}

function helpText() {
  return `MarketingOS external release verifier\n\nUsage:\n  node ${BOOTSTRAP_NAME} --artifact <release.zip|release.tar.gz> --pin <marketingos-trust-pins.v1.json> [--state <channel-state.json>] [--receipt <external-bootstrap-receipt.json>] [--require-published]\n\nThe verifier derives every sidecar name from the canonical Windows ZIP or POSIX TAR.GZ name. Production acquisition supplies --require-published. Offline preparation tests may deliberately validate prepared-not-live trust pins without that flag. Compare this verifier's SHA256 through an independent MarketingOS channel before running it. A receipt records this completed external verification but is not itself a publisher signature. Moving the bundle requires revalidation and a new receipt.\n`;
}

function writeExternalBootstrapReceipt({
  receiptPath,
  artifactPath,
  pinPath,
  selfPath,
  selfDigest,
  manifest,
  manifestDigest,
  channelSignature,
  releaseFiles,
  actualDigests,
}) {
  const bundleDirectory = realpathSync.native(path.dirname(artifactPath));
  const pinDigest = secureDigestFile(pinPath, "trust pin publication");
  const channelSignatureDigest = secureDigestFile(
    releaseFiles.channelSignature,
    "release channel signature",
  );
  const files = [
    manifest.artifact,
    ...manifest.sidecars,
    {
      kind: "release-channel",
      name: path.basename(releaseFiles.channelManifest),
      bytes: manifestDigest.bytes,
      sha256: manifestDigest.sha256,
    },
    {
      kind: "release-channel-signature",
      name: path.basename(releaseFiles.channelSignature),
      bytes: channelSignatureDigest.bytes,
      sha256: channelSignatureDigest.sha256,
    },
  ];
  for (const record of files.slice(0, 6)) {
    const observed = actualDigests.get(record.kind);
    if (!observed || observed.bytes !== record.bytes || observed.sha256 !== record.sha256) {
      throw new Error(`External receipt cannot bind an unverified release file: ${record.name}`);
    }
  }
  const unsigned = {
    schemaVersion: EXTERNAL_BOOTSTRAP_RECEIPT_SCHEMA,
    generatedAt: new Date().toISOString(),
    product: "MarketingOS",
    verificationBoundary:
      "This receipt records a completed external verification. Publisher authenticity comes from the reviewed verifier and official signatures, not from this receipt.",
    relocationPolicy:
      "The exact bundle directory is bound. Moving the artifact or sidecars requires external revalidation and a new receipt.",
    bundleDirectory: {
      path: bundleDirectory,
      pathSha256: createHash("sha256")
        .update(normalizedPathIdentity(bundleDirectory), "utf8")
        .digest("hex"),
    },
    artifact: {
      name: manifest.artifact.name,
      bytes: manifest.artifact.bytes,
      sha256: manifest.artifact.sha256,
    },
    files,
    publisherKey: {
      algorithm: "Ed25519",
      keyId: EMBEDDED_RELEASE_KEY_ID,
      spkiSha256: EMBEDDED_RELEASE_SPKI_SHA256,
    },
    channel: {
      name: manifest.channel,
      sequence: manifest.sequence,
      issuedAt: manifest.issuedAt,
      expiresAt: manifest.expiresAt,
      manifestSha256: manifestDigest.sha256,
      signatureSha256: channelSignatureDigest.sha256,
      signatureKeyId: channelSignature.keyId,
    },
    pin: {
      path: realpathSync.native(pinPath),
      bytes: pinDigest.bytes,
      sha256: pinDigest.sha256,
    },
    verifier: {
      path: realpathSync.native(selfPath),
      name: path.basename(selfPath),
      bytes: selfDigest.bytes,
      sha256: selfDigest.sha256,
    },
  };
  const receipt = {
    ...unsigned,
    receiptHash: createHash("sha256")
      .update(canonicalJson(unsigned), "utf8")
      .digest("hex"),
  };
  const target = path.resolve(receiptPath);
  const lock = acquireSequenceStateLock(target);
  try {
    atomicSecureJson(target, receipt, lock);
  } finally {
    releaseSequenceStateLock(lock);
  }
  const digest = secureDigestFile(target, "external bootstrap receipt");
  return Object.freeze({ path: target, sha256: digest.sha256 });
}

function normalizedPathIdentity(value) {
  const resolved = path.resolve(value);
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}

function expectedReleaseFiles(artifactPath) {
  const artifactName = path.basename(artifactPath);
  assertSafeBasename(artifactName, "artifact filename");
  const windowsZip = /^MarketingOS-Alpha-[A-Za-z0-9][A-Za-z0-9._-]*-windows-x64\.zip$/.test(artifactName);
  const portableTar = /^MarketingOS-Alpha-[A-Za-z0-9][A-Za-z0-9._-]*-(?:linux|macos)-(?:x64|arm64)\.tar\.gz$/.test(artifactName);
  const witnessTar = /^MarketingOS-Audit-Witness-[A-Za-z0-9][A-Za-z0-9._-]*-linux-(?:x64|arm64)\.tar\.gz$/.test(artifactName);
  if (!windowsZip && !portableTar && !witnessTar) {
    throw new Error("Artifact filename must be one canonical MarketingOS Windows ZIP or POSIX TAR.GZ");
  }
  const directory = path.dirname(artifactPath);
  const stem = windowsZip ? artifactName.slice(0, -4) : artifactName;
  const names = {
    artifact: artifactName,
    checksum: `${artifactName}.sha256`,
    "release-evidence": `${stem}.release-evidence.json`,
    sbom: `${stem}.sbom.cdx.json`,
    provenance: `${stem}.intoto.json`,
    "release-signature": `${stem}.signature.json`,
  };
  const byKind = Object.fromEntries(Object.entries(names).map(([kind, name]) => [kind, resolveReleaseFile(directory, name)]));
  return Object.freeze({
    directory,
    stem,
    names,
    byKind,
    channelManifest: resolveReleaseFile(directory, `${stem}.channel.json`),
    channelSignature: resolveReleaseFile(directory, `${stem}.channel.signature.json`),
  });
}

function resolveReleaseFile(directory, name) {
  assertSafeBasename(name, "release filename");
  const root = path.resolve(directory);
  const target = path.resolve(root, name);
  if (path.dirname(target) !== root) throw new Error("Release filename escapes the artifact directory");
  return target;
}

function validateTrustPin(pin, { requirePublished = false } = {}) {
  exactKeys(pin, [
    "acquisition",
    "bootstrap",
    "channels",
    "entitlementKey",
    "product",
    "publicationStatus",
    "publicationVersion",
    "publications",
    "releaseKey",
    "revocationKey",
    "schemaVersion",
    "verificationBoundary",
  ], "trust pin publication");
  if (pin.schemaVersion !== PIN_SCHEMA || pin.product !== "MarketingOS") throw new Error("Trust pin publication schema is invalid");
  if (!Number.isSafeInteger(pin.publicationVersion) || pin.publicationVersion < 1) throw new Error("Trust pin publication version is invalid");
  if (!["prepared-not-live", "published"].includes(pin.publicationStatus)) throw new Error("Trust pin publication status is invalid");
  if (requirePublished && pin.publicationStatus !== "published") throw new Error("Published trust pin publication is required");
  if (pin.verificationBoundary !== VERIFICATION_BOUNDARY) throw new Error("Trust pin verification boundary is invalid");

  exactKeys(pin.acquisition, ["bytes", "minimumNodeVersion", "name", "reviewStatus", "runtime", "sha256"], "trust pin acquisition bootstrap");
  if (pin.acquisition.name !== ACQUISITION_NAME || pin.acquisition.runtime !== "Node.js" || pin.acquisition.reviewStatus !== "reviewed") {
    throw new Error("Trust pin acquisition bootstrap identity is invalid");
  }
  assertDigestRecord(pin.acquisition, "trust pin acquisition bootstrap");
  requireVersion(pin.acquisition.minimumNodeVersion, "trust pin acquisition minimumNodeVersion");

  exactKeys(pin.bootstrap, ["bytes", "minimumNodeVersion", "name", "reviewStatus", "runtime", "sha256"], "trust pin bootstrap");
  if (pin.bootstrap.name !== BOOTSTRAP_NAME || pin.bootstrap.runtime !== "Node.js" || pin.bootstrap.reviewStatus !== "reviewed") {
    throw new Error("Trust pin bootstrap identity is invalid");
  }
  assertDigestRecord(pin.bootstrap, "trust pin bootstrap");
  requireVersion(pin.bootstrap.minimumNodeVersion, "trust pin minimumNodeVersion");

  exactKeys(pin.releaseKey, ["algorithm", "changePolicy", "keyId", "spkiSha256"], "trust pin release key");
  if (pin.releaseKey.algorithm !== "Ed25519"
    || pin.releaseKey.changePolicy !== "manual-independent-publication-required"
    || pin.releaseKey.keyId !== EMBEDDED_RELEASE_KEY_ID
    || pin.releaseKey.spkiSha256 !== EMBEDDED_RELEASE_SPKI_SHA256) {
    throw new Error("Trust pin release key does not match the reviewed verifier key");
  }
  validatePublishedPurposeKey(pin.entitlementKey, {
    label: "entitlement key",
    purpose: "offline-addon-entitlements",
    keyId: REVIEWED_ENTITLEMENT_KEY_ID,
    spkiSha256: REVIEWED_ENTITLEMENT_SPKI_SHA256,
  });
  validatePublishedPurposeKey(pin.revocationKey, {
    label: "revocation key",
    purpose: "signed-entitlement-revocation-snapshots",
    keyId: REVIEWED_REVOCATION_KEY_ID,
    spkiSha256: REVIEWED_REVOCATION_SPKI_SHA256,
  });

  if (!Array.isArray(pin.channels) || pin.channels.length < 1 || pin.channels.length > 8) throw new Error("Trust pin channels are invalid");
  const seenChannels = new Set();
  let previous = "";
  for (const record of pin.channels) {
    exactKeys(record, ["channel", "minimumSequence"], "trust pin channel");
    requireChannel(record.channel, "trust pin channel");
    if (!Number.isSafeInteger(record.minimumSequence) || record.minimumSequence < 1) throw new Error("Trust pin minimum sequence is invalid");
    if (seenChannels.has(record.channel) || (previous && record.channel.localeCompare(previous, "en") <= 0)) {
      throw new Error("Trust pin channels must be unique and sorted");
    }
    seenChannels.add(record.channel);
    previous = record.channel;
  }

  exactKeys(pin.publications, ["dns", "website"], "trust pin publications");
  exactKeys(pin.publications.website, ["kind", "locator"], "website publication");
  exactKeys(pin.publications.dns, ["kind", "locator", "records"], "DNS publication");
  if (pin.publications.website.kind !== "https" || pin.publications.website.locator !== WEBSITE_PIN_URL
    || pin.publications.dns.kind !== "dns-txt" || pin.publications.dns.locator !== DNS_PIN_NAME) {
    throw new Error("Trust pin publication locators are invalid");
  }
  const expectedRecords = expectedDnsRecords(pin);
  if (!Array.isArray(pin.publications.dns.records)
    || pin.publications.dns.records.length !== expectedRecords.length
    || pin.publications.dns.records.some((record, index) => record !== expectedRecords[index] || Buffer.byteLength(record, "utf8") > 255)) {
    throw new Error("Trust pin DNS records are not reproducible");
  }
}

function validatePublishedPurposeKey(value, expected) {
  exactKeys(value, ["algorithm", "changePolicy", "keyId", "purpose", "spkiSha256"], `trust pin ${expected.label}`);
  if (value.algorithm !== "Ed25519"
    || value.changePolicy !== "manual-independent-publication-required"
    || value.purpose !== expected.purpose
    || value.keyId !== expected.keyId
    || value.spkiSha256 !== expected.spkiSha256) {
    throw new Error(`Trust pin ${expected.label} is invalid`);
  }
}

function expectedDnsRecords(pin) {
  const sequences = pin.channels.map((entry) => `${entry.channel}-min-sequence=${entry.minimumSequence}`).join("; ");
  return [
    `v=marketingos1; acquisition-sha256=${pin.acquisition.sha256}; verifier-sha256=${pin.bootstrap.sha256}`,
    `release-spki-sha256=${pin.releaseKey.spkiSha256}; entitlement-spki-sha256=${pin.entitlementKey.spkiSha256}`,
    `revocation-spki-sha256=${pin.revocationKey.spkiSha256}; ${sequences}`,
  ];
}

function validateEmbeddedReleaseKey(pinKey) {
  const key = createPublicKey(EMBEDDED_RELEASE_PUBLIC_KEY_PEM);
  if (key.asymmetricKeyType !== "ed25519") throw new Error("Embedded release key is not Ed25519");
  const digest = createHash("sha256").update(key.export({ type: "spki", format: "der" })).digest("hex");
  const derivedKeyId = `marketingos-release-ed25519:${digest.slice(0, 32)}`;
  if (digest !== EMBEDDED_RELEASE_SPKI_SHA256 || derivedKeyId !== EMBEDDED_RELEASE_KEY_ID
    || pinKey.spkiSha256 !== digest || pinKey.keyId !== derivedKeyId) {
    throw new Error("Embedded release key identity is inconsistent");
  }
  return key;
}

function validateChannelManifest(manifest, files, pin) {
  exactKeys(manifest, [
    "architecture",
    "artifact",
    "channel",
    "expiresAt",
    "issuedAt",
    "minimumVersions",
    "platform",
    "product",
    "releaseKey",
    "schemaVersion",
    "sequence",
    "sidecars",
    "version",
  ], "release channel manifest");
  if (manifest.schemaVersion !== CHANNEL_SCHEMA || manifest.product !== "MarketingOS") throw new Error("Release channel manifest schema is invalid");
  if (!Number.isSafeInteger(manifest.sequence) || manifest.sequence < 1) throw new Error("Release channel sequence is invalid");
  requireChannel(manifest.channel, "release channel");
  requireVersion(manifest.version, "release version");
  if (!["win32", "linux", "darwin"].includes(manifest.platform)) throw new Error("Release platform is invalid");
  if (!["x64", "arm64"].includes(manifest.architecture)) throw new Error("Release architecture is invalid");
  const platformLabel = manifest.platform === "win32"
    ? "windows"
    : manifest.platform === "darwin"
      ? "macos"
      : "linux";
  const artifactLabel = files.names.artifact.startsWith("MarketingOS-Audit-Witness-")
    ? "MarketingOS-Audit-Witness"
    : "MarketingOS-Alpha";
  const expectedArtifactName = `${artifactLabel}-${manifest.version}-${platformLabel}-${manifest.architecture}${manifest.platform === "win32" ? ".zip" : ".tar.gz"}`;
  if (files.names.artifact !== expectedArtifactName) {
    throw new Error("Signed release identity does not match its canonical artifact filename");
  }
  const issued = parseIsoInstant(manifest.issuedAt, "release issuedAt");
  const expires = parseIsoInstant(manifest.expiresAt, "release expiresAt");
  if (expires <= issued || expires - issued > MAX_VALIDITY_MS) throw new Error("Release channel validity is invalid");

  exactKeys(manifest.minimumVersions, ["hermes", "node", "openclaw"], "release minimum versions");
  for (const [runtime, version] of Object.entries(manifest.minimumVersions)) requireVersion(version, `minimum ${runtime} version`);
  if (compareVersions(manifest.minimumVersions.node, pin.bootstrap.minimumNodeVersion) < 0) {
    throw new Error("Release Node.js minimum is below the trust bootstrap minimum");
  }
  exactKeys(manifest.releaseKey, ["algorithm", "keyId", "spkiSha256"], "release key metadata");
  if (manifest.releaseKey.algorithm !== "Ed25519"
    || manifest.releaseKey.keyId !== EMBEDDED_RELEASE_KEY_ID
    || manifest.releaseKey.spkiSha256 !== EMBEDDED_RELEASE_SPKI_SHA256) {
    throw new Error("Release channel attempts an unapproved key change");
  }

  validateFileRecord(manifest.artifact, "artifact", files.names.artifact, "artifact record");
  const expectedKinds = ["checksum", "release-evidence", "sbom", "provenance", "release-signature"];
  if (!Array.isArray(manifest.sidecars) || manifest.sidecars.length !== expectedKinds.length) throw new Error("Release channel sidecars are incomplete");
  const names = new Set([manifest.artifact.name]);
  for (let index = 0; index < expectedKinds.length; index += 1) {
    const kind = expectedKinds[index];
    const record = manifest.sidecars[index];
    validateFileRecord(record, kind, files.names[kind], `sidecar ${kind}`);
    if (names.has(record.name)) throw new Error("Release channel filenames are not unique");
    names.add(record.name);
  }
}

function validateChannelSignature(envelope, manifest, files, publicKey) {
  exactKeys(envelope, ["algorithm", "keyId", "schemaVersion", "signature", "signedAt", "subject"], "release channel signature");
  if (envelope.schemaVersion !== CHANNEL_SIGNATURE_SCHEMA || envelope.algorithm !== "Ed25519" || envelope.keyId !== EMBEDDED_RELEASE_KEY_ID) {
    throw new Error("Release channel signature identity is invalid");
  }
  if (envelope.signedAt !== manifest.issuedAt) throw new Error("Release channel signature timestamp does not match issuedAt");
  parseIsoInstant(envelope.signedAt, "release channel signedAt");
  exactKeys(envelope.subject, ["bytes", "kind", "name", "sha256"], "release channel signature subject");
  validateFileRecord(envelope.subject, "release-channel", `${files.stem}.channel.json`, "release channel signature subject");
  const digest = secureDigestFile(files.channelManifest, "release channel manifest");
  if (digest.bytes !== envelope.subject.bytes || digest.sha256 !== envelope.subject.sha256) {
    throw new Error("Release channel manifest does not match its signed subject");
  }
  verifyEnvelopeSignature(envelope, publicKey, "release channel");
}

function validateChannelTime(manifest) {
  const now = Date.now();
  const issued = parseIsoInstant(manifest.issuedAt, "release issuedAt");
  const expires = parseIsoInstant(manifest.expiresAt, "release expiresAt");
  if (issued > now + CLOCK_SKEW_MS) throw new Error("Release channel has not been issued yet");
  if (expires <= now) throw new Error("Release channel manifest has expired");
}

function validateSequence(manifest, pin, statePath, manifestPath) {
  const pinRecord = pin.channels.find((entry) => entry.channel === manifest.channel);
  if (!pinRecord) throw new Error(`Release channel ${manifest.channel} is not present in the independently published pin`);
  if (manifest.sequence < pinRecord.minimumSequence) throw new Error("Release channel sequence is below the independently published minimum");
  if (!statePath || !existsSync(statePath)) return;
  const state = readValidatedSequenceState(statePath, manifest);
  const manifestDigest = secureDigestFile(manifestPath, "release channel manifest");
  if (manifest.sequence < state.highestSequence) throw new Error("Release channel rollback sequence rejected");
  if (manifest.sequence === state.highestSequence && manifestDigest.sha256 !== state.manifestSha256) {
    throw new Error("Release channel sequence was reused for different bytes");
  }
}

function readValidatedSequenceState(statePath, manifest) {
  assertPrivateStateFileBoundary(statePath, "release channel state");
  const state = readSecureJson(statePath, "release channel state");
  exactKeys(state, ["architecture", "channel", "highestSequence", "manifestSha256", "platform", "schemaVersion", "verifiedAt"], "release channel state");
  if (state.schemaVersion !== CHANNEL_STATE_SCHEMA || state.channel !== manifest.channel
    || state.platform !== manifest.platform || state.architecture !== manifest.architecture
    || !Number.isSafeInteger(state.highestSequence) || state.highestSequence < 1
    || !/^[a-f0-9]{64}$/.test(String(state.manifestSha256 || ""))) {
    throw new Error("Release channel state is invalid");
  }
  parseIsoInstant(state.verifiedAt, "release channel state verifiedAt");
  return state;
}

function recordSequenceState(statePath, manifest, manifestSha256, stateLock) {
  assertHeldSequenceStateLock(stateLock, statePath);
  if (existsSync(statePath)) {
    assertPrivateStateFileBoundary(statePath, "release channel state");
    const current = readValidatedSequenceState(statePath, manifest);
    if (current.highestSequence > manifest.sequence) throw new Error("Release channel rollback sequence rejected before state update");
    if (current.highestSequence === manifest.sequence && current.manifestSha256 !== manifestSha256) {
      throw new Error("Release channel sequence reuse rejected before state update");
    }
    if (current.highestSequence === manifest.sequence) return;
  } else {
    assertSafeParentForCreate(statePath);
  }
  const state = {
    schemaVersion: CHANNEL_STATE_SCHEMA,
    channel: manifest.channel,
    platform: manifest.platform,
    architecture: manifest.architecture,
    highestSequence: manifest.sequence,
    manifestSha256,
    verifiedAt: new Date().toISOString(),
  };
  atomicSecureJson(statePath, state, stateLock);
}

function validateReleaseSignature(envelope, manifest, files, digests, publicKey) {
  exactKeys(envelope, ["algorithm", "keyId", "schemaVersion", "signature", "signedAt", "subjects"], "release signature");
  if (envelope.schemaVersion !== RELEASE_SIGNATURE_SCHEMA || envelope.algorithm !== "Ed25519" || envelope.keyId !== EMBEDDED_RELEASE_KEY_ID) {
    throw new Error("Release signature identity is invalid");
  }
  const signedAt = parseIsoInstant(envelope.signedAt, "release signedAt");
  if (signedAt > parseIsoInstant(manifest.issuedAt, "release issuedAt") + CLOCK_SKEW_MS) {
    throw new Error("Release signature is newer than the release channel issuance");
  }
  if (!Array.isArray(envelope.subjects) || envelope.subjects.length !== 4) throw new Error("Release signature must have exactly four subjects");
  const exactSubjects = [
    ["artifact", files.names.artifact],
    ["release-evidence", files.names["release-evidence"]],
    ["sbom", files.names.sbom],
    ["provenance", files.names.provenance],
  ];
  for (let index = 0; index < exactSubjects.length; index += 1) {
    const [kind, name] = exactSubjects[index];
    const subject = envelope.subjects[index];
    validateFileRecord(subject, kind, name, `release signature subject ${index}`);
    const actual = digests.get(kind);
    if (subject.bytes !== actual.bytes || subject.sha256 !== actual.sha256) {
      throw new Error(`Release signature subject mismatch for ${name}`);
    }
  }
  verifyEnvelopeSignature(envelope, publicKey, "release");
}

function verifyEnvelopeSignature(envelope, publicKey, label) {
  if (!/^[A-Za-z0-9_-]{86}$/.test(String(envelope.signature || ""))) throw new Error(`${label} signature encoding is invalid`);
  const signature = Buffer.from(envelope.signature, "base64url");
  if (signature.length !== 64 || signature.toString("base64url") !== envelope.signature) {
    throw new Error(`${label} signature encoding is not canonical`);
  }
  const unsigned = Object.create(null);
  for (const [key, value] of Object.entries(envelope)) if (key !== "signature") unsigned[key] = value;
  const valid = verifyEd25519(
    null,
    Buffer.from(canonicalJson(unsigned), "utf8"),
    publicKey,
    signature,
  );
  if (!valid) throw new Error(`${label} Ed25519 signature is invalid`);
}

function validateFileRecord(record, expectedKind, expectedName, label) {
  exactKeys(record, ["bytes", "kind", "name", "sha256"], label);
  if (record.kind !== expectedKind || record.name !== expectedName) throw new Error(`${label} identity is invalid`);
  assertSafeBasename(record.name, `${label} filename`);
  assertDigestRecord(record, label);
}

function assertDigestRecord(record, label) {
  if (!Number.isSafeInteger(record.bytes) || record.bytes < 0 || !/^[a-f0-9]{64}$/.test(String(record.sha256 || ""))) {
    throw new Error(`${label} digest metadata is invalid`);
  }
}

function secureDigestFile(filePath, label) {
  const resolved = assertSafeExistingFile(filePath, label);
  const before = lstatSync(resolved, { bigint: true });
  const flags = fsConstants.O_RDONLY | (typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0);
  const descriptor = openSync(resolved, flags);
  try {
    const openedBefore = fstatSync(descriptor, { bigint: true });
    assertStableFileIdentity(before, openedBefore, label);
    const hash = createHash("sha256");
    const buffer = Buffer.allocUnsafe(1024 * 1024);
    let bytes = 0;
    while (true) {
      const count = readSync(descriptor, buffer, 0, buffer.length, null);
      if (count === 0) break;
      hash.update(buffer.subarray(0, count));
      bytes += count;
    }
    const openedAfter = fstatSync(descriptor, { bigint: true });
    const after = lstatSync(resolved, { bigint: true });
    assertStableFileIdentity(openedBefore, openedAfter, label);
    assertStableFileIdentity(openedAfter, after, label);
    if (BigInt(bytes) !== openedAfter.size) throw new Error(`${label} changed while it was read`);
    return Object.freeze({ bytes, sha256: hash.digest("hex") });
  } finally {
    closeSync(descriptor);
  }
}

function secureReadFile(filePath, label, maximumBytes = MAX_JSON_BYTES) {
  const digest = secureDigestFile(filePath, label);
  if (digest.bytes > maximumBytes) throw new Error(`${label} exceeds the maximum accepted size`);
  const buffer = readFileSync(path.resolve(filePath));
  if (buffer.length !== digest.bytes || createHash("sha256").update(buffer).digest("hex") !== digest.sha256) {
    throw new Error(`${label} changed between validation and read`);
  }
  return buffer;
}

function readSecureJson(filePath, label) {
  const text = secureReadFile(filePath, label).toString("utf8");
  if (text.charCodeAt(0) === 0xfeff) throw new Error(`${label} must not contain a byte order mark`);
  return new StrictJsonParser(text, label).parse();
}

function assertSafeExistingFile(filePath, label) {
  const resolved = path.resolve(filePath);
  assertSafePathComponents(resolved, label);
  const info = lstatSync(resolved, { bigint: true });
  if (!info.isFile() || info.isSymbolicLink()) throw new Error(`${label} must be a regular file`);
  if (info.nlink !== 1n) throw new Error(`${label} must not be a hardlink`);
  const real = realpathSync.native(resolved);
  if (!samePath(real, resolved)) throw new Error(`${label} resolves through a link or junction`);
  return resolved;
}

function assertSafePathComponents(resolved, label) {
  if (!path.isAbsolute(resolved)) throw new Error(`${label} path must resolve absolutely`);
  const parsed = path.parse(resolved);
  const relative = resolved.slice(parsed.root.length);
  let current = parsed.root;
  const parts = relative.split(path.sep).filter(Boolean);
  for (const part of parts) {
    current = path.join(current, part);
    if (!existsSync(current)) throw new Error(`${label} does not exist`);
    const info = lstatSync(current, { bigint: true });
    if (info.isSymbolicLink()) throw new Error(`${label} path contains a symbolic link`);
    assertNoWindowsReparsePoint(current, label);
  }
}

function assertNoWindowsReparsePoint(target, label) {
  if (process.platform !== "win32") return;
  const cacheKey = path.resolve(target).toLowerCase();
  if (reparseChecks.has(cacheKey)) return;
  const command = "$ErrorActionPreference='Stop'; $item=Get-Item -LiteralPath $env:MARKETINGOS_VERIFY_PATH -Force; if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { exit 33 }";
  const environment = Object.create(null);
  for (const key of ["SystemRoot", "WINDIR", "TEMP", "TMP", "USERPROFILE"]) {
    if (process.env[key] !== undefined) environment[key] = process.env[key];
  }
  environment.MARKETINGOS_VERIFY_PATH = target;
  const result = spawnSync(trustedWindowsPowerShell(), [
    "-NoProfile",
    "-NonInteractive",
    "-EncodedCommand",
    Buffer.from(command, "utf16le").toString("base64"),
  ], {
    encoding: "utf8",
    env: environment,
    shell: false,
    windowsHide: true,
    timeout: 15_000,
    maxBuffer: 64 * 1024,
  });
  if (result.status === 33) throw new Error(`${label} path contains a Windows reparse point`);
  if (result.status !== 0) throw new Error(`${label} Windows reparse point check failed`);
  reparseChecks.add(cacheKey);
}

let cachedWindowsPowerShell = null;
function trustedWindowsPowerShell() {
  if (cachedWindowsPowerShell) return cachedWindowsPowerShell;
  const systemRoot = path.win32.resolve("C:\\Windows");
  if (process.env.SystemRoot && !samePath(path.resolve(process.env.SystemRoot), path.resolve(systemRoot))) {
    throw new Error("Windows system root is not the supported canonical C:\\Windows directory");
  }
  if (process.env.WINDIR && !samePath(path.resolve(process.env.WINDIR), path.resolve(systemRoot))) {
    throw new Error("Windows system directory environment is inconsistent");
  }
  const executable = path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
  const parsed = path.parse(executable);
  let current = parsed.root;
  for (const component of executable.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
    current = path.join(current, component);
    if (!existsSync(current)) throw new Error("Trusted Windows PowerShell path is unavailable");
    const info = lstatSync(current, { bigint: true });
    if (info.isSymbolicLink()) throw new Error("Trusted Windows PowerShell path contains a link");
    if (!samePath(realpathSync.native(current), current)) {
      throw new Error("Trusted Windows PowerShell path resolves through a link or junction");
    }
  }
  const info = lstatSync(executable, { bigint: true });
  if (!info.isFile() || info.isSymbolicLink() || info.nlink < 1n) {
    throw new Error("Trusted Windows PowerShell is not a regular system file");
  }
  cachedWindowsPowerShell = executable;
  return executable;
}

function assertStableFileIdentity(left, right, label) {
  if (!right.isFile() || right.isSymbolicLink() || right.nlink !== 1n
    || left.dev !== right.dev || left.ino !== right.ino || left.size !== right.size
    || left.mtimeNs !== right.mtimeNs || left.ctimeNs !== right.ctimeNs) {
    throw new Error(`${label} identity changed or is unsafe`);
  }
}

function assertSafeParentForCreate(target) {
  const parent = path.dirname(path.resolve(target));
  if (!existsSync(parent)) createPrivateStateDirectories(parent);
  assertSafePathComponents(parent, "channel state parent");
  const info = lstatSync(parent, { bigint: true });
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("Channel state parent must be a regular directory");
  const real = realpathSync.native(parent);
  if (!samePath(real, parent)) throw new Error("Channel state parent resolves through a link or junction");
  assertPrivateStateBoundary(parent, "channel state parent");
}

function createPrivateStateDirectories(parent) {
  const missing = [];
  let existing = path.resolve(parent);
  while (!existsSync(existing)) {
    missing.unshift(existing);
    const next = path.dirname(existing);
    if (next === existing) throw new Error("Channel state path has no existing parent");
    existing = next;
  }
  assertSafePathComponents(existing, "channel state existing parent");
  assertPrivateStateBoundary(existing, "channel state existing parent", {
    allowSharedCreate: true,
  });
  for (const directory of missing) {
    mkdirSync(directory, { mode: 0o700 });
    assertSafePathComponents(directory, "new channel state parent");
    if (process.platform === "win32") {
      assertWindowsStateBoundary(directory, "new channel state parent", true);
    }
    assertPrivateStateBoundary(directory, "new channel state parent");
  }
}

function assertPrivateStateBoundary(directory, label, { allowSharedCreate = false } = {}) {
  if (process.platform === "win32") {
    assertWindowsStateBoundary(directory, label, false, allowSharedCreate);
    return;
  }
  if (typeof process.getuid !== "function") {
    throw new Error(`${label} cannot establish the current POSIX user identity`);
  }
  const currentUid = BigInt(process.getuid());
  const absolute = path.resolve(directory);
  const parsed = path.parse(absolute);
  let current = parsed.root;
  for (const component of absolute.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
    current = path.join(current, component);
    const info = lstatSync(current, { bigint: true });
    if (!info.isDirectory() || info.isSymbolicLink()) {
      throw new Error(`${label} path is not a real directory`);
    }
    const mode = Number(info.mode & 0o7777n);
    const sharedWritable = (mode & 0o022) !== 0;
    const sticky = (mode & 0o1000) !== 0;
    if (info.uid !== currentUid && info.uid !== 0n) {
      throw new Error(`${label} path is owned by another POSIX principal`);
    }
    if (sharedWritable && !sticky) {
      throw new Error(`${label} path is writable by another POSIX principal`);
    }
  }
}

function assertWindowsStateBoundary(directory, label, harden, allowSharedCreate = false) {
  const script = [
    "$ErrorActionPreference='Stop'",
    "$target=[IO.Path]::GetFullPath($env:MARKETINGOS_VERIFY_ACL_PATH)",
    "$current=[Security.Principal.WindowsIdentity]::GetCurrent().User",
    "$system=New-Object Security.Principal.SecurityIdentifier('S-1-5-18')",
    "$admins=New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')",
    "$creator=New-Object Security.Principal.SecurityIdentifier('S-1-3-0')",
    "$trustedInstaller=New-Object Security.Principal.SecurityIdentifier('S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')",
    "if ($env:MARKETINGOS_VERIFY_ACL_HARDEN -eq '1') {",
    "  $next=New-Object Security.AccessControl.DirectorySecurity",
    "  $next.SetOwner($current)",
    "  $next.SetAccessRuleProtection($true,$false)",
    "  $inherit=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'",
    "  $prop=[Security.AccessControl.PropagationFlags]::None",
    "  foreach($sid in @($current,$system,$admins)) { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,[Security.AccessControl.FileSystemRights]::FullControl,$inherit,$prop,[Security.AccessControl.AccessControlType]::Allow); [void]$next.AddAccessRule($rule) }",
    "  Set-Acl -LiteralPath $target -AclObject $next",
    "}",
    "$allowed=@($current.Value,$system.Value,$admins.Value,$creator.Value,$trustedInstaller.Value)",
    "$danger=[int]([Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership)",
    "$targetWrite=[int]([Security.AccessControl.FileSystemRights]::WriteData -bor [Security.AccessControl.FileSystemRights]::AppendData -bor [Security.AccessControl.FileSystemRights]::WriteAttributes -bor [Security.AccessControl.FileSystemRights]::WriteExtendedAttributes)",
    "$chain=New-Object Collections.Generic.List[string]",
    "$cursor=[IO.Path]::GetPathRoot($target)",
    "[void]$chain.Add($cursor)",
    "$remainder=$target.Substring($cursor.Length).Split([IO.Path]::DirectorySeparatorChar,[StringSplitOptions]::RemoveEmptyEntries)",
    "foreach($part in $remainder) { $cursor=Join-Path $cursor $part; [void]$chain.Add($cursor) }",
    "$unsafeCount=0",
    "$targetProtected=$false",
    "foreach($probe in $chain) {",
    "  $item=Get-Item -LiteralPath $probe -Force",
    "  if (-not $item.PSIsContainer -or (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) { throw 'unsafe directory chain' }",
    "  $acl=Get-Acl -LiteralPath $probe",
    "  $owner=(New-Object Security.Principal.NTAccount($acl.Owner)).Translate([Security.Principal.SecurityIdentifier]).Value",
    "  if ($allowed -notcontains $owner) { $unsafeCount++ }",
    "  $mask=$danger; if ($probe -eq $target -and $env:MARKETINGOS_VERIFY_ACL_ALLOW_SHARED_CREATE -ne '1') { $mask=$mask -bor $targetWrite }",
    "  $unsafeCount += @($acl.Access | Where-Object { $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and (($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0) } | Where-Object { $sid=$_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value; (([int]$_.FileSystemRights -band $mask) -ne 0) -and ($allowed -notcontains $sid) }).Count",
    "  if ($probe -eq $target) { $targetProtected=$acl.AreAccessRulesProtected }",
    "}",
    "[pscustomobject]@{Protected=$targetProtected;Unsafe=$unsafeCount}|ConvertTo-Json -Compress",
  ].join("; ");
  const encoded = Buffer.from(script, "utf16le").toString("base64");
  const environment = Object.create(null);
  for (const key of ["SystemRoot", "WINDIR", "TEMP", "TMP", "USERPROFILE"]) {
    if (process.env[key] !== undefined) environment[key] = process.env[key];
  }
  environment.MARKETINGOS_VERIFY_ACL_PATH = directory;
  environment.MARKETINGOS_VERIFY_ACL_HARDEN = harden ? "1" : "0";
  environment.MARKETINGOS_VERIFY_ACL_ALLOW_SHARED_CREATE = allowSharedCreate ? "1" : "0";
  const result = spawnSync(
    trustedWindowsPowerShell(),
    ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded],
    {
      encoding: "utf8",
      env: environment,
      shell: false,
      windowsHide: true,
      timeout: 15_000,
      maxBuffer: 64 * 1024,
    },
  );
  if (result.status !== 0) throw new Error(`${label} Windows ACL inspection failed`);
  let posture;
  try {
    posture = JSON.parse(String(result.stdout || "").trim());
  } catch {
    throw new Error(`${label} Windows ACL inspection returned invalid output`);
  }
  if (posture.Unsafe !== 0 || (harden && posture.Protected !== true)) {
    throw new Error(`${label} Windows ACL permits another local principal to replace channel state`);
  }
}

function assertPrivateStateFileBoundary(file, label) {
  const absolute = assertSafeExistingFile(file, label);
  if (process.platform !== "win32") {
    if (typeof process.getuid !== "function") {
      throw new Error(`${label} cannot establish the current POSIX user identity`);
    }
    const info = lstatSync(absolute, { bigint: true });
    if (info.uid !== BigInt(process.getuid()) || Number(info.mode & 0o022n) !== 0) {
      throw new Error(`${label} is writable by or owned by another POSIX principal`);
    }
    return;
  }
  const script = [
    "$ErrorActionPreference='Stop'",
    "$target=[IO.Path]::GetFullPath($env:MARKETINGOS_VERIFY_STATE_FILE)",
    "$item=Get-Item -LiteralPath $target -Force",
    "if ($item.PSIsContainer -or (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) { throw 'unsafe state file' }",
    "$current=[Security.Principal.WindowsIdentity]::GetCurrent().User",
    "$system=New-Object Security.Principal.SecurityIdentifier('S-1-5-18')",
    "$admins=New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')",
    "$allowed=@($current.Value,$system.Value,$admins.Value)",
    "$acl=Get-Acl -LiteralPath $target",
    "$owner=(New-Object Security.Principal.NTAccount($acl.Owner)).Translate([Security.Principal.SecurityIdentifier]).Value",
    "$danger=[int]([Security.AccessControl.FileSystemRights]::WriteData -bor [Security.AccessControl.FileSystemRights]::AppendData -bor [Security.AccessControl.FileSystemRights]::WriteAttributes -bor [Security.AccessControl.FileSystemRights]::WriteExtendedAttributes -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership)",
    "$unsafe=@($acl.Access | Where-Object { $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and (($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0) } | Where-Object { $sid=$_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value; (([int]$_.FileSystemRights -band $danger) -ne 0) -and ($allowed -notcontains $sid) }).Count",
    "[pscustomobject]@{Owner=$owner;Current=$current.Value;Unsafe=$unsafe}|ConvertTo-Json -Compress",
  ].join("; ");
  const environment = Object.create(null);
  for (const key of ["SystemRoot", "WINDIR", "TEMP", "TMP", "USERPROFILE"]) {
    if (process.env[key] !== undefined) environment[key] = process.env[key];
  }
  environment.MARKETINGOS_VERIFY_STATE_FILE = absolute;
  const result = spawnSync(
    trustedWindowsPowerShell(),
    ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
    {
      encoding: "utf8",
      env: environment,
      shell: false,
      windowsHide: true,
      timeout: 15_000,
      maxBuffer: 64 * 1024,
    },
  );
  if (result.status !== 0) throw new Error(`${label} Windows ACL inspection failed`);
  let posture;
  try {
    posture = JSON.parse(String(result.stdout || "").trim());
  } catch {
    throw new Error(`${label} Windows ACL inspection returned invalid output`);
  }
  if (posture.Owner !== posture.Current && posture.Owner !== "S-1-5-18" && posture.Owner !== "S-1-5-32-544") {
    throw new Error(`${label} is owned by another Windows principal`);
  }
  if (posture.Unsafe !== 0) {
    throw new Error(`${label} is writable by another Windows principal`);
  }
}

function acquireSequenceStateLock(statePath) {
  const target = path.resolve(statePath);
  assertSafeParentForCreate(target);
  const lockPath = `${target}.lock`;
  let created = false;
  try {
    mkdirSync(lockPath, { mode: 0o700 });
    created = true;
  } catch (error) {
    if (error?.code !== "EEXIST") throw error;
    try {
      assertSafeLockDirectory(lockPath, "release channel state lock");
    } catch (unsafeError) {
      throw new Error(`Release channel state lock exists but is unsafe at ${lockPath}. Verification stopped. Inspect it manually and do not remove it while any verifier is running. ${String(unsafeError?.message || unsafeError)}`);
    }
    throw new Error(`Release channel state lock already exists at ${lockPath}. Verification stopped fail closed. Confirm that no verifier is running. Inspect the state, owner.json and adjacent .new files. Then manually remove this lock directory and only those abandoned temporary files before retrying.`);
  }

  const nonce = randomBytes(16).toString("hex");
  const ownerPath = path.join(lockPath, "owner.json");
  try {
    assertSafeLockDirectory(lockPath, "new release channel state lock");
    const owner = {
      schemaVersion: "marketingos.releaseChannelStateLock.v1",
      statePath: target,
      pid: process.pid,
      acquiredAt: new Date().toISOString(),
      nonce,
    };
    writeDurableExclusiveFile(ownerPath, `${JSON.stringify(owner, null, 2)}\n`, "release channel state lock owner");
    syncDirectory(lockPath, "release channel state lock directory");
    syncDirectory(path.dirname(lockPath), "release channel state lock parent");
    const info = assertSafeLockDirectory(lockPath, "release channel state lock");
    return Object.freeze({
      statePath: target,
      path: lockPath,
      ownerPath,
      nonce,
      dev: info.dev,
      ino: info.ino,
    });
  } catch (error) {
    if (created) cleanupNewSequenceStateLock(lockPath, ownerPath);
    throw error;
  }
}

function assertSafeLockDirectory(lockPath, label) {
  const resolved = path.resolve(lockPath);
  assertSafePathComponents(resolved, label);
  const info = lstatSync(resolved, { bigint: true });
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`${label} must be a regular directory`);
  const real = realpathSync.native(resolved);
  if (!samePath(real, resolved)) throw new Error(`${label} resolves through a link or junction`);
  return info;
}

function assertHeldSequenceStateLock(lock, statePath) {
  if (!lock || !samePath(lock.statePath, statePath)) throw new Error("Release channel state update requires its exclusive lock");
  const info = assertSafeLockDirectory(lock.path, "release channel state lock");
  if (info.dev !== lock.dev || info.ino !== lock.ino) throw new Error("Release channel state lock identity changed");
  const owner = readSecureJson(lock.ownerPath, "release channel state lock owner");
  exactKeys(owner, ["acquiredAt", "nonce", "pid", "schemaVersion", "statePath"], "release channel state lock owner");
  if (owner.schemaVersion !== "marketingos.releaseChannelStateLock.v1"
    || owner.statePath !== lock.statePath
    || owner.pid !== process.pid
    || owner.nonce !== lock.nonce
    || !/^[a-f0-9]{32}$/.test(owner.nonce)) {
    throw new Error("Release channel state lock ownership is invalid");
  }
  parseIsoInstant(owner.acquiredAt, "release channel state lock acquiredAt");
}

function releaseSequenceStateLock(lock) {
  assertHeldSequenceStateLock(lock, lock.statePath);
  unlinkSync(lock.ownerPath);
  const info = assertSafeLockDirectory(lock.path, "release channel state lock");
  if (info.dev !== lock.dev || info.ino !== lock.ino) throw new Error("Release channel state lock identity changed during release");
  rmdirSync(lock.path);
  syncDirectory(path.dirname(lock.path), "release channel state lock parent");
}

function cleanupNewSequenceStateLock(lockPath, ownerPath) {
  try {
    if (existsSync(ownerPath)) {
      assertSafeExistingFile(ownerPath, "new release channel state lock owner");
      unlinkSync(ownerPath);
    }
    if (existsSync(lockPath)) {
      assertSafeLockDirectory(lockPath, "new release channel state lock");
      rmdirSync(lockPath);
    }
  } catch {
    // A partially created or unexpectedly changed lock is deliberately left for manual recovery.
  }
}

function atomicSecureJson(target, value, stateLock) {
  assertHeldSequenceStateLock(stateLock, target);
  assertSafeParentForCreate(target);
  if (existsSync(target)) assertPrivateStateFileBoundary(target, "channel state");
  const temporary = `${target}.new-${process.pid}-${randomBytes(12).toString("hex")}`;
  const text = `${JSON.stringify(value, null, 2)}\n`;
  let temporaryExists = false;
  try {
    writeDurableExclusiveFile(temporary, text, "temporary channel state");
    temporaryExists = true;
    assertPrivateStateFileBoundary(temporary, "temporary channel state");
    const temporaryDigest = secureDigestFile(temporary, "temporary channel state");
    const expectedDigest = createHash("sha256").update(text, "utf8").digest("hex");
    if (temporaryDigest.bytes !== Buffer.byteLength(text, "utf8") || temporaryDigest.sha256 !== expectedDigest) {
      throw new Error("Temporary channel state bytes are not durable and exact");
    }
    runBootstrapTestCrash("after-durable-state-temp");
    assertHeldSequenceStateLock(stateLock, target);
    assertSafeParentForCreate(target);
    if (existsSync(target)) assertPrivateStateFileBoundary(target, "channel state");
    renameSync(temporary, target);
    temporaryExists = false;
    assertPrivateStateFileBoundary(target, "installed channel state");
    const installedDigest = secureDigestFile(target, "channel state");
    if (installedDigest.bytes !== temporaryDigest.bytes || installedDigest.sha256 !== temporaryDigest.sha256) {
      throw new Error("Installed channel state does not match the durable replacement");
    }
    flushSecureFile(target, "channel state");
    syncDirectory(path.dirname(target), "channel state parent");
    runBootstrapTestCrash("after-durable-state-replacement");
  } catch (error) {
    if (temporaryExists && existsSync(temporary)) {
      assertSafeExistingFile(temporary, "temporary channel state");
      unlinkSync(temporary);
    }
    throw error;
  }
}

function writeDurableExclusiveFile(target, text, label) {
  const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL
    | (typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0);
  const descriptor = openSync(target, flags, 0o600);
  try {
    writeFileSync(descriptor, text, { encoding: "utf8" });
    fsyncSync(descriptor);
  } finally {
    closeSync(descriptor);
  }
  assertSafeExistingFile(target, label);
}

function flushSecureFile(target, label) {
  const resolved = assertSafeExistingFile(target, label);
  const before = lstatSync(resolved, { bigint: true });
  const flags = fsConstants.O_RDWR | (typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0);
  const descriptor = openSync(resolved, flags);
  try {
    const opened = fstatSync(descriptor, { bigint: true });
    assertStableFileIdentity(before, opened, label);
    fsyncSync(descriptor);
    const after = fstatSync(descriptor, { bigint: true });
    assertStableFileIdentity(opened, after, label);
  } finally {
    closeSync(descriptor);
  }
}

function syncDirectory(directory, label) {
  if (process.platform === "win32") return;
  const resolved = path.resolve(directory);
  assertSafePathComponents(resolved, label);
  const info = lstatSync(resolved, { bigint: true });
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`${label} must be a regular directory`);
  const descriptor = openSync(resolved, fsConstants.O_RDONLY);
  try {
    fsyncSync(descriptor);
  } finally {
    closeSync(descriptor);
  }
}

function runBootstrapTestPauseAfterStateLock() {
  const raw = process.env.MARKETINGOS_RELEASE_VERIFY_TEST_HOLD_STATE_LOCK_MS;
  if (raw === undefined) return;
  requireExplicitBootstrapTestMode();
  const milliseconds = Number(raw);
  if (!Number.isSafeInteger(milliseconds) || milliseconds < 1 || milliseconds > 10_000) {
    throw new Error("Bootstrap state lock test hold duration is invalid");
  }
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
}

function runBootstrapTestCrash(point) {
  const configured = process.env.MARKETINGOS_RELEASE_VERIFY_TEST_CRASH_POINT;
  if (configured === undefined) return;
  requireExplicitBootstrapTestMode();
  if (!["after-durable-state-temp", "after-durable-state-replacement"].includes(configured)) {
    throw new Error("Bootstrap state crash test point is invalid");
  }
  if (configured === point) process.exit(point === "after-durable-state-temp" ? 86 : 87);
}

function requireExplicitBootstrapTestMode() {
  if (process.env.MARKETINGOS_RELEASE_VERIFY_TEST_MODE !== "1") {
    throw new Error("Bootstrap state test hooks require explicit test mode");
  }
}

function samePath(left, right) {
  return process.platform === "win32"
    ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase()
    : path.resolve(left) === path.resolve(right);
}

function exactKeys(value, expectedKeys, label) {
  if (!isPlainObject(value)) throw new Error(`${label} must be an object`);
  const actual = Object.keys(value).sort();
  const expected = [...expectedKeys].sort();
  if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
    throw new Error(`${label} has unexpected or missing fields`);
  }
}

function assertSafeBasename(value, label) {
  if (typeof value !== "string" || !value || value === "." || value === ".."
    || path.basename(value) !== value || value.includes("/") || value.includes("\\")
    || /[\u0000-\u001f\u007f]/.test(value)) {
    throw new Error(`${label} is not a safe basename`);
  }
}

function requireChannel(value, label) {
  if (!["alpha", "beta", "stable"].includes(value)) throw new Error(`${label} is invalid`);
}

function requireVersion(value, label) {
  const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
  if (typeof value !== "string" || value.length > 128 || !semver.test(value)) throw new Error(`${label} is invalid`);
}

function assertVersionAtLeast(actual, minimum, label) {
  requireVersion(actual, `${label} version`);
  requireVersion(minimum, `${label} minimum version`);
  if (compareVersions(actual, minimum) < 0) throw new Error(`${label} ${minimum} or newer is required`);
}

function compareVersions(left, right) {
  const a = left.split(/[+-]/, 1)[0].split(".").map(Number);
  const b = right.split(/[+-]/, 1)[0].split(".").map(Number);
  for (let index = 0; index < 3; index += 1) {
    if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1;
  }
  return 0;
}

function parseIsoInstant(value, label) {
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) {
    throw new Error(`${label} must be an exact UTC ISO instant`);
  }
  const parsed = Date.parse(value);
  if (!Number.isFinite(parsed) || new Date(parsed).toISOString() !== value) throw new Error(`${label} is invalid`);
  return parsed;
}

function canonicalJson(value) {
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
  if (typeof value === "number") {
    if (!Number.isFinite(value)) throw new Error("Canonical JSON rejects non finite numbers");
    return JSON.stringify(Object.is(value, -0) ? 0 : value);
  }
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
  if (!isPlainObject(value)) throw new Error("Canonical JSON requires plain objects");
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
}

function isPlainObject(value) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}

class StrictJsonParser {
  constructor(text, label) {
    this.text = text;
    this.label = label;
    this.index = 0;
    this.depth = 0;
  }

  parse() {
    const value = this.parseValue();
    this.skipWhitespace();
    if (this.index !== this.text.length) this.fail("contains trailing data");
    return value;
  }

  parseValue() {
    this.skipWhitespace();
    const char = this.text[this.index];
    if (char === "{") return this.parseObject();
    if (char === "[") return this.parseArray();
    if (char === "\"") return this.parseString();
    if (char === "t") return this.parseLiteral("true", true);
    if (char === "f") return this.parseLiteral("false", false);
    if (char === "n") return this.parseLiteral("null", null);
    if (char === "-" || (char >= "0" && char <= "9")) return this.parseNumber();
    this.fail("contains an invalid value");
  }

  parseObject() {
    this.enter();
    this.index += 1;
    const result = Object.create(null);
    const seen = new Set();
    this.skipWhitespace();
    if (this.text[this.index] === "}") {
      this.index += 1;
      this.leave();
      return result;
    }
    let count = 0;
    while (true) {
      this.skipWhitespace();
      if (this.text[this.index] !== "\"") this.fail("contains a non string object key");
      const key = this.parseString();
      if (seen.has(key)) this.fail(`contains duplicate object key ${JSON.stringify(key)}`);
      seen.add(key);
      this.skipWhitespace();
      if (this.text[this.index] !== ":") this.fail("is missing an object colon");
      this.index += 1;
      result[key] = this.parseValue();
      count += 1;
      if (count > 4096) this.fail("contains too many object entries");
      this.skipWhitespace();
      const char = this.text[this.index];
      if (char === "}") {
        this.index += 1;
        this.leave();
        return result;
      }
      if (char !== ",") this.fail("is missing an object comma");
      this.index += 1;
    }
  }

  parseArray() {
    this.enter();
    this.index += 1;
    const result = [];
    this.skipWhitespace();
    if (this.text[this.index] === "]") {
      this.index += 1;
      this.leave();
      return result;
    }
    while (true) {
      result.push(this.parseValue());
      if (result.length > 4096) this.fail("contains too many array entries");
      this.skipWhitespace();
      const char = this.text[this.index];
      if (char === "]") {
        this.index += 1;
        this.leave();
        return result;
      }
      if (char !== ",") this.fail("is missing an array comma");
      this.index += 1;
    }
  }

  parseString() {
    const start = this.index;
    this.index += 1;
    while (this.index < this.text.length) {
      const code = this.text.charCodeAt(this.index);
      if (code === 0x22) {
        this.index += 1;
        try {
          return JSON.parse(this.text.slice(start, this.index));
        } catch {
          this.fail("contains an invalid JSON string");
        }
      }
      if (code < 0x20) this.fail("contains a control character in a string");
      if (code === 0x5c) {
        this.index += 1;
        const escape = this.text[this.index];
        if (escape === "u") {
          const hex = this.text.slice(this.index + 1, this.index + 5);
          if (!/^[a-fA-F0-9]{4}$/.test(hex)) this.fail("contains an invalid Unicode escape");
          this.index += 5;
          continue;
        }
        if (!["\"", "\\", "/", "b", "f", "n", "r", "t"].includes(escape)) this.fail("contains an invalid string escape");
      }
      this.index += 1;
    }
    this.fail("contains an unterminated string");
  }

  parseNumber() {
    const match = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(this.text.slice(this.index));
    if (!match) this.fail("contains an invalid number");
    this.index += match[0].length;
    const value = Number(match[0]);
    if (!Number.isFinite(value)) this.fail("contains a non finite number");
    return value;
  }

  parseLiteral(source, value) {
    if (this.text.slice(this.index, this.index + source.length) !== source) this.fail("contains an invalid literal");
    this.index += source.length;
    return value;
  }

  skipWhitespace() {
    while ([" ", "\t", "\r", "\n"].includes(this.text[this.index])) this.index += 1;
  }

  enter() {
    this.depth += 1;
    if (this.depth > 64) this.fail("exceeds the maximum nesting depth");
  }

  leave() {
    this.depth -= 1;
  }

  fail(message) {
    throw new Error(`${this.label} ${message} at byte ${Buffer.byteLength(this.text.slice(0, this.index), "utf8")}`);
  }
}

try {
  main();
} catch (error) {
  process.stderr.write(`MarketingOS release verification failed: ${String(error?.message || error)}\n`);
  process.exitCode = 1;
}
