{"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 pointer digest recomputes exactly\n * (the `pointerDigest` field ≡ `pointerDigest(config)` over the same config), and\n * JSON round-trips preserve that order.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, 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 { digestOfParts, pointerDigest } from \"../registry/digest\";\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(2),\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 pointer digest 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 template sync baseline (ADR 0047 — the absorbed\n     * `.bos/sync-snapshot.json`): per-file template hashes recorded at\n     * init/sync/import, read by `bos sync`'s three-way comparison. A local\n     * annotation, never produced by `lockfileOf` — writers carry it forward\n     * from the existing file, and it never enters the lockfile digest (the\n     * digest answers \"what exact composition was live\"; the baseline is not\n     * composition). */\n    template: z\n      .object({\n        syncedAt: z.string().min(1),\n        files: z.record(z.string(), z.string()),\n      })\n      .strict()\n      .optional(),\n    /** THE composition identity — equal to `pointerDigest(config)` by\n     * construction (`lockfileOf`), recomputable from `remotes` alone\n     * (`lockfilePointerDigest`). */\n    pointerDigest: 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 pointer digest from the\n * stored `remotes` record (insertion order — JSON round-trips preserve it)\n * and compare. A mismatch means the file was hand-edited or written by a\n * different digest implementation — refuse, loud. */\nexport function lockfilePointerDigest(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 digestOfParts(parts);\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: 2,\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    pointerDigest: pointerDigest(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/** Writers carry the `template` annotation forward from the existing file:\n * `lockfileOf` never produces it, so a producer rewrite (`bos lock`, the\n * deploy train's persist leg) must not silently drop the sync baseline the\n * file already carries. A corrupt existing file degrades to a plain write. */\nfunction carriedTemplate(lock: CompositionLockfile, existing: string | null): CompositionLockfile {\n  if (!existing) return lock;\n  try {\n    const parsed = parseLockfile(existing);\n    if (!parsed.template) return lock;\n    return { ...lock, template: parsed.template };\n  } catch {\n    return lock;\n  }\n}\n\n/** The lockfile's content digest — what a deployment record names when it\n * answers \"what exact composition was live\". Producers serialize `lockfileOf`\n * output, which never carries the `template` annotation, so the digest stays\n * a composition identity even when the on-disk file carries a baseline. */\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. Carries the `template`\n * annotation forward from the existing file. */\nexport function writeLockfileSync(lock: CompositionLockfile, configDir?: string): string {\n  const target = lockfilePath(configDir);\n  const existing = existsSync(target) ? readFileSync(target, \"utf8\") : null;\n  mkdirSync(path.dirname(target), { recursive: true });\n  const temp = `${target}.tmp`;\n  writeFileSync(temp, serializeLockfile(carriedTemplate(lock, existing)));\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  pointerDigest: 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 existing = await readFile(target, \"utf8\").catch(() => null);\n  const serialized = serializeLockfile(carriedTemplate(lock, existing));\n  if (opts?.check) {\n    if (existing === null) {\n      return {\n        status: \"drift\",\n        path: target,\n        pointerDigest: lock.pointerDigest,\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        pointerDigest: lock.pointerDigest,\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, pointerDigest: lock.pointerDigest, 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    pointerDigest: lock.pointerDigest,\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,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