{"version":3,"file":"resolution.mjs","names":[],"sources":["../../../src/services/registry/resolution.ts"],"sourcesContent":["/**\n * The resolution state machine (sprint registry-primitive, ticket 03): one\n * authored pin or latest query in, one structured outcome out.\n *\n * Queries: `Pinned | Latest → Resolved | Unresolved`.\n * - `Pinned(ref, release)` scans the extends chain's version records —\n *   immutable, so a root release never strands a child pin (#574).\n * - `Latest(ref)` reads the manifest tag — the moving pointer.\n * - `Unresolved` carries a structured reason (`absent | unreachable |\n *   integrityFailure`) plus manifest context: what the tag serves, the\n *   extends chain walked, and the dead-end diagnostic — when the chain\n *   terminates at a runtime that publishes no manifest legs, the outcome\n *   says so with the terminus's last write date (the permanent lesson of\n *   the false FastKV data-loss alarm: `dev.everything.dev` is an abandoned\n *   dead-end gateway; the release root is `dev.everything.near/everything.dev`).\n * - The thin-tag digest chain: post-cutover the tag is `{ version, digest }`;\n *   resolution verifies the digest against the fetched version record's bytes\n *   before returning — a mismatch is `Unresolved(integrityFailure)`, never a\n *   silent pass.\n *\n * The cache (`registry/cache.ts`) is the stand-in layer: pin-match + TTL,\n * offline dev only. All I/O is injectable — the test seam.\n */\nimport { createHash } from \"node:crypto\";\nimport { getExtendsRef, parseBosRef } from \"../../utils/bos-ref\";\nimport {\n  type PlatformReleaseManifest,\n  PlatformReleaseManifestSchema,\n} from \"../platform/manifest-schema\";\nimport { fetchParentConfig } from \"../resolution/init-source\";\nimport {\n  MANIFEST_CACHE_TTL_MS,\n  type ManifestCacheRead,\n  type ManifestCacheRecord,\n  readManifestCache,\n  writeManifestCache,\n} from \"./cache\";\nimport { fetchConfigHistory, fetchRegistryKey, fetchRegistryKeyOrNull } from \"./fastkv\";\nimport { parseRuntimeRef, type RuntimeRef, runtimeRefOf } from \"./keys\";\n\nexport interface ExtendsChainNode {\n  account: string;\n  gateway: string;\n}\n\nexport interface ExtendsChainWalk {\n  /** child → root, nearest first — `chain[0]` is the local extends target */\n  chain: ExtendsChainNode[];\n  /** the most rootward `repository` seen — parent configs override the child's */\n  repository?: string;\n  /** set when the walk revisits a node — a pathological extends chain */\n  circularAt?: string;\n}\n\n/**\n * The ONE extends-chain walk (child → root via registry parent configs): the\n * resolution machine and the upgrade source resolution share this\n * implementation. A fetch failure (throw or null) stops the walk — the chain\n * gathered so far is still returned.\n */\nexport async function walkExtendsChain(input: {\n  localConfig: Record<string, unknown>;\n  localRepository?: string;\n  fetchParent?: (account: string, gateway: string) => Promise<Record<string, unknown> | null>;\n}): Promise<ExtendsChainWalk> {\n  const fetchParent =\n    input.fetchParent ??\n    (async (account: string, gateway: string) =>\n      fetchParentConfig(account, gateway)\n        .then((config) => config as Record<string, unknown>)\n        .catch(() => null));\n  const chain: ExtendsChainNode[] = [];\n  let repository = input.localRepository;\n\n  const startsRef = getExtendsRef(input.localConfig);\n  let cursor: ExtendsChainNode | null =\n    typeof startsRef === \"string\" && startsRef.startsWith(\"bos://\")\n      ? (parseBosRef(startsRef) ?? null)\n      : null;\n  const visited = new Set<string>();\n  let circularAt: string | undefined;\n\n  while (cursor) {\n    const ref = `bos://${cursor.account}/${cursor.gateway}`;\n    if (visited.has(ref)) {\n      circularAt = ref;\n      break;\n    }\n    visited.add(ref);\n    chain.push(cursor);\n\n    const parentConfig = await fetchParent(cursor.account, cursor.gateway);\n    if (!parentConfig) break;\n    if (typeof parentConfig.repository === \"string\" && parentConfig.repository) {\n      repository = parentConfig.repository;\n    }\n    const nextRef = getExtendsRef(parentConfig);\n    cursor =\n      typeof nextRef === \"string\" && nextRef.startsWith(\"bos://\")\n        ? (parseBosRef(nextRef) ?? null)\n        : null;\n  }\n\n  return {\n    chain,\n    ...(repository !== undefined ? { repository } : {}),\n    ...(circularAt ? { circularAt } : {}),\n  };\n}\n\n// ---------------------------------------------------------------------------\n// the machine\n\nexport type ResolutionQuery =\n  | { readonly kind: \"Pinned\"; readonly release: string; readonly ref?: RuntimeRef }\n  | { readonly kind: \"Latest\"; readonly ref?: RuntimeRef };\n\n/** What the tag home serves: the thin `{ version, digest }` pointer\n * (post-cutover), the full manifest (the pre-cutover pointer), or nothing. */\nexport type TagServes = \"thin\" | \"full\" | \"none\";\n\nexport interface DeadEndContext {\n  ref: RuntimeRef;\n  /** The terminus's last registry write, when the history endpoint served one. */\n  lastWrite?: string;\n}\n\n/** A type alias (not an interface) so the shape stays assignable to\n * `Record<string, unknown>` across the RPC contract boundary. */\nexport type ResolutionContext = {\n  /** child → root, nearest first — the chain that was scanned */\n  chain: readonly RuntimeRef[];\n  tagServes: TagServes;\n  /** the node a read or parse failed on, when the outcome is unreachable */\n  failureAt?: { account: string; gateway: string };\n  /** set when the chain terminates at a runtime that publishes no manifest\n   * legs — \"is this the runtime you meant?\" */\n  deadEnd?: DeadEndContext;\n};\n\nexport type ResolutionOutcome =\n  | {\n      readonly state: \"Resolved\";\n      readonly manifest: PlatformReleaseManifest;\n      /** the chain node that served the bytes */\n      readonly source: { account: string; gateway: string };\n      /** which home resolved the query: a version record (pinned), the\n       * manifest tag (latest), or the cache stand-in */\n      readonly from: \"version\" | \"manifest\" | \"cache\";\n      readonly provenance: \"slot\" | \"pointer\";\n      readonly fromCache: boolean;\n    }\n  | {\n      readonly state: \"Unresolved\";\n      readonly reason: \"absent\" | \"unreachable\" | \"integrityFailure\";\n      readonly detail?: string;\n      readonly context: ResolutionContext;\n    };\n\nexport interface ResolutionSeams {\n  /** The tag home (`manifest.json` post-cutover). Null = absent; throws =\n   * unreachable. */\n  readManifestTag(ref: RuntimeRef): Promise<unknown>;\n  /** The immutable version record's raw bytes (the digest chain verifies\n   * over text). Null = absent; throws = unreachable. */\n  readVersionRecord(ref: RuntimeRef, release: string): Promise<string | null>;\n  /** Parse a full manifest or record payload. Throws on a corrupt payload —\n   * the machine records it as unreachable. */\n  parseManifest(value: unknown): PlatformReleaseManifest;\n  fetchParent(account: string, gateway: string): Promise<Record<string, unknown> | null>;\n  cacheRead(pin?: string): ManifestCacheRead;\n  cacheWrite(record: ManifestCacheRecord): void;\n  /** Best-effort last-write date for the dead-end diagnostic — failures are\n   * swallowed (the field is simply omitted). */\n  lastWriteAt?(ref: RuntimeRef): Promise<string | undefined>;\n}\n\nconst refOf = (node: ExtendsChainNode): RuntimeRef =>\n  runtimeRefOf({ accountId: node.account, gatewayId: node.gateway });\n\n/** True when the tag payload is the thin `{ version, digest }` pointer —\n * the post-cutover wire that carries its own integrity reference. */\nfunction isThinTag(value: unknown): value is { version: string; digest: string } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as { version?: unknown }).version === \"string\" &&\n    typeof (value as { digest?: unknown }).digest === \"string\"\n  );\n}\n\nfunction sha256Hex(text: string): string {\n  return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\nasync function probeDeadEnd(\n  seams: ResolutionSeams,\n  terminus: ExtendsChainNode,\n): Promise<DeadEndContext | undefined> {\n  try {\n    const tag = await seams.readManifestTag(refOf(terminus));\n    if (tag) return undefined;\n  } catch {\n    // unreachable tag home — keep probing\n  }\n  const deadEnd: DeadEndContext = { ref: refOf(terminus) };\n  if (seams.lastWriteAt) {\n    try {\n      const lastWrite = await seams.lastWriteAt(refOf(terminus));\n      if (lastWrite) deadEnd.lastWrite = lastWrite;\n    } catch {\n      // best-effort\n    }\n  }\n  return deadEnd;\n}\n\nexport async function resolveRelease(input: {\n  query: ResolutionQuery;\n  localConfig: Record<string, unknown>;\n  localRepository?: string;\n  /** The cache location for the default (pre-cutover) seams. */\n  configDir?: string;\n  /** Partial overrides over the production seams — the test hook. */\n  seams?: Partial<ResolutionSeams>;\n  fetchParent?: (account: string, gateway: string) => Promise<Record<string, unknown> | null>;\n  now?: () => number;\n}): Promise<ResolutionOutcome> {\n  const now = input.now ?? Date.now;\n  const defaults = preCutoverSeams(input.configDir ?? process.cwd(), now);\n  const seams: ResolutionSeams = { ...defaults, ...input.seams };\n  const { chain } = await walkExtendsChain({\n    localConfig: input.localConfig,\n    ...(input.localRepository !== undefined ? { localRepository: input.localRepository } : {}),\n    ...(input.fetchParent ? { fetchParent: input.fetchParent } : {}),\n  });\n  const chainRefs = chain.map(refOf);\n\n  const writeCache = (\n    manifest: PlatformReleaseManifest,\n    node: ExtendsChainNode,\n    provenance: \"slot\" | \"pointer\",\n  ): void => {\n    seams.cacheWrite({\n      schemaVersion: 1,\n      kind: \"everything-dev/platform-manifest-cache\",\n      resolvedAt: new Date(now()).toISOString(),\n      source: { account: node.account, gateway: node.gateway },\n      manifest,\n      provenance,\n    });\n  };\n\n  const deadEndProbe = async (): Promise<DeadEndContext | undefined> => {\n    const terminus = chain.at(-1);\n    return terminus ? probeDeadEnd(seams, terminus) : undefined;\n  };\n\n  if (input.query.kind === \"Pinned\") {\n    const release = input.query.release;\n    for (const node of chain) {\n      let text: string | null;\n      try {\n        text = await seams.readVersionRecord(refOf(node), release);\n      } catch (error) {\n        // The record read failed: the offline cache may stand in (pin-match\n        // + TTL — an offline-dev aid, not stale-pin grace) — otherwise the\n        // outcome is unreachable with the failure node named.\n        const cached = seams.cacheRead(release);\n        if (cached.state === \"hit\") {\n          return {\n            state: \"Resolved\",\n            manifest: cached.record.manifest,\n            source: cached.record.source,\n            from: \"cache\",\n            provenance: cached.record.provenance ?? \"slot\",\n            fromCache: true,\n          };\n        }\n        return {\n          state: \"Unresolved\",\n          reason: \"unreachable\",\n          detail: error instanceof Error ? error.message : String(error),\n          context: { chain: chainRefs, tagServes: \"none\", failureAt: node },\n        };\n      }\n      if (text !== null) {\n        let manifest: PlatformReleaseManifest;\n        try {\n          manifest = seams.parseManifest(JSON.parse(text));\n        } catch (error) {\n          return {\n            state: \"Unresolved\",\n            reason: \"unreachable\",\n            detail: error instanceof Error ? error.message : String(error),\n            context: { chain: chainRefs, tagServes: \"none\", failureAt: node },\n          };\n        }\n        writeCache(manifest, node, \"slot\");\n        return {\n          state: \"Resolved\",\n          manifest,\n          source: { account: node.account, gateway: node.gateway },\n          from: \"version\",\n          provenance: \"slot\",\n          fromCache: false,\n        };\n      }\n    }\n    // Record miss across the chain — the release's manifest leg never\n    // published (the npm-version-exists / manifest-not-published race,\n    // #568). Slots are immutable, so this state means the release deploy\n    // must be re-run.\n    const deadEnd = await deadEndProbe();\n    return {\n      state: \"Unresolved\",\n      reason: \"absent\",\n      detail:\n        \"no version record in the extends chain\" +\n        (chainRefs.length > 0 ? ` (${chainRefs.join(\" → \")})` : \"\") +\n        ` — the release's manifest leg never published ${release}; re-run the release deploy (or \\`bos upgrade\\` to re-pin)`,\n      context: {\n        chain: chainRefs,\n        tagServes: \"none\",\n        ...(deadEnd ? { deadEnd } : {}),\n      },\n    };\n  }\n\n  // Latest: read the tag — the moving pointer.\n  let unreachable: { detail: string; node: ExtendsChainNode } | undefined;\n  let tagServes: TagServes = \"none\";\n  for (const node of chain) {\n    let tag: unknown;\n    try {\n      tag = await seams.readManifestTag(refOf(node));\n    } catch (error) {\n      unreachable = {\n        detail: error instanceof Error ? error.message : String(error),\n        node,\n      };\n      break;\n    }\n    if (!tag) continue;\n    if (isThinTag(tag)) {\n      tagServes = \"thin\";\n      let text: string | null;\n      try {\n        text = await seams.readVersionRecord(refOf(node), tag.version);\n      } catch (error) {\n        return {\n          state: \"Unresolved\",\n          reason: \"unreachable\",\n          detail: error instanceof Error ? error.message : String(error),\n          context: { chain: chainRefs, tagServes, failureAt: node },\n        };\n      }\n      if (text === null) {\n        return {\n          state: \"Unresolved\",\n          reason: \"absent\",\n          detail: `the manifest tag names ${tag.version} but its version record is absent at ${refOf(node)}`,\n          context: { chain: chainRefs, tagServes },\n        };\n      }\n      if (sha256Hex(text) !== tag.digest) {\n        return {\n          state: \"Unresolved\",\n          reason: \"integrityFailure\",\n          detail: `the manifest tag's digest does not match the version record's bytes at ${refOf(node)} — refusing`,\n          context: { chain: chainRefs, tagServes },\n        };\n      }\n      let manifest: PlatformReleaseManifest;\n      try {\n        manifest = seams.parseManifest(JSON.parse(text));\n      } catch (error) {\n        return {\n          state: \"Unresolved\",\n          reason: \"unreachable\",\n          detail: error instanceof Error ? error.message : String(error),\n          context: { chain: chainRefs, tagServes, failureAt: node },\n        };\n      }\n      writeCache(manifest, node, \"pointer\");\n      return {\n        state: \"Resolved\",\n        manifest,\n        source: { account: node.account, gateway: node.gateway },\n        from: \"manifest\",\n        provenance: \"pointer\",\n        fromCache: false,\n      };\n    }\n    // full manifest tag (pre-cutover pointer)\n    tagServes = \"full\";\n    let manifest: PlatformReleaseManifest;\n    try {\n      manifest = seams.parseManifest(tag);\n    } catch (error) {\n      unreachable = {\n        detail: error instanceof Error ? error.message : String(error),\n        node,\n      };\n      break;\n    }\n    writeCache(manifest, node, \"pointer\");\n    return {\n      state: \"Resolved\",\n      manifest,\n      source: { account: node.account, gateway: node.gateway },\n      from: \"manifest\",\n      provenance: \"pointer\",\n      fromCache: false,\n    };\n  }\n\n  if (unreachable) {\n    return {\n      state: \"Unresolved\",\n      reason: \"unreachable\",\n      detail: unreachable.detail,\n      context: { chain: chainRefs, tagServes, failureAt: unreachable.node },\n    };\n  }\n\n  const cached = seams.cacheRead();\n  if (cached.state === \"hit\") {\n    return {\n      state: \"Resolved\",\n      manifest: cached.record.manifest,\n      source: cached.record.source,\n      from: \"cache\",\n      provenance: cached.record.provenance ?? \"pointer\",\n      fromCache: true,\n    };\n  }\n  const deadEnd = await deadEndProbe();\n  return {\n    state: \"Unresolved\",\n    reason: \"absent\",\n    context: {\n      chain: chainRefs,\n      tagServes,\n      ...(deadEnd ? { deadEnd } : {}),\n    },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// the production seams — the pre-cutover transport\n\n// TODO(cutover): the train still writes `platform.json` and\n// `platform-versions/<v>.json` (ticket 10 flips the wire to `manifest.json` /\n// `versions/<v>.json`). This transport and the two inline key templates read\n// the current wire and are deleted at the cutover — the machine itself\n// speaks only in RuntimeRef terms.\nfunction tagKeyOf(account: string, gateway: string): string {\n  return `apps/${account}/${gateway}/platform.json`;\n}\n\nfunction versionKeyOf(account: string, gateway: string, version: string): string {\n  return `apps/${account}/${gateway}/platform-versions/${version}.json`;\n}\n\nfunction preCutoverSeams(configDir: string, now: () => number): ResolutionSeams {\n  return {\n    async readManifestTag(ref) {\n      const { accountId, gatewayId } = parseRuntimeRef(ref);\n      const raw = await fetchRegistryKeyOrNull<unknown>(accountId, gatewayId, \"platform.json\");\n      return raw ?? null;\n    },\n    async readVersionRecord(ref, release) {\n      const { accountId, gatewayId } = parseRuntimeRef(ref);\n      // NOT the OrNull variant: a read failure must stay distinguishable\n      // from a clean absent record — the machine fails loud with the node\n      // named on a failure and treats null as absence.\n      const raw = await fetchRegistryKey<unknown>(\n        accountId,\n        gatewayId,\n        versionKeyOf(accountId, gatewayId, release),\n      );\n      return raw === null ? null : JSON.stringify(raw);\n    },\n    parseManifest(value) {\n      return PlatformReleaseManifestSchema.parse(value);\n    },\n    fetchParent(account, gateway) {\n      return fetchParentConfig(account, gateway)\n        .then((config) => config as Record<string, unknown>)\n        .catch(() => null);\n    },\n    cacheRead(pin) {\n      return readManifestCache({\n        configDir,\n        ...(pin !== undefined ? { pin } : {}),\n        now,\n      });\n    },\n    cacheWrite(record) {\n      writeManifestCache({ configDir, record });\n    },\n    async lastWriteAt(ref) {\n      try {\n        const { accountId, gatewayId } = parseRuntimeRef(ref);\n        const entries = await fetchConfigHistory({\n          accountId,\n          gatewayId,\n          limit: 1,\n          keyPath: tagKeyOf(accountId, gatewayId),\n        });\n        const ns = entries[0]?.blockTimestampNs;\n        if (!ns) return undefined;\n        const ms = Number(ns) / 1_000_000;\n        return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;\n      } catch {\n        return undefined;\n      }\n    },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// the compatibility adapter — the old resolver's exact signature and\n// semantics, implemented on the machine. Callers consume the machine through\n// this shape until the outcome-typed migration (ticket 05+).\n\nexport interface ResolvedPlatformManifest {\n  manifest: PlatformReleaseManifest;\n  source: { account: string; gateway: string };\n  fromCache: boolean;\n  /** Where the resolved bytes came from (#574): an immutable version record\n   * (an exact pin's target) or the moving tag (unpinned \"latest\"\n   * resolution). */\n  provenance: \"slot\" | \"pointer\";\n}\n\nexport type PlatformManifestCache = ManifestCacheRecord;\n\nexport interface ResolvePlatformManifestOptions {\n  configDir: string;\n  localConfig: Record<string, unknown>;\n  fetchManifest?: (account: string, gateway: string) => Promise<PlatformReleaseManifest | null>;\n  /** The immutable version-record read (#574) — an exact pin's target.\n   * Throws on read failure (distinct from a clean absent record). */\n  fetchSlot?: (account: string, gateway: string, version: string) => Promise<unknown>;\n  fetchParent?: (account: string, gateway: string) => Promise<Record<string, unknown> | null>;\n  cacheRead?: () => PlatformManifestCache | null;\n  cacheWrite?: (cached: PlatformManifestCache) => void;\n  /** injectable clock for the cache-freshness check (test seam) */\n  now?: () => number;\n  /** injectable freshness bound (test seam); defaults to {@link MANIFEST_CACHE_TTL_MS} */\n  cacheTtlMs?: number;\n}\n\nexport async function resolvePlatformManifest(\n  opts: ResolvePlatformManifestOptions,\n): Promise<ResolvedPlatformManifest | null> {\n  const pin =\n    typeof opts.localConfig.platform === \"string\" && opts.localConfig.platform\n      ? opts.localConfig.platform\n      : undefined;\n\n  const overrides: Partial<ResolutionSeams> = {};\n  if (opts.fetchManifest) {\n    overrides.readManifestTag = async (ref) => {\n      const { accountId, gatewayId } = parseRuntimeRef(ref);\n      return opts.fetchManifest!(accountId, gatewayId);\n    };\n  }\n  if (opts.fetchSlot) {\n    overrides.readVersionRecord = async (ref, release) => {\n      const { accountId, gatewayId } = parseRuntimeRef(ref);\n      const raw = await opts.fetchSlot!(accountId, gatewayId, release);\n      return raw === null || raw === undefined ? null : JSON.stringify(raw);\n    };\n  }\n  if (opts.cacheRead) {\n    overrides.cacheRead = (pinKey) => {\n      const record = opts.cacheRead?.();\n      if (!record) return { state: \"miss\" };\n      const now = (opts.now ?? Date.now)();\n      const ttl = opts.cacheTtlMs ?? MANIFEST_CACHE_TTL_MS;\n      const resolvedAt = Date.parse(record.resolvedAt);\n      if (Number.isNaN(resolvedAt) || now - resolvedAt > ttl) return { state: \"stale\", record };\n      if (pinKey !== undefined && record.manifest.frameworkVersion !== pinKey) {\n        return { state: \"stale\", record };\n      }\n      return { state: \"hit\", record };\n    };\n  }\n  if (opts.cacheWrite) {\n    overrides.cacheWrite = (record) => opts.cacheWrite?.(record);\n  }\n\n  const query: ResolutionQuery = pin ? { kind: \"Pinned\", release: pin } : { kind: \"Latest\" };\n  const outcome = await resolveRelease({\n    query,\n    localConfig: opts.localConfig,\n    configDir: opts.configDir,\n    ...(opts.now ? { now: opts.now } : {}),\n    ...(Object.keys(overrides).length > 0 ? { seams: overrides } : {}),\n    ...(opts.fetchParent ? { fetchParent: opts.fetchParent } : {}),\n  });\n\n  if (outcome.state === \"Resolved\") {\n    return {\n      manifest: outcome.manifest,\n      source: outcome.source,\n      fromCache: outcome.fromCache,\n      provenance: outcome.provenance,\n    };\n  }\n\n  // Unresolved → the old failure surface: null for clean absence on\n  // latest, loud errors for everything a caller must act on.\n  const chainUrls = outcome.context.chain.join(\" → \");\n  if (outcome.reason === \"unreachable\") {\n    if (pin) {\n      const node = outcome.context.failureAt;\n      const slotKey = node\n        ? versionKeyOf(node.account, node.gateway, pin)\n        : `platform-versions/${pin}.json`;\n      throw new Error(\n        `platform pin ${pin}: the version slot read failed (${slotKey}): ${outcome.detail}`,\n      );\n    }\n    throw new Error(outcome.detail ?? \"the manifest tag read failed\");\n  }\n  if (pin) {\n    throw new Error(\n      `platform pin ${pin}: no version slot in the extends chain` +\n        (chainUrls ? ` (${chainUrls})` : \"\") +\n        ` — the release's manifest leg never published it; re-run the release deploy (or \\`bos upgrade\\` to re-pin)`,\n    );\n  }\n  return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,eAAsB,iBAAiB,OAIT;CAC5B,MAAM,cACJ,MAAM,gBACL,OAAO,SAAiB,YACvB,kBAAkB,SAAS,OAAO,CAAC,CAChC,MAAM,WAAW,MAAiC,CAAC,CACnD,YAAY,IAAI;CACvB,MAAM,QAA4B,CAAC;CACnC,IAAI,aAAa,MAAM;CAEvB,MAA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