{"version":3,"file":"schema.mjs","names":[],"sources":["../../../src/services/lockfile/schema.ts"],"sourcesContent":["/**\n * The composition lockfile's wire schema (ADR 0042) — a leaf module so the\n * producers (`bos lock`, the deploy train), the boot consumer, and the\n * runtime-map generator can all import it without a cycle. The lockfile\n * freezes one runtime's exact composition: what the author wants\n * (`bos.app.ts`) resolved to named bytes. The pinned descriptor's `{base,\n * digest}` shape is deliberately the release manifest's `remotes:` entry shape\n * (ADR 0040) — one vocabulary for the same bytes; the scope differs (the\n * platform's per-release memory of inherited slots vs this app's frozen\n * whole). The `remotes` record is written in `walkRemotes` order — including\n * entries that freeze nothing — so the stored fingerprint recomputes exactly\n * (`lockfileFingerprint` ≡ `pointerFingerprint` over the same config), and\n * JSON round-trips preserve that order.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, renameSync, writeFileSync } from \"node:fs\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { BosConfig } from \"../../types\";\nimport { pointerFingerprint } from \"../registry/fingerprint\";\nimport { walkRemotes } from \"../remotes\";\n\nexport const LOCKFILE_NAME = \"bos.lock.json\";\n\n/** A frozen remote coordinate. `descriptor` mirrors the release manifest's\n * remote entry — `digest` (the immutable manifest pointer), a direct entry\n * `integrity` (digest-less fixed-name remotes), and the `base` they resolve\n * against; fields are individually optional because the freeze is faithful to\n * what the config carries, not to what a producer wishes it carried.\n * `pluginRef` freezes a bare plugin reference (`plugins.<id>: \"<key>\"`). */\nexport const LockfileRemoteSchema = z.discriminatedUnion(\"kind\", [\n  z\n    .object({\n      kind: z.literal(\"descriptor\"),\n      base: z.string().min(1).optional(),\n      digest: z.object({ manifest: z.string().min(1), integrity: z.string().min(1) }).optional(),\n      integrity: z.string().min(1).optional(),\n    })\n    .strict(),\n  z\n    .object({\n      kind: z.literal(\"pluginRef\"),\n      ref: z.string().min(1),\n    })\n    .strict(),\n]);\nexport type LockfileRemote = z.infer<typeof LockfileRemoteSchema>;\n\nexport const CompositionLockfileSchema = z\n  .object({\n    schemaVersion: z.literal(1),\n    kind: z.literal(\"everything-dev/composition-lockfile\"),\n    runtimeRef: z.string().regex(/^bos:\\/\\/[^/]+\\/[^/]+$/),\n    /** The release the composition resolves to; null when the runtime is\n     * unpinned — the lockfile still freezes what channel resolution\n     * returned. */\n    release: z.string().min(1).nullable(),\n    /** The frozen composition, in `walkRemotes` order (dotted config path →\n     * coordinate). Order is load-bearing: the fingerprint recomputes from it. */\n    remotes: z.record(z.string(), LockfileRemoteSchema),\n    /** Shared-singleton versions the composition is verified against —\n     * recorded when the sources provide them (remote plugin manifests, the\n     * release manifest's `sharedDeps`); tightened as producers mature. */\n    sharedSingletons: z.record(z.string(), z.string()).optional(),\n    /** Per-remote contract hash (`plugin.manifest.json`'s\n     * `contract.types.sha256`). */\n    contracts: z.record(z.string(), z.string()).optional(),\n    /** THE composition identity — equal to `pointerFingerprint(config)` by\n     * construction (`lockfileOf`), recomputable from `remotes` alone\n     * (`lockfileFingerprint`). */\n    fingerprint: z.string().regex(/^[0-9a-f]{16}$/),\n    resolvedAt: z.string().min(1),\n  })\n  .strict();\nexport type CompositionLockfile = z.infer<typeof CompositionLockfileSchema>;\n\nexport function lockfilePath(configDir: string = process.cwd()): string {\n  return path.join(configDir, LOCKFILE_NAME);\n}\n\nfunction descriptorPart(\n  remote: string,\n  entry: Extract<LockfileRemote, { kind: \"descriptor\" }>,\n): string {\n  const digestPart = entry.digest ? `${entry.digest.manifest}:${entry.digest.integrity}` : \"\";\n  const directPart = entry.integrity ?? \"\";\n  return `${remote}:${digestPart}:${directPart}`;\n}\n\n/** The load-side identity check: recompute the fingerprint from the stored\n * `remotes` record (insertion order — JSON round-trips preserve it) and\n * compare. A mismatch means the file was hand-edited or written by a\n * different fingerprint implementation — refuse, loud. */\nexport function lockfileFingerprint(lock: CompositionLockfile): string {\n  const parts = Object.entries(lock.remotes).map(([remote, entry]) =>\n    entry.kind === \"pluginRef\" ? `${remote}:${entry.ref}` : descriptorPart(remote, entry),\n  );\n  return createHash(\"sha256\").update(parts.join(\"|\")).digest(\"hex\").slice(0, 16);\n}\n\nexport function lockfileOf(input: {\n  account: string;\n  gateway: string;\n  config: BosConfig;\n  release?: string | null;\n  sharedSingletons?: Record<string, string>;\n  contracts?: Record<string, string>;\n  resolvedAt?: string;\n}): CompositionLockfile {\n  const remotes: Record<string, LockfileRemote> = {};\n  walkRemotes(\n    input.config as unknown as Record<string, unknown>,\n    ({ remote, entry, isPluginRef }) => {\n      if (isPluginRef) {\n        remotes[remote] = { kind: \"pluginRef\", ref: entry as string };\n        return;\n      }\n      if (!entry || typeof entry !== \"object\") return;\n      const ref = entry as {\n        production?: unknown;\n        integrity?: unknown;\n        digest?: { manifest?: unknown; integrity?: unknown };\n      };\n      const base = typeof ref.production === \"string\" ? ref.production : undefined;\n      const digest =\n        ref.digest &&\n        typeof ref.digest.manifest === \"string\" &&\n        typeof ref.digest.integrity === \"string\"\n          ? { manifest: ref.digest.manifest, integrity: ref.digest.integrity }\n          : undefined;\n      const integrity = typeof ref.integrity === \"string\" ? ref.integrity : undefined;\n      remotes[remote] = {\n        kind: \"descriptor\",\n        ...(base ? { base } : {}),\n        ...(digest ? { digest } : {}),\n        ...(integrity ? { integrity } : {}),\n      };\n    },\n  );\n  return CompositionLockfileSchema.parse({\n    schemaVersion: 1,\n    kind: \"everything-dev/composition-lockfile\",\n    runtimeRef: `bos://${input.account}/${input.gateway}`,\n    release: input.release ?? null,\n    remotes,\n    ...(input.sharedSingletons ? { sharedSingletons: input.sharedSingletons } : {}),\n    ...(input.contracts ? { contracts: input.contracts } : {}),\n    fingerprint: pointerFingerprint(input.config),\n    resolvedAt: input.resolvedAt ?? new Date().toISOString(),\n  });\n}\n\nexport function serializeLockfile(lock: CompositionLockfile): string {\n  return `${JSON.stringify(lock, null, 2)}\\n`;\n}\n\n/** The lockfile's content digest — what a deployment record names when it\n * answers \"what exact composition was live\". */\nexport function digestOfLockfile(serialized: string): string {\n  return createHash(\"sha256\").update(serialized).digest(\"hex\");\n}\n\nexport function parseLockfile(bytes: string): CompositionLockfile {\n  return CompositionLockfileSchema.parse(JSON.parse(bytes));\n}\n\n/** The sync producer for the deploy train (its publish path is sync-fs):\n * atomic temp + rename, parent dirs created. */\nexport function writeLockfileSync(lock: CompositionLockfile, configDir?: string): string {\n  const target = lockfilePath(configDir);\n  mkdirSync(path.dirname(target), { recursive: true });\n  const temp = `${target}.tmp`;\n  writeFileSync(temp, serializeLockfile(lock));\n  renameSync(temp, target);\n  return target;\n}\n\n/** Absent or unparseable → null: the lockfile is an input, and a corrupt one\n * degrades the explainer's provenance rather than failing a build. */\nexport async function readLockfileIfExists(\n  configDir?: string,\n): Promise<CompositionLockfile | null> {\n  try {\n    return parseLockfile(await readFile(lockfilePath(configDir), \"utf8\"));\n  } catch {\n    return null;\n  }\n}\n\nexport interface LockWriteResult {\n  status: \"written\" | \"unchanged\" | \"drift\";\n  path: string;\n  fingerprint: string;\n  /** The `--check` refusal reasons — empty unless status is \"drift\". */\n  drift: string[];\n}\n\n/** The producer seam both writers share (`bos lock`, and the deploy train's\n * post-publish leg): freeze the resolved composition, atomically, with the\n * `--check` refusal the CI gate exits on. */\nexport async function writeLockfile(\n  lock: CompositionLockfile,\n  configDir?: string,\n  opts?: { check?: boolean },\n): Promise<LockWriteResult> {\n  const target = lockfilePath(configDir);\n  const serialized = serializeLockfile(lock);\n  const existing = await readFile(target, \"utf8\").catch(() => null);\n  if (opts?.check) {\n    if (existing === null) {\n      return {\n        status: \"drift\",\n        path: target,\n        fingerprint: lock.fingerprint,\n        drift: [\"bos.lock.json is missing — run `bos lock` and commit the result\"],\n      };\n    }\n    if (existing !== serialized) {\n      return {\n        status: \"drift\",\n        path: target,\n        fingerprint: lock.fingerprint,\n        drift: [\n          \"bos.lock.json differs from the resolved composition — run `bos lock` and commit the result\",\n        ],\n      };\n    }\n    return { status: \"unchanged\", path: target, fingerprint: lock.fingerprint, drift: [] };\n  }\n  await mkdir(path.dirname(target), { recursive: true });\n  const temp = `${target}.tmp`;\n  await writeFile(temp, serialized);\n  await rename(temp, target);\n  return {\n    status: existing === serialized ? \"unchanged\" : \"written\",\n    path: target,\n    fingerprint: lock.fingerprint,\n    drift: [],\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,gBAAgB;;;;;;;AAQ7B,MAAa,uBAAuB,EAAE,mBAAmB,QAAQ,CAC/D,EACG,OAAO;CACN,MAAM,EAAE,QAAQ,YAAY;CAC5B,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CACjC,QAAQ,EAAE,OAAO;EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EAAG,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAAE,CAAC,CAAC,CAAC,SAAS;CACzF,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;AACxC,CAAC,CAAC,CACD,OAAO,GACV,EACG,OAAO;CACN,MAAM,EAAE,QAAQ,WAAW;CAC3B,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AACvB,CAAC,CAAC,CACD,OAAO,CACZ,CAAC;AAGD,MAAa,4BAA4B,EACtC,OAAO;CACN,eAAe,EAAE,QAAQ,CAAC;CAC1B,MAAM,EAAE,QAAQ,qCAAqC;CACrD,YAAY,EAAE,OAAO,CAAC,CAAC,MAAM,wBAAwB;;;;CAIrD,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;CAGpC,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,oBAAoB;;;;CAIlD,kBAAkB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;;;CAG5D,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;;;;CAIrD,aA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