{"version":3,"file":"release-composition.mjs","names":[],"sources":["../../../src/services/resolution/release-composition.ts"],"sourcesContent":["import { SHARED_DEP_SPECS } from \"every-plugin/shared-deps-spec\";\nimport { resolveRemoteVersion } from \"../deploy/version-manifest\";\nimport type { RemoteRecord } from \"../platform/manifest\";\nimport { ensureObjectContainers, type Remote, walkRemotes } from \"../remotes\";\nimport { isPlainObject } from \"./merge\";\n\n/**\n * The release plane (ADR 0034 amendment — release-scoped extends\n * inheritance): a platform-pinned child composes the remotes the pinned\n * release recorded instead of drifting with the parent's live config\n * pointer. One implementation, two adapters: the deploy train stamps the\n * child's publish payload before it publishes, and every consumer boot\n * stamps the extends-merged shape before composition — so production, local\n * dev, and type generation all resolve the same release bytes.\n *\n * Without the plane, a root publish (rc.N+1) moves the inherited auth pin\n * while a platform-pinned child's own ui stays built against rc.N — the\n * host's shared-singleton guard (#546) refuses the composition at boot.\n */\n\n/** Keys that name where a remote's code comes from — owning the remote's bytes. */\nconst REMOTE_SOURCE_KEYS = [\"production\", \"development\", \"digest\", \"extends\", \"proxy\"] as const;\n\n/**\n * A remote is authored when its entry names a code source (or opts out with\n * `ui: false` / owns it via a bare plugin ref). An entry that only configures\n * an inherited remote — `variables`, `secrets`, `routes`, … — does not own its\n * bytes, so the release still pins them.\n */\nfunction declaresRemoteSource(entry: Remote[\"entry\"]): boolean {\n  if (entry === false || typeof entry === \"string\") return true;\n  return REMOTE_SOURCE_KEYS.some((key) => entry[key] !== undefined);\n}\n\n/** Authored remote paths: every remote whose code source the leaf itself declares. */\nexport function authoredRemoteKeys(config: Record<string, unknown>): Set<string> {\n  const paths = new Set<string>();\n  walkRemotes(config, ({ remote, entry, isPluginRef }) => {\n    if (declaresRemoteSource(entry)) paths.add(remote);\n    // KEEP: a bare-string plugin ref (`extends: \"bos://…\"`) owns its whole\n    // surface — composed resolution derives its ui from the extended config,\n    // so the ownership set must include it independently of the `ui` key.\n    if (isPluginRef) paths.add(`${remote}.ui`);\n  });\n  return paths;\n}\n\n/** Stamped and omitted remote paths (diagnostic), in stamp order. */\nexport interface StampOutcome {\n  stamped: string[];\n  omitted: string[];\n}\n\n/**\n * `payload` — the deploy train's publish-payload seam: `app.*` remotes only,\n * created when absent (a payload's authored config may know nothing about an\n * inherited app remote; the stamp is its introduction). Creating plugin entries\n * is deliberately refused — a child's declared `plugins` object owns the\n * whole domain in one wholesale replace (`mergeBosConfigWithExtends`), so a\n * stamped plugin ui record alone carries no required `name` and the wholesale\n * replace never fills it (the feedback.nearbuilders.org rc.26 incident).\n *\n * `consumer` — every consumer boot (`bos dev`, host boot, tenant\n * resolution): `app.*` AND `plugins.*` stamp by **merging `{ production, pin\n * }` into the existing inherited entry** — schema-valid by construction (the\n * live entry already carries the remote's full shape). Nothing is created: a\n * path absent from the merged shape is a post-release provisioned remote the\n * pinned plane cannot claim, so it is omitted and reported for the dev\n * audit instead of being silently live-followed (the skew bug class).\n */\nexport type CompositionMode = \"payload\" | \"consumer\";\n\nexport function stampInheritedRemotes(input: {\n  config: Record<string, unknown>;\n  authoredConfig: Record<string, unknown>;\n  remotes: Record<string, RemoteRecord> | undefined;\n  mode: CompositionMode;\n}): StampOutcome {\n  const remotes = input.remotes ?? {};\n  const authored = authoredRemoteKeys(input.authoredConfig);\n  const stamped: string[] = [];\n  const omitted: string[] = [];\n\n  for (const [remotePath, record] of Object.entries(remotes)) {\n    const isAppRemote = /^app\\.[^.]+(\\.ui)?$/.test(remotePath);\n    if (input.mode === \"payload\" && !isAppRemote) continue;\n    if (authored.has(remotePath)) continue;\n    if (input.mode === \"consumer\" && !remoteEntryAt(input.config, remotePath)) {\n      omitted.push(remotePath);\n      continue;\n    }\n    stampRemoteRecord(input.config, remotePath, record);\n    stamped.push(remotePath);\n  }\n  return { stamped, omitted };\n}\n\n/** The entry object at a dotted remote path (2–3 segments), if it exists. */\nfunction remoteEntryAt(\n  config: Record<string, unknown>,\n  remotePath: string,\n): Record<string, unknown> | undefined {\n  const segments = remotePath.split(\".\");\n  if ((segments.length !== 2 && segments.length !== 3) || !segments[0] || !segments[1]) {\n    return undefined;\n  }\n  let node: unknown = config;\n  for (const segment of segments.slice(0, -1)) {\n    if (!isPlainObject(node)) return undefined;\n    node = node[segment];\n  }\n  if (!isPlainObject(node)) return undefined;\n  const leaf = segments.at(-1);\n  if (leaf === undefined) return undefined;\n  const entry = node[leaf];\n  return isPlainObject(entry) ? entry : undefined;\n}\n\n/** Write `{ production, digest }` for one dotted remote path (2–3 segments),\n * merging into an existing entry rather than replacing it. */\nfunction stampRemoteRecord(\n  config: Record<string, unknown>,\n  remotePath: string,\n  record: RemoteRecord,\n): void {\n  const segments = remotePath.split(\".\");\n  if ((segments.length !== 2 && segments.length !== 3) || !segments[0] || !segments[1]) return;\n  const leaf = segments.at(-1);\n  const container = ensureObjectContainers(config, segments.slice(0, -1));\n  if (!leaf) return;\n  const existing = container[leaf];\n  const entry: Record<string, unknown> = isPlainObject(existing) ? { ...existing } : {};\n  entry.production = record.base;\n  entry.digest = { manifest: record.digest.manifest, integrity: record.digest.integrity };\n  container[leaf] = entry;\n}\n\nexport interface CompositionAuditLine {\n  remote: string;\n  kind: \"inherited\" | \"owned\" | \"provisioned\" | \"uncomposed\";\n  message: string;\n}\n\n/** The package name a subpath singleton resolves through: `everything-dev/ui/auth`\n * → `everything-dev` (scoped: `@scope/pkg/sub` → `@scope/pkg`; a bare package\n * name — including `@scope/pkg` — has no subpath and yields undefined). */\nfunction subpathBaseName(name: string): string | undefined {\n  if (!name.includes(\"/\")) return undefined;\n  if (name.startsWith(\"@\")) {\n    const segments = name.split(\"/\");\n    return segments.length >= 3 ? `${segments[0]}/${segments[1]}` : undefined;\n  }\n  const [pkg] = name.split(\"/\");\n  return pkg;\n}\n\n/**\n * The publish key an owned remote realigns through: the workspace key the\n * scoped deploy train and `bos plugin publish` understand — `app.<key>` and\n * `app.<key>.ui` publish as the app key (`ui`, `api`, …), `plugins.<id>` and\n * `plugins.<id>.ui` as the plugin id. Remote paths themselves are not keys.\n */\nexport function workspaceKeyOfRemote(remote: string): string {\n  const [domain, key] = remote.split(\".\");\n  return domain === \"app\" || domain === \"plugins\" ? (key ?? remote) : remote;\n}\n\n/** The repair instruction for an owned remote diverging on shared singletons:\n * app remotes republish through the scoped deploy train (they are not plugins);\n * plugin remotes through the single-plugin publish. */\nfunction ownedRemoteRepair(remote: string): string {\n  const key = workspaceKeyOfRemote(remote);\n  const command = remote.startsWith(\"app.\")\n    ? `bos deploy --packages ${key}`\n    : `bos plugin publish ${key}`;\n  return `run ${command} (built against an older chain)`;\n}\n\n/**\n * The dev-boot chain audit (ADR 0034 + #546's shared-singleton trust):\n * every pinned remote's embedded singleton versions are compared\n * against the local workspace catalog — the same `satisfiesConstraint`\n * family the deploy-train compat-window gate speaks, so one mismatch\n * reads the same way in the train and on screen. One line per divergent\n * remote, with the repair named for its ownership: inherited →\n * `bos upgrade` (the pin trails the chain serving the remote); owned →\n * `bos plugin publish <key>` (built against an older chain). Empty out:\n * the whole composition composes coherently.\n *\n * Two composition-shape signals ride beside the version check:\n * - a config remote the pinned manifest does not record is genuinely\n *   provisioned upstream after the pin — it composes live, unpinned bytes,\n *   and `bos upgrade` claims it;\n * - a manifest remote the merged config does not compose is NOT an upgrade\n *   candidate — a child declaring its own `plugins` domain wholesale-\n *   replaces the inherited one by design, so that is an uncomposed remote\n *   note, never a \"run bos upgrade\" instruction (an upgrade cannot change\n *   the merged shape).\n */\nexport async function auditReleaseComposition(input: {\n  remotes: Array<{ remote: string; base: string; digest: { manifest: string; integrity: string } }>;\n  authoredPaths: Set<string>;\n  /** The installed version this runtime composes for one singleton name —\n   * the probe the boot guard consults too (catalog for framework names,\n   * node_modules for the rest). */\n  localVersionOf: (name: string) => string | undefined;\n  provisionedRemotes?: readonly string[];\n  /** Every remote path the merged resolved config walks (authored + inherited). */\n  configRemotePaths?: readonly string[];\n  /** Remote paths the pinned release manifest records. */\n  manifestRemotePaths?: readonly string[];\n  pinnedReleaseVersion?: string;\n  /** test seam — threaded to the version-manifest fetch */\n  fetchImpl?: typeof fetch;\n}): Promise<CompositionAuditLine[]> {\n  const lines: CompositionAuditLine[] = [];\n  const strictness = new Map(SHARED_DEP_SPECS.map((spec) => [spec.name, spec.critical]));\n  const manifestRemotePaths = new Set(input.manifestRemotePaths ?? []);\n\n  for (const { remote, base, digest } of input.remotes) {\n    const kind = input.authoredPaths.has(remote) ? \"owned\" : \"inherited\";\n    const repair =\n      kind === \"owned\"\n        ? ownedRemoteRepair(remote)\n        : \"run bos upgrade (the pin trails the chain serving this remote)\";\n    // Subpath singletons (`everything-dev/ui/auth`, `everything-dev/ui/i18n`)\n    // never resolve as local packages — no own package.json or catalog row —\n    // so the probe falls back to the base package's installed version: the\n    // same package ships the subpath, one version serves both names.\n    const localOf = (sharedName: string): string | undefined => {\n      const local = input.localVersionOf(sharedName);\n      if (local !== undefined) return local;\n      const base = subpathBaseName(sharedName);\n      return base ? input.localVersionOf(base) : undefined;\n    };\n    try {\n      const resolved = await resolveRemoteVersion({\n        base,\n        digest,\n        ...(input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}),\n      });\n      for (const [name, version] of Object.entries(resolved.sharedVersions ?? {})) {\n        // Strict singletons must agree exactly (shareConfigFor: critical ⇒\n        // strictVersion true); non-strict names range-coexist by design — no line.\n        if (!strictness.get(name)) continue;\n        const local = localOf(name);\n        if (local !== undefined && local === version) continue;\n        lines.push({\n          remote,\n          kind,\n          message:\n            `${remote} was built against ${name}@${version}, this runtime composes ${name}@${local ?? \"unknown\"} — ` +\n            `${repair}`,\n        });\n        break;\n      }\n    } catch (error) {\n      const reason = error instanceof Error ? error.message : String(error);\n      lines.push({\n        remote,\n        kind,\n        message: `${remote}'s version manifest does not serve at its production URL (${reason}) — ${repair}`,\n      });\n    }\n  }\n\n  // Config remotes the pinned manifest does not record: genuinely provisioned\n  // upstream after the pin — they compose live, unpinned bytes, so the repair\n  // is a real re-pin. Inherited only (authored remotes are the leaf's own\n  // decision, and pinned ones are already claimed by the manifest).\n  const pinnedRemotes = new Set(input.remotes.map((ref) => ref.remote));\n  for (const remote of input.configRemotePaths ?? []) {\n    if (\n      !manifestRemotePaths.has(remote) &&\n      !pinnedRemotes.has(remote) &&\n      !input.authoredPaths.has(remote)\n    ) {\n      // The auth mirror (config.ts adds plugins.auth mirroring app.auth — the\n      // plugin runtime's compose surface) composes app.auth's pinned bytes;\n      // the release manifest records the remote under its app domain (\"its\n      // pins live on app.auth\" — resolution/runtime.ts). A recorded app.auth\n      // covers the mirror; without one the mirror is genuinely unpinned.\n      if (remote === \"plugins.auth\" && manifestRemotePaths.has(\"app.auth\")) continue;\n      lines.push({\n        remote,\n        kind: \"provisioned\",\n        message:\n          `remote \"${remote}\" is served by the extends chain but missing from the ` +\n          `${input.pinnedReleaseVersion ?? \"pinned\"} release composition — it composes live, unpinned bytes; ` +\n          `run bos upgrade to re-pin and claim it`,\n      });\n    }\n  }\n\n  for (const remote of input.provisionedRemotes ?? []) {\n    lines.push({\n      remote,\n      kind: \"uncomposed\",\n      message:\n        `remote \"${remote}\" is recorded in the ${input.pinnedReleaseVersion ?? \"pinned\"} release ` +\n        `but not composed by this config — declare it in your config's app/plugins domain to compose it`,\n    });\n  }\n  return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,qBAAqB;CAAC;CAAc;CAAe;CAAU;CAAW;AAAO;;;;;;;AAQrF,SAAS,qBAAqB,OAAiC;CAC7D,IAAI,UAAU,SAAS,OAAO,UAAU,UAAU,OAAO;CACzD,OAAO,mBAAmB,MAAM,QAAQ,MAAM,SAAS,MAAS;AAClE;;AAGA,SAAgB,mBAAmB,QAA8C;CAC/E,MAAM,wBAAQ,IAAI,IAAY;CAC9B,YAAY,SAAS,EAAE,QAAQ,OAAO,kBAAkB;EACtD,IAAI,qBAAqB,KAAK,GAAG,MAAM,IAAI,MAAM;EAIjD,IAAI,aAAa,MAAM,IAAI,GAAG,OAAO,IAAI;CAC3C,CAAC;CACD,OAAO;AACT;AA2BA,SAAgB,s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