{"version":3,"file":"confirm.mjs","names":[],"sources":["../../../src/services/registry/confirm.ts"],"sourcesContent":["import { registryClientShape } from \"./client\";\nimport { keyPathOf, type RegistryKey } from \"./keys\";\n\n/**\n * The publish-confirmation state machine: a registry write is verified, not\n * assumed. Every leg the publish wrote — the runtime config always, the\n * manifest tag and its version record on release trains — must read back\n * byte-equal before the publish counts, because FastKV writes are\n * action-indexed: the on-chain transaction's execution is irrelevant\n * (CodeDoesNotExist is the designed success path), the read-back is the\n * only authority.\n *\n * States: Pending → Indexed (the tx is visible in the registry's history;\n * the cheap probe) → Verified (every leg reads back deep-equal) | TimedOut\n * (deadline; the unverified legs are named). Two provisions carry over from\n * the polling loop this replaces: the history probe is informative only —\n * after two informative-but-absent probes, or any history failure, the\n * machine falls back permanently to plain content polling, so a registry\n * whose history never carries the tx still verifies; and a leg read failure\n * never skips the leg — it retries until the deadline.\n */\n\nexport type ConfirmLegKind = \"runtimeConfig\" | \"manifest\" | \"version\" | \"platformPointer\";\n\nexport interface ConfigConfirmLeg {\n  readonly kind: \"runtimeConfig\" | \"manifest\" | \"version\";\n  readonly key: RegistryKey;\n  /** The expected value — the exact publish payload (deep-equality via\n   * JSON compare; the registry serves the written value verbatim). */\n  readonly expected: unknown;\n}\n\nexport interface PlatformPointerConfirmLeg {\n  readonly kind: \"platformPointer\";\n  /** The pre-cutover wire key (`apps/<a>/<g>/platform.json`) — named\n   * verbatim in the timeout message. The pointer lives outside the key\n   * model's union until ticket 10's cutover, so it carries its wire key\n   * explicitly instead of a RegistryKey. */\n  readonly wireKey: string;\n  /** The pre-cutover transport, injected — `readPlatformPointer` bound to\n   * the runtime; never baked into keys.ts. */\n  readonly read: () => Promise<unknown>;\n  /** The expected value — the composed release manifest the leg wrote. */\n  readonly expected: unknown;\n}\n\nexport type ConfirmLeg = ConfigConfirmLeg | PlatformPointerConfirmLeg;\n\nexport type ConfirmVerdict =\n  | { readonly ok: true; readonly verified: readonly ConfirmLegKind[] }\n  | {\n      readonly ok: false;\n      readonly unverified: readonly ConfirmLegKind[];\n      readonly lastError?: string;\n    };\n\nexport interface ConfirmOptions {\n  readonly legs: readonly ConfirmLeg[];\n  /** The submit's tx hash (#430) — enables the indexed-probe fast path. */\n  readonly txHash?: string;\n  readonly timeoutMs?: number;\n  readonly intervalMs?: number;\n  /** Seams — tests substitute fakes; production defaults to the client. */\n  readonly read?: (key: RegistryKey) => Promise<unknown>;\n  readonly history?: (key: RegistryKey, limit: number) => Promise<Array<{ txHash?: string }>>;\n  readonly now?: () => number;\n  readonly sleep?: (ms: number) => Promise<void>;\n}\n\nconst envMs = (name: string): number | undefined => {\n  const raw = Number(process.env[name]);\n  return Number.isFinite(raw) && raw > 0 ? raw : undefined;\n};\n\nconst deepEqual = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);\n\nexport async function confirmPublish(opts: ConfirmOptions): Promise<ConfirmVerdict> {\n  const timeoutMs = opts.timeoutMs ?? envMs(\"BOS_PUBLISH_CONFIRMATION_TIMEOUT_MS\") ?? 120_000;\n  const intervalMs = opts.intervalMs ?? envMs(\"BOS_PUBLISH_CONFIRMATION_INTERVAL_MS\") ?? 3_000;\n  const read = opts.read ?? ((key: RegistryKey) => registryClientShape.read(key));\n  const history =\n    opts.history ?? ((key: RegistryKey, limit: number) => registryClientShape.history(key, limit));\n  const now = opts.now ?? Date.now;\n  const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n\n  const verified = new Set<ConfirmLegKind>();\n  const pending = () => opts.legs.filter((leg) => !verified.has(leg.kind));\n  const lastErrors = new Map<ConfirmLegKind, string>();\n\n  // The tx probe is informative only: after TX_PROBE_SKIP_LIMIT\n  // informative-but-absent probes — or any probe failure — the machine\n  // tracks by content alone. It probes the first keyed leg (the runtime\n  // config, always present in a real publish).\n  const TX_PROBE_SKIP_LIMIT = 2;\n  const probeLeg = opts.legs.find((leg): leg is ConfigConfirmLeg => \"key\" in leg);\n  let trackByTx = opts.txHash !== undefined && opts.history !== undefined && probeLeg !== undefined;\n  let txProbeSkips = 0;\n  let indexed = false;\n\n  const startedAt = now();\n  while (now() - startedAt < timeoutMs) {\n    if (trackByTx && !indexed) {\n      try {\n        const entries = await history(probeLeg!.key, 5);\n        if (entries.some((entry) => entry.txHash === opts.txHash)) {\n          indexed = true;\n          txProbeSkips = 0;\n        } else {\n          txProbeSkips += 1;\n          if (txProbeSkips >= TX_PROBE_SKIP_LIMIT) trackByTx = false;\n          await sleep(intervalMs);\n          continue;\n        }\n      } catch {\n        trackByTx = false;\n      }\n    }\n\n    for (const leg of pending()) {\n      try {\n        const served = \"read\" in leg ? await leg.read() : await read(leg.key);\n        if (deepEqual(served, leg.expected)) {\n          verified.add(leg.kind);\n          lastErrors.delete(leg.kind);\n        } else {\n          lastErrors.set(leg.kind, \"registry serves a different value\");\n        }\n      } catch (error) {\n        lastErrors.set(leg.kind, error instanceof Error ? error.message : String(error));\n      }\n    }\n\n    if (pending().length === 0) {\n      return { ok: true, verified: [...verified] };\n    }\n    await sleep(intervalMs);\n  }\n\n  const unverified = pending().map((leg) => leg.kind);\n  const lastError = [...lastErrors.values()].at(-1);\n  return { ok: false, unverified, ...(lastError ? { lastError } : {}) };\n}\n\n/** The train-facing failure message — the wire form of `TimedOut` (#422's\n * confirm channel): the legs' actual wire keys, named. */\nexport function describeConfirmTimeout(\n  legs: readonly ConfirmLeg[],\n  verdict: Extract<ConfirmVerdict, { ok: false }>,\n): string {\n  const unverifiedKeys = legs\n    .filter((leg) => verdict.unverified.includes(leg.kind))\n    .map((leg) => (\"wireKey\" in leg ? leg.wireKey : keyPathOf(leg.key)));\n  return (\n    `Timed out waiting for publish confirmation — unverified: ${unverifiedKeys.join(\", \")}` +\n    (verdict.lastError ? ` (last error: ${verdict.lastError})` : \"\")\n  );\n}\n"],"mappings":";;;;AAqEA,MAAM,SAAS,SAAqC;CAClD,MAAM,MAAM,OAAO,QAAQ,IAAI,KAAK;CACpC,OAAO,OAAO,SAAS,GAAG,KA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