{"version":3,"file":"runner.mjs","names":[],"sources":["../../../src/services/seed/runner.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { sql } from \"drizzle-orm\";\nimport type { PgDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { Effect } from \"effect\";\nimport { resolveDatabaseUrl } from \"../../db/binding\";\nimport { getMigrationStorage, pluginMigrationSlug } from \"../../db/core\";\nimport { createDatabaseDriver, pluginSchemaName } from \"../../db/driver\";\nimport type { WorkspaceIdentity } from \"../../db/identity\";\nimport { workspaceIdentityFromWorkspaceDir } from \"../../db/identity\";\nimport { loadMigrations, runMigrations } from \"../../db/run-migrations\";\nimport type { SeedConfig, SeedOwnerAdmin } from \"../../types\";\nimport { type PidEntry, pruneDead, readRegistry } from \"../processes/registry\";\n\n/**\n * The seed phase (#865): run the app's declared seed before services serve.\n *\n * Ordering is forced by the database topology. In dev every workspace DB is a\n * PGlite data dir held open by its service process for the process's lifetime\n * (ADR 0044) — cross-process opens block on the file lock — so nothing here\n * may run while services are up. The phase therefore runs pre-spawn, which\n * also means it must ensure the schema itself: a fresh checkout has no tables\n * until the services' in-process migrate-on-boot fires, and this phase runs\n * before it. `loadMigrations` + `runMigrations` replay each local workspace's\n * migrations against the same per-workspace journal the services use (ADR\n * 0045), so the later in-process run converges to a no-op.\n *\n * Steps are the general surface — arbitrary idempotent scripts (upserts by\n * contract) against any workspace DB, run once per `seed.version`. The marker\n * (one `bos_seed_state` row in the api database) records the version that\n * produced the current state; a matching version short-circuits the whole\n * phase, a bump re-runs it deliberately.\n *\n * The owner-admin bootstrap is framework-provided and always first: direct\n * writes into the auth database in exactly the row shape the SIWN flow\n * expects (`user` + `near_account` + `account`), so the configured owner\n * signs in with platform-admin rights immediately — `/near/verify` finds the\n * pre-provisioned `near_account` row and hands out a session for the admin\n * user instead of creating a second user. The row shapes couple this module\n * to the auth plugin's schema; both ship in release lockstep from this repo,\n * and a missing `near_account` table (schema drift) fails loudly before any\n * write.\n */\n\nexport const SEED_MARKER_TABLE = \"bos_seed_state\";\nconst SEED_MARKER_ID = \"app\";\n\ntype SeedDb = PgDatabase<PgQueryResultHKT, Record<string, unknown>>;\n\nexport class SeedPhaseError extends Error {\n  constructor(\n    message: string,\n    readonly stage: string,\n    readonly step?: string,\n  ) {\n    super(message);\n    this.name = \"SeedPhaseError\";\n  }\n}\n\nexport interface SeedOwnerCredential {\n  nearAccount?: string;\n  email?: string;\n}\n\n/** The runtime slice the phase needs — a full `RuntimeConfig` satisfies it. */\nexport interface SeedRuntimeShape {\n  api?: { localPath?: string } | null;\n  auth?: { localPath?: string } | null;\n  plugins?: Record<string, { localPath?: string }> | null;\n  networkId?: \"mainnet\" | \"testnet\";\n}\n\nexport interface SeedPhaseInput {\n  /** The app root (repo root) — step paths resolve against it. */\n  configDir: string;\n  seed: SeedConfig;\n  /** The resolved runtime — local workspace paths and the active network. */\n  runtime: SeedRuntimeShape;\n  /** Top-level `account` — the owner identity behind `ownerAdmin: true`. */\n  fallbackAccount?: string;\n  /** The siwn recipient for synthetic owner emails. */\n  siwnRecipient?: string;\n  /** The merged operator environment (already-loaded `.env` included). */\n  env: Record<string, string | undefined>;\n  /**\n   * Production credentials — env-provided, never config defaults. When set,\n   * they replace the authored owner identity entirely.\n   */\n  ownerOverride?: SeedOwnerCredential;\n  /** Re-run owner + steps even when the marker version matches. */\n  force?: boolean;\n}\n\nexport interface SeedStepOutcome {\n  step: string;\n  status: \"ran\" | \"failed\";\n  error?: string;\n}\n\nexport interface SeedOwnerOutcome {\n  mode: \"near\" | \"email\";\n  provisioned: boolean;\n  accountId: string;\n}\n\nexport interface SeedPhaseResult {\n  status: \"seeded\" | \"already-seeded\";\n  version: number;\n  markerWas: number | null;\n  workspaces: string[];\n  owner: SeedOwnerOutcome | null;\n  steps: SeedStepOutcome[];\n}\n\ninterface SeedWorkspace {\n  key: string;\n  slug: string;\n  workspaceDir: string | undefined;\n  identity: WorkspaceIdentity;\n  url: string;\n  schemaName: string | undefined;\n  hasMigrations: boolean;\n}\n\ninterface RuntimeEntry {\n  localPath?: string;\n}\n\nconst migrationsJournalPath = (workspaceDir: string): string =>\n  join(workspaceDir, \"src\", \"db\", \"migrations\", \"meta\", \"_journal.json\");\n\nconst secretNameForSlug = (slug: string): string =>\n  `${slug.toUpperCase().replace(/-/g, \"_\")}_DATABASE_URL`;\n\n/**\n * The workspaces the phase touches, in dependency order: auth first (the\n * owner bootstrap writes there), then the api shell (the marker's home),\n * then every local plugin. Remote entries resolve to their secret name with\n * no local dir — migrations are skipped for them (nothing to load) but the\n * binding still addresses the right database.\n */\nexport function resolveSeedWorkspaces(\n  runtime: SeedRuntimeShape,\n  configDir: string,\n  env: Record<string, string | undefined>,\n): SeedWorkspace[] {\n  const entries: Array<{ key: string; entry: RuntimeEntry | undefined; plugin: boolean }> = [\n    { key: \"auth\", entry: (runtime.auth ?? undefined) as RuntimeEntry | undefined, plugin: false },\n    { key: \"api\", entry: (runtime.api ?? undefined) as RuntimeEntry | undefined, plugin: false },\n    ...Object.keys(runtime.plugins ?? {})\n      .sort()\n      .map((key) => ({\n        key,\n        entry: runtime.plugins?.[key] as RuntimeEntry | undefined,\n        plugin: true,\n      })),\n  ];\n\n  const workspaces: SeedWorkspace[] = [];\n  for (const { key, entry, plugin } of entries) {\n    if (!entry) continue;\n    const slug = pluginMigrationSlug(key);\n    const workspaceDir = entry.localPath ? resolve(configDir, entry.localPath) : undefined;\n    const identity = workspaceDir\n      ? workspaceIdentityFromWorkspaceDir(workspaceDir)\n      : {\n          slug,\n          secretName: secretNameForSlug(slug),\n          journal: getMigrationStorage(slug),\n          workspaceDir: undefined,\n        };\n    const hasMigrations =\n      workspaceDir !== undefined && existsSync(migrationsJournalPath(workspaceDir));\n    // Addressable means the phase can at least open a database for the entry:\n    // a local workspace (pglite default applies) or an explicit URL in the\n    // environment. Skip only remotes we cannot address at all.\n    const addressable =\n      hasMigrations || workspaceDir !== undefined || Boolean(env[identity.secretName]);\n    if (!addressable) {\n      continue;\n    }\n    workspaces.push({\n      key,\n      slug: identity.slug,\n      workspaceDir,\n      identity,\n      url: resolveDatabaseUrl(identity, { env }),\n      schemaName: plugin ? pluginSchemaName(identity.slug) : undefined,\n      hasMigrations,\n    });\n  }\n  return workspaces;\n}\n\n/** Sequential open → use → close — the phase holds no driver across steps. */\nasync function withWorkspaceDb<T>(ws: SeedWorkspace, run: (db: SeedDb) => Promise<T>): Promise<T> {\n  const driver = await createDatabaseDriver<Record<string, unknown>>(\n    ws.url,\n    {},\n    ws.schemaName,\n    `${ws.identity.journal.schema}.${ws.identity.journal.table}`,\n  );\n  try {\n    return await run(driver.db);\n  } finally {\n    await driver.close();\n  }\n}\n\nfunction rowsOf(result: unknown): Array<Record<string, unknown>> {\n  if (Array.isArray(result)) return result as Array<Record<string, unknown>>;\n  const rows = (result as { rows?: unknown[] }).rows;\n  return Array.isArray(rows) ? (rows as Array<Record<string, unknown>>) : [];\n}\n\nasync function ensureMarkerTable(db: SeedDb): Promise<void> {\n  await db.execute(\n    sql.raw(\n      `CREATE TABLE IF NOT EXISTS \"${SEED_MARKER_TABLE}\" (` +\n        \"id text PRIMARY KEY, \" +\n        \"version integer NOT NULL, \" +\n        \"seeded_at timestamptz NOT NULL DEFAULT now(), \" +\n        \"steps jsonb)\",\n    ),\n  );\n}\n\nasync function readSeedMarker(api: SeedWorkspace): Promise<number | null> {\n  return withWorkspaceDb(api, async (db) => {\n    await ensureMarkerTable(db);\n    const result = await db.execute(\n      sql`SELECT version FROM ${sql.identifier(SEED_MARKER_TABLE)} WHERE id = ${SEED_MARKER_ID}`,\n    );\n    const row = rowsOf(result)[0];\n    return typeof row?.version === \"number\" ? row.version : null;\n  });\n}\n\nasync function writeSeedMarker(\n  api: SeedWorkspace,\n  version: number,\n  steps: string[],\n): Promise<void> {\n  await withWorkspaceDb(api, async (db) => {\n    await ensureMarkerTable(db);\n    await db.execute(\n      sql`INSERT INTO ${sql.identifier(SEED_MARKER_TABLE)} (id, version, steps)\n          VALUES (${SEED_MARKER_ID}, ${version}, ${JSON.stringify(steps)}::jsonb)\n          ON CONFLICT (id) DO UPDATE SET version = ${version}, seeded_at = now(), steps = ${JSON.stringify(steps)}::jsonb`,\n    );\n  });\n}\n\n/** Replay each local workspace's migrations against its own journal. */\nasync function ensureWorkspaceSchemas(workspaces: SeedWorkspace[]): Promise<string[]> {\n  const migrated: string[] = [];\n  for (const ws of workspaces) {\n    if (!ws.hasMigrations || !ws.workspaceDir) continue;\n    const loaded = await Effect.runPromise(\n      loadMigrations({ fromDir: join(ws.workspaceDir, \"src\", \"db\") }),\n    ).catch((cause: unknown) => {\n      throw new SeedPhaseError(\n        `loading migrations for \"${ws.key}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n        \"migrate\",\n      );\n    });\n    if (loaded.migrations.length === 0) continue;\n    await withWorkspaceDb(ws, (db) =>\n      Effect.runPromise(\n        runMigrations(db, loaded.migrations, {\n          journal: ws.identity.journal,\n          schemaName: ws.schemaName,\n        }),\n      ).catch((cause: unknown) => {\n        throw new SeedPhaseError(\n          `migrating \"${ws.key}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n          \"migrate\",\n        );\n      }),\n    );\n    migrated.push(ws.slug);\n  }\n  return migrated;\n}\n\n/**\n * Mirror better-near-auth's `deriveEmail` with a deterministic tail: the\n * single-segment `.near` shape the SIWN flow derives, or the recognized\n * `temp-<hex>@<recipient>` synthetic form (stable hash — re-runs must not\n * mint a second identity).\n */\nexport function ownerEmailForAccount(accountId: string, recipient: string): string {\n  if (accountId.endsWith(\".near\")) {\n    const localPart = accountId.slice(0, -5);\n    if (!localPart.includes(\".\")) return `${localPart}@near.email`;\n  }\n  const hash = createHash(\"sha256\").update(accountId).digest(\"hex\").slice(0, 8);\n  return `temp-${hash}@${recipient}`;\n}\n\nexport function resolveOwnerCredential(\n  ownerAdmin: SeedOwnerAdmin | undefined,\n  fallbackAccount: string | undefined,\n  override: SeedOwnerCredential | undefined,\n): SeedOwnerCredential | null {\n  if (override) {\n    if (!override.nearAccount && !override.email) return null;\n    return override;\n  }\n  if (!ownerAdmin) return null;\n  if (ownerAdmin === true) {\n    return fallbackAccount ? { nearAccount: fallbackAccount } : null;\n  }\n  const credential: SeedOwnerCredential = {};\n  if (ownerAdmin.nearAccount) credential.nearAccount = ownerAdmin.nearAccount;\n  if (ownerAdmin.email) credential.email = ownerAdmin.email;\n  return credential.nearAccount || credential.email ? credential : null;\n}\n\nconst findUserIdByNearAccount = async (db: SeedDb, accountId: string): Promise<string | null> => {\n  const result = await db.execute(\n    sql`SELECT u.id FROM \"user\" u JOIN near_account na ON na.user_id = u.id WHERE na.account_id = ${accountId} LIMIT 1`,\n  );\n  const row = rowsOf(result)[0];\n  return typeof row?.id === \"string\" ? row.id : null;\n};\n\nconst findUserIdByEmail = async (db: SeedDb, email: string): Promise<string | null> => {\n  const result = await db.execute(sql`SELECT id FROM \"user\" WHERE email = ${email} LIMIT 1`);\n  const row = rowsOf(result)[0];\n  return typeof row?.id === \"string\" ? row.id : null;\n};\n\nconst promoteToAdmin = async (db: SeedDb, userId: string): Promise<void> => {\n  await db.execute(sql`UPDATE \"user\" SET role = 'admin', updated_at = now() WHERE id = ${userId}`);\n};\n\n/**\n * Provision the owner as platform admin (`user.role = 'admin'`) in the auth\n * database. NEAR owners get the full SIWN row shape — `user`, `near_account`\n * (unique on `(account_id, network)`, which is exactly what `/near/verify`\n * resolves first), and the `account` provider row — so first sign-in finds\n * the admin user instead of minting a duplicate.\n */\nexport async function provisionOwnerAdmin(\n  auth: SeedWorkspace,\n  credential: SeedOwnerCredential,\n  options: { networkId?: string; recipient?: string },\n): Promise<SeedOwnerOutcome> {\n  return withWorkspaceDb(auth, async (db) => {\n    const nearTable = await db.execute(sql`SELECT to_regclass('public.near_account') AS reg`);\n    const reg = rowsOf(nearTable)[0]?.reg;\n    if (!reg) {\n      throw new SeedPhaseError(\n        \"the auth database has no near_account table — the auth plugin schema is missing or from an incompatible version; run `bos db doctor auth`\",\n        \"owner\",\n      );\n    }\n\n    const networkId = options.networkId ?? \"mainnet\";\n    const recipient = options.recipient ?? \"seed.internal\";\n\n    const ensureAdmin = async (userId: string): Promise<void> => {\n      const current = await db.execute(sql`SELECT role FROM \"user\" WHERE id = ${userId}`);\n      const role = rowsOf(current)[0]?.role;\n      if (role !== \"admin\") await promoteToAdmin(db, userId);\n    };\n\n    if (credential.nearAccount) {\n      const accountId = credential.nearAccount;\n      const existing =\n        (await findUserIdByNearAccount(db, accountId)) ??\n        (await findUserIdByEmail(db, ownerEmailForAccount(accountId, recipient)));\n      if (existing) {\n        await ensureAdmin(existing);\n        return { mode: \"near\", provisioned: true, accountId: existing };\n      }\n\n      const userId = randomUUID();\n      const email = ownerEmailForAccount(accountId, recipient);\n      await db.execute(\n        sql`INSERT INTO \"user\" (id, name, email, email_verified, role, created_at, updated_at)\n            VALUES (${userId}, ${accountId}, ${email}, true, 'admin', now(), now())`,\n      );\n      await db.execute(\n        sql`INSERT INTO near_account (id, user_id, account_id, network, public_key, is_primary, created_at)\n            VALUES (${randomUUID()}, ${userId}, ${accountId}, ${networkId}, 'seed:pending', true, now())`,\n      );\n      const providerAccountId = `${accountId}:${networkId}`;\n      const providerExists = rowsOf(\n        await db.execute(\n          sql`SELECT id FROM \"account\" WHERE provider_id = 'siwn' AND account_id = ${providerAccountId} LIMIT 1`,\n        ),\n      )[0];\n      if (!providerExists) {\n        await db.execute(\n          sql`INSERT INTO \"account\" (id, account_id, provider_id, user_id, created_at, updated_at)\n              VALUES (${randomUUID()}, ${providerAccountId}, 'siwn', ${userId}, now(), now())`,\n        );\n      }\n      return { mode: \"near\", provisioned: true, accountId: userId };\n    }\n\n    const email = credential.email!;\n    const existing = await findUserIdByEmail(db, email);\n    if (existing) {\n      await ensureAdmin(existing);\n      return { mode: \"email\", provisioned: true, accountId: existing };\n    }\n    const userId = randomUUID();\n    await db.execute(\n      sql`INSERT INTO \"user\" (id, name, email, email_verified, role, created_at, updated_at)\n          VALUES (${userId}, ${email.split(\"@\")[0]}, ${email}, true, 'admin', now(), now())`,\n    );\n    return { mode: \"email\", provisioned: true, accountId: userId };\n  });\n}\n\nasync function runSeedStep(\n  configDir: string,\n  step: string,\n  env: Record<string, string | undefined>,\n): Promise<void> {\n  const scriptPath = resolve(configDir, step);\n  if (!existsSync(scriptPath)) {\n    throw new SeedPhaseError(`seed step not found: ${step}`, \"steps\", step);\n  }\n  const timeoutRaw = env.SEED_STEP_TIMEOUT_MS;\n  const timeoutParsed = timeoutRaw ? Number(timeoutRaw) : Number.NaN;\n  const timeoutMs = Number.isFinite(timeoutParsed) && timeoutParsed > 0 ? timeoutParsed : undefined;\n  return new Promise((resolvePromise, reject) => {\n    // Own process group: the timeout must reach the whole step tree (tsx\n    // spawns the script as a child of itself — a bare child.kill can strand\n    // the inner process holding the pipes open).\n    const child = spawn(\"pnpm\", [\"exec\", \"tsx\", scriptPath], {\n      cwd: configDir,\n      env: env as NodeJS.ProcessEnv,\n      stdio: \"inherit\",\n      detached: process.platform !== \"win32\",\n    });\n    let timedOut = false;\n    let killTimer: NodeJS.Timeout | undefined;\n    const timer = timeoutMs\n      ? setTimeout(() => {\n          timedOut = true;\n          try {\n            if (child.pid) process.kill(-child.pid, \"SIGTERM\");\n          } catch {\n            child.kill(\"SIGTERM\");\n          }\n          killTimer = setTimeout(() => {\n            try {\n              if (child.pid) process.kill(-child.pid, \"SIGKILL\");\n            } catch {\n              child.kill(\"SIGKILL\");\n            }\n          }, 5_000);\n          killTimer.unref();\n        }, timeoutMs)\n      : undefined;\n    timer?.unref();\n    const cleanup = (): void => {\n      clearTimeout(timer);\n      clearTimeout(killTimer);\n    };\n    child.on(\"error\", (cause) => {\n      cleanup();\n      reject(\n        new SeedPhaseError(\n          `seed step \"${step}\" could not start (tsx must be installed at the workspace root): ${cause.message}`,\n          \"steps\",\n          step,\n        ),\n      );\n    });\n    child.on(\"exit\", (code) => {\n      cleanup();\n      if (timedOut) {\n        reject(\n          new SeedPhaseError(\n            `seed step \"${step}\" timed out after ${timeoutMs}ms (SEED_STEP_TIMEOUT_MS) — steps are idempotent by contract; fix and re-run (bump seed.version or pass --force)`,\n            \"steps\",\n            step,\n          ),\n        );\n        return;\n      }\n      if (code === 0) {\n        resolvePromise();\n        return;\n      }\n      reject(\n        new SeedPhaseError(\n          `seed step \"${step}\" exited with code ${code} — steps are idempotent by contract; fix and re-run (bump seed.version or pass --force)`,\n          \"steps\",\n          step,\n        ),\n      );\n    });\n  });\n}\n\n/**\n * A dev stack holds its PGlite data dirs open for its services' lifetime — a\n * cross-process seed run would queue on the file lock indefinitely (ADR 0044).\n * Fail fast when the shared pid registry shows a live session for this\n * project. Postgres workspaces are unaffected; an unreadable registry degrades\n * to best-effort (proceed).\n */\nexport function guardAgainstLiveStack(configDir: string, workspaces: SeedWorkspace[]): void {\n  if (!workspaces.some((ws) => ws.url.startsWith(\"pglite:\"))) return;\n  let live: PidEntry[];\n  try {\n    live = pruneDead(readRegistry());\n  } catch {\n    return;\n  }\n  const root = resolve(configDir);\n  const held = live.some((entry) => resolve(entry.configDir) === root);\n  if (held) {\n    throw new SeedPhaseError(\n      \"a dev stack for this project appears to be running (`bos ps`) — its services hold this \" +\n        \"project's PGlite data dirs open and a seed run would block on the file lock. Stop it \" +\n        \"first (`bos kill`), then re-run.\",\n      \"guard\",\n    );\n  }\n}\n\nexport async function runSeedPhase(input: SeedPhaseInput): Promise<SeedPhaseResult> {\n  const { seed, configDir, env, runtime } = input;\n  const workspaces = resolveSeedWorkspaces(runtime, configDir, env);\n  guardAgainstLiveStack(configDir, workspaces);\n  const api = workspaces.find((ws) => ws.key === \"api\");\n  if (!api) {\n    throw new SeedPhaseError(\n      \"no api workspace binding — the seed marker lives in the api database\",\n      \"marker\",\n    );\n  }\n  const auth = workspaces.find((ws) => ws.key === \"auth\");\n\n  // The marker gates everything: a matching version means the phase's writes\n  // already happened, so the boot pays one api-database open (the marker read)\n  // and skips migrations entirely — the services' in-process migrate-on-boot\n  // owns schema currency on that path. Migrations run only when the phase\n  // will actually seed.\n  const markerWas = await readSeedMarker(api);\n  const declaredSteps = seed.steps ?? [];\n  if (!input.force && markerWas === seed.version) {\n    return {\n      status: \"already-seeded\",\n      version: seed.version,\n      markerWas,\n      workspaces: [],\n      owner: null,\n      steps: [],\n    };\n  }\n\n  const migrated = await ensureWorkspaceSchemas(workspaces);\n\n  const credential = resolveOwnerCredential(\n    seed.auth?.ownerAdmin,\n    input.fallbackAccount,\n    input.ownerOverride,\n  );\n  let owner: SeedOwnerOutcome | null = null;\n  if (credential) {\n    if (!auth) {\n      throw new SeedPhaseError(\n        \"seed.auth.ownerAdmin is declared but the app has no auth slot to provision into\",\n        \"owner\",\n      );\n    }\n    owner = await provisionOwnerAdmin(auth, credential, {\n      networkId: runtime.networkId,\n      recipient: input.siwnRecipient,\n    });\n  }\n\n  const stepEnv: Record<string, string | undefined> = { ...process.env, ...env };\n  for (const ws of workspaces) {\n    if (!stepEnv[ws.identity.secretName]) {\n      stepEnv[ws.identity.secretName] = ws.url;\n    }\n  }\n\n  const outcomes: SeedStepOutcome[] = [];\n  for (const step of declaredSteps) {\n    try {\n      await runSeedStep(configDir, step, stepEnv);\n      outcomes.push({ step, status: \"ran\" });\n    } catch (error) {\n      const message = error instanceof Error ? error.message : String(error);\n      outcomes.push({ step, status: \"failed\", error: message });\n      throw error;\n    }\n  }\n\n  await writeSeedMarker(api, seed.version, declaredSteps);\n\n  return {\n    status: \"seeded\",\n    version: seed.version,\n    markerWas,\n    workspaces: migrated,\n    owner,\n    steps: outcomes,\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,oBAAoB;AACjC,MAAM,iBAAiB;AAIvB,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CAHX,YACE,SACA,AAAS,OACT,AAAS,MACT;EACA,MAAM,OAAO;EAHJ;EAC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