@powerhousedao/switchboard 6.2.3-dev.96 → 6.2.3-dev.98
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +14 -0
- package/README.md +1 -0
- package/dist/boot.d.mts +1 -1
- package/dist/boot.mjs +1 -1
- package/dist/config/from-env.d.mts +1 -1
- package/dist/config/from-env.d.mts.map +1 -1
- package/dist/config/from-env.mjs +3 -3
- package/dist/config/schema.d.mts +1 -1
- package/dist/config/schema.mjs +3 -3
- package/dist/{from-env-C6dHDvAu.mjs → from-env-FH4fPeIE.mjs} +12 -5
- package/dist/from-env-FH4fPeIE.mjs.map +1 -0
- package/dist/index.mjs +3 -3
- package/dist/{plugin-host-H2uebOKI.d.mts → plugin-host-CK9_tVak.d.mts} +2 -2
- package/dist/{plugin-host-H2uebOKI.d.mts.map → plugin-host-CK9_tVak.d.mts.map} +1 -1
- package/dist/plugins/ai.d.mts +1 -1
- package/dist/plugins/attachments.d.mts +1 -1
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/plugins/mcp.d.mts +1 -1
- package/dist/plugins/privacy.d.mts +1 -1
- package/dist/plugins/workflows.d.mts +1 -1
- package/dist/{schema-B11_2pKM.mjs → schema-CsY8bjsu.mjs} +5 -4
- package/dist/schema-CsY8bjsu.mjs.map +1 -0
- package/dist/{schema-BRNH0PaA.d.mts → schema-MAUTnmj1.d.mts} +5 -1
- package/dist/schema-MAUTnmj1.d.mts.map +1 -0
- package/dist/{server-DyLVCH38.mjs → server-CirQ9hyu.mjs} +7 -5
- package/dist/{server-DyLVCH38.mjs.map → server-CirQ9hyu.mjs.map} +1 -1
- package/dist/server.d.mts +2 -2
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -4
- package/dist/{types-DzO3_320.d.mts → types-CidZdkhU.d.mts} +8 -2
- package/dist/types-CidZdkhU.d.mts.map +1 -0
- package/dist/utils.d.mts +1 -1
- package/package.json +17 -17
- package/test/config-merge.test.ts +22 -0
- package/dist/from-env-C6dHDvAu.mjs.map +0 -1
- package/dist/schema-B11_2pKM.mjs.map +0 -1
- package/dist/schema-BRNH0PaA.d.mts.map +0 -1
- package/dist/types-DzO3_320.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-DyLVCH38.mjs","sources":["../src/profiler.ts","../src/permissions-backfill.mts","../src/attachments/auth.ts","../src/attachments/mount-auth.ts","../src/attachments/routes.ts","../src/attachments/index.ts","../src/workflow/oauth-apps-config.ts","../src/attachment-reference-read-model.mts","../src/builder-defaults.mts","../src/plugins/attachments.mts","../src/plugin-host.mts","../src/processor-timing-log.mts","../src/pglite-dialect.ts","../src/pglite-migration.ts","../src/pglite-preflight.ts","../src/pglite-store.mts","../src/create-signature-policy.mts","../src/renown.ts","../src/store-lock.mts","../src/server.mts"],"sourcesContent":["import type { PyroscopeConfig } from \"@pyroscope/nodejs\";\n\nlet started = false;\n\n// Once per process: the standalone entry and an embedding host (ph vetra) both\n// ask, and Pyroscope must only be initialised once.\nexport async function initProfilerFromEnv(env: typeof process.env) {\n if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;\n started = true;\n const {\n PYROSCOPE_SERVER_ADDRESS: serverAddress,\n PYROSCOPE_APPLICATION_NAME: appName,\n PYROSCOPE_USER: basicAuthUser,\n PYROSCOPE_PASSWORD: basicAuthPassword,\n PYROSCOPE_WALL_ENABLED: wallEnabled,\n PYROSCOPE_HEAP_ENABLED: heapEnabled,\n } = env;\n\n const options: PyroscopeConfig = {\n serverAddress,\n appName,\n basicAuthUser,\n basicAuthPassword,\n // Wall profiling captures wall-clock time (includes async I/O waits)\n // This shows GraphQL resolvers even when waiting for database\n wall: {\n samplingDurationMs: 10000, // 10 second sampling windows\n samplingIntervalMicros: 10000, // 10ms sampling interval (100 samples/sec)\n collectCpuTime: true, // Also collect CPU time alongside wall time\n },\n // Heap profiling for memory allocation tracking\n heap: {\n samplingIntervalBytes: 512 * 1024, // Sample every 512KB allocated\n stackDepth: 64, // Capture deeper stacks for better context\n },\n };\n return initProfiler(options, {\n wallEnabled: wallEnabled !== \"false\",\n heapEnabled: heapEnabled === \"true\",\n });\n}\n\ninterface ProfilerFlags {\n wallEnabled?: boolean;\n heapEnabled?: boolean;\n}\n\nexport async function initProfiler(\n options?: PyroscopeConfig,\n flags: ProfilerFlags = { wallEnabled: true, heapEnabled: false },\n) {\n console.log(\"Initializing Pyroscope profiler at:\", options?.serverAddress);\n console.log(\" Wall profiling:\", flags.wallEnabled ? \"enabled\" : \"disabled\");\n console.log(\" Heap profiling:\", flags.heapEnabled ? \"enabled\" : \"disabled\");\n\n const { default: Pyroscope } = await import(\"@pyroscope/nodejs\");\n Pyroscope.init(options);\n\n // Start wall profiling (captures async I/O time - shows resolvers)\n if (flags.wallEnabled) {\n Pyroscope.startWallProfiling();\n }\n\n // Start CPU profiling (captures CPU-bound work)\n Pyroscope.startCpuProfiling();\n\n // Optionally start heap profiling (memory allocations)\n if (flags.heapEnabled) {\n Pyroscope.startHeapProfiling();\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { sql, type Generated, type Kysely, type Transaction } from \"kysely\";\n\n/** The permission tables, as reactor-api once kept them on the read-model store. */\nexport const PERMISSION_TABLES = [\n \"DocumentPermission\",\n \"OperationUserPermission\",\n \"DocumentProtection\",\n] as const;\n\nexport type PermissionTable = (typeof PERMISSION_TABLES)[number];\n\n/** What a read-model table is renamed to once its rows live in the reactor store. */\nexport const MIGRATED_TABLE_SUFFIX = \"_migrated_2026_10_25\";\n\nexport type PermissionTableCounts = Record<PermissionTable, number>;\n\nexport type PermissionBackfillOutcome =\n /** The read-model store never had the tables. */\n | { status: \"fresh-install\" }\n /** An earlier boot copied the rows and renamed the tables. */\n | { status: \"already-backfilled\" }\n /** Rows copied now, read-model tables renamed. */\n | { status: \"copied\"; counts: PermissionTableCounts }\n /** An earlier boot copied the rows but stopped before renaming. */\n | { status: \"rename-completed\"; counts: PermissionTableCounts }\n /** Left both stores untouched; the reason says what needs a person. */\n | { status: \"refused\"; reason: string };\n\ninterface DocumentPermissionRow {\n documentId: string;\n userAddress: string;\n permission: string;\n grantedBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface OperationUserPermissionRow {\n documentId: string;\n operationType: string;\n userAddress: string;\n grantedBy: string;\n createdAt: Date;\n}\n\ninterface DocumentProtectionRow {\n documentId: string;\n protected: boolean;\n ownerAddress: string | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface PermissionTablesDatabase {\n DocumentPermission: DocumentPermissionRow & { id: Generated<number> };\n OperationUserPermission: OperationUserPermissionRow & {\n id: Generated<number>;\n };\n DocumentProtection: DocumentProtectionRow;\n}\n\nconst INSERT_BATCH_SIZE = 500;\n\n/**\n * Moves the document permission rows from the read-model store into the\n * reactor store, once.\n *\n * Runs at boot after the reactor's migrations (029 creates the target tables)\n * and before the permission service serves a check. When the read-model\n * store still has the legacy tables and the reactor store's are empty, every\n * row is copied in one reactor-store transaction (ids are not carried: no\n * table references them, and the target's serial assigns fresh ones), then\n * the legacy tables are renamed to `<name>_migrated_2026_10_25` so the copy\n * cannot run again. The renamed tables are kept for a release.\n *\n * Idempotent across crashes: when the copy committed but the rename did not,\n * the next boot finds equal row counts on both sides and only renames. Any\n * other mix of rows on both sides is refused with a warning and both stores\n * are left as they are. Plain SQL throughout, so a PGlite or Postgres read\n * store behaves the same.\n */\nexport async function backfillPermissionTables(\n readModelDb: Kysely<unknown>,\n reactorDb: Kysely<unknown>,\n logger: ILogger,\n): Promise<PermissionBackfillOutcome> {\n const source = readModelDb as Kysely<PermissionTablesDatabase>;\n const target = reactorDb as Kysely<PermissionTablesDatabase>;\n\n const present = await existingTables(source);\n const legacy = PERMISSION_TABLES.filter((table) => present.has(table));\n if (legacy.length === 0) {\n const migrated = PERMISSION_TABLES.some((table) =>\n present.has(migratedName(table)),\n );\n if (migrated) {\n logger.debug(\n \"Permission tables backfill: already done; the read-model tables carry the \" +\n MIGRATED_TABLE_SUFFIX +\n \" suffix\",\n );\n return { status: \"already-backfilled\" };\n }\n logger.debug(\n \"Permission tables backfill: the read-model store has no permission tables; nothing to copy\",\n );\n return { status: \"fresh-install\" };\n }\n\n const blocked = legacy.filter((table) => present.has(migratedName(table)));\n if (blocked.length > 0) {\n return refuse(\n logger,\n `the read-model store has both ${blocked.join(\", \")} and ${blocked\n .map(migratedName)\n .join(\", \")}; drop or rename one of each pair`,\n );\n }\n\n const legacyCounts = await countRows(source, present);\n const reactorCounts = await countRows(target, new Set(PERMISSION_TABLES));\n const reactorTotal = PERMISSION_TABLES.reduce(\n (sum, table) => sum + reactorCounts[table],\n 0,\n );\n\n if (reactorTotal > 0) {\n if (!countsEqual(legacyCounts, reactorCounts)) {\n return refuse(\n logger,\n `the reactor store already has permission rows (${formatCounts(\n reactorCounts,\n )}) that differ from the read-model store's (${formatCounts(\n legacyCounts,\n )})`,\n );\n }\n await renameLegacyTables(source, legacy);\n logger.info(\n `Permission tables backfill: rows were copied by an earlier boot (${formatCounts(\n legacyCounts,\n )}); renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`,\n );\n return { status: \"rename-completed\", counts: legacyCounts };\n }\n\n await target.transaction().execute(async (trx) => {\n if (present.has(\"DocumentPermission\")) {\n await copyDocumentPermissions(source, trx);\n }\n if (present.has(\"OperationUserPermission\")) {\n await copyOperationUserPermissions(source, trx);\n }\n if (present.has(\"DocumentProtection\")) {\n await copyDocumentProtections(source, trx);\n }\n const copied = await countRows(trx, new Set(PERMISSION_TABLES));\n if (!countsEqual(copied, legacyCounts)) {\n throw new Error(\n `Permission tables backfill copied ${formatCounts(copied)} but the read-model store has ${formatCounts(legacyCounts)}; rolled back`,\n );\n }\n });\n await renameLegacyTables(source, legacy);\n logger.info(\n `Permission tables backfill: copied ${formatCounts(\n legacyCounts,\n )} from the read-model store to the reactor store; renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`,\n );\n return { status: \"copied\", counts: legacyCounts };\n}\n\nfunction migratedName(table: PermissionTable): string {\n return `${table}${MIGRATED_TABLE_SUFFIX}`;\n}\n\nfunction refuse(logger: ILogger, reason: string): PermissionBackfillOutcome {\n logger.warn(\n `Permission tables backfill refused: ${reason}. Permission checks read the reactor store; both stores were left unchanged.`,\n );\n return { status: \"refused\", reason };\n}\n\n/** The permission tables, legacy or renamed, in the read-model store's own schema. */\nasync function existingTables(\n db: Kysely<PermissionTablesDatabase>,\n): Promise<Set<string>> {\n const names = PERMISSION_TABLES.flatMap((table) => [\n table,\n migratedName(table),\n ]);\n const result = await sql<{ table_name: string }>`\n select table_name from information_schema.tables\n where table_schema = current_schema()\n and table_name in (${sql.join(names)})\n `.execute(db);\n return new Set(result.rows.map((row) => row.table_name));\n}\n\nasync function countRows(\n db: Kysely<PermissionTablesDatabase> | Transaction<PermissionTablesDatabase>,\n tables: ReadonlySet<string>,\n): Promise<PermissionTableCounts> {\n const counts: PermissionTableCounts = {\n DocumentPermission: 0,\n OperationUserPermission: 0,\n DocumentProtection: 0,\n };\n for (const table of PERMISSION_TABLES) {\n if (!tables.has(table)) continue;\n const row = await db\n .selectFrom(table)\n .select((eb) => eb.fn.countAll<string | number>().as(\"count\"))\n .executeTakeFirstOrThrow();\n counts[table] = Number(row.count);\n }\n return counts;\n}\n\nfunction countsEqual(\n a: PermissionTableCounts,\n b: PermissionTableCounts,\n): boolean {\n return PERMISSION_TABLES.every((table) => a[table] === b[table]);\n}\n\nfunction formatCounts(counts: PermissionTableCounts): string {\n return PERMISSION_TABLES.map((table) => `${table}=${counts[table]}`).join(\n \", \",\n );\n}\n\nasync function copyDocumentPermissions(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: DocumentPermissionRow[] = await source\n .selectFrom(\"DocumentPermission\")\n .select([\n \"documentId\",\n \"userAddress\",\n \"permission\",\n \"grantedBy\",\n \"createdAt\",\n \"updatedAt\",\n ])\n .orderBy(\"id\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"DocumentPermission\").values(batch).execute();\n }\n}\n\nasync function copyOperationUserPermissions(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: OperationUserPermissionRow[] = await source\n .selectFrom(\"OperationUserPermission\")\n .select([\n \"documentId\",\n \"operationType\",\n \"userAddress\",\n \"grantedBy\",\n \"createdAt\",\n ])\n .orderBy(\"id\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"OperationUserPermission\").values(batch).execute();\n }\n}\n\nasync function copyDocumentProtections(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: DocumentProtectionRow[] = await source\n .selectFrom(\"DocumentProtection\")\n .select([\n \"documentId\",\n \"protected\",\n \"ownerAddress\",\n \"createdAt\",\n \"updatedAt\",\n ])\n .orderBy(\"documentId\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"DocumentProtection\").values(batch).execute();\n }\n}\n\nfunction* batches<T>(rows: T[]): Generator<T[]> {\n for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) {\n yield rows.slice(start, start + INSERT_BATCH_SIZE);\n }\n}\n\nasync function renameLegacyTables(\n db: Kysely<PermissionTablesDatabase>,\n tables: PermissionTable[],\n): Promise<void> {\n await db.transaction().execute(async (trx) => {\n for (const table of tables) {\n await sql`ALTER TABLE ${sql.id(table)} RENAME TO ${sql.id(\n migratedName(table),\n )}`.execute(trx);\n }\n });\n}\n","import type { AuthContext, AuthService } from \"@powerhousedao/reactor-api\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/**\n * Verified actor context for authenticated attachment handlers. The user comes\n * exclusively from bearer verification: when auth is disabled (OPEN mode)\n * `user` is undefined and `authEnabled` is false, and handlers must treat the\n * caller as anonymous. Caller-supplied identity headers are never consulted.\n */\nexport type AttachmentActorContext = {\n user: AuthContext[\"user\"];\n authEnabled: boolean;\n};\n\nconst ANONYMOUS_ACTOR: AttachmentActorContext = {\n user: undefined,\n authEnabled: false,\n};\n\nexport type NodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n actor?: AttachmentActorContext,\n) => Promise<void> | void;\n\nexport type RequireAuthOptions = {\n /**\n * Let requests without a bearer identity through as anonymous actors\n * instead of answering 401, so the handler's own document authorization\n * decides. A bearer that IS supplied must still verify — an invalid token\n * is rejected, never downgraded to anonymous.\n */\n allowAnonymous?: boolean;\n /**\n * Whether the deployment has said it accepts no anonymous callers at all\n * (`REQUIRE_AUTHENTICATED_CALLER`). It overrides `allowAnonymous`, because\n * the two answer different questions: `allowAnonymous` says \"this handler\n * authorizes per document, so it does not need identity to decide\", while\n * this says \"this server does not serve callers it cannot name\". A route can\n * be happy to decide without identity and still not be allowed to.\n *\n * These routes are mounted straight on the HTTP adapter, so the fetch chain's\n * own require-auth middleware never sees them — this is how the same floor\n * reaches them.\n */\n requireAuthenticatedCaller?: boolean;\n};\n\n/**\n * Wrap a Node-style handler so that, when `authService` is provided and auth is\n * enabled, the request must carry a verifiable Bearer token. The handler always\n * receives an actor context: the verified bearer user when auth is enabled, or\n * the anonymous context when it is disabled. With `allowAnonymous`, a missing\n * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —\n * unless `requireAuthenticatedCaller` says the deployment refuses anonymous\n * callers outright, which overrides it.\n *\n * With no `authService` there is no bearer to read and every caller is\n * anonymous, so nothing is refused here. That combination cannot carry the\n * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with\n * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity\n * resolution is what builds the service.\n */\nexport function requireAuth(\n authService: AuthService | undefined,\n handler: NodeHandler,\n options?: RequireAuthOptions,\n): NodeHandler {\n if (!authService) {\n return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);\n }\n\n return async (req, res, body) => {\n let result;\n try {\n result = await authService.verifyBearer(req.headers.authorization);\n } catch {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal authentication error\" }));\n return;\n }\n\n if (result instanceof Response) {\n const body = await result.text();\n res.statusCode = result.status;\n const contentType = result.headers.get(\"content-type\");\n if (contentType) res.setHeader(\"Content-Type\", contentType);\n res.end(body);\n return;\n }\n\n if (!result.user) {\n const refuse =\n options?.requireAuthenticatedCaller === true ||\n (result.auth_enabled && !options?.allowAnonymous);\n if (refuse) {\n res.statusCode = 401;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Authentication required\" }));\n return;\n }\n }\n\n await handler(req, res, body, {\n user: result.user,\n authEnabled: result.auth_enabled,\n });\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport {\n requireAuth,\n type NodeHandler,\n type RequireAuthOptions,\n} from \"./auth.js\";\n\nexport type HttpMethod = \"DELETE\" | \"GET\" | \"HEAD\" | \"POST\" | \"PUT\";\n\n// rawBody dispatches ahead of every body parser, so the handler streams `req`.\ntype MountOptions = Pick<\n NonNullable<Parameters<API[\"httpAdapter\"][\"mountNodeRoute\"]>[3]>,\n \"rawBody\"\n>;\n\n/**\n * Mount a Node-style attachment route with `requireAuth` applied unconditionally.\n * When `api.authService` is undefined (auth disabled), the handler still runs\n * through `requireAuth` and receives the anonymous actor context — that is the\n * only way to opt out of bearer verification. To register a route without auth\n * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.\n *\n * `allowAnonymous` is reserved for routes whose handlers make a per-document\n * authorization decision themselves; identity-only routes must not use it. It\n * is also not the last word: a deployment that refuses anonymous callers\n * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes\n * are mounted on the HTTP adapter and never reach the fetch chain that carries\n * that floor for GraphQL. The flag is read from the API, so every route\n * mounted through here inherits it without each one remembering to.\n */\nexport function mountAuthenticatedNodeRoute(\n api: Pick<API, \"httpAdapter\" | \"authService\" | \"requireAuthenticatedCaller\">,\n method: HttpMethod,\n path: string,\n handler: NodeHandler,\n options?: RequireAuthOptions & MountOptions,\n): void {\n const { rawBody, ...authOptions } = options ?? {};\n api.httpAdapter.mountNodeRoute(\n method,\n path,\n requireAuth(api.authService, handler, {\n ...authOptions,\n requireAuthenticatedCaller: api.requireAuthenticatedCaller,\n }),\n { rawBody: rawBody ?? false },\n );\n}\n","import {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n HashMismatch,\n InvalidAttachmentMetadata,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n createRef,\n parseAttachmentDownloadTarget,\n validateReserveMetadata,\n type AttachmentBuildResult,\n type AttachmentDownloadTarget,\n type ReserveAttachmentOptions,\n type ReserveMetadata,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { IAttachmentAccessService } from \"@powerhousedao/reactor-api\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport type { AttachmentActorContext } from \"./auth.js\";\nimport type { AttachmentUrlSigner } from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nconst RETRY_AFTER_SECONDS = 5;\n\n// Canonical form is lowercase hex (the SHA-256 hasher emits lowercase), but\n// accept either case from the wire and normalise before lookup. This keeps\n// the API forgiving for hand-typed URLs without changing storage semantics.\nconst HASH_PATTERN = /^[a-f0-9]{64}$/i;\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify(body));\n}\n\nfunction sendError(res: ServerResponse, status: number, message: string): void {\n sendJson(res, status, { error: message });\n}\n\nfunction statusForError(err: unknown): number {\n if (err instanceof AttachmentNotFound) return 404;\n if (err instanceof ReservationNotFound) return 404;\n if (err instanceof InvalidAttachmentRef) return 400;\n if (err instanceof UploadTooLarge) return 413;\n return 500;\n}\n\nfunction sendErrorFromException(res: ServerResponse, err: unknown): void {\n const status = statusForError(err);\n if (status >= 500) {\n logger.error(\"Attachment route error: @error\", err);\n sendError(res, status, \"Internal error\");\n return;\n }\n sendError(res, status, err instanceof Error ? err.message : String(err));\n}\n\nasync function readJsonBody(\n req: IncomingMessage,\n body: unknown,\n): Promise<unknown> {\n // The Express body-parser may have already populated `body`. When that\n // happens we trust it; otherwise read the raw stream ourselves so this\n // module is independent of upstream middleware ordering.\n if (body !== undefined && body !== null && typeof body === \"object\") {\n return body;\n }\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(chunk as Buffer);\n }\n if (chunks.length === 0) return undefined;\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (text.length === 0) return undefined;\n return JSON.parse(text);\n}\n\nexport function parseReserveOptions(\n input: unknown,\n): ReserveAttachmentOptions | null {\n if (input === null || typeof input !== \"object\") return null;\n const obj = input as Record<string, unknown>;\n const { mimeType, fileName } = obj;\n const extension = obj.extension ?? null;\n try {\n validateReserveMetadata({\n mimeType,\n fileName,\n extension,\n } as ReserveMetadata);\n } catch (err) {\n if (err instanceof InvalidAttachmentMetadata) return null;\n throw err;\n }\n if (typeof mimeType !== \"string\" || typeof fileName !== \"string\") return null;\n if (extension !== null && typeof extension !== \"string\") return null;\n\n // Hash-first mode: clientHash triggers this path; sizeBytes is required alongside it.\n // A body with sizeBytes but no clientHash falls through to the legacy path unchanged.\n if (obj.clientHash !== undefined) {\n if (\n typeof obj.clientHash !== \"string\" ||\n !HASH_PATTERN.test(obj.clientHash)\n ) {\n return null;\n }\n // Zero is accepted: an empty file is a real upload. The hash-first check\n // still binds the bytes received to the declared hash and size, so a\n // drained body cannot pass as an empty file unless one was declared.\n if (\n typeof obj.sizeBytes !== \"number\" ||\n !Number.isSafeInteger(obj.sizeBytes) ||\n obj.sizeBytes < 0\n ) {\n return null;\n }\n return {\n mimeType,\n fileName,\n extension,\n clientHash: obj.clientHash.toLowerCase() as AttachmentHash,\n sizeBytes: obj.sizeBytes,\n };\n }\n\n return {\n mimeType,\n fileName,\n extension,\n };\n}\n\nexport function quoteFilename(name: string): string {\n // RFC 6266: quoted-string with internal \" and \\ escaped.\n return `\"${name.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nexport function buildContentDisposition(fileName: string): string {\n // ASCII fallback: replace any byte outside printable ASCII (0x20-0x7e),\n // plus `\"` and `\\`, with `_`. Browsers fall back to this when they don't\n // grok `filename*=`; the modern parameter carries the real name.\n const ascii = fileName.replace(/[^\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]/g, \"_\");\n // RFC 5987: percent-encode UTF-8 bytes. encodeURIComponent leaves a few\n // chars that 5987 disallows in token; re-encode them.\n const encoded = encodeURIComponent(fileName).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;\n}\n\nexport function makeReserveHandler(attachments: AttachmentBuildResult) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ): Promise<void> => {\n let parsed: unknown;\n try {\n parsed = await readJsonBody(req, body);\n } catch {\n sendError(res, 400, \"Invalid JSON body\");\n return;\n }\n const opts = parseReserveOptions(parsed);\n if (!opts) {\n sendError(\n res,\n 400,\n \"Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }\",\n );\n return;\n }\n\n let upload;\n try {\n upload = await attachments.service.reserve(opts);\n } catch (err) {\n if (err instanceof AttachmentAlreadyExists) {\n sendJson(res, 409, { error: \"already_exists\", ref: err.ref });\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n sendJson(res, 201, {\n reservationId: upload.reservationId,\n ref: upload.ref,\n expiresAtUtc: upload.expiresAtUtc,\n ...(upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}),\n });\n };\n}\n\nexport function makeUploadHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n if (attachments.backend?.kind === \"s3\") {\n sendError(res, 405, \"Use the reservation uploadTarget for S3 uploads\");\n return;\n }\n\n let reservation;\n try {\n reservation = await attachments.reservations.get(reservationId);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n const upload = attachments.uploadFactory.createUpload(reservation);\n\n const webStream = Readable.toWeb(\n req as Readable,\n ) as ReadableStream<Uint8Array>;\n\n try {\n const result = await upload.send(webStream);\n sendJson(res, 200, result);\n } catch (err) {\n if (err instanceof HashMismatch) {\n sendJson(res, 422, {\n error: \"hash_mismatch\",\n claimed: err.claimed,\n actual: err.actual,\n });\n return;\n }\n if (err instanceof SizeMismatch) {\n sendJson(res, 422, {\n error: \"size_mismatch\",\n declared: err.declared,\n actual: err.actual,\n });\n return;\n }\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDownloadHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n const controller = new AbortController();\n req.once(\"close\", () => controller.abort());\n\n let response;\n try {\n response = await attachments.store.get(\n canonicalHash,\n controller.signal,\n grant.documentId,\n );\n } catch (err) {\n if (err instanceof AttachmentPending) {\n res.statusCode = 202;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: err.expiresAtUtc,\n ...(err.metadata ?? {}),\n }),\n );\n res.end();\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n const { header, body } = response;\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n\n const source = Readable.fromWeb(\n body as unknown as NodeReadableStream<Uint8Array>,\n );\n // The blob is opened lazily, so a file missing from disk (metadata still\n // says \"available\", e.g. a pod-local store lost on restart) surfaces here\n // as a stream error. `.pipe()` does not forward it: without a listener it\n // is an unhandled 'error' event and takes the whole process down.\n source.once(\"error\", (err) => handleDownloadStreamError(res, hash, err));\n source.pipe(res);\n };\n}\n\nfunction handleDownloadStreamError(\n res: ServerResponse,\n hash: string,\n err: unknown,\n): void {\n if (res.headersSent) {\n // Bytes are already on the wire; finishing normally would hand the client\n // a truncated file as if it were complete. Cut the connection instead —\n // without passing the error, which would re-emit it on the response.\n logger.error(\"Attachment stream failed mid-download: @error\", err);\n res.destroy();\n return;\n }\n // Nothing sent yet: drop the download headers so they cannot describe the\n // JSON error body, then answer like any other missing attachment.\n res.removeHeader(\"Content-Length\");\n res.removeHeader(\"Content-Disposition\");\n res.removeHeader(\"Attachment-Metadata\");\n if ((err as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\") {\n logger.warn(\n \"Attachment @hash is recorded as available but its blob is missing\",\n hash,\n );\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment stream failed before sending: @error\", err);\n sendError(res, 500, \"Internal error\");\n}\n\n// Node rejects header values above U+00FF. Escaping everything outside\n// printable ASCII keeps the header valid; JSON.parse restores the original.\nfunction toAsciiJson(value: unknown): string {\n return JSON.stringify(value).replace(\n /[\\u007f-\\uffff]/g,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\nexport function buildPendingHeader(pending: {\n expiresAtUtc: string | null;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n}): string {\n return toAsciiJson(pending);\n}\n\nexport function buildMetadataHeader(header: {\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n extension: string | null;\n createdAtUtc: string;\n lastAccessedAtUtc: string;\n}): string {\n return toAsciiJson({\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n extension: header.extension,\n createdAtUtc: header.createdAtUtc,\n lastAccessedAtUtc: header.lastAccessedAtUtc,\n });\n}\n\nexport function makeStatHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n res.setHeader(\"Cache-Control\", \"private\");\n if (header.status === \"pending\") {\n res.statusCode = 202;\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: header.expiresAtUtc,\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n }),\n );\n res.end();\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n res.end();\n };\n}\n\nexport function makeGetReservationHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n const reservation = await attachments.reservations.get(reservationId);\n sendJson(res, 200, reservation);\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDeleteReservationHandler(\n attachments: AttachmentBuildResult,\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n await attachments.reservations.delete(reservationId);\n res.statusCode = 204;\n res.end();\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nfunction extractParam(req: IncomingMessage, name: string): string | undefined {\n const expressParams = (\n req as IncomingMessage & {\n params?: Record<string, string>;\n }\n ).params;\n return expressParams?.[name];\n}\n\nconst MAX_DOCUMENT_ID_LEN = 512;\nconst ATTACHMENT_NOT_FOUND_BODY = { error: \"Attachment not found\" };\n// SigV4 presigned URLs cannot outlive 7 days; requests above the cap are\n// clamped rather than rejected so clients need not know the ceiling.\nconst MAX_DOWNLOAD_TARGET_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * How long a download target may live, by default.\n *\n * The authorization behind a presigned URL is decided once, when it is issued,\n * and the URL keeps working until it expires however the document's policy\n * changes in between. A week of that is a revocation that does not revoke: an\n * account deactivated, a company reassigned or a group left, and the bytes stay\n * fetchable by anyone holding the link. Minutes are enough to open a file;\n * days are only enough to lose control of it.\n *\n * A deployment that needs longer sets `attachments.downloadTargetMaxTtlSeconds`\n * (ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS at the edge), still bounded by the\n * signing ceiling above.\n */\nconst DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;\n\n/** A configured ceiling, bounded by the signing maximum; unset is the default. */\nexport function downloadTargetTtlCapSeconds(\n configured: number | undefined,\n): number {\n return configured === undefined\n ? DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS\n : Math.min(configured, MAX_DOWNLOAD_TARGET_TTL_SECONDS);\n}\n\n/**\n * Returns the single `documentId` query value, or null when it is missing,\n * duplicated, blank, or oversized. Validation happens before authorization so\n * malformed requests never reach the access service.\n */\nfunction extractSingleDocumentId(req: IncomingMessage): string | null {\n if (!req.url) return null;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(\"documentId\");\n if (values.length !== 1) return null;\n const value = values[0];\n if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) {\n return null;\n }\n return value;\n}\n\n/**\n * Returns the target TTL in seconds, or \"invalid\" when the caller's own value\n * is malformed (duplicated, non-integer, or non-positive).\n *\n * The cap applies whether or not the caller asked for a lifetime: omitting\n * `expiresIn` used to fall through to whatever the storage backend was\n * configured with, which would make the ceiling something a client opts out of\n * by saying nothing.\n */\nfunction extractExpiresIn(\n req: IncomingMessage,\n cap: number,\n): number | \"invalid\" {\n if (!req.url) return cap;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return cap;\n }\n const values = url.searchParams.getAll(\"expiresIn\");\n if (values.length === 0) return cap;\n if (values.length > 1) return \"invalid\";\n const parsed = Number(values[0]);\n if (!Number.isInteger(parsed) || parsed <= 0) return \"invalid\";\n return Math.min(parsed, cap);\n}\n\ntype ByteGrant =\n | { kind: \"granted\"; documentId: string }\n | { kind: \"denied\" }\n | { kind: \"unavailable\" }\n | { kind: \"error\" };\n\nfunction singleQueryValue(\n params: URLSearchParams,\n name: string,\n): string | null {\n const values = params.getAll(name);\n return values.length === 1 ? values[0] : null;\n}\n\n/**\n * Byte routes serve only under a grant: a signed URL minted by the\n * download-target route, or a documentId the caller may read the attachment\n * through. A signed request is judged by its signature alone.\n */\nasync function resolveByteGrant(\n req: IncomingMessage,\n hash: AttachmentHash,\n actor: AttachmentActorContext | undefined,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n): Promise<ByteGrant> {\n let params: URLSearchParams;\n try {\n params = new URL(req.url ?? \"\", \"http://switchboard.invalid\").searchParams;\n } catch {\n return { kind: \"denied\" };\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) return { kind: \"denied\" };\n\n if (params.has(\"signature\") || params.has(\"expires\")) {\n const signature = singleQueryValue(params, \"signature\");\n const expires = singleQueryValue(params, \"expires\");\n if (!urlSigner || signature === null || expires === null) {\n return { kind: \"denied\" };\n }\n return urlSigner.verify(hash, documentId, expires, signature)\n ? { kind: \"granted\", documentId }\n : { kind: \"denied\" };\n }\n\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(hash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n return { kind: \"error\" };\n }\n if (decision.kind === \"projection-unavailable\") {\n return { kind: \"unavailable\" };\n }\n if (decision.kind === \"denied\") return { kind: \"denied\" };\n return { kind: \"granted\", documentId: decision.documentId };\n}\n\n/** Answers a refused grant; true when the request may proceed. */\nfunction admitGrant(\n res: ServerResponse,\n grant: ByteGrant,\n): grant is { kind: \"granted\"; documentId: string } {\n switch (grant.kind) {\n case \"granted\":\n return true;\n case \"denied\":\n // 404, never 403: a refusal must not reveal that the hash exists.\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return false;\n case \"unavailable\":\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return false;\n case \"error\":\n sendError(res, 500, \"Internal error\");\n return false;\n }\n}\n\n/**\n * Base URL of this Switchboard as seen by the caller, used to build\n * filesystem `switchboard` download targets that point back at the signed\n * byte route.\n */\nfunction requestBaseUrl(req: IncomingMessage): string | null {\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const proto =\n (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n ?.split(\",\")[0]\n ?.trim() ||\n ((req.socket as { encrypted?: boolean }).encrypted ? \"https\" : \"http\");\n const forwardedHost = req.headers[\"x-forwarded-host\"];\n const host =\n (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ??\n req.headers.host;\n if (!host) return null;\n return `${proto}://${host}`;\n}\n\nexport function makeDownloadTargetHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n ttlCapSeconds = downloadTargetTtlCapSeconds(undefined),\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n // Target responses carry short-lived URLs and authorization decisions;\n // no intermediary may cache them.\n res.setHeader(\"Cache-Control\", \"no-store\");\n\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) {\n sendError(\n res,\n 400,\n \"documentId is required exactly once as a non-empty query parameter\",\n );\n return;\n }\n const expiresIn = extractExpiresIn(req, ttlCapSeconds);\n if (expiresIn === \"invalid\") {\n sendError(\n res,\n 400,\n \"expiresIn must be a single positive integer number of seconds\",\n );\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(canonicalHash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n\n if (decision.kind === \"projection-unavailable\") {\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return;\n }\n if (decision.kind === \"denied\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n if (err instanceof AttachmentNotFound) {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment metadata lookup failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n if (header.status !== \"available\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let target: AttachmentDownloadTarget;\n if (attachments.backend && attachments.backend.kind !== \"filesystem\") {\n try {\n target = await attachments.backend.prepareDownloadTarget(\n canonicalHash,\n expiresIn,\n );\n } catch {\n // Backend errors are sanitized at the backend boundary; no URLs or\n // signatures reach this scope, and none may be logged from here.\n sendError(res, 502, \"Attachment download target unavailable\");\n return;\n }\n } else {\n if (!urlSigner) {\n sendError(res, 503, \"Attachment download signing is not configured\");\n return;\n }\n const base = requestBaseUrl(req);\n if (!base) {\n sendError(res, 500, \"Internal error\");\n return;\n }\n const signed = urlSigner.sign(\n canonicalHash,\n decision.documentId,\n expiresIn,\n );\n try {\n target = parseAttachmentDownloadTarget({\n kind: \"switchboard\",\n method: \"GET\",\n url: `${base}/attachments/${canonicalHash}?${signed.query}`,\n headers: {},\n expiresAtUtc: signed.expiresAtUtc,\n });\n } catch {\n sendError(res, 500, \"Internal error\");\n return;\n }\n }\n\n sendJson(res, 200, target);\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport { childLogger } from \"document-model\";\nimport { mountAuthenticatedNodeRoute } from \"./mount-auth.js\";\nimport {\n makeDeleteReservationHandler,\n makeDownloadHandler,\n downloadTargetTtlCapSeconds,\n makeDownloadTargetHandler,\n makeGetReservationHandler,\n makeReserveHandler,\n makeStatHandler,\n makeUploadHandler,\n} from \"./routes.js\";\nimport {\n ATTACHMENT_URL_SIGNING_SECRET_ENV,\n resolveAttachmentUrlSigning,\n type AttachmentUrlSigner,\n} from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nexport type RegisterAttachmentRoutesOptions = {\n /** Overrides the signer resolved from the environment; null disables signing. */\n urlSigner?: AttachmentUrlSigner | null;\n /** The switchboard's settings; unset means their defaults. */\n config?: {\n urlSigningSecret?: string;\n downloadTargetMaxTtlSeconds?: number;\n };\n};\n\nexport function registerAttachmentRoutes(\n api: API,\n options: RegisterAttachmentRoutesOptions = {},\n): void {\n const { attachments, attachmentAccess } = api;\n const { config } = options;\n const urlSigner =\n options.urlSigner === undefined\n ? signerFromEnvironment(attachments.backend?.kind ?? \"filesystem\", {\n [ATTACHMENT_URL_SIGNING_SECRET_ENV]: config?.urlSigningSecret,\n NODE_ENV: process.env.NODE_ENV,\n })\n : options.urlSigner;\n const ttlCapSeconds = downloadTargetTtlCapSeconds(\n config?.downloadTargetMaxTtlSeconds,\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"POST\",\n \"/attachments/reservations\",\n makeReserveHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/reservations/:reservationId\",\n makeGetReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"DELETE\",\n \"/attachments/reservations/:reservationId\",\n makeDeleteReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"PUT\",\n \"/attachments/reservations/:reservationId\",\n makeUploadHandler(attachments),\n // Streams to storage; no parser may buffer or drain the body first.\n { rawBody: true },\n );\n\n // Anonymous-capable: authorization is purely the document's (or a signed\n // URL minted under it), exactly as it is for the document itself.\n mountAuthenticatedNodeRoute(\n api,\n \"HEAD\",\n \"/attachments/:hash\",\n makeStatHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash/download-target\",\n makeDownloadTargetHandler(\n attachments,\n attachmentAccess,\n urlSigner,\n ttlCapSeconds,\n ),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash\",\n makeDownloadHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n}\n\nfunction signerFromEnvironment(\n backend: \"filesystem\" | \"s3\",\n env: Readonly<Record<string, string | undefined>>,\n): AttachmentUrlSigner | null {\n const signing = resolveAttachmentUrlSigning(env);\n if (signing.status === \"unconfigured\") {\n if (backend === \"filesystem\") {\n logger.error(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`,\n );\n }\n return null;\n }\n if (signing.status === \"ephemeral\" && backend === \"filesystem\") {\n logger.warn(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`,\n );\n }\n return signing.signer;\n}\n","import path from \"node:path\";\n\n/**\n * A token broker for an app's web client (see the reactor-workflow README,\n * \"OAuth2 connections\"). The workflow runtime checks it when it loads the\n * apps: a client id and two absolute https URLs, else it is dropped with a\n * warning.\n */\nexport interface OAuthAppRelayConfig {\n clientId: string;\n redirectUri: string;\n tokenUrl: string;\n}\n\n/** One publisher OAuth2 app as `workflows.oauthApps` names it. */\nexport interface OAuthAppConfig {\n id: string;\n clients: { desktop?: string; web?: string };\n relay?: OAuthAppRelayConfig;\n}\n\n/**\n * The config file's `workflows.oauthApps`, client file paths made absolute\n * from `dir`, the config file's folder. A malformed entry is left out; a\n * relay that is not an object is dropped and reported, the app kept without\n * it. The relay's fields are checked by the runtime, as for apps a host\n * passes itself.\n */\nexport function parseOAuthApps(\n raw: unknown,\n dir: string,\n onDroppedRelay?: (appId: string, relay: unknown) => void,\n): OAuthAppConfig[] {\n if (!Array.isArray(raw)) return [];\n const at = (p: unknown) =>\n typeof p === \"string\" && p ? path.resolve(dir, p) : undefined;\n return raw.flatMap((entry: unknown) => {\n const app = (entry ?? {}) as {\n id?: unknown;\n clients?: { desktop?: unknown; web?: unknown };\n relay?: unknown;\n };\n if (typeof app.id !== \"string\" || !app.id) return [];\n const desktop = at(app.clients?.desktop);\n const web = at(app.clients?.web);\n let relay: OAuthAppRelayConfig | undefined;\n if (app.relay !== undefined) {\n if (\n typeof app.relay === \"object\" &&\n app.relay !== null &&\n !Array.isArray(app.relay)\n ) {\n relay = app.relay as OAuthAppRelayConfig;\n } else {\n onDroppedRelay?.(app.id, app.relay);\n }\n }\n return [\n {\n id: app.id,\n clients: { ...(desktop ? { desktop } : {}), ...(web ? { web } : {}) },\n ...(relay ? { relay } : {}),\n },\n ];\n });\n}\n","import {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport type { AttachmentReferenceProjectionCapability } from \"@powerhousedao/reactor-api\";\nimport {\n AttachmentReferenceReadModel,\n AttachmentSchemaCompiler,\n type IAttachmentReferenceWriter,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { Kysely } from \"kysely\";\n\nexport type AttachmentReferenceReadModelRegistration = {\n attachmentReferenceWriter: IAttachmentReferenceWriter;\n baseKysely: Kysely<unknown>;\n};\n\nconst attachmentSchemaCompiler = new AttachmentSchemaCompiler();\n\nfunction createAttachmentReferenceReadModel(\n baseKysely: Kysely<unknown>,\n dependencies: {\n operationIndex: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[1];\n writeCache: ConstructorParameters<typeof AttachmentReferenceReadModel>[2];\n processorManagerConsistencyTracker: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[3];\n documentModelRegistry: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[4];\n },\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): AttachmentReferenceReadModel {\n return new AttachmentReferenceReadModel(\n baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n dependencies.operationIndex,\n dependencies.writeCache,\n dependencies.processorManagerConsistencyTracker,\n dependencies.documentModelRegistry,\n attachmentSchemaCompiler,\n attachmentReferenceWriter,\n );\n}\n\nexport function registerAttachmentReferenceReadModel(\n reactorBuilder: ReactorBuilder,\n registration: AttachmentReferenceReadModelRegistration,\n): void {\n reactorBuilder.withReadModelFactory(\n async ({\n documentModelRegistry,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const readModel = createAttachmentReferenceReadModel(\n registration.baseKysely,\n {\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n documentModelRegistry,\n },\n registration.attachmentReferenceWriter,\n );\n await readModel.init();\n return readModel;\n },\n );\n}\n\nexport async function registerAttachmentReferenceReadModelOnModule(\n clientModule: InProcessReactorClientModule,\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): Promise<AttachmentReferenceProjectionCapability> {\n const reactorModule = clientModule.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n const readModel = createAttachmentReferenceReadModel(\n reactorModule.database as unknown as Kysely<unknown>,\n {\n operationIndex: reactorModule.operationIndex,\n writeCache: reactorModule.writeCache,\n processorManagerConsistencyTracker:\n reactorModule.processorManagerConsistencyTracker,\n documentModelRegistry: reactorModule.documentModelRegistry,\n },\n attachmentReferenceWriter,\n );\n\n await readModel.init();\n coordinator.addReadModel(readModel, \"pre_ready\");\n await readModel.init();\n\n return { status: \"available\" };\n}\n","import type {\n ReactorBuilder,\n ReactorFeatureFlags,\n} from \"@powerhousedao/reactor\";\nimport {\n ChannelScheme,\n type IDocumentModelLoader,\n type ReactorClientBuilder,\n type SignerConfig,\n} from \"@powerhousedao/reactor\";\nimport {\n baseDocumentModels,\n getUniqueDocumentModels,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n SignaturePolicy,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\nexport type SwitchboardReactorDefaultsOptions = {\n // Extra models registered alongside the baseline (document-model, drive,\n // reactor-drive, reactor-group). Pass vetra models here in studio/dev.\n // Deduped by id.\n documentModels?: DocumentModelModule[];\n /** Upgrade manifests for versioned models, one per document type. */\n upgradeManifests?: UpgradeManifest<readonly number[]>[];\n /** Default true. */\n includeBaseModels?: boolean;\n /**\n * Channel scheme. Defaults to `ChannelScheme.SWITCHBOARD`, which populates\n * `reactorModule.syncModule.syncManager` — required by reactor-api. Set\n * to `false` if the caller configures sync itself (`withChannelScheme` or\n * `withSync`); the builder refuses both together.\n */\n channelScheme?: ChannelScheme | false;\n /** Defaults to true. Set false when the caller owns SIGINT handling. */\n signalHandlers?: boolean;\n /** Executor tuning. Omit to use the reactor's own defaults. */\n executorConfig?: {\n maxSkipThreshold?: number;\n featureFlags?: Partial<ReactorFeatureFlags>;\n };\n /** Wire dynamic document-model loading via HTTP. */\n documentModelLoader?: IDocumentModelLoader;\n logger?: ILogger;\n /**\n * Identity signer (typically from `getRenownSignerConfig`). Signs client\n * writes and the operations the executor synthesizes, in pooled workers\n * through `workerSigner`; omit for unsigned operation.\n */\n signer?: SignerConfig;\n /**\n * Which keys may sign as which users (typically from\n * `getRenownTrustPolicyConfig`); wins over one carried by `signer`.\n */\n trustPolicy?: Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">;\n /** What the client creates new documents as; see `resolveCreateSignaturePolicy`. */\n createSignaturePolicy?: SignaturePolicy;\n};\n\n/**\n * Apply switchboard's standard configuration to a reactor + client builder\n * pair. Each piece is opt-out via the options object; defaults mirror what\n * `startSwitchboard` does when building a reactor itself. Mutates both\n * builders in place.\n *\n * Does NOT touch kysely or read models — callers wire those themselves\n * (see `withKysely` / `withReadModelFactory` on the reactor builder).\n */\n/** The models switchboard always registers alongside package models. */\nexport function switchboardBaseDocumentModels() {\n return baseDocumentModels.map(([, model]) => model);\n}\n\nexport function applySwitchboardReactorDefaults(\n reactorBuilder: ReactorBuilder,\n clientBuilder: ReactorClientBuilder,\n options: SwitchboardReactorDefaultsOptions = {},\n): void {\n const baseModels =\n options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];\n const extra = options.documentModels ?? [];\n if (baseModels.length || extra.length) {\n reactorBuilder.withDocumentModelSources(\n getUniqueDocumentModels(baseModels, extra),\n );\n }\n\n if (options.upgradeManifests?.length) {\n reactorBuilder.withUpgradeManifests(options.upgradeManifests);\n }\n\n const scheme =\n options.channelScheme === undefined\n ? ChannelScheme.SWITCHBOARD\n : options.channelScheme;\n if (scheme !== false) {\n reactorBuilder.withChannelScheme(scheme);\n }\n\n if (options.signalHandlers !== false) {\n reactorBuilder.withSignalHandlers();\n }\n\n if (\n options.executorConfig?.maxSkipThreshold !== undefined ||\n options.executorConfig?.featureFlags !== undefined\n ) {\n reactorBuilder.withExecutorConfig({\n ...(options.executorConfig.maxSkipThreshold !== undefined\n ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold }\n : {}),\n ...(options.executorConfig.featureFlags !== undefined\n ? { featureFlags: options.executorConfig.featureFlags }\n : {}),\n });\n }\n\n if (options.documentModelLoader) {\n reactorBuilder.withDocumentModelLoader(options.documentModelLoader);\n }\n\n if (options.logger) {\n reactorBuilder.withLogger(options.logger);\n }\n\n if (options.signer) {\n clientBuilder.withSigner(options.signer);\n reactorBuilder.withSigner(\n options.signer.signer,\n options.signer.workerSigner,\n );\n }\n\n if (options.createSignaturePolicy) {\n clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);\n }\n\n const trust = options.trustPolicy ?? options.signer;\n if (trust?.trustPolicy) {\n reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);\n }\n}\n","import { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport type { IRenown } from \"@renown/sdk\";\nimport type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { registerAttachmentRoutes } from \"../attachments/index.js\";\nimport { deriveAttachmentServiceConfig } from \"../server.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport { z } from \"zod\";\n\n/** No entry config: presence is the whole activation. A typo'd config key\n * fails at resolution instead of being silently ignored. */\nexport const attachmentsPluginConfigSchema = z.strictObject({});\n\nexport type AttachmentsPluginConfig = z.input<\n typeof attachmentsPluginConfigSchema\n>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/attachments\": AttachmentsPluginConfig;\n }\n}\n\n/**\n * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments\n * routes mount at onHttpMounting and the remote attachment service is created\n * for the returned handle. Presence is activation — removed from the\n * composition, the routes and service do not exist. NOT yet carved: the\n * attachment-reference read model registered inside reactor construction\n * (carve map: server.mts initializeClient) — it follows with the\n * onReadModelsRegistering step in R2 step 2; until then it registers on both\n * paths (a dormant read model when the plugin is absent, harmless).\n *\n * Inputs (carve map): api (routes), config.attachments (signing, TTL),\n * options.attachmentServiceUrl / https + serverPort + renown (service config).\n */\nexport const attachmentsPlugin: HostPlugin<{\n onHttpMounting: (ctx: SwitchboardHostContext) => void;\n}> = {\n name: \"switchboard-attachments\",\n appliesTo: \"switchboard\",\n configSchema: attachmentsPluginConfigSchema,\n hooks: {\n onHttpMounting: (ctx) => {\n registerAttachmentRoutes(\n ctx.api as Parameters<typeof registerAttachmentRoutes>[0],\n { config: ctx.config?.attachments },\n );\n ctx.attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(\n ctx.options as { attachmentServiceUrl?: string; https?: boolean },\n ctx.serverPort as number,\n ctx.renown as IRenown | null,\n ),\n );\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default attachmentsPlugin;\n","import { attachmentsPlugin } from \"./plugins/attachments.mjs\";\nimport { privacyPlugin } from \"./plugins/privacy.mjs\";\nimport { workflowsPlugin } from \"./plugins/workflows.mjs\";\nimport { mcpPlugin } from \"./plugins/mcp.mjs\";\nimport {\n mergeContributions,\n resolveOrder,\n runObserveHook,\n runObserveHookSequential,\n runTransformHook,\n type HostPlugin,\n type MergedContribution,\n type ResolvedPlugin,\n} from \"@powerhousedao/host-core\";\nimport type { SwitchboardConfig } from \"./config/schema.js\";\n\n/**\n * R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:\n * uniform-runners-plan/rewire/r2-carve-map.md). Behind\n * FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing\n * inline path byte-identically; flag on, the five subsystems run as built-in\n * plugins through these hook moments. Subsystems carve one per commit; until\n * a subsystem is carved, its inline code runs on BOTH paths and its plugin\n * twin does not exist.\n *\n * Hook vocabulary (SwitchboardHooks), anchored to the boot spine:\n * - transformServerOptions — after option/flag resolution, before anything opens\n * - onReadModelsRegistering — inside reactor construction (build-time read models)\n * - onHttpMounting — api exists; routes mount here\n * - onSubgraphsRegistering — push into lateSubgraphs before the drain\n * - onReactorReady — client + graphqlManager destructured\n * - onDrivesReady — after core drive seeding / remote attachment\n * - onShutdown — first in the subsystem-ordered teardown\n */\n\nexport { isPluginHostEnabled, PLUGIN_HOST_FLAG } from \"./plugin-host-flag.mjs\";\n\n/**\n * The context plugins receive. Fields are populated as the boot spine reaches\n * them (api/client/graphqlManager are undefined before stage 17); concrete\n * types stay in server.mts — subsystem carves tighten their own slices.\n */\nexport interface SwitchboardHostContext {\n /** The switchboard's ILogger; typed loosely here to avoid pinning the\n * logger package in the scaffold — subsystem carves use it as-is. */\n logger: unknown;\n options: Record<string, unknown>;\n /** The parsed config the switchboard booted with. */\n config?: SwitchboardConfig;\n renown: unknown;\n serverPort?: number;\n /** Set by the attachments plugin at onHttpMounting; the boot reads it for\n * the returned handle. */\n attachmentService?: unknown;\n /** Privacy plugin state: config resolved at transformServerOptions\n * (fail-fast), the running subsystem set at onSubgraphsRegistering. */\n privacyConfig?: unknown;\n privacy?: unknown;\n /** Workflows plugin: wiring closures handed in by server.mts, runtime +\n * retry handles stored by the plugin. */\n workflowsOrchestration?: unknown;\n workflows?: unknown;\n workflowsRetry?: unknown;\n api?: unknown;\n /** @deprecated The facade; plugins that have moved take `read` and `write`. */\n client?: unknown;\n /** The reactor's read half (IReactorReadClient), set at onReactorReady. */\n read?: unknown;\n /** The reactor's write half (IReactorWriteClient), set at onReactorReady. */\n write?: unknown;\n graphqlManager?: unknown;\n reactorClientModule?: unknown;\n /** Late subgraph registrations drain before the readiness router update. */\n lateSubgraphs?: Promise<unknown>[];\n contributions: Record<string, MergedContribution[]>;\n}\n\nexport interface SwitchboardPluginHost {\n readonly plugins: readonly HostPlugin[];\n readonly ctx: SwitchboardHostContext;\n transformOptions<T>(seed: T): Promise<T>;\n observe(\n hook:\n | \"onReadModelsRegistering\"\n | \"onHttpMounting\"\n | \"onSubgraphsRegistering\"\n | \"onReactorReady\"\n | \"onDrivesReady\"\n | \"onShutdown\",\n ): Promise<void>;\n}\n\n/** Built-in plugins, pre-listed (the default composition until host.js\n * entries map in R2 step 2). Subsystems join as R2 carves them. */\nexport function builtinSwitchboardPlugins(): ResolvedPlugin[] {\n const entry = { enabled: true, verbs: \"*\" as const, config: {} };\n return [\n {\n plugin: mcpPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: { ...entry, module: \"@powerhousedao/switchboard/plugins/mcp\" },\n },\n {\n plugin: attachmentsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/attachments\",\n },\n },\n {\n plugin: privacyPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/privacy\",\n },\n },\n // Registered after privacy ON PURPOSE: onShutdown runs sequentially in\n // registration order, preserving the inline teardown (privacy stops\n // before workflows, both before api.dispose — carve map).\n {\n plugin: workflowsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/workflows\",\n },\n },\n ];\n}\n\nexport function createSwitchboardPluginHost(\n ctx: Omit<SwitchboardHostContext, \"contributions\">,\n resolved?: readonly ResolvedPlugin[],\n): SwitchboardPluginHost {\n resolved ??= builtinSwitchboardPlugins();\n const ordered = resolveOrder(resolved.map((r) => r.plugin));\n const contributions = mergeContributions(\n resolved.map((r) => ({ plugin: r.plugin, provenance: r.provenance })),\n );\n const fullCtx: SwitchboardHostContext = { ...ctx, contributions };\n\n // Change 2: the composition is observable on the `ph run` terminal. Report\n // the activated plugins once at construction, then which plugins run each\n // lifecycle hook as it fires.\n const LOG = \"[switchboard:plugins]\";\n console.log(\n `${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(\", \") || \"(none)\"}`,\n );\n for (const r of resolved) {\n const cfg = Object.keys(r.entry.config ?? {});\n console.log(\n `${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\"),\n );\n }\n const ranBy = (hook: string) =>\n ordered.filter((p) => (p.hooks as Record<string, unknown>)?.[hook]);\n const logHook = (hook: string) => {\n const names = ranBy(hook).map((p) => p.name);\n console.log(\n `${LOG} hook ${hook} → ${names.length ? names.join(\", \") : \"(no implementers)\"}`,\n );\n };\n\n return {\n plugins: ordered,\n ctx: fullCtx,\n transformOptions: (seed) => {\n logHook(\"transformServerOptions\");\n return runTransformHook(\"transformServerOptions\", ordered, fullCtx, seed);\n },\n observe: (hook) => {\n logHook(hook);\n return hook === \"onShutdown\"\n ? runObserveHookSequential(hook, ordered, fullCtx)\n : runObserveHook(hook, ordered, fullCtx);\n },\n };\n}\n","import {\n isCatchingUp,\n rankSlowest,\n renderDoneSummary,\n renderSlowLine,\n type InspectorProcessorTimingReport,\n} from \"@powerhousedao/reactor\";\n\nconst TOP = 5;\n\nexport type ProcessorTimingLogOptions = {\n intervalMs: number;\n read: () => InspectorProcessorTimingReport;\n log: (line: string) => void;\n now?: () => number;\n};\n\n/**\n * The console's `catch-up slowest` line for a host without the ph-cli display:\n * one every interval while catching up, and one summary when it ends. Silent\n * while timing is off or nothing is catching up. Returns the stop.\n */\nexport function startProcessorTimingLog(\n options: ProcessorTimingLogOptions,\n): () => void {\n const now = options.now ?? (() => Date.now());\n let busySince: number | undefined;\n\n const tick = () => {\n const report = options.read();\n if (report.level === \"off\") return;\n if (isCatchingUp(report)) {\n busySince ??= now();\n const rows = rankSlowest(report, TOP, \"window\");\n if (rows.length > 0) options.log(renderSlowLine(rows, report.windowMs));\n return;\n }\n if (busySince === undefined) return;\n const wallMs = now() - busySince;\n busySince = undefined;\n options.log(renderDoneSummary(rankSlowest(report, TOP, \"total\"), wallMs));\n };\n\n const timer = setInterval(tick, options.intervalMs);\n timer.unref();\n return () => clearInterval(timer);\n}\n","import {\n HardenedPGliteDialect,\n type HardenedPGliteDialectOptions,\n} from \"@powerhousedao/reactor\";\nimport type {\n DatabaseIntrospector,\n Dialect,\n DialectAdapter,\n Driver,\n QueryCompiler,\n} from \"kysely\";\nimport type { ILogger } from \"document-model\";\nimport type { PGliteLike } from \"@powerhousedao/reactor-api/pglite-node\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */\nexport function reactorPgliteDialectOptions(\n logger: ILogger,\n proc?: FatalProcess,\n): Partial<HardenedPGliteDialectOptions> {\n return {\n onDiagnostic: (message, error) =>\n logger.error(`[pglite-dialect] ${message}: @error`, error),\n onPoisoned: (cause) => {\n if (!triggerFatalShutdown(\"PGlite session poisoned\", cause, proc)) {\n logger.error(\"PGlite session poisoned: @error\", cause);\n }\n },\n };\n}\n\ntype IntrospectedDatabase = Parameters<Dialect[\"createIntrospector\"]>[0];\n\n// kysely-pglite-dialect's driver.destroy() only nulls its reference to the\n// PGlite client — it never calls pglite.close(). Without close(), the store\n// misses its shutdown checkpoint and the next open runs WAL recovery. This\n// wrapper closes the dialect's PGlite as part of the reactor's\n// database.destroy() chain.\nexport class ClosablePGliteDialect implements Dialect {\n readonly #inner: HardenedPGliteDialect;\n readonly #pglite: PGliteLike;\n\n constructor(\n pglite: PGliteLike,\n options: Partial<HardenedPGliteDialectOptions> = {},\n ) {\n this.#pglite = pglite;\n this.#inner = new HardenedPGliteDialect(pglite, options);\n }\n\n createAdapter(): DialectAdapter {\n return this.#inner.createAdapter();\n }\n\n createDriver(): Driver {\n const driver = this.#inner.createDriver();\n const pglite = this.#pglite;\n const innerDestroy = driver.destroy.bind(driver);\n driver.destroy = async () => {\n await innerDestroy();\n if (pglite.closed) return;\n try {\n await pglite.close();\n } catch (err) {\n // An aborted runtime (Postgres PANIC) has nothing left to flush.\n if (!/PGlite aborted/.test(String(err))) throw err;\n }\n };\n return driver;\n }\n\n createQueryCompiler(): QueryCompiler {\n return this.#inner.createQueryCompiler();\n }\n\n createIntrospector(db: IntrospectedDatabase): DatabaseIntrospector {\n return this.#inner.createIntrospector(db);\n }\n}\n","import { syncTree } from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n loadPGliteModule,\n loadPgDump,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype PGliteLike = {\n waitReady: Promise<void>;\n exec: (sql: string) => Promise<unknown>;\n close: () => Promise<void>;\n dumpDataDir: (compression: \"none\") => Promise<Blob>;\n};\n\ntype PGliteCtor = {\n new (dataDir: string, options?: Record<string, unknown>): PGliteLike;\n new (options: Record<string, unknown>): PGliteLike;\n};\n\nfunction backupPath(dataDir: string, major: number): string {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${dataDir}.backup-pg${major}-${stamp}`;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction logRestoreFailure(\n dataDir: string,\n sql: string,\n err: unknown,\n logger: ILogger,\n): void {\n const errObj = err as {\n message?: string;\n position?: string | number;\n severity?: string;\n code?: string;\n detail?: string;\n where?: string;\n };\n const position =\n typeof errObj.position === \"string\"\n ? parseInt(errObj.position, 10)\n : typeof errObj.position === \"number\"\n ? errObj.position\n : NaN;\n\n logger.error(\n `[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? \"\"} severity=${errObj.severity ?? \"\"} message=${errObj.message ?? \"\"} sqlLength=${sql.length}`,\n );\n\n if (Number.isFinite(position) && position > 0) {\n const zeroBased = position - 1;\n const start = Math.max(0, zeroBased - 200);\n const end = Math.min(sql.length, zeroBased + 200);\n const before = sql.slice(start, zeroBased);\n const at = sql.slice(zeroBased, zeroBased + 1);\n const after = sql.slice(zeroBased + 1, end);\n logger.error(\n `[pglite-migration] SQL context around position ${position}:\\n${before}»${at}«${after}`,\n );\n } else {\n logger.error(\n `[pglite-migration] No position info. First 2000 chars of dump:\\n${sql.slice(0, 2000)}`,\n );\n }\n}\n\n/**\n * Migrate a filesystem PGLite data directory from a legacy PG major to the\n * current one. Renames the existing dir to a timestamped backup, dumps via the\n * matching legacy `pg_dump`, restores into a fresh current-version PGLite at\n * the original path. On failure, the original dir is restored from the backup.\n *\n * No-op when the dir is missing or already at the current major.\n */\nexport async function migratePgliteDir(\n dataDir: string,\n logger: ILogger,\n): Promise<void> {\n const major = await readPgVersionFile(dataDir);\n if (major === null) {\n logger.info(\n `[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`,\n );\n return;\n }\n if (major === CURRENT_PG_MAJOR) return;\n\n if (!isSupportedMajor(major)) {\n throw new Error(\n `Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`,\n );\n }\n\n const backupDir = backupPath(dataDir, major);\n logger.info(\n `[pglite-migration] Migrating ${dataDir} from PG${major} to PG${CURRENT_PG_MAJOR}; backup: ${backupDir}`,\n );\n\n await fs.rename(dataDir, backupDir);\n\n let sql: string;\n try {\n const [legacyMod, pgDump] = await Promise.all([\n loadPGliteModule(major as SupportedPgMajor),\n loadPgDump(major as SupportedPgMajor),\n ]);\n const LegacyPGlite = (legacyMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // pglite-tools 0.2.x talks to the server through files in the PGlite\n // FS, and 0.2.17's NODEFS write drops the view's byteOffset, so every\n // query arrives as zeros. Dump from an in-memory copy instead.\n const onDisk = new LegacyPGlite(backupDir);\n let tar: Blob;\n try {\n await onDisk.waitReady;\n tar = await onDisk.dumpDataDir(\"none\");\n } finally {\n await onDisk.close();\n }\n const pg = new LegacyPGlite({ loadDataDir: tar });\n try {\n await pg.waitReady;\n const file = await pgDump({ pg });\n sql = await file.text();\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n try {\n const currentMod = await loadPGliteModule(CURRENT_PG_MAJOR);\n const CurrentPGlite = (currentMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // Stock NodeFS never syncs to the host; one pass after close does.\n const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });\n try {\n await pg.waitReady;\n try {\n await pg.exec(\"SET standard_conforming_strings = off;\");\n } catch (gucErr) {\n logger.warn(\n `[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`,\n );\n }\n try {\n await pg.exec(sql);\n } catch (execErr) {\n logRestoreFailure(dataDir, sql, execErr, logger);\n throw execErr;\n }\n } finally {\n await pg.close();\n }\n syncTree(dataDir);\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n logger.info(\n `[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`,\n );\n}\n\nasync function rollback(\n dataDir: string,\n backupDir: string,\n originalError: unknown,\n logger: ILogger,\n): Promise<void> {\n try {\n if (await pathExists(dataDir)) {\n await fs.rm(dataDir, { recursive: true, force: true });\n }\n if (await pathExists(backupDir)) {\n await fs.rename(backupDir, dataDir);\n }\n } catch (rollbackErr) {\n logger.error(\n `[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`,\n );\n return;\n }\n logger.error(\n `[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`,\n );\n}\n","import {\n preparePgliteDataDir,\n removeStalePgliteFiles,\n type ConversionDeps,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport { migratePgliteDir } from \"./pglite-migration.js\";\nimport {\n CURRENT_PG_MAJOR,\n openForVerify,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\nexport interface PglitePreflightOptions {\n /** Local PGlite data dirs; Postgres URLs are already filtered out. */\n dirs: string[];\n forcePgVersion?: SupportedPgMajor;\n migratePglite?: boolean;\n /** PH_PGLITE_IN_MEMORY: the dirs are never opened, so nothing is touched. */\n inMemory: boolean;\n logger: ILogger;\n /** Test hook; defaults to the module-matched stock NodeFS. */\n openForVerify?: ConversionDeps[\"openForVerify\"];\n}\n\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 10,\n retryDelay: 100,\n} as const;\n\n/**\n * Prepares every local PGlite dir before the first open and returns the\n * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot\n * runs for every dir, before the major is read, so a pure-snapshot PG16 dir\n * is converted and then migrated.\n */\nexport async function runPglitePreflight(\n options: PglitePreflightOptions,\n): Promise<Map<string, number>> {\n const { dirs, logger } = options;\n const detectedMajors = new Map<string, number>();\n if (options.inMemory || dirs.length === 0) return detectedMajors;\n\n if (options.forcePgVersion !== undefined) {\n if (options.migratePglite) {\n logger.warn(\n \"PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.\",\n );\n }\n logger.warn(\n `PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`,\n );\n for (const dir of dirs) {\n // Conversion siblings go too, or the next boot refuses to initdb beside them.\n for (const p of [dir, `${dir}.converting`, `${dir}.old`]) {\n await fs.rm(p, RM_OPTIONS);\n }\n logger.info(`Wiped PGLite data dir ${dir}`);\n }\n return detectedMajors;\n }\n\n const deps: ConversionDeps = {\n openForVerify: options.openForVerify ?? openForVerify,\n logger,\n };\n for (const dir of dirs) {\n await preparePgliteDataDir(dir, deps);\n const major = await readPgVersionFile(dir);\n if (major !== null) detectedMajors.set(dir, major);\n }\n\n if (options.migratePglite) {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n await migratePgliteDir(dir, logger);\n // The migration's own close leaves a lockfile in the new dir.\n await removeStalePgliteFiles(dir, logger);\n const after = await readPgVersionFile(dir);\n if (after !== null) detectedMajors.set(dir, after);\n }\n } else {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n logger.warn(\n `PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG${CURRENT_PG_MAJOR}. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`,\n );\n }\n }\n return detectedMajors;\n}\n","import type { PGliteOptions } from \"@electric-sql/pglite\";\nimport {\n createDurableNodeFs,\n PGLITE_UTC_PARSERS,\n pgliteWorkerEntryPath,\n DEFAULT_PGLITE_WORKER_MEMORY_MB,\n resolvePgliteMaintenance,\n ThreadedPGlite,\n type DurableNodeFs,\n type PGliteAbortListener,\n type PGliteExitListener,\n type PGliteLike,\n type PGliteParserPreset,\n type PgliteMaintenanceSettings,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport {\n startProgressHeartbeat,\n type HardenedPGliteDialectOptions,\n} from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\nimport {\n loadNodeFsClass,\n loadPGliteModule,\n pgliteModuleSpec,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n// A Postgres PANIC (ENOSPC on WAL, a failed fdatasync) aborts the wasm\n// runtime; the store is dead and the process must not keep accepting writes.\nexport function onPgliteAbort(\n logger: ILogger,\n what: unknown,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite aborted\", what, proc)) {\n logger.error(\"PGlite aborted: @error\", what);\n }\n}\n\n/** A store's worker thread died: every later query would fail, so the process shuts down. */\nexport function onPgliteWorkerExit(\n logger: ILogger,\n error: Error,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite worker exited\", error, proc)) {\n logger.error(\"PGlite worker exited: @error\", error);\n }\n}\n\n/** The events a worker-backed store raises; {@link ThreadedPGlite} has them. */\nexport interface PgliteWorkerEvents {\n onAbort(listener: PGliteAbortListener): () => void;\n onExit(listener: PGliteExitListener): () => void;\n}\n\n/** Sends a worker's abort and its unexpected exit to the fatal shutdown. */\nexport function routePgliteWorkerFailures(\n store: PgliteWorkerEvents,\n logger: ILogger,\n proc?: FatalProcess,\n): void {\n store.onAbort((reason) => onPgliteAbort(logger, reason, proc));\n store.onExit((error) => {\n if (error !== null) onPgliteWorkerExit(logger, error, proc);\n });\n}\n\n/** A store whose thread can be stopped at once. */\nexport interface TerminableStore {\n terminate(): Promise<void>;\n}\n\n/**\n * Adds a terminate of the store's worker to the dialect's `onPoisoned`: a\n * statement that never settled holds the worker's only connection, and the\n * fatal shutdown's close would otherwise queue behind it until its grace ran\n * out.\n */\nexport function terminateOnPoisoned(\n options: Partial<HardenedPGliteDialectOptions>,\n store: TerminableStore,\n): Partial<HardenedPGliteDialectOptions> {\n const reportPoisoned = options.onPoisoned;\n return {\n ...options,\n onPoisoned: (cause) => {\n reportPoisoned?.(cause);\n void store.terminate();\n },\n };\n}\n\n// 0.2.17 syncs WAL through open_datasync, which NODEFS cannot honour, so on\n// PG16 only checkpoints reach the host disk; commits are durable against an\n// app crash, not a power loss, until --migrate-pglite upgrades the dir.\nfunction pgliteFsyncFor(\n wanted: boolean,\n major: SupportedPgMajor,\n dir: string,\n logger: ILogger,\n): boolean {\n if (wanted && major === 16) {\n logger.warn(\n `PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`,\n );\n }\n return wanted;\n}\n\n/** The VACUUM FULL settings from the environment; see `resolvePgliteMaintenance`. */\nexport const vacuumFullTimingFromEnv = resolvePgliteMaintenance;\n\n/** The VACUUM FULL settings a config asks for, with the env parser's rules. */\nexport function vacuumFullTimingOf(vacuumFull: {\n mode: \"off\" | \"quiet\" | \"forced\";\n aboveMb?: number;\n quietMs?: number;\n maxDeferMs?: number;\n}): PgliteMaintenanceSettings {\n return resolvePgliteMaintenance({\n PH_PGLITE_VACUUM_FULL: vacuumFull.mode,\n PH_PGLITE_VACUUM_FULL_ABOVE_MB: vacuumFull.aboveMb?.toString(),\n PH_PGLITE_VACUUM_FULL_QUIET_MS: vacuumFull.quietMs?.toString(),\n PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS: vacuumFull.maxDeferMs?.toString(),\n });\n}\n\n/** How each PGlite store runs; unset fields take the defaults. */\nexport interface PgliteStoreSettings {\n fsync?: boolean;\n maintenance?: PgliteMaintenanceSettings;\n workerMemoryMb?: number;\n}\n\nconst DEFAULT_MAINTENANCE: PgliteMaintenanceSettings = {\n vacuumFullAboveBytes: 0,\n};\n\n/** Preloads the module's NodeFS so the returned factory can be synchronous. */\nexport async function loadDurableFsFactory(\n major: SupportedPgMajor,\n logger: ILogger,\n proc?: FatalProcess,\n settings: PgliteStoreSettings = {},\n): Promise<(dir: string) => DurableNodeFs> {\n const NodeFS = await loadNodeFsClass(major);\n const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;\n return (dir) =>\n createDurableNodeFs(NodeFS, dir, {\n fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),\n ...timing,\n logger,\n onAbort: (what) => onPgliteAbort(logger, what, proc),\n });\n}\n\nexport type PgliteStoreLabel = \"reactor-storage\" | \"read-storage\";\n\nexport interface PgliteStoreOptions {\n label: PgliteStoreLabel;\n major: SupportedPgMajor;\n parsers: PGliteParserPreset;\n /** PH_PGLITE_IN_MEMORY: the store ignores its dir. */\n inMemory: boolean;\n /** Open the store in its own worker thread (PH_PGLITE_WORKERS / `pgliteWorkers`). */\n threaded: boolean;\n settings?: PgliteStoreSettings;\n logger: ILogger;\n /** Where fatal conditions go; the process by default. */\n proc?: FatalProcess;\n}\n\n/** Opens a store on a data dir; synchronous because reactor-api's read store opens synchronously. */\nexport type PgliteStoreFactory = (dataDir: string) => PGliteLike;\n\nexport const REACTOR_STORE = {\n label: \"reactor-storage\",\n parsers: \"none\",\n} as const;\n\nexport const READ_STORE = {\n label: \"read-storage\",\n parsers: \"utc-timestamps\",\n} as const;\n\n/** A host's two stores, opening side by side. */\nexport interface StoresOpening {\n reactor: PGliteLike;\n readModel: PGliteLike;\n /** Rejects with the first store's failure, once the other has closed. */\n failed: Promise<never>;\n close(): Promise<void>;\n}\n\n/**\n * Starts both stores at once, so the wait is the slower of the two rather than\n * their sum. A store left by a crash spends seconds recovering in its thread.\n * If one can't open, the other is closed, not left recovering for nobody.\n */\nexport function openStoresTogether(\n openReactor: () => PGliteLike,\n openReadModel: () => PGliteLike,\n): StoresOpening {\n const reactor = openReactor();\n let readModel: PGliteLike;\n try {\n readModel = openReadModel();\n } catch (error) {\n void reactor.close().catch(() => undefined);\n throw error;\n }\n const close = async () => {\n await Promise.allSettled([reactor.close(), readModel.close()]);\n };\n const stays = () => new Promise<never>(() => undefined);\n const failed = Promise.race([\n reactor.waitReady.then(stays),\n readModel.waitReady.then(stays),\n ]).catch(async (error: unknown) => {\n await close();\n throw error;\n });\n failed.catch(() => undefined);\n return { reactor, readModel, failed, close };\n}\n\n/**\n * The factory for one PGlite store: in a worker thread when `threaded` (and a\n * worker script exists here), else in the main thread as before. Either way\n * the store runs DurableNodeFs over its dir with the same fsync choice, and a\n * wasm abort takes the fatal shutdown.\n */\nexport async function createPgliteStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n if (options.threaded) {\n if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);\n options.logger.warn(\n `${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`,\n );\n }\n return mainThreadStoreFactory(options);\n}\n\nfunction threadedStoreFactory(options: PgliteStoreOptions): PgliteStoreFactory {\n const { label, major, parsers, inMemory, logger, proc } = options;\n const settings = options.settings ?? {};\n const memoryLimitMb =\n settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;\n const module = pgliteModuleSpec(major);\n return (dir) => {\n const store = new ThreadedPGlite({\n store: {\n label,\n dataDir: inMemory ? null : dir,\n module,\n durableFs: inMemory\n ? null\n : {\n fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),\n ...(settings.maintenance ?? DEFAULT_MAINTENANCE),\n },\n parsers,\n },\n memoryLimitMb,\n logger,\n });\n routePgliteWorkerFailures(store, logger, proc);\n logger.info(\n `${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`,\n );\n // Opening a large store (loading the data dir, a crash-recovery sweep)\n // can take a while before the first query answers: say so while it lasts.\n const opening = startProgressHeartbeat({\n logger,\n label: `${label}: opening the store`,\n });\n store.waitReady.then(\n () => opening.stop(),\n () => opening.stop(\"failed\"),\n );\n return store;\n };\n}\n\nasync function mainThreadStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n const { label, major, inMemory, logger, proc } = options;\n const { PGlite } = await loadPGliteModule(major);\n const durableFs = inMemory\n ? null\n : await loadDurableFsFactory(major, logger, proc, options.settings);\n const base: PGliteOptions =\n options.parsers === \"utc-timestamps\" ? { parsers: PGLITE_UTC_PARSERS } : {};\n return (dir) => {\n logger.info(\n `${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`,\n );\n return durableFs === null\n ? new PGlite(base)\n : new PGlite({ ...base, fs: durableFs(dir) });\n };\n}\n\nfunction where(inMemory: boolean, dir: string): string {\n return inMemory ? \", in memory [PH_PGLITE_IN_MEMORY=1]\" : ` at ${dir}`;\n}\n","import {\n DEFAULT_SIGNATURE_POLICY,\n isSignaturePolicy,\n type SignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\n/**\n * What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a\n * signer this switchboard cannot write to a v2-required document, so it falls\n * back to legacy and says so.\n */\nexport function resolveCreateSignaturePolicy(\n env: NodeJS.ProcessEnv,\n options: SignerFallbackOptions,\n): SignaturePolicy {\n const raw = env.CREATE_SIGNATURE_POLICY?.trim();\n let policy: SignaturePolicy = DEFAULT_SIGNATURE_POLICY;\n if (raw) {\n if (!isSignaturePolicy(raw)) {\n throw new Error(\n `CREATE_SIGNATURE_POLICY must be \"legacy\" or \"v2-required\", got \"${raw}\"`,\n );\n }\n policy = raw;\n }\n return createSignaturePolicyFor(policy, options);\n}\n\ntype SignerFallbackOptions = {\n hasSigner: boolean;\n logger?: Pick<ILogger, \"warn\">;\n};\n\n/** The requested policy, or legacy when it needs a signer this switchboard lacks. */\nexport function createSignaturePolicyFor(\n policy: SignaturePolicy,\n options: SignerFallbackOptions,\n): SignaturePolicy {\n if (policy === \"v2-required\" && !options.hasSigner) {\n options.logger?.warn(\n \"No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.\",\n );\n return \"legacy\";\n }\n return policy;\n}\n","import type { FactorySpec, SignerConfig } from \"@powerhousedao/reactor\";\nimport {\n createRenownTrustPolicy,\n DEFAULT_KEYPAIR_PATH,\n DEFAULT_RENOWN_URL,\n NodeKeyStorage,\n RenownBuilder,\n RenownCryptoBuilder,\n resolveSwitchboardEndpoint,\n type IRenown,\n type RenownTrustPolicyOptions,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { childLogger } from \"document-model\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\n\nconst logger = childLogger([\"switchboard\", \"renown\"]);\n\nexport interface RenownOptions {\n /** Path to the keypair file. Defaults to .ph/.keypair.json in cwd */\n keypairPath?: string;\n /** If true, won't generate a new keypair if none exists */\n requireExisting?: boolean;\n /** Base url of the Renown instance to use */\n baseUrl?: string;\n /** Renown user storage; defaults to .ph/.renown.json under `userDataDir`, else renown's own default. */\n storagePath?: string;\n /** The relocated `.ph` root (PH_USER_DATA_DIR at the edge). */\n userDataDir?: string;\n}\n\n/**\n * Initialize Renown for the Switchboard instance.\n * This allows Switchboard to authenticate with remote services\n * using the same identity established during `ph login`.\n */\nexport async function initRenown(\n options: RenownOptions = {},\n): Promise<IRenown | null> {\n const {\n keypairPath,\n requireExisting = false,\n baseUrl = DEFAULT_RENOWN_URL,\n userDataDir,\n storagePath = userDataDir\n ? join(\n resolvePhDir(undefined, { PH_USER_DATA_DIR: userDataDir }),\n \".renown.json\",\n )\n : undefined,\n } = options;\n\n const keyStorage = new NodeKeyStorage(keypairPath, {\n logger,\n });\n\n // Check if we have an existing keypair\n const existingKeyPair = await keyStorage.loadKeyPair();\n\n if (!existingKeyPair && requireExisting) {\n throw new Error(\n \"No existing keypair found and requireExisting is true. \" +\n 'Run \"ph login\" to create one.',\n );\n }\n\n if (!existingKeyPair) {\n logger.info(\"No existing keypair found. A new one will be generated.\");\n }\n\n const renownCrypto = await new RenownCryptoBuilder()\n .withKeyPairStorage(keyStorage)\n .build();\n\n // keyPath too: the builder's default key storage mkdirs <cwd>/.ph.\n const renown = await new RenownBuilder(\"switchboard\", {\n ...(storagePath ? { storagePath } : {}),\n ...(keypairPath ? { keyPath: keypairPath } : {}),\n })\n .withCrypto(renownCrypto)\n .withBaseUrl(baseUrl)\n .build();\n\n logger.info(\"Switchboard identity initialized: @did\", renownCrypto.did);\n\n return renown;\n}\n\n/**\n * Get the signer config for the given renown instance.\n *\n * @param renown - The renown instance\n * @param keypairPath - Where `initRenown` loaded the key from\n */\nexport function getRenownSignerConfig(\n renown: IRenown,\n keypairPath?: string,\n): SignerConfig {\n return {\n signer: renown.signer,\n workerSigner: getRenownWorkerSignerSpec(renown, keypairPath),\n };\n}\n\n/**\n * What a pooled executor worker imports to sign as this switchboard: it\n * reloads the key `initRenown` stored, and takes the user known at boot.\n */\nexport function getRenownWorkerSignerSpec(\n renown: IRenown,\n keypairPath?: string,\n): FactorySpec {\n const { signer } = renown;\n const user = signer.user;\n return {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createNodeRenownSigner\",\n },\n initArgs: {\n appName: signer.app?.name ?? \"switchboard\",\n keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),\n ...(signer.app?.key ? { did: signer.app.key } : {}),\n ...(user\n ? {\n user: {\n address: user.address,\n networkId: user.networkId,\n chainId: user.chainId,\n },\n }\n : {}),\n },\n };\n}\n\n/**\n * What a host with `authEnforcement` off installs: a delegated signer is\n * verified from what it carries, and every other signer is accepted as the\n * default would. No lookup, so it needs no network, at boot or after.\n */\nexport function getDelegationTrustPolicyConfig(\n renown: IRenown | null,\n): Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\"> {\n const ownSigner = renown?.signer;\n const self = ownIdentity(renown);\n return {\n trustPolicy: createRenownTrustPolicy({ delegationOnly: true, ownSigner }),\n workerTrustPolicy: {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createRenownTrustPolicy\",\n },\n initArgs: { delegationOnly: true, ...(self ? { self } : {}) },\n },\n };\n}\n\n/** Where switchboard reads the credentials binding keys to wallets. */\nexport type RenownTrustSource =\n | { source: \"remote\"; renownUrl?: string; switchboardUrl?: string }\n | { source: \"self\"; request: SwitchboardRequestFn };\n\n/**\n * Admits a key as a signer for an address a Renown credential binds it to; a\n * `self` source has no worker spec. In process, the switchboard's own key is\n * matched against its current user; the worker spec carries the user known now.\n */\nexport async function getRenownTrustPolicyConfig(\n trustSource: RenownTrustSource,\n renown: IRenown | null,\n): Promise<Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">> {\n const ownSigner = renown?.signer;\n if (trustSource.source === \"self\") {\n return {\n trustPolicy: createRenownTrustPolicy({\n switchboard: trustSource.request,\n ownSigner,\n }),\n };\n }\n\n const switchboardUrl = await resolveSwitchboardEndpoint({\n switchboardUrl: trustSource.switchboardUrl,\n baseUrl: trustSource.renownUrl,\n });\n const options = {\n ...(switchboardUrl ? { switchboard: switchboardUrl } : {}),\n ...(trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}),\n } satisfies RenownTrustPolicyOptions;\n const self = ownIdentity(renown);\n return {\n trustPolicy: createRenownTrustPolicy({ ...options, ownSigner }),\n workerTrustPolicy: {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createRenownTrustPolicy\",\n },\n initArgs: { ...options, ...(self ? { self } : {}) },\n },\n };\n}\n\nfunction ownIdentity(\n renown: IRenown | null,\n): RenownTrustPolicyOptions[\"self\"] | undefined {\n const key = renown?.signer.app?.key;\n if (!key) {\n return undefined;\n }\n const user = renown.signer.user;\n return {\n key,\n user: {\n address: user?.address ?? \"\",\n networkId: user?.networkId ?? \"\",\n chainId: user?.chainId ?? 0,\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * One process per PGlite store. PGlite is an in-process Postgres with no\n * postmaster to arbitrate: two processes opening the same data dir are two\n * writers on one PGDATA, which tears the store (it then aborts at the next\n * checkpoint or refuses to reopen). Hosts share one `.ph` tree by design\n * (`ph run vetra`, `ph run cli`, `ph run desktop`, classic `ph vetra` /\n * `ph switchboard` all use `.ph/reactor-storage` + `.ph/read-storage`), and the\n * per-host run records cannot see each other — so the guard lives here,\n * below every host: the switchboard takes a lock per store dir before\n * opening it.\n *\n * The lock is a SIBLING file (`<dir>.lock`), not a file inside the data dir:\n * initdb refuses a non-empty directory. A lock whose owner is dead (a\n * hard-killed process) is stale and taken over; the owner releases it on\n * exit. The same process may re-acquire its own lock (in-process restarts).\n */\nexport interface StoreLockOwner {\n pid: number;\n startedAt: string;\n command: string;\n}\n\nexport class StoreInUseError extends Error {\n constructor(\n readonly dir: string,\n readonly owner: StoreLockOwner,\n ) {\n super(\n `The PGlite store ${dir} is in use by another process (pid ${owner.pid}, since ${owner.startedAt}: ${owner.command}). ` +\n \"Two processes on one PGlite store corrupt it. Stop that process first, or point this one at a different store.\",\n );\n this.name = \"StoreInUseError\";\n }\n}\n\nconst lockPathOf = (dir: string) => `${path.resolve(dir)}.lock`;\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nfunction readOwner(file: string): StoreLockOwner | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as StoreLockOwner;\n } catch {\n return undefined;\n }\n}\n\nconst held = new Set<string>();\nlet exitHookInstalled = false;\n\nfunction releaseAll(): void {\n for (const file of held) {\n const owner = readOwner(file);\n if (owner?.pid === process.pid) {\n try {\n fs.rmSync(file);\n } catch {\n // already gone\n }\n }\n }\n held.clear();\n}\n\n/** Take the lock for each store dir, or throw StoreInUseError naming the\n * live owner. Idempotent within one process. */\nexport function acquireStoreLocks(\n dirs: readonly string[],\n isPidAlive: (pid: number) => boolean = isAlive,\n): void {\n const mine: StoreLockOwner = {\n pid: process.pid,\n startedAt: new Date().toISOString(),\n command: process.argv.slice(1).join(\" \").slice(0, 200),\n };\n for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {\n const file = lockPathOf(dir);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const owner = readOwner(file);\n if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) {\n throw new StoreInUseError(dir, owner);\n }\n // free, stale (dead owner) or already ours: write our claim\n fs.writeFileSync(file, `${JSON.stringify(mine)}\\n`);\n held.add(file);\n }\n if (!exitHookInstalled) {\n exitHookInstalled = true;\n process.on(\"exit\", releaseAll);\n }\n}\n\n/** Release this process's store locks (tests; orderly shutdown). */\nexport function releaseStoreLocks(): void {\n releaseAll();\n}\n","#!/usr/bin/env node\nimport { metrics, trace } from \"@opentelemetry/api\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { ReactorInstrumentation } from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport {\n CatchUpPriority,\n computeProcessorTiming,\n DriveCollectionId,\n EventBus,\n IN_MEMORY_PGLITE_STORAGE_FACTS,\n PGLITE_PATH_STORAGE_FACTS,\n POSTGRES_STORAGE_FACTS,\n REACTOR_SCHEMA,\n ReactorBuilder,\n ReactorClientBuilder,\n createHybridProjectionCoordinatorFactory,\n instrumentPgPool,\n MemoryTelemetry,\n parseDriveUrl,\n ProcessorTimingSettings,\n parseKeyframeSettings,\n type Database,\n type InProcessReactorClientModule,\n type InProcessReactorModule,\n type IStoreMaintenance,\n type JwtHandler,\n type KeyframeSettings,\n type PoolInstrumentation,\n type ReactorStorageFacts,\n UnsupportedStoredProtocolError,\n withProgressHeartbeat,\n} from \"@powerhousedao/reactor\";\nimport {\n createHeapSnapshotWriter,\n HttpPackageLoader,\n ImportPackageLoader,\n memoryFileSink,\n NodeMemorySampler,\n PackageManagementService,\n PackagesSubgraph,\n initializeAndStartAPI,\n NodeEventLoopDelay,\n RequestLoadRecorder,\n reportFailure,\n resolveRenownConfig,\n runDetached,\n telemetryDir,\n type CanonicalDocumentId,\n type ClientInitializerDependencies,\n type CredentialVerifier,\n type DocumentPermissionDatabase,\n type IPackageLoader,\n type PgliteFactory,\n type ResolvedRenownConfig,\n} from \"@powerhousedao/reactor-api\";\nimport { httpsHooksPath } from \"@powerhousedao/reactor-api/https-hooks\";\nimport {\n disableWasmWrapperTiering,\n maintenanceOf,\n pgliteWorkerEntryPath,\n ThreadedPGlite,\n type PGliteLike,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { VitePackageLoader } from \"@powerhousedao/reactor-api/vite\";\nimport { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport {\n createReactorDriveWriteStrategy,\n DriveNodeView,\n NodeProcessor,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n ReactorDriveClient,\n type ReactorDriveDatabase,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n createReactorDriveResolvers,\n REACTOR_DRIVE_SUBGRAPH_NAME,\n reactorDriveSubgraphTypeDefs,\n} from \"@powerhousedao/reactor-drive/subgraph\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n createLocalCredentialVerifier,\n RENOWN_READ_MODEL_SUBGRAPH,\n type CredentialCheck,\n type IRenown,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport { childLogger, setLogLevel, type ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\nimport { Kysely, PostgresDialect } from \"kysely\";\nimport { backfillPermissionTables } from \"./permissions-backfill.mjs\";\nimport { register } from \"node:module\";\nimport type http from \"node:http\";\nimport net from \"node:net\";\nimport path from \"path\";\nimport { Pool } from \"pg\";\nimport type { ViteDevServer } from \"vite\";\nimport { registerAttachmentRoutes } from \"./attachments/index.js\";\nimport {\n parseOAuthApps,\n type OAuthAppConfig,\n} from \"./workflow/oauth-apps-config.js\";\nimport {\n registerAttachmentReferenceReadModel,\n registerAttachmentReferenceReadModelOnModule,\n} from \"./attachment-reference-read-model.mjs\";\nimport { installFatalErrorShutdown, raiseSigterm } from \"./fatal-shutdown.mjs\";\nimport {\n resolvePrivacy,\n startPrivacy,\n type ResolvedPrivacy,\n type RunningPrivacy,\n} from \"./privacy.mjs\";\nimport { applySwitchboardReactorDefaults } from \"./builder-defaults.mjs\";\nimport {\n createSwitchboardPluginHost,\n type SwitchboardPluginHost,\n} from \"./plugin-host.mjs\";\nimport {\n assertProjectionWorkerSupported,\n resolveProjectionWorkerOptions,\n} from \"./projection-worker.mjs\";\nimport {\n buildWorkerDbConfig,\n keepImportableSources,\n resolveWorkerModelSources,\n resolveWorkerPoolOptions,\n} from \"./worker-pool.mjs\";\nimport { initProfilerFromEnv } from \"./profiler.js\";\nimport { switchboardConfigFromEnv } from \"./config/from-env.js\";\nimport { startProcessorTimingLog } from \"./processor-timing-log.mjs\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigSchema,\n type SwitchboardConfig,\n type SwitchboardConfigInput,\n} from \"./config/schema.js\";\nimport {\n WORKFLOW_PACKAGE_NAME,\n WORKFLOW_TELEMETRY_SCOPE,\n composeWorkflowRuntime,\n modelManifestSource,\n assertWorkflowPackageLoadable,\n isWorkflowSingletonConflict,\n retryWorkflowSingleton,\n workflowSingletonLossHandler,\n type WorkflowSingletonRetry,\n type ComposedWorkflowRuntime,\n type ModelManifestSource,\n} from \"./workflow-runtime.mjs\";\nimport {\n ClosablePGliteDialect,\n reactorPgliteDialectOptions,\n} from \"./pglite-dialect.js\";\nimport { runPglitePreflight } from \"./pglite-preflight.js\";\nimport {\n createPgliteStoreFactory,\n openStoresTogether,\n READ_STORE,\n REACTOR_STORE,\n terminateOnPoisoned,\n vacuumFullTimingOf,\n type PgliteStoreSettings,\n type StoresOpening,\n} from \"./pglite-store.mjs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\nimport { reactorFeatureFlagsOf } from \"./reactor-feature-flags.mjs\";\nimport { createSignaturePolicyFor } from \"./create-signature-policy.mjs\";\nimport { workerPoolIssues } from \"./boot-preconditions.mjs\";\nimport { renownLayers } from \"./renown-layers.mjs\";\nimport {\n getDelegationTrustPolicyConfig,\n getRenownSignerConfig,\n getRenownTrustPolicyConfig,\n initRenown,\n} from \"./renown.js\";\nimport type {\n StartServerOptions,\n SwitchboardDeps,\n SwitchboardReactor,\n} from \"./types.js\";\nimport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\nimport { ensureDrive, isPostgresUrl } from \"./utils.mjs\";\nimport { acquireStoreLocks } from \"./store-lock.mjs\";\nimport {\n defaultStoreDirs,\n resolvePhDir,\n} from \"@powerhousedao/shared/clis/ph-dir\";\nimport { isDotenvDisabled } from \"@powerhousedao/shared/clis/project-env\";\n\nconst defaultLogger = childLogger([\"switchboard\"]);\n\n// Edges map process.env after importing this, so the cwd .env is in it by then.\nif (!isDotenvDisabled()) dotenv.config();\n\n/** Process-wide settings an edge applies once, before its first `startSwitchboard`. */\nexport function initSwitchboardProcess(\n options: Pick<SwitchboardConfigInput, \"logLevel\"> = {},\n): void {\n setLogLevel(options.logLevel ?? \"info\");\n}\n\n// Module hooks are process-wide; registering them per server would stack them.\nlet httpsHooksRegistered = false;\nfunction registerHttpsHooks(): void {\n if (httpsHooksRegistered) return;\n httpsHooksRegistered = true;\n register(httpsHooksPath, import.meta.url);\n}\n\n// How many ports forward from the requested one we will try before giving up.\nconst PORT_FALLBACK_ATTEMPTS = 20;\n\n// Retired with the snapshot store; PGlite writes through NodeFS now.\nlet flushIntervalWarned = false;\nfunction warnIgnoredFlushInterval(logger: ILogger): void {\n if (flushIntervalWarned) return;\n if (process.env.PGLITE_FLUSH_INTERVAL_MS === undefined) return;\n flushIntervalWarned = true;\n logger.warn(\n \"PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.\",\n );\n}\n\n/**\n * Attempt to bind a throwaway TCP server to the given port. Resolves true if\n * the port is free, false if the OS reports it in use. Any other error is\n * surfaced so we don't silently mask real issues (permissions, bad host, …).\n */\nexport async function isPortAvailable(port: number): Promise<boolean> {\n try {\n // `::` is dual-stack on most systems, so it sees IPv6 and IPv4 listeners.\n return await probePort(port, \"::\");\n } catch (error) {\n // A host without IPv6, e.g. a container, can only probe IPv4.\n if (!isNoIpv6Error(error)) throw portProbeError(port, error);\n try {\n return await probePort(port, \"0.0.0.0\");\n } catch (ipv4Error) {\n throw portProbeError(port, ipv4Error);\n }\n }\n}\n\nconst isNoIpv6Error = (error: unknown) =>\n [\"EAFNOSUPPORT\", \"EADDRNOTAVAIL\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n );\n\nconst portProbeError = (port: number, error: unknown) =>\n new Error(\n `Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n\nfunction probePort(port: number, host: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const tester = net.createServer();\n tester.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" || err.code === \"EACCES\") {\n resolve(false);\n } else {\n reject(err);\n }\n });\n tester.once(\"listening\", () => {\n tester.close(() => resolve(true));\n });\n tester.listen({ port, host });\n });\n}\n\n/** The powerhouse.config.json this run reads, defaulting to the cwd copy. */\nfunction resolveConfigPath(configFile: string | undefined): string {\n return configFile ?? path.join(process.cwd(), \"powerhouse.config.json\");\n}\n\n/**\n * The config file's `workflows.oauthApps`, client file paths made absolute\n * from the config file's folder. An unreadable file or a malformed entry\n * means none: a missing app is reported when a sign-in asks for it.\n */\nfunction readConfigOAuthApps(\n configPath: string,\n logger: ILogger,\n): OAuthAppConfig[] {\n let raw: unknown;\n try {\n raw = (getConfig(configPath) as { workflows?: { oauthApps?: unknown } })\n .workflows?.oauthApps;\n } catch {\n return [];\n }\n return parseOAuthApps(\n raw,\n path.dirname(path.resolve(configPath)),\n (id, relay) =>\n logger.warn(\n `workflows.oauthApps \"${id}\": relay ${JSON.stringify(relay)} is not an object with clientId, redirectUri and tokenUrl; ignored`,\n ),\n );\n}\n\n// An unreadable config file means \"not configured\", not a boot failure:\n// workflows are opt-in.\n/** `PH_KEYFRAMES` (or a caller's layer) wins whole over the project config. */\nexport function resolveKeyframes(\n configured: SwitchboardConfig[\"storage\"][\"keyframes\"],\n fromFile: unknown,\n configPath: string,\n): KeyframeSettings | undefined {\n if (configured) return configured;\n return fromFile === undefined\n ? undefined\n : parseKeyframeSettings(fromFile, `${configPath} reactor.keyframes`);\n}\n\nfunction readConfigWorkflowsEnabled(configPath: string): boolean {\n try {\n return getConfig(configPath).workflows?.enabled ?? false;\n } catch {\n return false;\n }\n}\n\nasync function resolveServerPort(\n requested: number,\n strictPort: boolean,\n logger: ILogger,\n): Promise<number> {\n // 0 asks the OS for a free port at bind time: nothing to probe.\n if (requested === 0 || strictPort) return requested;\n for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {\n const candidate = requested + i;\n if (await isPortAvailable(candidate)) {\n if (candidate !== requested) {\n logger.info(\n `Port ${requested} is in use. Falling back to port ${candidate}.`,\n );\n }\n return candidate;\n }\n }\n // Couldn't find a free port in the window; let the caller surface the\n // original EADDRINUSE when the real bind attempts runs.\n return requested;\n}\n\n/**\n * The reactor's storage handle, plus the pool instrumentation when that\n * storage is Postgres. The PGlite branch has no `pg.Pool` at all, so the\n * instrumentation is absent rather than optional-by-convention.\n */\ntype ReactorStorage = {\n kysely: Kysely<Database>;\n poolInstrumentation: PoolInstrumentation | undefined;\n storageFacts: ReactorStorageFacts;\n /** Absent on Postgres, where the host does not own the connection. */\n storeMaintenance?: IStoreMaintenance;\n};\n\nexport async function createReactorKysely(opts: {\n reactorDbUrl: string | undefined;\n reactorPgliteDir: string | null;\n reactorPgliteMajor: SupportedPgMajor | null;\n inMemory: boolean;\n /** Called only on the Postgres branch, the one with a host pool. */\n hostPoolSize: () => number;\n /** Open the PGlite store in its own worker thread. */\n pgliteWorkers: boolean;\n pgliteSettings?: PgliteStoreSettings;\n /** The store, when it's already opening. */\n openingStore?: PGliteLike;\n logger: ILogger;\n}): Promise<ReactorStorage> {\n const {\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n hostPoolSize,\n pgliteWorkers,\n pgliteSettings,\n openingStore,\n logger,\n } = opts;\n\n if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {\n const connectionString = reactorDbUrl.includes(\"?\")\n ? reactorDbUrl\n : `${reactorDbUrl}?sslmode=disable`;\n const poolSize = hostPoolSize();\n const pool = new Pool({ connectionString, max: poolSize });\n // Named to match the reactor's own convention for the pools it opens\n // itself (`reactor-worker-N`, `projection-shard-N`).\n const poolInstrumentation = instrumentPgPool(pool, \"reactor-host\");\n logger.info(\n `Using PostgreSQL for reactor storage (host pool max ${poolSize})`,\n );\n return {\n kysely: new Kysely<Database>({ dialect: new PostgresDialect({ pool }) }),\n poolInstrumentation,\n storageFacts: POSTGRES_STORAGE_FACTS,\n };\n }\n\n if (!reactorPgliteDir || reactorPgliteMajor === null) {\n throw new Error(\"Reactor PGLite directory not resolved\");\n }\n const pglite =\n openingStore ??\n (\n await createPgliteStoreFactory({\n ...REACTOR_STORE,\n major: reactorPgliteMajor,\n inMemory,\n threaded: pgliteWorkers,\n settings: pgliteSettings,\n logger,\n })\n )(reactorPgliteDir);\n const dialectOptions =\n pglite instanceof ThreadedPGlite\n ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite)\n : reactorPgliteDialectOptions(logger);\n return {\n kysely: new Kysely<Database>({\n dialect: new ClosablePGliteDialect(pglite, dialectOptions),\n }),\n poolInstrumentation: undefined,\n storageFacts: inMemory\n ? IN_MEMORY_PGLITE_STORAGE_FACTS\n : PGLITE_PATH_STORAGE_FACTS,\n storeMaintenance:\n pglite instanceof ThreadedPGlite\n ? pglite\n : maintenanceOf(pglite as { fs?: unknown }),\n };\n}\n\nexport interface PgliteStorageDirs {\n /** Read-model store: a Postgres URL or a PGlite dir. */\n readModelPath: string;\n /** Reactor store: a Postgres URL or a PGlite dir. */\n reactorPath: string;\n /** PGlite dir for the reactor, null for Postgres or a caller-owned reactor. */\n reactorPgliteDir: string | null;\n /** PGlite dir for the read model, null for Postgres. */\n readModelPgliteDir: string | null;\n /** The PGlite dirs for the pre-flight, as before (not deduplicated). */\n pgliteDirs: string[];\n /** Set when BOTH stores are PGlite on one dir (see resolvePgliteStorageDirs). */\n sharedPgliteDir: string | null;\n}\n\n/**\n * Where the two stores live — the classic resolution, relocated verbatim.\n * Classic layout: `./.ph/reactor-storage` for the reactor and\n * `.ph/read-storage` for the read model (the same names inside\n * `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names\n * the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone\n * both stores share one location. That is the long-standing contract of\n * `--db-path` and fine for one Postgres database, but for PGlite it is two\n * postmasters on one data dir — reported via `sharedPgliteDir` so the caller\n * warns. Not refused: changing that contract is a separate decision.\n */\nexport function resolvePgliteStorageDirs(opts: {\n dbPath: string | undefined;\n reactorDbUrl: string | undefined;\n /** The caller passed its own reactor — the reactor-side dir is unused. */\n callerReactor: boolean;\n /** The relocated `.ph` root (PH_USER_DATA_DIR at the edge). */\n userDataDir?: string;\n phDir?: string;\n}): PgliteStorageDirs {\n const { dbPath, reactorDbUrl, callerReactor } = opts;\n const defaults = defaultStoreDirs(\n { PH_USER_DATA_DIR: opts.userDataDir },\n opts.phDir,\n );\n const readModelPath = dbPath || defaults.readModel;\n const reactorPath = reactorDbUrl || defaults.reactor;\n const reactorPgliteDir = callerReactor\n ? null\n : !reactorDbUrl || !isPostgresUrl(reactorDbUrl)\n ? reactorPath\n : null;\n const readModelPgliteDir =\n !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;\n const sharedPgliteDir =\n reactorPgliteDir !== null &&\n readModelPgliteDir !== null &&\n path.resolve(reactorPgliteDir) === path.resolve(readModelPgliteDir)\n ? path.resolve(reactorPgliteDir)\n : null;\n const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter(\n (d): d is string => d !== null,\n );\n return {\n readModelPath,\n reactorPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n };\n}\n\n/** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */\nexport function deriveAttachmentServiceConfig(\n options: Pick<StartServerOptions, \"attachmentServiceUrl\" | \"https\">,\n serverPort: number,\n renown: IRenown | null,\n): { remoteUrl: string; jwtHandler: JwtHandler | undefined } {\n const protocol = options.https ? \"https\" : \"http\";\n const remoteUrl =\n options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`;\n const jwtHandler: JwtHandler | undefined = renown\n ? async (url: string) =>\n renown.user\n ? renown.getBearerToken({ expiresIn: 10, aud: url })\n : undefined\n : undefined;\n return { remoteUrl, jwtHandler };\n}\n\n/** Sentry starts only under SENTRY_DSN (observability.mts), and is a lot to load. */\nasync function captureInSentry(error: unknown): Promise<void> {\n if (!process.env.SENTRY_DSN) return;\n const Sentry = await import(\"@sentry/node\");\n Sentry.captureException(error);\n}\n\nasync function initServer(\n requestedPort: number,\n options: StartServerOptions,\n config: SwitchboardConfig,\n renown: IRenown | null,\n renownConfig: ResolvedRenownConfig,\n reportError: (error: unknown) => void,\n /** Filled in once the stores start, for a boot that fails after that. */\n opening: { stores?: StoresOpening },\n) {\n const {\n dev,\n packages = [],\n remoteDrives = [],\n logger = defaultLogger,\n } = options;\n\n // R2 plugin pipeline (FEATURE_PLUGIN_HOST_ENABLED): flag off, the inline\n // path below runs byte-identically; flag on, carved subsystems run as\n // built-in plugins through the hook moments marked along this function.\n const pluginHost: SwitchboardPluginHost | null = config.features.pluginHost\n ? createSwitchboardPluginHost(\n {\n logger,\n options: options as unknown as Record<string, unknown>,\n config,\n renown,\n },\n options.pluginComposition,\n )\n : null;\n if (pluginHost) {\n options = await pluginHost.transformOptions(options);\n // Presence is activation: whatever no plugin (or explicit option) set\n // stays OFF. The mcp/workflows plugins set these true at\n // transformServerOptions; their absence must actually deactivate.\n options.mcp ??= false;\n options.workflows = {\n ...options.workflows,\n enabled: options.workflows?.enabled === true,\n };\n }\n logger.level = config.logLevel;\n const dbPath = config.storage.readModel.url;\n const reactorDbUrl = config.storage.reactor.url;\n const inMemory = config.storage.inMemory;\n const pgliteSettings: PgliteStoreSettings = {\n fsync: config.storage.pglite.fsync,\n maintenance: vacuumFullTimingOf(config.storage.pglite.vacuumFull),\n workerMemoryMb: config.storage.pglite.workerMemoryMb,\n };\n // Postgres URLs or local PGlite dirs under the project's .ph tree. When\n // the caller passes in a reactor, the reactor-side PGLite dir is unused —\n // the caller owns its own storage. Only the read-model dir is still needed\n // by reactor-api itself. Refuses one PGlite dir for both stores.\n const {\n readModelPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n } = resolvePgliteStorageDirs({\n dbPath,\n reactorDbUrl,\n callerReactor: options.reactor !== undefined,\n userDataDir: config.storage.userDataDir,\n });\n if (sharedPgliteDir !== null) {\n logger.warn(\n `The reactor and read-model PGlite stores share one directory (${sharedPgliteDir}): ` +\n \"two PGlite instances on one data dir can abort at the first checkpoint and leave the store unopenable. \" +\n \"Set PH_REACTOR_DATABASE_URL to a separate directory, or leave dbPath unset for the classic \" +\n \"./.ph/reactor-storage + .ph/read-storage layout.\",\n );\n }\n\n // PGLite pre-flight: convert legacy single-file snapshot stores, clear\n // stale lock and WAL temp files, then detect PG_VERSION and migrate or\n // warn. Under PH_FORCE_PG_VERSION the dirs are wiped instead.\n // One process per PGlite store, before anything (the pre-flight included)\n // touches it: hosts share one .ph tree, so a second `ph run …` / `ph vetra`\n // in the same project must fail here instead of tearing the store.\n if (!inMemory) acquireStoreLocks(pgliteDirs);\n warnIgnoredFlushInterval(logger);\n const detectedMajors = await runPglitePreflight({\n dirs: pgliteDirs,\n forcePgVersion: options.forcePgVersion,\n migratePglite: options.migratePglite,\n inMemory,\n logger,\n });\n\n function resolvePgliteMajorForDir(dir: string): SupportedPgMajor {\n if (options.forcePgVersion !== undefined) return options.forcePgVersion;\n const detected = detectedMajors.get(dir);\n if (detected === undefined) return CURRENT_PG_MAJOR;\n if (!isSupportedMajor(detected)) {\n throw new Error(\n `Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`,\n );\n }\n return detected;\n }\n\n const reactorPgliteMajor = reactorPgliteDir\n ? resolvePgliteMajorForDir(reactorPgliteDir)\n : null;\n const readModelPgliteMajor = readModelPgliteDir\n ? resolvePgliteMajorForDir(readModelPgliteDir)\n : null;\n\n const inspectionThrottle =\n config.inspection.callsPerMinute === undefined\n ? {}\n : { callsPerMinute: config.inspection.callsPerMinute };\n // The env is empty: the edges mapped it into the config.\n let workerPool = resolveWorkerPoolOptions(options.workerPool, {});\n if (workerPool && options.reactor) {\n logger.warn(\n \"Worker pool configuration ignored: the caller-provided reactor owns its own executor\",\n );\n workerPool = null;\n }\n if (workerPool) {\n const issue = workerPoolIssues({\n dev: dev === true,\n workers: workerPool.numWorkers,\n projectionWorker: false,\n reactorDbUrl,\n authEnforcement: config.protocol.featureFlags.authEnforcement,\n renownSource: renownConfig.source,\n }).at(0);\n if (issue) throw new Error(issue);\n }\n\n const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(\n options.unsupportedStoredDocuments,\n {},\n );\n\n let projectionWorker = resolveProjectionWorkerOptions(\n options.projectionWorker,\n {},\n );\n if (projectionWorker && options.reactor) {\n logger.warn(\n \"Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator\",\n );\n projectionWorker = null;\n }\n if (projectionWorker) {\n assertProjectionWorkerSupported({ dev: dev === true, reactorDbUrl });\n }\n\n // The reactor-api owns its own PGlite/HTTP/WS resources but has no shutdown\n // path of its own; we register `api.dispose` as a reactor shutdown hook so\n // those resources drain inside the reactor's SIGINT chain. The reference\n // is forward — `initializeClient` runs (and registers the hook) before\n // `initializeAndStartAPI` returns the api — so the closure reads `apiRef`\n // at hook-fire time, not at registration time.\n const apiRef: { current: { dispose: () => Promise<void> } | undefined } = {\n current: undefined,\n };\n let driveNodeView: DriveNodeView | undefined;\n\n // HTTP registry package loading\n const configPath = resolveConfigPath(options.configFile);\n const fileConfig = getConfig(configPath);\n const registryUrl = options.registryUrl ?? fileConfig.packageRegistryUrl;\n const registryPackages = config.packages.registryPackages;\n const dynamicModelLoading = options.dynamicModelLoading === true;\n let httpLoader: HttpPackageLoader | undefined;\n\n if (registryUrl) {\n // Register HTTP/HTTPS module loader hooks for dynamic package imports\n registerHttpsHooks();\n httpLoader = new HttpPackageLoader({\n registryUrl,\n cacheDir: path.join(\n resolvePhDir(undefined, {\n PH_USER_DATA_DIR: config.storage.userDataDir,\n }),\n \"registry-packages\",\n ),\n });\n for (const name of registryPackages) {\n if (!packages.includes(name)) {\n packages.push(name);\n }\n }\n }\n\n // Registry packages import from the on-disk cache, which workers can read.\n const registryPackageNames = new Set(registryPackages.filter(Boolean));\n const resolveRegistryModels = async (\n identifier: string,\n ): Promise<string | null> =>\n httpLoader && registryPackageNames.has(identifier)\n ? ((await httpLoader.cachePackage(identifier)).entries.documentModels ??\n null)\n : null;\n\n const reactorLogger = logger.child([\"reactor\"]);\n // Latched: dropWriteReady reports the fatal once per dropped job.\n let projectionWorkerFatalFired = false;\n const onProjectionWorkerFatal = (shardId: string, reason: Error) => {\n if (projectionWorkerFatalFired) {\n return;\n }\n projectionWorkerFatalFired = true;\n reactorLogger.error(\n `Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`,\n reason,\n );\n // SIGTERM takes the builder's withSignalHandlers() path: kill, hooks, db.\n raiseSigterm();\n };\n // Resolved in startSwitchboard, which owns the flag mechanism; initServer\n // only reads the answer.\n const workflowsEnabled = options.workflows?.enabled === true;\n // Resolved before the reactor is built: a bad secret fails the boot early.\n // Flag-on, the privacy plugin owns this resolve (same fail-fast timing, in\n // transformServerOptions above).\n const privacyConfig = pluginHost\n ? ({ enabled: false } as ResolvedPrivacy)\n : resolvePrivacy(options.privacy, {});\n\n // Through the package manager like any other, so one route carries the\n // models, the subgraphs and the piece.\n if (workflowsEnabled) {\n await assertWorkflowPackageLoadable();\n if (!packages.includes(WORKFLOW_PACKAGE_NAME)) {\n packages.push(WORKFLOW_PACKAGE_NAME);\n }\n }\n\n // Set only when we build the reactor ourselves; a caller-provided one keeps\n // its own lifecycle and must not be torn down here.\n let ownedReactorModule: InProcessReactorClientModule | undefined;\n // Paces an owned reactor's processor backfills; fed by this server's load.\n const catchUpPriority = new CatchUpPriority(\n config.protocol.catchUpPriority === \"dynamic\"\n ? { mode: \"dynamic\" }\n : { mode: \"fixed\", level: config.protocol.catchUpPriority },\n );\n const processorTiming = new ProcessorTimingSettings({\n level: config.protocol.processorTiming,\n windowMs: config.protocol.processorTimingWindowMs,\n slowBatchMs: config.protocol.processorSlowBatchMs,\n });\n const memoryTelemetry = createMemoryTelemetry(config, reactorLogger);\n // The models workers and workflow pieces import; only on a reactor built here.\n let workerModels: ModelManifestSource | undefined;\n // Bound once the api serves the renown read model; see `localCredentialCheck`.\n let localRenownRequest: SwitchboardRequestFn | undefined;\n const initializeClient = async (\n documentModels: DocumentModelModule[],\n {\n attachmentReferenceWriter,\n upgradeManifests,\n readModelDb,\n }: ClientInitializerDependencies,\n ) => {\n // When the caller hands us a pre-built reactor module, reuse it\n // instead of constructing one. The caller owns the reactor lifecycle\n // and must call `switchboard.shutdown()` from their own teardown to\n // drain /graphql, MCP, attachments, etc.\n if (options.reactor) {\n const attachmentReferenceProjection =\n await registerAttachmentReferenceReadModelOnModule(\n options.reactor,\n attachmentReferenceWriter,\n );\n if (options.reactor.reactorModule) {\n const instrumentation = new ReactorInstrumentation(\n options.reactor.reactorModule,\n );\n instrumentation.start();\n reactorLogger.info(\n \"Reactor metrics instrumentation started (using caller-provided reactor)\",\n );\n }\n return {\n module: options.reactor,\n attachmentReferenceProjection,\n };\n }\n\n const {\n kysely: baseKysely,\n poolInstrumentation,\n storageFacts,\n storeMaintenance,\n } = await createReactorKysely({\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n hostPoolSize: () => config.workers.hostPoolSize,\n pgliteWorkers: options.pgliteWorkers === true,\n pgliteSettings,\n openingStore: opening.stores?.reactor,\n logger,\n });\n\n const maxSkipThreshold = config.protocol.maxSkipThreshold;\n const hasSkipThreshold = maxSkipThreshold !== undefined;\n if (hasSkipThreshold) {\n logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);\n }\n\n // Flip these per document-sharing fleet, never per node: replay decisions\n // are consensus outcomes, so nodes that disagree on the flags diverge.\n const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =\n reactorFeatureFlagsOf(config.protocol.featureFlags);\n if (enabledFeatureFlags.length > 0) {\n logger.info(\n `Reactor feature flags enabled: ${enabledFeatureFlags.join(\", \")}`,\n );\n }\n if (reactorFeatureFlags.undoV3 === false) {\n logger.info(\"Reactor undoV3 is off: new documents take base-reducer 2\");\n }\n\n const reactorBuilder = new ReactorBuilder()\n .withEventBus(new EventBus())\n .withKysely(baseKysely)\n .withStorageFacts(storageFacts)\n .withFeatures({\n legacyProcessorIds: config.protocol.legacyProcessorIds,\n })\n .withUnsupportedStoredDocuments(unsupportedStoredDocuments)\n .withCatchUpPriority(catchUpPriority)\n .withProcessorTiming(processorTiming)\n .withMemoryTelemetry(memoryTelemetry);\n\n const keyframes = resolveKeyframes(\n config.storage.keyframes,\n fileConfig.reactor?.keyframes,\n configPath,\n );\n if (keyframes) {\n logger.info(\n `Keyframes: default ${JSON.stringify(keyframes.default ?? {})}, ${Object.keys(keyframes.types ?? {}).length} document type(s) with their own rule`,\n );\n reactorBuilder.withKeyframes(keyframes);\n }\n if (storeMaintenance) {\n reactorBuilder.withStoreMaintenance(storeMaintenance);\n }\n\n // Feeds `module.pools`, which ReactorInstrumentation reads to emit\n // reactor.db.pool.{acquire.wait_duration,size,idle,waiting}. Without this\n // the host pool is the one pool the reactor opens that nobody can see.\n // Note the gauges observe pg-pool only: behind a transaction-mode\n // pgbouncer, `waiting` can read 0 while requests queue in the pooler.\n if (poolInstrumentation) {\n reactorBuilder.withInstrumentedPool(poolInstrumentation);\n }\n\n const clientBuilder = new ReactorClientBuilder().withReactorBuilder(\n reactorBuilder,\n );\n\n // Subpath import keeps vetra's React editors out of the node bundle.\n const vetraDocumentModels: DocumentModelModule[] = dev\n ? (\n Object.values(\n await import(\"@powerhousedao/vetra/document-models\"),\n ) as unknown[]\n ).filter(\n (m): m is DocumentModelModule =>\n typeof m === \"object\" &&\n m !== null &&\n \"documentModel\" in m &&\n \"reducer\" in m,\n )\n : [];\n\n applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {\n signalHandlers: options.signalHandlers,\n documentModels: [...documentModels, ...vetraDocumentModels],\n upgradeManifests,\n // Always: an explicit undoV3 false enables nothing but must still reach\n // the reactor.\n executorConfig: {\n ...(hasSkipThreshold ? { maxSkipThreshold } : {}),\n featureFlags: reactorFeatureFlags,\n },\n documentModelLoader:\n httpLoader && dynamicModelLoading\n ? httpLoader.documentModelLoader\n : undefined,\n logger: reactorLogger,\n signer: renown\n ? getRenownSignerConfig(renown, options.identity?.keypairPath)\n : undefined,\n createSignaturePolicy: createSignaturePolicyFor(\n config.protocol.createSignaturePolicy,\n { hasSigner: renown !== null, logger },\n ),\n trustPolicy: reactorFeatureFlags.authEnforcement\n ? await getRenownTrustPolicyConfig(\n renownConfig.source === \"self\"\n ? {\n source: \"self\",\n request: (query, variables) =>\n localRenownRequest\n ? localRenownRequest(query, variables)\n : Promise.reject(\n new Error(\n \"The local renown read model is not bound yet\",\n ),\n ),\n }\n : {\n source: \"remote\",\n renownUrl: renownConfig.url,\n switchboardUrl: renownConfig.switchboardUrl,\n },\n renown,\n )\n : getDelegationTrustPolicyConfig(renown),\n });\n\n // File sources give workers and workflow pieces importable paths for the\n // models registered above; the builder dedupes them.\n if (workerPool || projectionWorker || workflowsEnabled) {\n const sources = await resolveWorkerModelSources(packages, reactorLogger, {\n resolveRemote: resolveRegistryModels,\n });\n // Workers need every model; workflow pieces can do without a broken one.\n reactorBuilder.withDocumentModelSources(\n workerPool || projectionWorker\n ? sources\n : await keepImportableSources(sources, reactorLogger),\n );\n }\n workerModels = modelManifestSource(reactorBuilder);\n\n if (workerPool) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: worker pool enabled without a reactor database URL\",\n );\n }\n // The builder fails the boot if a model lacks an importable source.\n reactorBuilder.withWorkerPool({\n numWorkers: workerPool.numWorkers,\n db: buildWorkerDbConfig(reactorDbUrl, workerPool),\n });\n reactorLogger.info(\n `Executor worker pool enabled: ${workerPool.numWorkers} worker threads${\n workerPool.mode === \"auto\" ? \" (auto-sized from cores)\" : \"\"\n }`,\n );\n }\n\n reactorBuilder.withReadModelFactory(\n async ({\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const nodeProcessor = new NodeProcessor(\n baseKysely as unknown as Kysely<unknown>,\n REACTOR_SCHEMA,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n );\n await nodeProcessor.init();\n return nodeProcessor;\n },\n );\n\n registerAttachmentReferenceReadModel(reactorBuilder, {\n baseKysely: baseKysely as unknown as Kysely<unknown>,\n attachmentReferenceWriter,\n });\n\n if (projectionWorker) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: projection worker enabled without a reactor database URL\",\n );\n }\n const db = {\n ...buildWorkerDbConfig(reactorDbUrl, {\n dbPoolSizePerWorker: projectionWorker.dbPoolSize,\n acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5000,\n }),\n applicationName: \"switchboard-projection\",\n };\n reactorBuilder.withReadModelCoordinatorFactory(\n createHybridProjectionCoordinatorFactory({\n shardCount: 1,\n poolSize: projectionWorker.dbPoolSize,\n db,\n onFatal: onProjectionWorkerFatal,\n }),\n );\n reactorLogger.info(\n `Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`,\n );\n }\n\n reactorBuilder.withShutdownHook(async () => {\n if (apiRef.current) await apiRef.current.dispose();\n });\n\n const reactorDriveSchemaDb = baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<ReactorDriveDatabase>;\n const nodeView = new DriveNodeView(reactorDriveSchemaDb);\n driveNodeView = nodeView;\n clientBuilder\n .withDriveNodeSource(nodeView)\n .withDriveWriteStrategy(\n REACTOR_DRIVE_DOCUMENT_TYPE,\n createReactorDriveWriteStrategy,\n );\n\n let module: InProcessReactorClientModule;\n try {\n module = await withProgressHeartbeat(\n {\n logger,\n label:\n \"Starting the reactor (migrations, document view, indexer, processors)\",\n },\n () => clientBuilder.buildModule(),\n );\n } catch (error) {\n try {\n await baseKysely.destroy();\n } catch (destroyError) {\n logger.error(\n \"Aborting boot: reactor database destroy failed: @error\",\n destroyError,\n );\n }\n if (UnsupportedStoredProtocolError.isError(error)) {\n throw new StoredDocumentsRefusedError(error);\n }\n throw error;\n }\n\n if (module.reactorModule) {\n const instrumentation = new ReactorInstrumentation(module.reactorModule);\n instrumentation.start();\n reactorLogger.info(\"Reactor metrics instrumentation started\");\n memoryTelemetry.addGauge(\"otel\", () => instrumentation.stats());\n }\n\n const reactorDriveClient = new ReactorDriveClient({\n read: module.read,\n write: module.write,\n readModel: nodeView,\n });\n\n ownedReactorModule = module;\n if (options.fatalErrorShutdown) {\n installFatalErrorShutdown(logger);\n }\n\n // The permission tables live in the reactor store (reactor migration 029,\n // applied by buildModule above); move what the read-model store still\n // holds before the permission service serves a check. A reactor-api that\n // predates the move hands over no read-model store and keeps its tables\n // there, so nothing is moved.\n const permissionsDb = baseKysely.withSchema(REACTOR_SCHEMA);\n try {\n if (readModelDb) {\n await withProgressHeartbeat(\n { logger, label: \"Moving the permission tables\" },\n () =>\n backfillPermissionTables(\n readModelDb,\n permissionsDb as unknown as Kysely<unknown>,\n logger,\n ),\n );\n }\n } catch (error) {\n logger.error(\n \"Aborting boot: permission tables backfill failed: @error\",\n error,\n );\n try {\n await module.reactorModule?.shutdown();\n } catch (shutdownError) {\n logger.error(\n \"Aborting boot: reactor shutdown failed: @error\",\n shutdownError,\n );\n }\n throw error;\n }\n\n return {\n module,\n reactorDriveClient,\n driveNodes: nodeView,\n attachmentReferenceProjection: { status: \"available\" as const },\n permissionsDb:\n permissionsDb as unknown as Kysely<DocumentPermissionDatabase>,\n };\n };\n\n // Tear down a partially booted stack in the reactor's own order: reactor\n // first, then the api's HTTP/WS/db handles, then the database pool. An\n // owned reactor goes through its module's shutdown, so the other hooks run\n // too and a later signal joins this teardown instead of repeating it.\n const abortBoot = async (api: { dispose: () => Promise<void> }) => {\n let disposed: Promise<void> | undefined;\n const disposeApi = () => (disposed ??= api.dispose());\n apiRef.current = { dispose: disposeApi };\n const owned = ownedReactorModule;\n if (owned?.reactorModule) {\n try {\n await owned.reactorModule.shutdown();\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n } else if (owned) {\n try {\n await owned.reactor.kill().completed;\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n }\n // Already done by the shutdown hook unless the reactor failed to stop.\n try {\n await disposeApi();\n } catch (error) {\n logger.error(\"Aborting boot: api dispose failed: @error\", error);\n }\n };\n\n // Reading credentials from this switchboard's own reactor needs the GraphQL\n // manager, which only exists once the api is up: bind the check afterwards.\n let localCredentialCheck: CredentialCheck | undefined;\n const verifyCredential: CredentialVerifier | undefined =\n renownConfig.source === \"self\"\n ? (params) =>\n localCredentialCheck\n ? localCredentialCheck(params)\n : Promise.reject(\n new Error(\"The local renown read model is not bound yet\"),\n )\n : undefined;\n\n let defaultDriveUrl: undefined | string = undefined;\n\n // TODO get path from powerhouse config\n const basePath = process.cwd();\n\n const reporting = { logger, report: reportError };\n\n // import Vite loader only if dev mode is enabled\n let vite: ViteDevServer | undefined;\n let viteLoader: VitePackageLoader | undefined;\n if (dev) {\n const { VitePackageLoader, createViteLogger, startViteServer } =\n await import(\"@powerhousedao/reactor-api/vite\");\n vite = await startViteServer(process.cwd(), createViteLogger(logger));\n // Packages switchboard brings, like the workflow package, resolve from\n // here when the project does not install them itself.\n viteLoader = VitePackageLoader.build(vite, {\n resolveFrom: [import.meta.url],\n reportError,\n });\n }\n\n // Vetra is builder-only and bundled (not CDN-loadable); lazy-load its\n // processor only in dev, where builder tooling runs (e.g. `ph vetra`).\n const vetraProcessorFactory = dev\n ? (await import(\"@powerhousedao/vetra/processors\")).processorFactory\n : undefined;\n\n // get paths to local document models\n if (!options.disableLocalPackages) {\n packages.push(basePath);\n }\n\n // create loaders\n const packageLoaders: IPackageLoader[] = [];\n if (viteLoader) {\n packageLoaders.push(viteLoader);\n } else {\n packageLoaders.push(new ImportPackageLoader());\n }\n if (httpLoader) {\n packageLoaders.push(httpLoader);\n for (const name of registryPackages) {\n if (!packages.includes(name)) {\n packages.push(name);\n }\n }\n }\n\n const apiLogger = logger.child([\"reactor-api\"]);\n // When the read-model store is on disk, hand reactor-api a factory that\n // constructs the matching PGLite (current or legacy) for the detected\n // PG_VERSION. reactor-api calls the factory synchronously, so the legacy\n // module is preloaded above.\n let pgliteFactory: PgliteFactory | undefined;\n let storeFailed: (error: unknown) => void = () => undefined;\n const storesFailed = new Promise<never>((_, reject) => {\n storeFailed = reject;\n });\n storesFailed.catch(() => undefined);\n if (readModelPgliteDir && readModelPgliteMajor !== null) {\n const storeOptions = {\n inMemory,\n threaded: options.pgliteWorkers === true,\n settings: pgliteSettings,\n logger,\n };\n const openReadStore = await createPgliteStoreFactory({\n ...storeOptions,\n ...READ_STORE,\n major: readModelPgliteMajor,\n });\n // With a thread each, the stores needn't take turns. Two on one dir must,\n // and in the main thread nothing would overlap.\n const openReactorStore =\n storeOptions.threaded &&\n pgliteWorkerEntryPath !== null &&\n sharedPgliteDir === null &&\n reactorPgliteDir &&\n reactorPgliteMajor !== null\n ? await createPgliteStoreFactory({\n ...storeOptions,\n ...REACTOR_STORE,\n major: reactorPgliteMajor,\n })\n : undefined;\n pgliteFactory = (connectionString) => {\n const dir = connectionString ?? readModelPgliteDir;\n if (\n !openReactorStore ||\n !reactorPgliteDir ||\n dir !== readModelPgliteDir\n ) {\n return openReadStore(dir);\n }\n // Here, not any sooner: reactor-api refuses what it won't run before it\n // reaches for this store, and a refused boot touches neither.\n opening.stores ??= openStoresTogether(\n () => openReactorStore(reactorPgliteDir),\n () => openReadStore(dir),\n );\n opening.stores.failed.catch(storeFailed);\n return opening.stores.readModel;\n };\n }\n\n const startingApi = initializeAndStartAPI(\n initializeClient,\n {\n port: requestedPort,\n dbPath: readModelPath,\n pgliteFactory,\n https: options.https,\n packageLoaders: packageLoaders.length > 0 ? packageLoaders : undefined,\n packages: packages,\n processorConfig: options.processorConfig,\n ...(renown ? { hostSigner: renown.signer } : {}),\n processors: vetraProcessorFactory\n ? { \"@powerhousedao/vetra\": [vetraProcessorFactory] }\n : {},\n configFile: configPath,\n server: {\n basePath: config.server.basePath,\n gatewayAdapter: config.server.gatewayAdapter,\n publicUrl: config.server.publicUrl,\n host: config.server.host,\n },\n auth: {\n ...authSectionOf(config.auth),\n stateDir: resolvePhDir(\n undefined,\n config.storage.userDataDir\n ? { PH_USER_DATA_DIR: config.storage.userDataDir }\n : process.env,\n ),\n },\n attachments: { storage: config.attachments.storage },\n mcp: options.mcp ?? true,\n inspection:\n options.inspection === false\n ? false\n : { throttle: inspectionThrottle, admin: config.inspection.admin },\n logger: apiLogger,\n reportError,\n enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,\n // The final update before readiness picks up everything added until then.\n hostRefreshesSupergraph: true,\n // Already resolved for this reactor's own identity; reuse it so an\n // invalid RENOWN_SOURCE is reported once, not once per resolution.\n renown: renownConfig,\n verifyCredential,\n },\n \"switchboard\",\n );\n // A store that can't open ends the boot now, with its own error, rather\n // than as a closed store's error once something reaches for the other one.\n const api = await Promise.race([startingApi, storesFailed]);\n apiRef.current = api;\n const serverPort = api.port;\n\n if (renownConfig.source === \"self\") {\n const { graphqlManager: manager } = api;\n // Credentials are checked from the first request, before the router update\n // that readiness waits for: a package's read model gets its handler now.\n if (\n !manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH) &&\n manager.getSubgraphByName(RENOWN_READ_MODEL_SUBGRAPH)\n ) {\n try {\n await manager.updateRouter(true);\n } catch (error) {\n await abortBoot(api);\n throw error;\n }\n }\n // Refuse to serve rather than 401 every request: the read model comes from\n // a loaded package, so a missing one is a deployment mistake.\n if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {\n await abortBoot(api);\n throw new Error(\n 'Renown credential verification is set to \"self\" (auth.renown.source ' +\n `or RENOWN_SOURCE) but no loaded package serves the ` +\n `\"${RENOWN_READ_MODEL_SUBGRAPH}\" subgraph. Install one ` +\n \"(@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.\",\n );\n }\n localRenownRequest = (query, variables) =>\n manager.executeSubgraphQuery(\n RENOWN_READ_MODEL_SUBGRAPH,\n query,\n variables,\n );\n localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, {\n onError: (error) =>\n logger.error(\"Renown read model query failed: @error\", error),\n });\n logger.info(\n \"Renown credentials will be verified against this switchboard's own \" +\n \"renown read model\",\n );\n }\n\n // R2.3: flag-on, the attachments plugin owns the route mount + service\n // creation at onHttpMounting; flag-off runs the inline path.\n let attachmentService:\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n if (pluginHost) {\n pluginHost.ctx.api = api;\n pluginHost.ctx.serverPort = serverPort;\n await pluginHost.observe(\"onHttpMounting\");\n attachmentService = pluginHost.ctx.attachmentService as\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n } else {\n registerAttachmentRoutes(api, { config: config.attachments });\n attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(options, serverPort, renown),\n );\n }\n\n if (process.env.SENTRY_DSN) {\n // Register Sentry error handler after all routes are established.\n // The adapter calls the framework-specific Sentry setup internally.\n api.httpAdapter.setupSentryErrorHandler(await import(\"@sentry/node\"));\n }\n\n // The framework wiring takes the halves; `client` (the facade) stays for\n // the consumers that have not moved.\n const { client, read, write, graphqlManager, documentModelRegistry } = api;\n\n const lateSubgraphs: Promise<unknown>[] = [];\n if (pluginHost) {\n pluginHost.ctx.client = client;\n pluginHost.ctx.read = read;\n pluginHost.ctx.write = write;\n pluginHost.ctx.graphqlManager = graphqlManager;\n pluginHost.ctx.lateSubgraphs = lateSubgraphs;\n pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;\n await pluginHost.observe(\"onReactorReady\");\n }\n\n // The workflow runtime is a switchboard component: composed from what the\n // api handed back, registered like any other late subgraph.\n let workflows: ComposedWorkflowRuntime | undefined;\n let workflowsRetry: WorkflowSingletonRetry | undefined;\n const composeWorkflows = () =>\n composeWorkflowRuntime({\n reactorClient: client,\n clientModule: options.reactor ?? ownedReactorModule,\n relationalDb: api.relationalDb,\n // A Postgres read model outlives the pod; a key file beside it would not.\n secretsKeyFile: readModelPgliteDir === null ? false : undefined,\n // The stable half of the default singleton owner name. Absolute, so\n // two Switchboards in different working directories differ.\n storageId:\n readModelPgliteDir === null\n ? readModelPath\n : path.resolve(readModelPath),\n attachments: createAttachmentClient(api.attachments.service),\n attachmentAccess: api.attachmentAccess,\n // The workflow package's own HTTP namespace: its webhook endpoints live\n // under it, not under the reactor's.\n webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,\n http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),\n // The host's option, else the config file's: under uniform runners the\n // plugins own the workflows switch and the classic config read is skipped.\n oauthApps:\n options.workflows?.oauthApps ??\n readConfigOAuthApps(resolveConfigPath(options.configFile), logger),\n authorizationService: api.authorizationService,\n // The manager that serves this reactor's subgraphs: a piece's index read\n // runs through it in process, as the run's user.\n indexQueries: api.graphqlManager,\n // The manager that already loads this reactor's packages: the project it\n // runs in is one of them, so its own pieces arrive with the rest.\n pieces: api.packageManager,\n pieceRegistryUrl: registryUrl,\n models: workerModels,\n // The piece pool leaves the reactor's threads their share of the cores.\n reactorThreads:\n (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),\n logger: logger.child([\"workflow-runtime\"]),\n exclusiveJournal: readModelPgliteDir !== null,\n onSingletonLost: workflowSingletonLossHandler(logger),\n // The providers observability.mts registered before this module loaded.\n telemetry: {\n tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),\n meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE),\n },\n });\n const registerWorkflowSubgraph = (composed: ComposedWorkflowRuntime) => {\n const WorkflowRuntimeSubgraph = composed.subgraph;\n const workflowSubgraph = new WorkflowRuntimeSubgraph({\n readClient: read,\n reactorClient: client,\n http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),\n relationalDb: api.relationalDb,\n analyticsStore: undefined as never,\n graphqlManager,\n syncManager: api.syncManager,\n authorizationService: graphqlManager.getAuthorizationService(),\n path: graphqlManager.getBasePath(),\n attachments: api.attachmentClientProvider,\n });\n return graphqlManager\n .registerSubgraphInstance(workflowSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register workflow-runtime subgraph: @error\",\n );\n });\n };\n if (!pluginHost && workflowsEnabled) {\n try {\n workflows = await composeWorkflows();\n } catch (error) {\n // Without the claim this host must not run workflows, but everything\n // else it serves still works, so it boots without the runtime.\n if (!isWorkflowSingletonConflict(error)) throw error;\n logger.warn(\n `Workflows are enabled but another live process (\"${error.owner ?? \"unknown\"}\") ` +\n `holds the workflow singleton until ${error.expiresAt ?? \"unknown\"}. ` +\n \"This Switchboard has booted WITHOUT the workflow runtime: no \" +\n \"trigger of any kind fires here, and the workflow GraphQL face is \" +\n \"absent. Everything else serves normally. Stop the other owner, or \" +\n \"set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the \" +\n \"slot that owns workflows. This Switchboard retries the claim and \" +\n \"starts workflows once the lease comes free.\",\n );\n workflowsRetry = retryWorkflowSingleton({\n compose: composeWorkflows,\n onComposed: async (composed) => {\n try {\n await composed.start();\n } catch (error) {\n // Hands the lease back so a retry or another replica can claim it.\n try {\n await composed.stop();\n } catch (stopError) {\n logger.error(\n \"Stopping the late workflow runtime failed: @error\",\n stopError,\n );\n }\n throw error;\n }\n logger.info(\"Workflow runtime started\");\n workflows = composed;\n await registerWorkflowSubgraph(composed);\n // Past boot nothing else rebuilds the router, so a subgraph\n // registered now is not served until this runs.\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n );\n }\n },\n logger,\n });\n }\n }\n if (workflows) {\n lateSubgraphs.push(registerWorkflowSubgraph(workflows));\n const runtime = workflows;\n await withProgressHeartbeat(\n { logger, label: \"Starting the workflow runtime\" },\n () => runtime.start(),\n );\n logger.info(\"Workflow runtime started\");\n api.inspection?.facts.setWorkflows(true);\n }\n\n // Plugins register their subgraphs here (push into lateSubgraphs, or mount\n // directly like privacy). The call site carries the inline privacy block's\n // failure semantics: stop workflows, abort the partial boot, rethrow.\n if (pluginHost) {\n pluginHost.ctx.workflowsOrchestration = {\n enabled: options.workflows?.enabled === true,\n composeWorkflows,\n registerWorkflowSubgraph,\n updateRouter: () => graphqlManager.updateRouter(true),\n reportMountFailure: (error: unknown) =>\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n ),\n setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true),\n };\n try {\n await pluginHost.observe(\"onSubgraphsRegistering\");\n } catch (error) {\n await (\n pluginHost.ctx.workflowsRetry as WorkflowSingletonRetry | undefined\n )?.stop();\n await (\n pluginHost.ctx.workflows as ComposedWorkflowRuntime | undefined\n )?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n let privacy: RunningPrivacy | undefined;\n if (!pluginHost && privacyConfig.enabled) {\n // The caller's reactor signs with a signer only the caller knows.\n const signer = options.reactor\n ? options.privacy?.signer\n : (options.privacy?.signer ?? renown?.signer);\n try {\n privacy = await startPrivacy({\n config: privacyConfig,\n reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,\n signer,\n authorizationService: api.authorizationService,\n documentPermissionService: api.documentPermissionService,\n graphqlManager,\n reactorClient: client,\n logger: logger.child([\"privacy\"]),\n });\n } catch (error) {\n await workflowsRetry?.stop();\n await workflows?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n // Ahead of the api: the runtime's store lives in the read-model database\n // that dispose closes, and its children outlive the reactor otherwise.\n // Memoized: the reactor's shutdown hook and a caller can both reach it.\n const stopCatchUpLoad = ownedReactorModule\n ? feedCatchUpPriority(catchUpPriority, api.httpServer)\n : () => {};\n const stopTimingLog = startOwnedTimingLog(\n ownedReactorModule?.reactorModule,\n processorTiming,\n config.protocol.processorTimingLogMs,\n reactorLogger,\n );\n if (ownedReactorModule?.reactorModule && config.telemetry.memory.enabled) {\n memoryTelemetry.start();\n }\n let apiDrained: Promise<void> | undefined;\n const drainApi = () =>\n (apiDrained ??= (async () => {\n stopCatchUpLoad();\n stopTimingLog();\n memoryTelemetry.stop();\n if (pluginHost) await pluginHost.observe(\"onShutdown\");\n await privacy?.stop();\n await workflowsRetry?.stop();\n await workflows?.stop();\n await api.dispose();\n })());\n apiRef.current = { dispose: drainApi };\n // An owned reactor's shutdown drains the api through the hook above, in the\n // signal path's order: kill, hooks, database. A caller's reactor is the\n // caller's to stop, so only the api is drained.\n const ownedReactor = ownedReactorModule?.reactorModule;\n const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;\n\n // Wire up dynamic package management if HTTP loader is configured\n if (httpLoader) {\n const packageManagementService = new PackageManagementService({\n defaultRegistryUrl: registryUrl,\n httpLoader,\n documentModelRegistry,\n packageManager: api.packageManager,\n });\n\n packageManagementService.setOnModelsChanged(() => {\n graphqlManager\n .regenerateDocumentModelSubgraphs()\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to regenerate document model subgraphs: @error\",\n );\n });\n });\n\n const packagesSubgraph = new PackagesSubgraph({\n relationalDb: undefined as never,\n analyticsStore: undefined as never,\n readClient: read,\n reactorClient: client,\n graphqlManager,\n syncManager: api.syncManager,\n path: graphqlManager.getBasePath(),\n authorizationService: graphqlManager.getAuthorizationService(),\n packageManagementService,\n http: graphqlManager.scopeForPackage(\"@powerhousedao/switchboard\"),\n attachments: api.attachmentClientProvider,\n });\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(packagesSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register packages subgraph: @error\",\n );\n }),\n );\n }\n\n if (driveNodeView) {\n graphqlManager.setAdditionalContextFields({\n readModel: driveNodeView,\n });\n\n const authorizationService = graphqlManager.getAuthorizationService();\n const reactorDriveSubgraph = {\n name: REACTOR_DRIVE_SUBGRAPH_NAME,\n path: graphqlManager.getBasePath(),\n resolvers: createReactorDriveResolvers({\n reactorClient: client,\n readModel: driveNodeView,\n hostCanRead: (documentId, address) =>\n authorizationService.canRead(\n documentId as CanonicalDocumentId,\n address,\n ),\n }),\n typeDefs: reactorDriveSubgraphTypeDefs,\n readClient: read,\n reactorClient: client,\n relationalDb: undefined as never,\n };\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(reactorDriveSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register reactor-drive subgraph: @error\",\n );\n }),\n );\n }\n\n // Create default drive if provided\n if (options.drive) {\n if (!renown) {\n throw new Error(\"Cannot create default drive without Renown identity\");\n }\n\n defaultDriveUrl = await ensureDrive(\n client,\n options.drive,\n serverPort,\n logger,\n );\n }\n\n // Ready once this server serves its own drives. Remote drives stay out: they\n // replicate from another server, which may be down.\n void runDetached(\n \"Marking the API ready\",\n async () => {\n await Promise.allSettled(lateSubgraphs);\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Final router update before readiness failed: @error\",\n );\n }\n try {\n await options.readyAfter;\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Not ready: the drives seeded after start failed: @error\",\n );\n return;\n }\n api.readiness.markReady();\n },\n reporting,\n );\n\n // add vite middleware after express app is initialized if applicable\n if (vite) {\n api.httpAdapter.mountRawMiddleware(vite.middlewares);\n }\n\n // Connect to remote drives AFTER packages are loaded\n if (remoteDrives.length > 0) {\n for (const remoteDriveUrl of remoteDrives) {\n let driveId: string | undefined;\n\n try {\n const { syncManager } = api;\n const parsed = parseDriveUrl(remoteDriveUrl);\n driveId = parsed.driveId;\n const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {\n type: \"gql\",\n parameters: { url: parsed.graphqlEndpoint },\n });\n logger.debug(\"Remote drive @remoteDriveUrl synced\", remoteDriveUrl);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"already exists\")\n ) {\n logger.debug(\n \"Remote drive already added: @remoteDriveUrl\",\n remoteDriveUrl,\n );\n driveId = remoteDriveUrl.split(\"/\").pop();\n } else {\n logger.error(\n \"Failed to connect to remote drive @remoteDriveUrl: @error\",\n remoteDriveUrl,\n error,\n );\n }\n } finally {\n // Construct local URL once in finally block\n if (!defaultDriveUrl && driveId) {\n const protocol = options.https ? \"https\" : \"http\";\n defaultDriveUrl = `${protocol}://localhost:${serverPort}/d/${driveId}`;\n }\n }\n }\n }\n\n // Drives exist (default created, remotes attached) — the barrier after the\n // future core drive seeding (R2 step 2 replaces the two blocks above).\n if (pluginHost) await pluginHost.observe(\"onDrivesReady\");\n\n return {\n defaultDriveUrl,\n api,\n reactor: client,\n attachmentService,\n attachmentReferenceProjection: api.attachmentReferenceProjection,\n // Read live: losing the singleton turns it unavailable.\n get workflowTriggers() {\n return (\n workflows ??\n (pluginHost?.ctx.workflows as ComposedWorkflowRuntime | undefined)\n )?.triggers;\n },\n workflowsEnabled,\n modelManifest: () => workerModels?.modelManifest() ?? [],\n privacy: (() => {\n const running =\n privacy ?? (pluginHost?.ctx.privacy as RunningPrivacy | undefined);\n return running ? { erasure: running.erasure } : undefined;\n })(),\n mcpEnabled: options.mcp !== false,\n inspectionEnabled: options.inspection !== false,\n inspector: api.inspection?.inspector,\n renown,\n port: serverPort,\n shutdown,\n };\n}\n\n/**\n * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.\n *\n * If `options.reactor` is provided, the switchboard reuses it instead of\n * building its own — the caller then owns the reactor's lifecycle and is\n * responsible for invoking `SwitchboardReactor.shutdown()` from their own\n * teardown / SIGINT path. The switchboard will not reach into the caller's\n * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources\n * dangling until the process exits.\n *\n * When `options.reactor` is omitted, the switchboard builds and owns the\n * reactor. `shutdown()` on the returned handle then runs the reactor\n * module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains\n * the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the\n * reactor database. It does not exit the process. It is the same memoized\n * teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling\n * it twice, or receiving a signal around it, tears down once.\n */\nexport const startSwitchboard = async (\n input: SwitchboardConfigInput = {},\n deps: SwitchboardDeps = {},\n): Promise<SwitchboardReactor> => {\n assertConfigShape(input);\n const configPath = resolveConfigPath(input.configFile);\n const fileConfig = getConfig(configPath);\n // The file's auth lies under the env and the caller, as under the env vars.\n const config = switchboardConfigSchema.parse(\n mergeSwitchboardConfig(\n {\n auth: {\n enabled: fileConfig.auth?.enabled,\n admins: fileConfig.auth?.admins,\n },\n },\n input,\n ),\n );\n const logger = deps.logger ?? defaultLogger;\n if (disableWasmWrapperTiering()) {\n logger.info(\"Wasm wrapper tier-up off on Node 24 (nodejs/node#66366)\");\n }\n // Here as well as in index.mts, so a host embedding the server is profiled.\n if (process.env.PYROSCOPE_SERVER_ADDRESS) {\n await initProfilerFromEnv(process.env).catch((error: unknown) =>\n logger.error(\"Error starting profiler: @error\", error),\n );\n }\n const serverPort = await resolveServerPort(\n config.server.port,\n config.server.strictPort,\n logger,\n );\n\n const options = serverOptionsOf(config, deps);\n // CLASSIC resolution of the carved subsystems' switches — flag-on, the\n // plugins own these (presence is activation): an ABSENT plugin can actually\n // deactivate its subsystem (initServer normalizes unset values to off after\n // transformServerOptions). An explicit config value always wins on both\n // paths. The inspection switch is a core capability (not carved).\n if (!config.features.pluginHost) {\n options.mcp = config.features.mcp ?? true;\n options.workflows = {\n enabled:\n config.features.workflows ?? readConfigWorkflowsEnabled(configPath),\n };\n }\n // This switchboard's own identity authenticates against the same Renown\n // instance it verifies incoming credentials against, unless told otherwise.\n const renownConfig = resolveRenownConfig(\n renownLayers(fileConfig.auth?.renown, config.auth.renown),\n {},\n logger,\n );\n const userDataDir = config.storage.userDataDir;\n options.identity = {\n ...options.identity,\n baseUrl: options.identity?.baseUrl ?? renownConfig.url,\n // Under a relocated .ph tree the identity lives in the user's .ph tree\n // with the stores, never in the install dir. Unset: unchanged — renown's\n // own `<cwd>/.ph/.keypair.json` default applies.\n keypairPath:\n options.identity?.keypairPath ??\n (userDataDir\n ? path.join(\n resolvePhDir(undefined, { PH_USER_DATA_DIR: userDataDir }),\n \".keypair.json\",\n )\n : undefined),\n };\n\n logger.info(\n \"Feature flags: @flags\",\n JSON.stringify(\n {\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,\n MCP_ENABLED: options.mcp,\n INSPECTION_ENABLED: options.inspection,\n PH_PGLITE_WORKERS: options.pgliteWorkers,\n PH_WORKFLOWS_ENABLED: options.workflows?.enabled,\n },\n null,\n 2,\n ),\n );\n\n // Initialize Renown if identity options are provided or keypair exists\n let renown: IRenown | null = null;\n try {\n renown = await initRenown({ ...options.identity, userDataDir });\n } catch (e) {\n logger.warn(\"Failed to initialize ConnectCrypto: @error\", e);\n if (options.identity.requireExisting) {\n throw new Error(\n 'Identity required but failed to initialize. Run \"ph login\" first.',\n { cause: e },\n );\n }\n }\n\n const reportError =\n deps.reportError ??\n ((error: unknown) => {\n void captureInSentry(error);\n });\n const opening: { stores?: StoresOpening } = {};\n try {\n return await initServer(\n serverPort,\n options,\n config,\n renown,\n renownConfig,\n reportError,\n opening,\n );\n } catch (e) {\n await opening.stores?.close();\n await captureInSentry(e);\n if (StoredDocumentsRefusedError.isError(e)) {\n logger.error(e.message);\n } else {\n logger.error(\"App crashed: @error\", e);\n }\n throw e;\n }\n};\n\n// Parsing strips unknown keys, so a caller still passing the old options would boot on defaults.\nfunction assertConfigShape(input: SwitchboardConfigInput): void {\n const unknown = Object.keys(input).filter(\n (key) => !(key in switchboardConfigSchema.shape),\n );\n if (unknown.length > 0) {\n throw new Error(\n `startSwitchboard(config, deps) got unknown config keys: ${unknown.join(\", \")}. ` +\n \"It takes the @powerhousedao/switchboard/config shape; runtime objects go in deps.\",\n );\n }\n}\n\n/** The options view plugins transform, from the config and deps. */\nfunction serverOptionsOf(\n config: SwitchboardConfig,\n deps: SwitchboardDeps,\n): StartServerOptions {\n const { executor, projection } = config.workers;\n return {\n reactor: deps.reactor,\n fatalErrorShutdown: deps.fatalErrorShutdown,\n signalHandlers: deps.signalHandlers,\n readyAfter: deps.readyAfter,\n pluginComposition: deps.pluginComposition,\n logger: deps.logger,\n registryUrl: config.packages.registryUrl,\n configFile: config.configFile,\n port: config.server.port,\n strictPort: config.server.strictPort,\n dev: config.server.dev,\n dbPath: config.storage.readModel.url,\n drive: config.drive as StartServerOptions[\"drive\"],\n packages: [...config.packages.list],\n remoteDrives: [...config.remoteDrives],\n https: config.server.https,\n identity: config.identity,\n attachmentServiceUrl: config.attachments.serviceUrl,\n mcp: config.features.mcp,\n inspection: config.inspection.enabled,\n pgliteWorkers: config.storage.pglite.workers,\n workflows:\n config.features.workflows === undefined\n ? undefined\n : { enabled: config.features.workflows },\n privacy: {\n enabled: config.features.privacy.enabled,\n deploymentSecret: config.features.privacy.deploymentSecret,\n intervalMs: config.features.privacy.intervalMs,\n deadlineMs: config.features.privacy.deadlineMs,\n markerGraceMs: config.features.privacy.markerGraceMs,\n purgeTimeoutMs: config.features.privacy.purgeTimeoutMs,\n signer: deps.privacySigner,\n },\n processorConfig: config.processorConfig,\n disableLocalPackages: config.packages.disableLocal,\n enableDocumentModelSubgraphs: config.features.documentModelSubgraphs,\n dynamicModelLoading: config.packages.dynamic,\n migratePglite: config.storage.migratePglite,\n forcePgVersion: config.storage.forcePgVersion,\n workerPool: {\n numWorkers: executor.count,\n dbPoolSizePerWorker: executor.poolSize,\n acquireTimeoutMs: executor.acquireTimeoutMs,\n },\n projectionWorker: {\n enabled: projection.enabled,\n dbPoolSize: projection.poolSize,\n },\n unsupportedStoredDocuments: config.protocol.unsupportedStoredDocuments,\n };\n}\n\n/** reactor-api's auth section; renown is resolved here, not there. */\nfunction authSectionOf(auth: SwitchboardConfig[\"auth\"]) {\n const { renown: _renown, ...section } = auth;\n return section;\n}\n\nexport {\n applySwitchboardReactorDefaults,\n type SwitchboardReactorDefaultsOptions,\n} from \"./builder-defaults.mjs\";\nexport * from \"./types.js\";\nexport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\n\nif (import.meta.main) {\n const config = switchboardConfigFromEnv(process.env);\n initSwitchboardProcess(config);\n await startSwitchboard(config, { fatalErrorShutdown: true });\n}\n\n/** Off in config, no timers or observers exist; a lever can still start it. */\nfunction createMemoryTelemetry(\n config: SwitchboardConfig,\n logger: ILogger,\n): MemoryTelemetry {\n const { memory, dir, heapSnapshotDir } = config.telemetry;\n const directory = dir ?? telemetryDir();\n return new MemoryTelemetry({\n sampler: new NodeMemorySampler(),\n config: {\n enabled: memory.enabled,\n intervalMs: memory.intervalMs,\n outputs: memory.outputs,\n filePath: memory.file.path,\n fileMaxMb: memory.file.maxMb,\n fileKeep: memory.file.keep,\n ringSize: memory.ringSize,\n consoleIntervalMs: memory.consoleIntervalMs,\n workers: memory.workers,\n windowMin: memory.windowMin,\n },\n fileSink: (settings) =>\n memoryFileSink(settings, { dir: directory, logger }),\n heapSnapshot: createHeapSnapshotWriter({\n dir: heapSnapshotDir ?? directory,\n }),\n logger,\n });\n}\n\n/** For a host with no ph-cli display: the slowest processors, through the log. */\nfunction startOwnedTimingLog(\n module: InProcessReactorModule | undefined,\n settings: ProcessorTimingSettings,\n intervalMs: number,\n logger: ILogger,\n): () => void {\n if (!module || intervalMs <= 0) return () => {};\n return startProcessorTimingLog({\n intervalMs,\n read: () =>\n computeProcessorTiming(\n module.processorManager.getAll(),\n module.catchUp.status(),\n settings.level,\n settings.windowMs,\n ),\n log: (line) => logger.info(\"@Line\", line),\n });\n}\n\n/**\n * Feeds the priority this server's request load and main-thread event-loop\n * delay, and ticks its controller every second. Returns the stop.\n */\nfunction feedCatchUpPriority(\n priority: CatchUpPriority,\n server: http.Server,\n): () => void {\n const recorder = new RequestLoadRecorder({\n eventLoopDelay: new NodeEventLoopDelay(),\n });\n recorder.attach(server);\n priority.setLoadSource(recorder);\n const stopTicking = priority.startTicking();\n return () => {\n stopTicking();\n priority.setLoadSource(undefined);\n recorder.stop();\n };\n}\n"],"names":["logger","logger","fs","fs","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAI,UAAU;AAId,eAAsB,oBAAoB,KAAyB;CACjE,IAAI,WAAW,CAAC,IAAI,0BAA0B;CAC9C,UAAU;CACV,MAAM,EACJ,0BAA0B,eAC1B,4BAA4B,SAC5B,gBAAgB,eAChB,oBAAoB,mBACpB,wBAAwB,aACxB,wBAAwB,gBACtB;CAoBJ,OAAO,aAAa;EAjBlB;EACA;EACA;EACA;EAGA,MAAM;GACJ,oBAAoB;GACpB,wBAAwB;GACxB,gBAAgB;EAClB;EAEA,MAAM;GACJ,uBAAuB;GACvB,YAAY;EACd;CAEwB,GAAG;EAC3B,aAAa,gBAAgB;EAC7B,aAAa,gBAAgB;CAC/B,CAAC;AACH;AAOA,eAAsB,aACpB,SACA,QAAuB;CAAE,aAAa;CAAM,aAAa;AAAM,GAC/D;CACA,QAAQ,IAAI,uCAAuC,SAAS,aAAa;CACzE,QAAQ,IAAI,qBAA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ACF,MAAM,SAAS,OAAO,KAAK,SAAS,IAAI;CAC1C,CAAC;AACH;;;;;AAMA,SAAS,oBACP,UACA,QACY;CACZ,MAAM,WAAW,IAAI,oBAAoB,EACvC,gBAAgB,IAAI,mBAAmB,EACzC,CAAC;CACD,SAAS,OAAO,MAAM;CACtB,SAAS,cAAc,QAAQ;CAC/B,MAAM,cAAc,SAAS,aAAa;CAC1C,aAAa;EACX,YAAY;EACZ,SAAS,cAAc,KAAA,CAAS;EAChC,SAAS,KAAK;CAChB;AACF","debug_id":"46f22af8-6209-58f8-a9b0-efcb80b20629"}
|
|
1
|
+
{"version":3,"file":"server-CirQ9hyu.mjs","sources":["../src/profiler.ts","../src/permissions-backfill.mts","../src/attachments/auth.ts","../src/attachments/mount-auth.ts","../src/attachments/routes.ts","../src/attachments/index.ts","../src/workflow/oauth-apps-config.ts","../src/attachment-reference-read-model.mts","../src/builder-defaults.mts","../src/plugins/attachments.mts","../src/plugin-host.mts","../src/processor-timing-log.mts","../src/pglite-dialect.ts","../src/pglite-migration.ts","../src/pglite-preflight.ts","../src/pglite-store.mts","../src/create-signature-policy.mts","../src/renown.ts","../src/store-lock.mts","../src/server.mts"],"sourcesContent":["import type { PyroscopeConfig } from \"@pyroscope/nodejs\";\n\nlet started = false;\n\n// Once per process: the standalone entry and an embedding host (ph vetra) both\n// ask, and Pyroscope must only be initialised once.\nexport async function initProfilerFromEnv(env: typeof process.env) {\n if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;\n started = true;\n const {\n PYROSCOPE_SERVER_ADDRESS: serverAddress,\n PYROSCOPE_APPLICATION_NAME: appName,\n PYROSCOPE_USER: basicAuthUser,\n PYROSCOPE_PASSWORD: basicAuthPassword,\n PYROSCOPE_WALL_ENABLED: wallEnabled,\n PYROSCOPE_HEAP_ENABLED: heapEnabled,\n } = env;\n\n const options: PyroscopeConfig = {\n serverAddress,\n appName,\n basicAuthUser,\n basicAuthPassword,\n // Wall profiling captures wall-clock time (includes async I/O waits)\n // This shows GraphQL resolvers even when waiting for database\n wall: {\n samplingDurationMs: 10000, // 10 second sampling windows\n samplingIntervalMicros: 10000, // 10ms sampling interval (100 samples/sec)\n collectCpuTime: true, // Also collect CPU time alongside wall time\n },\n // Heap profiling for memory allocation tracking\n heap: {\n samplingIntervalBytes: 512 * 1024, // Sample every 512KB allocated\n stackDepth: 64, // Capture deeper stacks for better context\n },\n };\n return initProfiler(options, {\n wallEnabled: wallEnabled !== \"false\",\n heapEnabled: heapEnabled === \"true\",\n });\n}\n\ninterface ProfilerFlags {\n wallEnabled?: boolean;\n heapEnabled?: boolean;\n}\n\nexport async function initProfiler(\n options?: PyroscopeConfig,\n flags: ProfilerFlags = { wallEnabled: true, heapEnabled: false },\n) {\n console.log(\"Initializing Pyroscope profiler at:\", options?.serverAddress);\n console.log(\" Wall profiling:\", flags.wallEnabled ? \"enabled\" : \"disabled\");\n console.log(\" Heap profiling:\", flags.heapEnabled ? \"enabled\" : \"disabled\");\n\n const { default: Pyroscope } = await import(\"@pyroscope/nodejs\");\n Pyroscope.init(options);\n\n // Start wall profiling (captures async I/O time - shows resolvers)\n if (flags.wallEnabled) {\n Pyroscope.startWallProfiling();\n }\n\n // Start CPU profiling (captures CPU-bound work)\n Pyroscope.startCpuProfiling();\n\n // Optionally start heap profiling (memory allocations)\n if (flags.heapEnabled) {\n Pyroscope.startHeapProfiling();\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { sql, type Generated, type Kysely, type Transaction } from \"kysely\";\n\n/** The permission tables, as reactor-api once kept them on the read-model store. */\nexport const PERMISSION_TABLES = [\n \"DocumentPermission\",\n \"OperationUserPermission\",\n \"DocumentProtection\",\n] as const;\n\nexport type PermissionTable = (typeof PERMISSION_TABLES)[number];\n\n/** What a read-model table is renamed to once its rows live in the reactor store. */\nexport const MIGRATED_TABLE_SUFFIX = \"_migrated_2026_10_25\";\n\nexport type PermissionTableCounts = Record<PermissionTable, number>;\n\nexport type PermissionBackfillOutcome =\n /** The read-model store never had the tables. */\n | { status: \"fresh-install\" }\n /** An earlier boot copied the rows and renamed the tables. */\n | { status: \"already-backfilled\" }\n /** Rows copied now, read-model tables renamed. */\n | { status: \"copied\"; counts: PermissionTableCounts }\n /** An earlier boot copied the rows but stopped before renaming. */\n | { status: \"rename-completed\"; counts: PermissionTableCounts }\n /** Left both stores untouched; the reason says what needs a person. */\n | { status: \"refused\"; reason: string };\n\ninterface DocumentPermissionRow {\n documentId: string;\n userAddress: string;\n permission: string;\n grantedBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface OperationUserPermissionRow {\n documentId: string;\n operationType: string;\n userAddress: string;\n grantedBy: string;\n createdAt: Date;\n}\n\ninterface DocumentProtectionRow {\n documentId: string;\n protected: boolean;\n ownerAddress: string | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface PermissionTablesDatabase {\n DocumentPermission: DocumentPermissionRow & { id: Generated<number> };\n OperationUserPermission: OperationUserPermissionRow & {\n id: Generated<number>;\n };\n DocumentProtection: DocumentProtectionRow;\n}\n\nconst INSERT_BATCH_SIZE = 500;\n\n/**\n * Moves the document permission rows from the read-model store into the\n * reactor store, once.\n *\n * Runs at boot after the reactor's migrations (029 creates the target tables)\n * and before the permission service serves a check. When the read-model\n * store still has the legacy tables and the reactor store's are empty, every\n * row is copied in one reactor-store transaction (ids are not carried: no\n * table references them, and the target's serial assigns fresh ones), then\n * the legacy tables are renamed to `<name>_migrated_2026_10_25` so the copy\n * cannot run again. The renamed tables are kept for a release.\n *\n * Idempotent across crashes: when the copy committed but the rename did not,\n * the next boot finds equal row counts on both sides and only renames. Any\n * other mix of rows on both sides is refused with a warning and both stores\n * are left as they are. Plain SQL throughout, so a PGlite or Postgres read\n * store behaves the same.\n */\nexport async function backfillPermissionTables(\n readModelDb: Kysely<unknown>,\n reactorDb: Kysely<unknown>,\n logger: ILogger,\n): Promise<PermissionBackfillOutcome> {\n const source = readModelDb as Kysely<PermissionTablesDatabase>;\n const target = reactorDb as Kysely<PermissionTablesDatabase>;\n\n const present = await existingTables(source);\n const legacy = PERMISSION_TABLES.filter((table) => present.has(table));\n if (legacy.length === 0) {\n const migrated = PERMISSION_TABLES.some((table) =>\n present.has(migratedName(table)),\n );\n if (migrated) {\n logger.debug(\n \"Permission tables backfill: already done; the read-model tables carry the \" +\n MIGRATED_TABLE_SUFFIX +\n \" suffix\",\n );\n return { status: \"already-backfilled\" };\n }\n logger.debug(\n \"Permission tables backfill: the read-model store has no permission tables; nothing to copy\",\n );\n return { status: \"fresh-install\" };\n }\n\n const blocked = legacy.filter((table) => present.has(migratedName(table)));\n if (blocked.length > 0) {\n return refuse(\n logger,\n `the read-model store has both ${blocked.join(\", \")} and ${blocked\n .map(migratedName)\n .join(\", \")}; drop or rename one of each pair`,\n );\n }\n\n const legacyCounts = await countRows(source, present);\n const reactorCounts = await countRows(target, new Set(PERMISSION_TABLES));\n const reactorTotal = PERMISSION_TABLES.reduce(\n (sum, table) => sum + reactorCounts[table],\n 0,\n );\n\n if (reactorTotal > 0) {\n if (!countsEqual(legacyCounts, reactorCounts)) {\n return refuse(\n logger,\n `the reactor store already has permission rows (${formatCounts(\n reactorCounts,\n )}) that differ from the read-model store's (${formatCounts(\n legacyCounts,\n )})`,\n );\n }\n await renameLegacyTables(source, legacy);\n logger.info(\n `Permission tables backfill: rows were copied by an earlier boot (${formatCounts(\n legacyCounts,\n )}); renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`,\n );\n return { status: \"rename-completed\", counts: legacyCounts };\n }\n\n await target.transaction().execute(async (trx) => {\n if (present.has(\"DocumentPermission\")) {\n await copyDocumentPermissions(source, trx);\n }\n if (present.has(\"OperationUserPermission\")) {\n await copyOperationUserPermissions(source, trx);\n }\n if (present.has(\"DocumentProtection\")) {\n await copyDocumentProtections(source, trx);\n }\n const copied = await countRows(trx, new Set(PERMISSION_TABLES));\n if (!countsEqual(copied, legacyCounts)) {\n throw new Error(\n `Permission tables backfill copied ${formatCounts(copied)} but the read-model store has ${formatCounts(legacyCounts)}; rolled back`,\n );\n }\n });\n await renameLegacyTables(source, legacy);\n logger.info(\n `Permission tables backfill: copied ${formatCounts(\n legacyCounts,\n )} from the read-model store to the reactor store; renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`,\n );\n return { status: \"copied\", counts: legacyCounts };\n}\n\nfunction migratedName(table: PermissionTable): string {\n return `${table}${MIGRATED_TABLE_SUFFIX}`;\n}\n\nfunction refuse(logger: ILogger, reason: string): PermissionBackfillOutcome {\n logger.warn(\n `Permission tables backfill refused: ${reason}. Permission checks read the reactor store; both stores were left unchanged.`,\n );\n return { status: \"refused\", reason };\n}\n\n/** The permission tables, legacy or renamed, in the read-model store's own schema. */\nasync function existingTables(\n db: Kysely<PermissionTablesDatabase>,\n): Promise<Set<string>> {\n const names = PERMISSION_TABLES.flatMap((table) => [\n table,\n migratedName(table),\n ]);\n const result = await sql<{ table_name: string }>`\n select table_name from information_schema.tables\n where table_schema = current_schema()\n and table_name in (${sql.join(names)})\n `.execute(db);\n return new Set(result.rows.map((row) => row.table_name));\n}\n\nasync function countRows(\n db: Kysely<PermissionTablesDatabase> | Transaction<PermissionTablesDatabase>,\n tables: ReadonlySet<string>,\n): Promise<PermissionTableCounts> {\n const counts: PermissionTableCounts = {\n DocumentPermission: 0,\n OperationUserPermission: 0,\n DocumentProtection: 0,\n };\n for (const table of PERMISSION_TABLES) {\n if (!tables.has(table)) continue;\n const row = await db\n .selectFrom(table)\n .select((eb) => eb.fn.countAll<string | number>().as(\"count\"))\n .executeTakeFirstOrThrow();\n counts[table] = Number(row.count);\n }\n return counts;\n}\n\nfunction countsEqual(\n a: PermissionTableCounts,\n b: PermissionTableCounts,\n): boolean {\n return PERMISSION_TABLES.every((table) => a[table] === b[table]);\n}\n\nfunction formatCounts(counts: PermissionTableCounts): string {\n return PERMISSION_TABLES.map((table) => `${table}=${counts[table]}`).join(\n \", \",\n );\n}\n\nasync function copyDocumentPermissions(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: DocumentPermissionRow[] = await source\n .selectFrom(\"DocumentPermission\")\n .select([\n \"documentId\",\n \"userAddress\",\n \"permission\",\n \"grantedBy\",\n \"createdAt\",\n \"updatedAt\",\n ])\n .orderBy(\"id\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"DocumentPermission\").values(batch).execute();\n }\n}\n\nasync function copyOperationUserPermissions(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: OperationUserPermissionRow[] = await source\n .selectFrom(\"OperationUserPermission\")\n .select([\n \"documentId\",\n \"operationType\",\n \"userAddress\",\n \"grantedBy\",\n \"createdAt\",\n ])\n .orderBy(\"id\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"OperationUserPermission\").values(batch).execute();\n }\n}\n\nasync function copyDocumentProtections(\n source: Kysely<PermissionTablesDatabase>,\n trx: Transaction<PermissionTablesDatabase>,\n): Promise<void> {\n const rows: DocumentProtectionRow[] = await source\n .selectFrom(\"DocumentProtection\")\n .select([\n \"documentId\",\n \"protected\",\n \"ownerAddress\",\n \"createdAt\",\n \"updatedAt\",\n ])\n .orderBy(\"documentId\")\n .execute();\n for (const batch of batches(rows)) {\n await trx.insertInto(\"DocumentProtection\").values(batch).execute();\n }\n}\n\nfunction* batches<T>(rows: T[]): Generator<T[]> {\n for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) {\n yield rows.slice(start, start + INSERT_BATCH_SIZE);\n }\n}\n\nasync function renameLegacyTables(\n db: Kysely<PermissionTablesDatabase>,\n tables: PermissionTable[],\n): Promise<void> {\n await db.transaction().execute(async (trx) => {\n for (const table of tables) {\n await sql`ALTER TABLE ${sql.id(table)} RENAME TO ${sql.id(\n migratedName(table),\n )}`.execute(trx);\n }\n });\n}\n","import type { AuthContext, AuthService } from \"@powerhousedao/reactor-api\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/**\n * Verified actor context for authenticated attachment handlers. The user comes\n * exclusively from bearer verification: when auth is disabled (OPEN mode)\n * `user` is undefined and `authEnabled` is false, and handlers must treat the\n * caller as anonymous. Caller-supplied identity headers are never consulted.\n */\nexport type AttachmentActorContext = {\n user: AuthContext[\"user\"];\n authEnabled: boolean;\n};\n\nconst ANONYMOUS_ACTOR: AttachmentActorContext = {\n user: undefined,\n authEnabled: false,\n};\n\nexport type NodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n actor?: AttachmentActorContext,\n) => Promise<void> | void;\n\nexport type RequireAuthOptions = {\n /**\n * Let requests without a bearer identity through as anonymous actors\n * instead of answering 401, so the handler's own document authorization\n * decides. A bearer that IS supplied must still verify — an invalid token\n * is rejected, never downgraded to anonymous.\n */\n allowAnonymous?: boolean;\n /**\n * Whether the deployment has said it accepts no anonymous callers at all\n * (`REQUIRE_AUTHENTICATED_CALLER`). It overrides `allowAnonymous`, because\n * the two answer different questions: `allowAnonymous` says \"this handler\n * authorizes per document, so it does not need identity to decide\", while\n * this says \"this server does not serve callers it cannot name\". A route can\n * be happy to decide without identity and still not be allowed to.\n *\n * These routes are mounted straight on the HTTP adapter, so the fetch chain's\n * own require-auth middleware never sees them — this is how the same floor\n * reaches them.\n */\n requireAuthenticatedCaller?: boolean;\n};\n\n/**\n * Wrap a Node-style handler so that, when `authService` is provided and auth is\n * enabled, the request must carry a verifiable Bearer token. The handler always\n * receives an actor context: the verified bearer user when auth is enabled, or\n * the anonymous context when it is disabled. With `allowAnonymous`, a missing\n * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —\n * unless `requireAuthenticatedCaller` says the deployment refuses anonymous\n * callers outright, which overrides it.\n *\n * With no `authService` there is no bearer to read and every caller is\n * anonymous, so nothing is refused here. That combination cannot carry the\n * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with\n * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity\n * resolution is what builds the service.\n */\nexport function requireAuth(\n authService: AuthService | undefined,\n handler: NodeHandler,\n options?: RequireAuthOptions,\n): NodeHandler {\n if (!authService) {\n return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);\n }\n\n return async (req, res, body) => {\n let result;\n try {\n result = await authService.verifyBearer(req.headers.authorization);\n } catch {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal authentication error\" }));\n return;\n }\n\n if (result instanceof Response) {\n const body = await result.text();\n res.statusCode = result.status;\n const contentType = result.headers.get(\"content-type\");\n if (contentType) res.setHeader(\"Content-Type\", contentType);\n res.end(body);\n return;\n }\n\n if (!result.user) {\n const refuse =\n options?.requireAuthenticatedCaller === true ||\n (result.auth_enabled && !options?.allowAnonymous);\n if (refuse) {\n res.statusCode = 401;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Authentication required\" }));\n return;\n }\n }\n\n await handler(req, res, body, {\n user: result.user,\n authEnabled: result.auth_enabled,\n });\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport {\n requireAuth,\n type NodeHandler,\n type RequireAuthOptions,\n} from \"./auth.js\";\n\nexport type HttpMethod = \"DELETE\" | \"GET\" | \"HEAD\" | \"POST\" | \"PUT\";\n\n// rawBody dispatches ahead of every body parser, so the handler streams `req`.\ntype MountOptions = Pick<\n NonNullable<Parameters<API[\"httpAdapter\"][\"mountNodeRoute\"]>[3]>,\n \"rawBody\"\n>;\n\n/**\n * Mount a Node-style attachment route with `requireAuth` applied unconditionally.\n * When `api.authService` is undefined (auth disabled), the handler still runs\n * through `requireAuth` and receives the anonymous actor context — that is the\n * only way to opt out of bearer verification. To register a route without auth\n * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.\n *\n * `allowAnonymous` is reserved for routes whose handlers make a per-document\n * authorization decision themselves; identity-only routes must not use it. It\n * is also not the last word: a deployment that refuses anonymous callers\n * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes\n * are mounted on the HTTP adapter and never reach the fetch chain that carries\n * that floor for GraphQL. The flag is read from the API, so every route\n * mounted through here inherits it without each one remembering to.\n */\nexport function mountAuthenticatedNodeRoute(\n api: Pick<API, \"httpAdapter\" | \"authService\" | \"requireAuthenticatedCaller\">,\n method: HttpMethod,\n path: string,\n handler: NodeHandler,\n options?: RequireAuthOptions & MountOptions,\n): void {\n const { rawBody, ...authOptions } = options ?? {};\n api.httpAdapter.mountNodeRoute(\n method,\n path,\n requireAuth(api.authService, handler, {\n ...authOptions,\n requireAuthenticatedCaller: api.requireAuthenticatedCaller,\n }),\n { rawBody: rawBody ?? false },\n );\n}\n","import {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n HashMismatch,\n InvalidAttachmentMetadata,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n createRef,\n parseAttachmentDownloadTarget,\n validateReserveMetadata,\n type AttachmentBuildResult,\n type AttachmentDownloadTarget,\n type ReserveAttachmentOptions,\n type ReserveMetadata,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { IAttachmentAccessService } from \"@powerhousedao/reactor-api\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport type { AttachmentActorContext } from \"./auth.js\";\nimport type { AttachmentUrlSigner } from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nconst RETRY_AFTER_SECONDS = 5;\n\n// Canonical form is lowercase hex (the SHA-256 hasher emits lowercase), but\n// accept either case from the wire and normalise before lookup. This keeps\n// the API forgiving for hand-typed URLs without changing storage semantics.\nconst HASH_PATTERN = /^[a-f0-9]{64}$/i;\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify(body));\n}\n\nfunction sendError(res: ServerResponse, status: number, message: string): void {\n sendJson(res, status, { error: message });\n}\n\nfunction statusForError(err: unknown): number {\n if (err instanceof AttachmentNotFound) return 404;\n if (err instanceof ReservationNotFound) return 404;\n if (err instanceof InvalidAttachmentRef) return 400;\n if (err instanceof UploadTooLarge) return 413;\n return 500;\n}\n\nfunction sendErrorFromException(res: ServerResponse, err: unknown): void {\n const status = statusForError(err);\n if (status >= 500) {\n logger.error(\"Attachment route error: @error\", err);\n sendError(res, status, \"Internal error\");\n return;\n }\n sendError(res, status, err instanceof Error ? err.message : String(err));\n}\n\nasync function readJsonBody(\n req: IncomingMessage,\n body: unknown,\n): Promise<unknown> {\n // The Express body-parser may have already populated `body`. When that\n // happens we trust it; otherwise read the raw stream ourselves so this\n // module is independent of upstream middleware ordering.\n if (body !== undefined && body !== null && typeof body === \"object\") {\n return body;\n }\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(chunk as Buffer);\n }\n if (chunks.length === 0) return undefined;\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (text.length === 0) return undefined;\n return JSON.parse(text);\n}\n\nexport function parseReserveOptions(\n input: unknown,\n): ReserveAttachmentOptions | null {\n if (input === null || typeof input !== \"object\") return null;\n const obj = input as Record<string, unknown>;\n const { mimeType, fileName } = obj;\n const extension = obj.extension ?? null;\n try {\n validateReserveMetadata({\n mimeType,\n fileName,\n extension,\n } as ReserveMetadata);\n } catch (err) {\n if (err instanceof InvalidAttachmentMetadata) return null;\n throw err;\n }\n if (typeof mimeType !== \"string\" || typeof fileName !== \"string\") return null;\n if (extension !== null && typeof extension !== \"string\") return null;\n\n // Hash-first mode: clientHash triggers this path; sizeBytes is required alongside it.\n // A body with sizeBytes but no clientHash falls through to the legacy path unchanged.\n if (obj.clientHash !== undefined) {\n if (\n typeof obj.clientHash !== \"string\" ||\n !HASH_PATTERN.test(obj.clientHash)\n ) {\n return null;\n }\n // Zero is accepted: an empty file is a real upload. The hash-first check\n // still binds the bytes received to the declared hash and size, so a\n // drained body cannot pass as an empty file unless one was declared.\n if (\n typeof obj.sizeBytes !== \"number\" ||\n !Number.isSafeInteger(obj.sizeBytes) ||\n obj.sizeBytes < 0\n ) {\n return null;\n }\n return {\n mimeType,\n fileName,\n extension,\n clientHash: obj.clientHash.toLowerCase() as AttachmentHash,\n sizeBytes: obj.sizeBytes,\n };\n }\n\n return {\n mimeType,\n fileName,\n extension,\n };\n}\n\nexport function quoteFilename(name: string): string {\n // RFC 6266: quoted-string with internal \" and \\ escaped.\n return `\"${name.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nexport function buildContentDisposition(fileName: string): string {\n // ASCII fallback: replace any byte outside printable ASCII (0x20-0x7e),\n // plus `\"` and `\\`, with `_`. Browsers fall back to this when they don't\n // grok `filename*=`; the modern parameter carries the real name.\n const ascii = fileName.replace(/[^\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]/g, \"_\");\n // RFC 5987: percent-encode UTF-8 bytes. encodeURIComponent leaves a few\n // chars that 5987 disallows in token; re-encode them.\n const encoded = encodeURIComponent(fileName).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;\n}\n\nexport function makeReserveHandler(attachments: AttachmentBuildResult) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ): Promise<void> => {\n let parsed: unknown;\n try {\n parsed = await readJsonBody(req, body);\n } catch {\n sendError(res, 400, \"Invalid JSON body\");\n return;\n }\n const opts = parseReserveOptions(parsed);\n if (!opts) {\n sendError(\n res,\n 400,\n \"Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }\",\n );\n return;\n }\n\n let upload;\n try {\n upload = await attachments.service.reserve(opts);\n } catch (err) {\n if (err instanceof AttachmentAlreadyExists) {\n sendJson(res, 409, { error: \"already_exists\", ref: err.ref });\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n sendJson(res, 201, {\n reservationId: upload.reservationId,\n ref: upload.ref,\n expiresAtUtc: upload.expiresAtUtc,\n ...(upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}),\n });\n };\n}\n\nexport function makeUploadHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n if (attachments.backend?.kind === \"s3\") {\n sendError(res, 405, \"Use the reservation uploadTarget for S3 uploads\");\n return;\n }\n\n let reservation;\n try {\n reservation = await attachments.reservations.get(reservationId);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n const upload = attachments.uploadFactory.createUpload(reservation);\n\n const webStream = Readable.toWeb(\n req as Readable,\n ) as ReadableStream<Uint8Array>;\n\n try {\n const result = await upload.send(webStream);\n sendJson(res, 200, result);\n } catch (err) {\n if (err instanceof HashMismatch) {\n sendJson(res, 422, {\n error: \"hash_mismatch\",\n claimed: err.claimed,\n actual: err.actual,\n });\n return;\n }\n if (err instanceof SizeMismatch) {\n sendJson(res, 422, {\n error: \"size_mismatch\",\n declared: err.declared,\n actual: err.actual,\n });\n return;\n }\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDownloadHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n const controller = new AbortController();\n req.once(\"close\", () => controller.abort());\n\n let response;\n try {\n response = await attachments.store.get(\n canonicalHash,\n controller.signal,\n grant.documentId,\n );\n } catch (err) {\n if (err instanceof AttachmentPending) {\n res.statusCode = 202;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: err.expiresAtUtc,\n ...(err.metadata ?? {}),\n }),\n );\n res.end();\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n const { header, body } = response;\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"private\");\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n\n const source = Readable.fromWeb(\n body as unknown as NodeReadableStream<Uint8Array>,\n );\n // The blob is opened lazily, so a file missing from disk (metadata still\n // says \"available\", e.g. a pod-local store lost on restart) surfaces here\n // as a stream error. `.pipe()` does not forward it: without a listener it\n // is an unhandled 'error' event and takes the whole process down.\n source.once(\"error\", (err) => handleDownloadStreamError(res, hash, err));\n source.pipe(res);\n };\n}\n\nfunction handleDownloadStreamError(\n res: ServerResponse,\n hash: string,\n err: unknown,\n): void {\n if (res.headersSent) {\n // Bytes are already on the wire; finishing normally would hand the client\n // a truncated file as if it were complete. Cut the connection instead —\n // without passing the error, which would re-emit it on the response.\n logger.error(\"Attachment stream failed mid-download: @error\", err);\n res.destroy();\n return;\n }\n // Nothing sent yet: drop the download headers so they cannot describe the\n // JSON error body, then answer like any other missing attachment.\n res.removeHeader(\"Content-Length\");\n res.removeHeader(\"Content-Disposition\");\n res.removeHeader(\"Attachment-Metadata\");\n if ((err as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\") {\n logger.warn(\n \"Attachment @hash is recorded as available but its blob is missing\",\n hash,\n );\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment stream failed before sending: @error\", err);\n sendError(res, 500, \"Internal error\");\n}\n\n// Node rejects header values above U+00FF. Escaping everything outside\n// printable ASCII keeps the header valid; JSON.parse restores the original.\nfunction toAsciiJson(value: unknown): string {\n return JSON.stringify(value).replace(\n /[\\u007f-\\uffff]/g,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\nexport function buildPendingHeader(pending: {\n expiresAtUtc: string | null;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n}): string {\n return toAsciiJson(pending);\n}\n\nexport function buildMetadataHeader(header: {\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n extension: string | null;\n createdAtUtc: string;\n lastAccessedAtUtc: string;\n}): string {\n return toAsciiJson({\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n extension: header.extension,\n createdAtUtc: header.createdAtUtc,\n lastAccessedAtUtc: header.lastAccessedAtUtc,\n });\n}\n\nexport function makeStatHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n const grant = await resolveByteGrant(\n req,\n canonicalHash,\n actor,\n attachmentAccess,\n urlSigner,\n );\n if (!admitGrant(res, grant)) return;\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n res.setHeader(\"Cache-Control\", \"private\");\n if (header.status === \"pending\") {\n res.statusCode = 202;\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n buildPendingHeader({\n expiresAtUtc: header.expiresAtUtc,\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n }),\n );\n res.end();\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n res.end();\n };\n}\n\nexport function makeGetReservationHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n const reservation = await attachments.reservations.get(reservationId);\n sendJson(res, 200, reservation);\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDeleteReservationHandler(\n attachments: AttachmentBuildResult,\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n await attachments.reservations.delete(reservationId);\n res.statusCode = 204;\n res.end();\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nfunction extractParam(req: IncomingMessage, name: string): string | undefined {\n const expressParams = (\n req as IncomingMessage & {\n params?: Record<string, string>;\n }\n ).params;\n return expressParams?.[name];\n}\n\nconst MAX_DOCUMENT_ID_LEN = 512;\nconst ATTACHMENT_NOT_FOUND_BODY = { error: \"Attachment not found\" };\n// SigV4 presigned URLs cannot outlive 7 days; requests above the cap are\n// clamped rather than rejected so clients need not know the ceiling.\nconst MAX_DOWNLOAD_TARGET_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * How long a download target may live, by default.\n *\n * The authorization behind a presigned URL is decided once, when it is issued,\n * and the URL keeps working until it expires however the document's policy\n * changes in between. A week of that is a revocation that does not revoke: an\n * account deactivated, a company reassigned or a group left, and the bytes stay\n * fetchable by anyone holding the link. Minutes are enough to open a file;\n * days are only enough to lose control of it.\n *\n * A deployment that needs longer sets `attachments.downloadTargetMaxTtlSeconds`\n * (ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS at the edge), still bounded by the\n * signing ceiling above.\n */\nconst DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;\n\n/** A configured ceiling, bounded by the signing maximum; unset is the default. */\nexport function downloadTargetTtlCapSeconds(\n configured: number | undefined,\n): number {\n return configured === undefined\n ? DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS\n : Math.min(configured, MAX_DOWNLOAD_TARGET_TTL_SECONDS);\n}\n\n/**\n * Returns the single `documentId` query value, or null when it is missing,\n * duplicated, blank, or oversized. Validation happens before authorization so\n * malformed requests never reach the access service.\n */\nfunction extractSingleDocumentId(req: IncomingMessage): string | null {\n if (!req.url) return null;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(\"documentId\");\n if (values.length !== 1) return null;\n const value = values[0];\n if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) {\n return null;\n }\n return value;\n}\n\n/**\n * Returns the target TTL in seconds, or \"invalid\" when the caller's own value\n * is malformed (duplicated, non-integer, or non-positive).\n *\n * The cap applies whether or not the caller asked for a lifetime: omitting\n * `expiresIn` used to fall through to whatever the storage backend was\n * configured with, which would make the ceiling something a client opts out of\n * by saying nothing.\n */\nfunction extractExpiresIn(\n req: IncomingMessage,\n cap: number,\n): number | \"invalid\" {\n if (!req.url) return cap;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return cap;\n }\n const values = url.searchParams.getAll(\"expiresIn\");\n if (values.length === 0) return cap;\n if (values.length > 1) return \"invalid\";\n const parsed = Number(values[0]);\n if (!Number.isInteger(parsed) || parsed <= 0) return \"invalid\";\n return Math.min(parsed, cap);\n}\n\ntype ByteGrant =\n | { kind: \"granted\"; documentId: string }\n | { kind: \"denied\" }\n | { kind: \"unavailable\" }\n | { kind: \"error\" };\n\nfunction singleQueryValue(\n params: URLSearchParams,\n name: string,\n): string | null {\n const values = params.getAll(name);\n return values.length === 1 ? values[0] : null;\n}\n\n/**\n * Byte routes serve only under a grant: a signed URL minted by the\n * download-target route, or a documentId the caller may read the attachment\n * through. A signed request is judged by its signature alone.\n */\nasync function resolveByteGrant(\n req: IncomingMessage,\n hash: AttachmentHash,\n actor: AttachmentActorContext | undefined,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n): Promise<ByteGrant> {\n let params: URLSearchParams;\n try {\n params = new URL(req.url ?? \"\", \"http://switchboard.invalid\").searchParams;\n } catch {\n return { kind: \"denied\" };\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) return { kind: \"denied\" };\n\n if (params.has(\"signature\") || params.has(\"expires\")) {\n const signature = singleQueryValue(params, \"signature\");\n const expires = singleQueryValue(params, \"expires\");\n if (!urlSigner || signature === null || expires === null) {\n return { kind: \"denied\" };\n }\n return urlSigner.verify(hash, documentId, expires, signature)\n ? { kind: \"granted\", documentId }\n : { kind: \"denied\" };\n }\n\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(hash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n return { kind: \"error\" };\n }\n if (decision.kind === \"projection-unavailable\") {\n return { kind: \"unavailable\" };\n }\n if (decision.kind === \"denied\") return { kind: \"denied\" };\n return { kind: \"granted\", documentId: decision.documentId };\n}\n\n/** Answers a refused grant; true when the request may proceed. */\nfunction admitGrant(\n res: ServerResponse,\n grant: ByteGrant,\n): grant is { kind: \"granted\"; documentId: string } {\n switch (grant.kind) {\n case \"granted\":\n return true;\n case \"denied\":\n // 404, never 403: a refusal must not reveal that the hash exists.\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return false;\n case \"unavailable\":\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return false;\n case \"error\":\n sendError(res, 500, \"Internal error\");\n return false;\n }\n}\n\n/**\n * Base URL of this Switchboard as seen by the caller, used to build\n * filesystem `switchboard` download targets that point back at the signed\n * byte route.\n */\nfunction requestBaseUrl(req: IncomingMessage): string | null {\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const proto =\n (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n ?.split(\",\")[0]\n ?.trim() ||\n ((req.socket as { encrypted?: boolean }).encrypted ? \"https\" : \"http\");\n const forwardedHost = req.headers[\"x-forwarded-host\"];\n const host =\n (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ??\n req.headers.host;\n if (!host) return null;\n return `${proto}://${host}`;\n}\n\nexport function makeDownloadTargetHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n urlSigner: AttachmentUrlSigner | null,\n ttlCapSeconds = downloadTargetTtlCapSeconds(undefined),\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n // Target responses carry short-lived URLs and authorization decisions;\n // no intermediary may cache them.\n res.setHeader(\"Cache-Control\", \"no-store\");\n\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) {\n sendError(\n res,\n 400,\n \"documentId is required exactly once as a non-empty query parameter\",\n );\n return;\n }\n const expiresIn = extractExpiresIn(req, ttlCapSeconds);\n if (expiresIn === \"invalid\") {\n sendError(\n res,\n 400,\n \"expiresIn must be a single positive integer number of seconds\",\n );\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(canonicalHash),\n userAddress: actor?.user?.address,\n appKey: actor?.user?.appKey,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n\n if (decision.kind === \"projection-unavailable\") {\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return;\n }\n if (decision.kind === \"denied\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n if (err instanceof AttachmentNotFound) {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment metadata lookup failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n if (header.status !== \"available\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let target: AttachmentDownloadTarget;\n if (attachments.backend && attachments.backend.kind !== \"filesystem\") {\n try {\n target = await attachments.backend.prepareDownloadTarget(\n canonicalHash,\n expiresIn,\n );\n } catch {\n // Backend errors are sanitized at the backend boundary; no URLs or\n // signatures reach this scope, and none may be logged from here.\n sendError(res, 502, \"Attachment download target unavailable\");\n return;\n }\n } else {\n if (!urlSigner) {\n sendError(res, 503, \"Attachment download signing is not configured\");\n return;\n }\n const base = requestBaseUrl(req);\n if (!base) {\n sendError(res, 500, \"Internal error\");\n return;\n }\n const signed = urlSigner.sign(\n canonicalHash,\n decision.documentId,\n expiresIn,\n );\n try {\n target = parseAttachmentDownloadTarget({\n kind: \"switchboard\",\n method: \"GET\",\n url: `${base}/attachments/${canonicalHash}?${signed.query}`,\n headers: {},\n expiresAtUtc: signed.expiresAtUtc,\n });\n } catch {\n sendError(res, 500, \"Internal error\");\n return;\n }\n }\n\n sendJson(res, 200, target);\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport { childLogger } from \"document-model\";\nimport { mountAuthenticatedNodeRoute } from \"./mount-auth.js\";\nimport {\n makeDeleteReservationHandler,\n makeDownloadHandler,\n downloadTargetTtlCapSeconds,\n makeDownloadTargetHandler,\n makeGetReservationHandler,\n makeReserveHandler,\n makeStatHandler,\n makeUploadHandler,\n} from \"./routes.js\";\nimport {\n ATTACHMENT_URL_SIGNING_SECRET_ENV,\n resolveAttachmentUrlSigning,\n type AttachmentUrlSigner,\n} from \"./url-signer.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nexport type RegisterAttachmentRoutesOptions = {\n /** Overrides the signer resolved from the environment; null disables signing. */\n urlSigner?: AttachmentUrlSigner | null;\n /** The switchboard's settings; unset means their defaults. */\n config?: {\n urlSigningSecret?: string;\n downloadTargetMaxTtlSeconds?: number;\n };\n};\n\nexport function registerAttachmentRoutes(\n api: API,\n options: RegisterAttachmentRoutesOptions = {},\n): void {\n const { attachments, attachmentAccess } = api;\n const { config } = options;\n const urlSigner =\n options.urlSigner === undefined\n ? signerFromEnvironment(attachments.backend?.kind ?? \"filesystem\", {\n [ATTACHMENT_URL_SIGNING_SECRET_ENV]: config?.urlSigningSecret,\n NODE_ENV: process.env.NODE_ENV,\n })\n : options.urlSigner;\n const ttlCapSeconds = downloadTargetTtlCapSeconds(\n config?.downloadTargetMaxTtlSeconds,\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"POST\",\n \"/attachments/reservations\",\n makeReserveHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/reservations/:reservationId\",\n makeGetReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"DELETE\",\n \"/attachments/reservations/:reservationId\",\n makeDeleteReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"PUT\",\n \"/attachments/reservations/:reservationId\",\n makeUploadHandler(attachments),\n // Streams to storage; no parser may buffer or drain the body first.\n { rawBody: true },\n );\n\n // Anonymous-capable: authorization is purely the document's (or a signed\n // URL minted under it), exactly as it is for the document itself.\n mountAuthenticatedNodeRoute(\n api,\n \"HEAD\",\n \"/attachments/:hash\",\n makeStatHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash/download-target\",\n makeDownloadTargetHandler(\n attachments,\n attachmentAccess,\n urlSigner,\n ttlCapSeconds,\n ),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash\",\n makeDownloadHandler(attachments, attachmentAccess, urlSigner),\n { allowAnonymous: true },\n );\n}\n\nfunction signerFromEnvironment(\n backend: \"filesystem\" | \"s3\",\n env: Readonly<Record<string, string | undefined>>,\n): AttachmentUrlSigner | null {\n const signing = resolveAttachmentUrlSigning(env);\n if (signing.status === \"unconfigured\") {\n if (backend === \"filesystem\") {\n logger.error(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`,\n );\n }\n return null;\n }\n if (signing.status === \"ephemeral\" && backend === \"filesystem\") {\n logger.warn(\n `${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`,\n );\n }\n return signing.signer;\n}\n","import path from \"node:path\";\n\n/**\n * A token broker for an app's web client (see the reactor-workflow README,\n * \"OAuth2 connections\"). The workflow runtime checks it when it loads the\n * apps: a client id and two absolute https URLs, else it is dropped with a\n * warning.\n */\nexport interface OAuthAppRelayConfig {\n clientId: string;\n redirectUri: string;\n tokenUrl: string;\n}\n\n/** One publisher OAuth2 app as `workflows.oauthApps` names it. */\nexport interface OAuthAppConfig {\n id: string;\n clients: { desktop?: string; web?: string };\n relay?: OAuthAppRelayConfig;\n}\n\n/**\n * The config file's `workflows.oauthApps`, client file paths made absolute\n * from `dir`, the config file's folder. A malformed entry is left out; a\n * relay that is not an object is dropped and reported, the app kept without\n * it. The relay's fields are checked by the runtime, as for apps a host\n * passes itself.\n */\nexport function parseOAuthApps(\n raw: unknown,\n dir: string,\n onDroppedRelay?: (appId: string, relay: unknown) => void,\n): OAuthAppConfig[] {\n if (!Array.isArray(raw)) return [];\n const at = (p: unknown) =>\n typeof p === \"string\" && p ? path.resolve(dir, p) : undefined;\n return raw.flatMap((entry: unknown) => {\n const app = (entry ?? {}) as {\n id?: unknown;\n clients?: { desktop?: unknown; web?: unknown };\n relay?: unknown;\n };\n if (typeof app.id !== \"string\" || !app.id) return [];\n const desktop = at(app.clients?.desktop);\n const web = at(app.clients?.web);\n let relay: OAuthAppRelayConfig | undefined;\n if (app.relay !== undefined) {\n if (\n typeof app.relay === \"object\" &&\n app.relay !== null &&\n !Array.isArray(app.relay)\n ) {\n relay = app.relay as OAuthAppRelayConfig;\n } else {\n onDroppedRelay?.(app.id, app.relay);\n }\n }\n return [\n {\n id: app.id,\n clients: { ...(desktop ? { desktop } : {}), ...(web ? { web } : {}) },\n ...(relay ? { relay } : {}),\n },\n ];\n });\n}\n","import {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport type { AttachmentReferenceProjectionCapability } from \"@powerhousedao/reactor-api\";\nimport {\n AttachmentReferenceReadModel,\n AttachmentSchemaCompiler,\n type IAttachmentReferenceWriter,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { Kysely } from \"kysely\";\n\nexport type AttachmentReferenceReadModelRegistration = {\n attachmentReferenceWriter: IAttachmentReferenceWriter;\n baseKysely: Kysely<unknown>;\n};\n\nconst attachmentSchemaCompiler = new AttachmentSchemaCompiler();\n\nfunction createAttachmentReferenceReadModel(\n baseKysely: Kysely<unknown>,\n dependencies: {\n operationIndex: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[1];\n writeCache: ConstructorParameters<typeof AttachmentReferenceReadModel>[2];\n processorManagerConsistencyTracker: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[3];\n documentModelRegistry: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[4];\n },\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): AttachmentReferenceReadModel {\n return new AttachmentReferenceReadModel(\n baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n dependencies.operationIndex,\n dependencies.writeCache,\n dependencies.processorManagerConsistencyTracker,\n dependencies.documentModelRegistry,\n attachmentSchemaCompiler,\n attachmentReferenceWriter,\n );\n}\n\nexport function registerAttachmentReferenceReadModel(\n reactorBuilder: ReactorBuilder,\n registration: AttachmentReferenceReadModelRegistration,\n): void {\n reactorBuilder.withReadModelFactory(\n async ({\n documentModelRegistry,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const readModel = createAttachmentReferenceReadModel(\n registration.baseKysely,\n {\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n documentModelRegistry,\n },\n registration.attachmentReferenceWriter,\n );\n await readModel.init();\n return readModel;\n },\n );\n}\n\nexport async function registerAttachmentReferenceReadModelOnModule(\n clientModule: InProcessReactorClientModule,\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): Promise<AttachmentReferenceProjectionCapability> {\n const reactorModule = clientModule.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n const readModel = createAttachmentReferenceReadModel(\n reactorModule.database as unknown as Kysely<unknown>,\n {\n operationIndex: reactorModule.operationIndex,\n writeCache: reactorModule.writeCache,\n processorManagerConsistencyTracker:\n reactorModule.processorManagerConsistencyTracker,\n documentModelRegistry: reactorModule.documentModelRegistry,\n },\n attachmentReferenceWriter,\n );\n\n await readModel.init();\n coordinator.addReadModel(readModel, \"pre_ready\");\n await readModel.init();\n\n return { status: \"available\" };\n}\n","import type {\n ReactorBuilder,\n ReactorFeatureFlags,\n} from \"@powerhousedao/reactor\";\nimport {\n ChannelScheme,\n type IDocumentModelLoader,\n type ReactorClientBuilder,\n type SignerConfig,\n} from \"@powerhousedao/reactor\";\nimport {\n baseDocumentModels,\n getUniqueDocumentModels,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n SignaturePolicy,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\nexport type SwitchboardReactorDefaultsOptions = {\n // Extra models registered alongside the baseline (document-model, drive,\n // reactor-drive, reactor-group). Pass vetra models here in studio/dev.\n // Deduped by id.\n documentModels?: DocumentModelModule[];\n /** Upgrade manifests for versioned models, one per document type. */\n upgradeManifests?: UpgradeManifest<readonly number[]>[];\n /** Default true. */\n includeBaseModels?: boolean;\n /**\n * Channel scheme. Defaults to `ChannelScheme.SWITCHBOARD`, which populates\n * `reactorModule.syncModule.syncManager` — required by reactor-api. Set\n * to `false` if the caller configures sync itself (`withChannelScheme` or\n * `withSync`); the builder refuses both together.\n */\n channelScheme?: ChannelScheme | false;\n /** Defaults to true. Set false when the caller owns SIGINT handling. */\n signalHandlers?: boolean;\n /** Executor tuning. Omit to use the reactor's own defaults. */\n executorConfig?: {\n maxSkipThreshold?: number;\n featureFlags?: Partial<ReactorFeatureFlags>;\n };\n /** Wire dynamic document-model loading via HTTP. */\n documentModelLoader?: IDocumentModelLoader;\n logger?: ILogger;\n /**\n * Identity signer (typically from `getRenownSignerConfig`). Signs client\n * writes and the operations the executor synthesizes, in pooled workers\n * through `workerSigner`; omit for unsigned operation.\n */\n signer?: SignerConfig;\n /**\n * Which keys may sign as which users (typically from\n * `getRenownTrustPolicyConfig`); wins over one carried by `signer`.\n */\n trustPolicy?: Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">;\n /** What the client creates new documents as; see `resolveCreateSignaturePolicy`. */\n createSignaturePolicy?: SignaturePolicy;\n};\n\n/**\n * Apply switchboard's standard configuration to a reactor + client builder\n * pair. Each piece is opt-out via the options object; defaults mirror what\n * `startSwitchboard` does when building a reactor itself. Mutates both\n * builders in place.\n *\n * Does NOT touch kysely or read models — callers wire those themselves\n * (see `withKysely` / `withReadModelFactory` on the reactor builder).\n */\n/** The models switchboard always registers alongside package models. */\nexport function switchboardBaseDocumentModels() {\n return baseDocumentModels.map(([, model]) => model);\n}\n\nexport function applySwitchboardReactorDefaults(\n reactorBuilder: ReactorBuilder,\n clientBuilder: ReactorClientBuilder,\n options: SwitchboardReactorDefaultsOptions = {},\n): void {\n const baseModels =\n options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];\n const extra = options.documentModels ?? [];\n if (baseModels.length || extra.length) {\n reactorBuilder.withDocumentModelSources(\n getUniqueDocumentModels(baseModels, extra),\n );\n }\n\n if (options.upgradeManifests?.length) {\n reactorBuilder.withUpgradeManifests(options.upgradeManifests);\n }\n\n const scheme =\n options.channelScheme === undefined\n ? ChannelScheme.SWITCHBOARD\n : options.channelScheme;\n if (scheme !== false) {\n reactorBuilder.withChannelScheme(scheme);\n }\n\n if (options.signalHandlers !== false) {\n reactorBuilder.withSignalHandlers();\n }\n\n if (\n options.executorConfig?.maxSkipThreshold !== undefined ||\n options.executorConfig?.featureFlags !== undefined\n ) {\n reactorBuilder.withExecutorConfig({\n ...(options.executorConfig.maxSkipThreshold !== undefined\n ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold }\n : {}),\n ...(options.executorConfig.featureFlags !== undefined\n ? { featureFlags: options.executorConfig.featureFlags }\n : {}),\n });\n }\n\n if (options.documentModelLoader) {\n reactorBuilder.withDocumentModelLoader(options.documentModelLoader);\n }\n\n if (options.logger) {\n reactorBuilder.withLogger(options.logger);\n }\n\n if (options.signer) {\n clientBuilder.withSigner(options.signer);\n reactorBuilder.withSigner(\n options.signer.signer,\n options.signer.workerSigner,\n );\n }\n\n if (options.createSignaturePolicy) {\n clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);\n }\n\n const trust = options.trustPolicy ?? options.signer;\n if (trust?.trustPolicy) {\n reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);\n }\n}\n","import { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport type { IRenown } from \"@renown/sdk\";\nimport type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { registerAttachmentRoutes } from \"../attachments/index.js\";\nimport { deriveAttachmentServiceConfig } from \"../server.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport { z } from \"zod\";\n\n/** No entry config: presence is the whole activation. A typo'd config key\n * fails at resolution instead of being silently ignored. */\nexport const attachmentsPluginConfigSchema = z.strictObject({});\n\nexport type AttachmentsPluginConfig = z.input<\n typeof attachmentsPluginConfigSchema\n>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/attachments\": AttachmentsPluginConfig;\n }\n}\n\n/**\n * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments\n * routes mount at onHttpMounting and the remote attachment service is created\n * for the returned handle. Presence is activation — removed from the\n * composition, the routes and service do not exist. NOT yet carved: the\n * attachment-reference read model registered inside reactor construction\n * (carve map: server.mts initializeClient) — it follows with the\n * onReadModelsRegistering step in R2 step 2; until then it registers on both\n * paths (a dormant read model when the plugin is absent, harmless).\n *\n * Inputs (carve map): api (routes), config.attachments (signing, TTL),\n * options.attachmentServiceUrl / https + serverPort + renown (service config).\n */\nexport const attachmentsPlugin: HostPlugin<{\n onHttpMounting: (ctx: SwitchboardHostContext) => void;\n}> = {\n name: \"switchboard-attachments\",\n appliesTo: \"switchboard\",\n configSchema: attachmentsPluginConfigSchema,\n hooks: {\n onHttpMounting: (ctx) => {\n registerAttachmentRoutes(\n ctx.api as Parameters<typeof registerAttachmentRoutes>[0],\n { config: ctx.config?.attachments },\n );\n ctx.attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(\n ctx.options as { attachmentServiceUrl?: string; https?: boolean },\n ctx.serverPort as number,\n ctx.renown as IRenown | null,\n ),\n );\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default attachmentsPlugin;\n","import { attachmentsPlugin } from \"./plugins/attachments.mjs\";\nimport { privacyPlugin } from \"./plugins/privacy.mjs\";\nimport { workflowsPlugin } from \"./plugins/workflows.mjs\";\nimport { mcpPlugin } from \"./plugins/mcp.mjs\";\nimport {\n mergeContributions,\n resolveOrder,\n runObserveHook,\n runObserveHookSequential,\n runTransformHook,\n type HostPlugin,\n type MergedContribution,\n type ResolvedPlugin,\n} from \"@powerhousedao/host-core\";\nimport type { SwitchboardConfig } from \"./config/schema.js\";\n\n/**\n * R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:\n * uniform-runners-plan/rewire/r2-carve-map.md). Behind\n * FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing\n * inline path byte-identically; flag on, the five subsystems run as built-in\n * plugins through these hook moments. Subsystems carve one per commit; until\n * a subsystem is carved, its inline code runs on BOTH paths and its plugin\n * twin does not exist.\n *\n * Hook vocabulary (SwitchboardHooks), anchored to the boot spine:\n * - transformServerOptions — after option/flag resolution, before anything opens\n * - onReadModelsRegistering — inside reactor construction (build-time read models)\n * - onHttpMounting — api exists; routes mount here\n * - onSubgraphsRegistering — push into lateSubgraphs before the drain\n * - onReactorReady — client + graphqlManager destructured\n * - onDrivesReady — after core drive seeding / remote attachment\n * - onShutdown — first in the subsystem-ordered teardown\n */\n\nexport { isPluginHostEnabled, PLUGIN_HOST_FLAG } from \"./plugin-host-flag.mjs\";\n\n/**\n * The context plugins receive. Fields are populated as the boot spine reaches\n * them (api/client/graphqlManager are undefined before stage 17); concrete\n * types stay in server.mts — subsystem carves tighten their own slices.\n */\nexport interface SwitchboardHostContext {\n /** The switchboard's ILogger; typed loosely here to avoid pinning the\n * logger package in the scaffold — subsystem carves use it as-is. */\n logger: unknown;\n options: Record<string, unknown>;\n /** The parsed config the switchboard booted with. */\n config?: SwitchboardConfig;\n renown: unknown;\n serverPort?: number;\n /** Set by the attachments plugin at onHttpMounting; the boot reads it for\n * the returned handle. */\n attachmentService?: unknown;\n /** Privacy plugin state: config resolved at transformServerOptions\n * (fail-fast), the running subsystem set at onSubgraphsRegistering. */\n privacyConfig?: unknown;\n privacy?: unknown;\n /** Workflows plugin: wiring closures handed in by server.mts, runtime +\n * retry handles stored by the plugin. */\n workflowsOrchestration?: unknown;\n workflows?: unknown;\n workflowsRetry?: unknown;\n api?: unknown;\n /** @deprecated The facade; plugins that have moved take `read` and `write`. */\n client?: unknown;\n /** The reactor's read half (IReactorReadClient), set at onReactorReady. */\n read?: unknown;\n /** The reactor's write half (IReactorWriteClient), set at onReactorReady. */\n write?: unknown;\n graphqlManager?: unknown;\n reactorClientModule?: unknown;\n /** Late subgraph registrations drain before the readiness router update. */\n lateSubgraphs?: Promise<unknown>[];\n contributions: Record<string, MergedContribution[]>;\n}\n\nexport interface SwitchboardPluginHost {\n readonly plugins: readonly HostPlugin[];\n readonly ctx: SwitchboardHostContext;\n transformOptions<T>(seed: T): Promise<T>;\n observe(\n hook:\n | \"onReadModelsRegistering\"\n | \"onHttpMounting\"\n | \"onSubgraphsRegistering\"\n | \"onReactorReady\"\n | \"onDrivesReady\"\n | \"onShutdown\",\n ): Promise<void>;\n}\n\n/** Built-in plugins, pre-listed (the default composition until host.js\n * entries map in R2 step 2). Subsystems join as R2 carves them. */\nexport function builtinSwitchboardPlugins(): ResolvedPlugin[] {\n const entry = { enabled: true, verbs: \"*\" as const, config: {} };\n return [\n {\n plugin: mcpPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: { ...entry, module: \"@powerhousedao/switchboard/plugins/mcp\" },\n },\n {\n plugin: attachmentsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/attachments\",\n },\n },\n {\n plugin: privacyPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/privacy\",\n },\n },\n // Registered after privacy ON PURPOSE: onShutdown runs sequentially in\n // registration order, preserving the inline teardown (privacy stops\n // before workflows, both before api.dispose — carve map).\n {\n plugin: workflowsPlugin as HostPlugin,\n provenance: \"built-in\",\n entry: {\n ...entry,\n module: \"@powerhousedao/switchboard/plugins/workflows\",\n },\n },\n ];\n}\n\nexport function createSwitchboardPluginHost(\n ctx: Omit<SwitchboardHostContext, \"contributions\">,\n resolved?: readonly ResolvedPlugin[],\n): SwitchboardPluginHost {\n resolved ??= builtinSwitchboardPlugins();\n const ordered = resolveOrder(resolved.map((r) => r.plugin));\n const contributions = mergeContributions(\n resolved.map((r) => ({ plugin: r.plugin, provenance: r.provenance })),\n );\n const fullCtx: SwitchboardHostContext = { ...ctx, contributions };\n\n // Change 2: the composition is observable on the `ph run` terminal. Report\n // the activated plugins once at construction, then which plugins run each\n // lifecycle hook as it fires.\n const LOG = \"[switchboard:plugins]\";\n console.log(\n `${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(\", \") || \"(none)\"}`,\n );\n for (const r of resolved) {\n const cfg = Object.keys(r.entry.config ?? {});\n console.log(\n `${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\"),\n );\n }\n const ranBy = (hook: string) =>\n ordered.filter((p) => (p.hooks as Record<string, unknown>)?.[hook]);\n const logHook = (hook: string) => {\n const names = ranBy(hook).map((p) => p.name);\n console.log(\n `${LOG} hook ${hook} → ${names.length ? names.join(\", \") : \"(no implementers)\"}`,\n );\n };\n\n return {\n plugins: ordered,\n ctx: fullCtx,\n transformOptions: (seed) => {\n logHook(\"transformServerOptions\");\n return runTransformHook(\"transformServerOptions\", ordered, fullCtx, seed);\n },\n observe: (hook) => {\n logHook(hook);\n return hook === \"onShutdown\"\n ? runObserveHookSequential(hook, ordered, fullCtx)\n : runObserveHook(hook, ordered, fullCtx);\n },\n };\n}\n","import {\n isCatchingUp,\n rankSlowest,\n renderDoneSummary,\n renderSlowLine,\n type InspectorProcessorTimingReport,\n} from \"@powerhousedao/reactor\";\n\nconst TOP = 5;\n\nexport type ProcessorTimingLogOptions = {\n intervalMs: number;\n read: () => InspectorProcessorTimingReport;\n log: (line: string) => void;\n now?: () => number;\n};\n\n/**\n * The console's `catch-up slowest` line for a host without the ph-cli display:\n * one every interval while catching up, and one summary when it ends. Silent\n * while timing is off or nothing is catching up. Returns the stop.\n */\nexport function startProcessorTimingLog(\n options: ProcessorTimingLogOptions,\n): () => void {\n const now = options.now ?? (() => Date.now());\n let busySince: number | undefined;\n\n const tick = () => {\n const report = options.read();\n if (report.level === \"off\") return;\n if (isCatchingUp(report)) {\n busySince ??= now();\n const rows = rankSlowest(report, TOP, \"window\");\n if (rows.length > 0) options.log(renderSlowLine(rows, report.windowMs));\n return;\n }\n if (busySince === undefined) return;\n const wallMs = now() - busySince;\n busySince = undefined;\n options.log(renderDoneSummary(rankSlowest(report, TOP, \"total\"), wallMs));\n };\n\n const timer = setInterval(tick, options.intervalMs);\n timer.unref();\n return () => clearInterval(timer);\n}\n","import {\n HardenedPGliteDialect,\n type HardenedPGliteDialectOptions,\n} from \"@powerhousedao/reactor\";\nimport type {\n DatabaseIntrospector,\n Dialect,\n DialectAdapter,\n Driver,\n QueryCompiler,\n} from \"kysely\";\nimport type { ILogger } from \"document-model\";\nimport type { PGliteLike } from \"@powerhousedao/reactor-api/pglite-node\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n/** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */\nexport function reactorPgliteDialectOptions(\n logger: ILogger,\n proc?: FatalProcess,\n): Partial<HardenedPGliteDialectOptions> {\n return {\n onDiagnostic: (message, error) =>\n logger.error(`[pglite-dialect] ${message}: @error`, error),\n onPoisoned: (cause) => {\n if (!triggerFatalShutdown(\"PGlite session poisoned\", cause, proc)) {\n logger.error(\"PGlite session poisoned: @error\", cause);\n }\n },\n };\n}\n\ntype IntrospectedDatabase = Parameters<Dialect[\"createIntrospector\"]>[0];\n\n// kysely-pglite-dialect's driver.destroy() only nulls its reference to the\n// PGlite client — it never calls pglite.close(). Without close(), the store\n// misses its shutdown checkpoint and the next open runs WAL recovery. This\n// wrapper closes the dialect's PGlite as part of the reactor's\n// database.destroy() chain.\nexport class ClosablePGliteDialect implements Dialect {\n readonly #inner: HardenedPGliteDialect;\n readonly #pglite: PGliteLike;\n\n constructor(\n pglite: PGliteLike,\n options: Partial<HardenedPGliteDialectOptions> = {},\n ) {\n this.#pglite = pglite;\n this.#inner = new HardenedPGliteDialect(pglite, options);\n }\n\n createAdapter(): DialectAdapter {\n return this.#inner.createAdapter();\n }\n\n createDriver(): Driver {\n const driver = this.#inner.createDriver();\n const pglite = this.#pglite;\n const innerDestroy = driver.destroy.bind(driver);\n driver.destroy = async () => {\n await innerDestroy();\n if (pglite.closed) return;\n try {\n await pglite.close();\n } catch (err) {\n // An aborted runtime (Postgres PANIC) has nothing left to flush.\n if (!/PGlite aborted/.test(String(err))) throw err;\n }\n };\n return driver;\n }\n\n createQueryCompiler(): QueryCompiler {\n return this.#inner.createQueryCompiler();\n }\n\n createIntrospector(db: IntrospectedDatabase): DatabaseIntrospector {\n return this.#inner.createIntrospector(db);\n }\n}\n","import { syncTree } from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n loadPGliteModule,\n loadPgDump,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype PGliteLike = {\n waitReady: Promise<void>;\n exec: (sql: string) => Promise<unknown>;\n close: () => Promise<void>;\n dumpDataDir: (compression: \"none\") => Promise<Blob>;\n};\n\ntype PGliteCtor = {\n new (dataDir: string, options?: Record<string, unknown>): PGliteLike;\n new (options: Record<string, unknown>): PGliteLike;\n};\n\nfunction backupPath(dataDir: string, major: number): string {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${dataDir}.backup-pg${major}-${stamp}`;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction logRestoreFailure(\n dataDir: string,\n sql: string,\n err: unknown,\n logger: ILogger,\n): void {\n const errObj = err as {\n message?: string;\n position?: string | number;\n severity?: string;\n code?: string;\n detail?: string;\n where?: string;\n };\n const position =\n typeof errObj.position === \"string\"\n ? parseInt(errObj.position, 10)\n : typeof errObj.position === \"number\"\n ? errObj.position\n : NaN;\n\n logger.error(\n `[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? \"\"} severity=${errObj.severity ?? \"\"} message=${errObj.message ?? \"\"} sqlLength=${sql.length}`,\n );\n\n if (Number.isFinite(position) && position > 0) {\n const zeroBased = position - 1;\n const start = Math.max(0, zeroBased - 200);\n const end = Math.min(sql.length, zeroBased + 200);\n const before = sql.slice(start, zeroBased);\n const at = sql.slice(zeroBased, zeroBased + 1);\n const after = sql.slice(zeroBased + 1, end);\n logger.error(\n `[pglite-migration] SQL context around position ${position}:\\n${before}»${at}«${after}`,\n );\n } else {\n logger.error(\n `[pglite-migration] No position info. First 2000 chars of dump:\\n${sql.slice(0, 2000)}`,\n );\n }\n}\n\n/**\n * Migrate a filesystem PGLite data directory from a legacy PG major to the\n * current one. Renames the existing dir to a timestamped backup, dumps via the\n * matching legacy `pg_dump`, restores into a fresh current-version PGLite at\n * the original path. On failure, the original dir is restored from the backup.\n *\n * No-op when the dir is missing or already at the current major.\n */\nexport async function migratePgliteDir(\n dataDir: string,\n logger: ILogger,\n): Promise<void> {\n const major = await readPgVersionFile(dataDir);\n if (major === null) {\n logger.info(\n `[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`,\n );\n return;\n }\n if (major === CURRENT_PG_MAJOR) return;\n\n if (!isSupportedMajor(major)) {\n throw new Error(\n `Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`,\n );\n }\n\n const backupDir = backupPath(dataDir, major);\n logger.info(\n `[pglite-migration] Migrating ${dataDir} from PG${major} to PG${CURRENT_PG_MAJOR}; backup: ${backupDir}`,\n );\n\n await fs.rename(dataDir, backupDir);\n\n let sql: string;\n try {\n const [legacyMod, pgDump] = await Promise.all([\n loadPGliteModule(major as SupportedPgMajor),\n loadPgDump(major as SupportedPgMajor),\n ]);\n const LegacyPGlite = (legacyMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // pglite-tools 0.2.x talks to the server through files in the PGlite\n // FS, and 0.2.17's NODEFS write drops the view's byteOffset, so every\n // query arrives as zeros. Dump from an in-memory copy instead.\n const onDisk = new LegacyPGlite(backupDir);\n let tar: Blob;\n try {\n await onDisk.waitReady;\n tar = await onDisk.dumpDataDir(\"none\");\n } finally {\n await onDisk.close();\n }\n const pg = new LegacyPGlite({ loadDataDir: tar });\n try {\n await pg.waitReady;\n const file = await pgDump({ pg });\n sql = await file.text();\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n try {\n const currentMod = await loadPGliteModule(CURRENT_PG_MAJOR);\n const CurrentPGlite = (currentMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n // Stock NodeFS never syncs to the host; one pass after close does.\n const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });\n try {\n await pg.waitReady;\n try {\n await pg.exec(\"SET standard_conforming_strings = off;\");\n } catch (gucErr) {\n logger.warn(\n `[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`,\n );\n }\n try {\n await pg.exec(sql);\n } catch (execErr) {\n logRestoreFailure(dataDir, sql, execErr, logger);\n throw execErr;\n }\n } finally {\n await pg.close();\n }\n syncTree(dataDir);\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n logger.info(\n `[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`,\n );\n}\n\nasync function rollback(\n dataDir: string,\n backupDir: string,\n originalError: unknown,\n logger: ILogger,\n): Promise<void> {\n try {\n if (await pathExists(dataDir)) {\n await fs.rm(dataDir, { recursive: true, force: true });\n }\n if (await pathExists(backupDir)) {\n await fs.rename(backupDir, dataDir);\n }\n } catch (rollbackErr) {\n logger.error(\n `[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`,\n );\n return;\n }\n logger.error(\n `[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`,\n );\n}\n","import {\n preparePgliteDataDir,\n removeStalePgliteFiles,\n type ConversionDeps,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport { migratePgliteDir } from \"./pglite-migration.js\";\nimport {\n CURRENT_PG_MAJOR,\n openForVerify,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\nexport interface PglitePreflightOptions {\n /** Local PGlite data dirs; Postgres URLs are already filtered out. */\n dirs: string[];\n forcePgVersion?: SupportedPgMajor;\n migratePglite?: boolean;\n /** PH_PGLITE_IN_MEMORY: the dirs are never opened, so nothing is touched. */\n inMemory: boolean;\n logger: ILogger;\n /** Test hook; defaults to the module-matched stock NodeFS. */\n openForVerify?: ConversionDeps[\"openForVerify\"];\n}\n\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 10,\n retryDelay: 100,\n} as const;\n\n/**\n * Prepares every local PGlite dir before the first open and returns the\n * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot\n * runs for every dir, before the major is read, so a pure-snapshot PG16 dir\n * is converted and then migrated.\n */\nexport async function runPglitePreflight(\n options: PglitePreflightOptions,\n): Promise<Map<string, number>> {\n const { dirs, logger } = options;\n const detectedMajors = new Map<string, number>();\n if (options.inMemory || dirs.length === 0) return detectedMajors;\n\n if (options.forcePgVersion !== undefined) {\n if (options.migratePglite) {\n logger.warn(\n \"PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.\",\n );\n }\n logger.warn(\n `PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`,\n );\n for (const dir of dirs) {\n // Conversion siblings go too, or the next boot refuses to initdb beside them.\n for (const p of [dir, `${dir}.converting`, `${dir}.old`]) {\n await fs.rm(p, RM_OPTIONS);\n }\n logger.info(`Wiped PGLite data dir ${dir}`);\n }\n return detectedMajors;\n }\n\n const deps: ConversionDeps = {\n openForVerify: options.openForVerify ?? openForVerify,\n logger,\n };\n for (const dir of dirs) {\n await preparePgliteDataDir(dir, deps);\n const major = await readPgVersionFile(dir);\n if (major !== null) detectedMajors.set(dir, major);\n }\n\n if (options.migratePglite) {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n await migratePgliteDir(dir, logger);\n // The migration's own close leaves a lockfile in the new dir.\n await removeStalePgliteFiles(dir, logger);\n const after = await readPgVersionFile(dir);\n if (after !== null) detectedMajors.set(dir, after);\n }\n } else {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n logger.warn(\n `PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG${CURRENT_PG_MAJOR}. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`,\n );\n }\n }\n return detectedMajors;\n}\n","import type { PGliteOptions } from \"@electric-sql/pglite\";\nimport {\n createDurableNodeFs,\n PGLITE_UTC_PARSERS,\n pgliteWorkerEntryPath,\n DEFAULT_PGLITE_WORKER_MEMORY_MB,\n resolvePgliteMaintenance,\n ThreadedPGlite,\n type DurableNodeFs,\n type PGliteAbortListener,\n type PGliteExitListener,\n type PGliteLike,\n type PGliteParserPreset,\n type PgliteMaintenanceSettings,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport {\n startProgressHeartbeat,\n type HardenedPGliteDialectOptions,\n} from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\nimport {\n loadNodeFsClass,\n loadPGliteModule,\n pgliteModuleSpec,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype FatalProcess = Parameters<typeof triggerFatalShutdown>[2];\n\n// A Postgres PANIC (ENOSPC on WAL, a failed fdatasync) aborts the wasm\n// runtime; the store is dead and the process must not keep accepting writes.\nexport function onPgliteAbort(\n logger: ILogger,\n what: unknown,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite aborted\", what, proc)) {\n logger.error(\"PGlite aborted: @error\", what);\n }\n}\n\n/** A store's worker thread died: every later query would fail, so the process shuts down. */\nexport function onPgliteWorkerExit(\n logger: ILogger,\n error: Error,\n proc?: FatalProcess,\n): void {\n if (!triggerFatalShutdown(\"PGlite worker exited\", error, proc)) {\n logger.error(\"PGlite worker exited: @error\", error);\n }\n}\n\n/** The events a worker-backed store raises; {@link ThreadedPGlite} has them. */\nexport interface PgliteWorkerEvents {\n onAbort(listener: PGliteAbortListener): () => void;\n onExit(listener: PGliteExitListener): () => void;\n}\n\n/** Sends a worker's abort and its unexpected exit to the fatal shutdown. */\nexport function routePgliteWorkerFailures(\n store: PgliteWorkerEvents,\n logger: ILogger,\n proc?: FatalProcess,\n): void {\n store.onAbort((reason) => onPgliteAbort(logger, reason, proc));\n store.onExit((error) => {\n if (error !== null) onPgliteWorkerExit(logger, error, proc);\n });\n}\n\n/** A store whose thread can be stopped at once. */\nexport interface TerminableStore {\n terminate(): Promise<void>;\n}\n\n/**\n * Adds a terminate of the store's worker to the dialect's `onPoisoned`: a\n * statement that never settled holds the worker's only connection, and the\n * fatal shutdown's close would otherwise queue behind it until its grace ran\n * out.\n */\nexport function terminateOnPoisoned(\n options: Partial<HardenedPGliteDialectOptions>,\n store: TerminableStore,\n): Partial<HardenedPGliteDialectOptions> {\n const reportPoisoned = options.onPoisoned;\n return {\n ...options,\n onPoisoned: (cause) => {\n reportPoisoned?.(cause);\n void store.terminate();\n },\n };\n}\n\n// 0.2.17 syncs WAL through open_datasync, which NODEFS cannot honour, so on\n// PG16 only checkpoints reach the host disk; commits are durable against an\n// app crash, not a power loss, until --migrate-pglite upgrades the dir.\nfunction pgliteFsyncFor(\n wanted: boolean,\n major: SupportedPgMajor,\n dir: string,\n logger: ILogger,\n): boolean {\n if (wanted && major === 16) {\n logger.warn(\n `PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`,\n );\n }\n return wanted;\n}\n\n/** The VACUUM FULL settings from the environment; see `resolvePgliteMaintenance`. */\nexport const vacuumFullTimingFromEnv = resolvePgliteMaintenance;\n\n/** The VACUUM FULL settings a config asks for, with the env parser's rules. */\nexport function vacuumFullTimingOf(vacuumFull: {\n mode: \"off\" | \"quiet\" | \"forced\";\n aboveMb?: number;\n quietMs?: number;\n maxDeferMs?: number;\n}): PgliteMaintenanceSettings {\n return resolvePgliteMaintenance({\n PH_PGLITE_VACUUM_FULL: vacuumFull.mode,\n PH_PGLITE_VACUUM_FULL_ABOVE_MB: vacuumFull.aboveMb?.toString(),\n PH_PGLITE_VACUUM_FULL_QUIET_MS: vacuumFull.quietMs?.toString(),\n PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS: vacuumFull.maxDeferMs?.toString(),\n });\n}\n\n/** How each PGlite store runs; unset fields take the defaults. */\nexport interface PgliteStoreSettings {\n fsync?: boolean;\n maintenance?: PgliteMaintenanceSettings;\n workerMemoryMb?: number;\n}\n\nconst DEFAULT_MAINTENANCE: PgliteMaintenanceSettings = {\n vacuumFullAboveBytes: 0,\n};\n\n/** Preloads the module's NodeFS so the returned factory can be synchronous. */\nexport async function loadDurableFsFactory(\n major: SupportedPgMajor,\n logger: ILogger,\n proc?: FatalProcess,\n settings: PgliteStoreSettings = {},\n): Promise<(dir: string) => DurableNodeFs> {\n const NodeFS = await loadNodeFsClass(major);\n const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;\n return (dir) =>\n createDurableNodeFs(NodeFS, dir, {\n fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),\n ...timing,\n logger,\n onAbort: (what) => onPgliteAbort(logger, what, proc),\n });\n}\n\nexport type PgliteStoreLabel = \"reactor-storage\" | \"read-storage\";\n\nexport interface PgliteStoreOptions {\n label: PgliteStoreLabel;\n major: SupportedPgMajor;\n parsers: PGliteParserPreset;\n /** PH_PGLITE_IN_MEMORY: the store ignores its dir. */\n inMemory: boolean;\n /** Open the store in its own worker thread (PH_PGLITE_WORKERS / `pgliteWorkers`). */\n threaded: boolean;\n settings?: PgliteStoreSettings;\n logger: ILogger;\n /** Where fatal conditions go; the process by default. */\n proc?: FatalProcess;\n}\n\n/** Opens a store on a data dir; synchronous because reactor-api's read store opens synchronously. */\nexport type PgliteStoreFactory = (dataDir: string) => PGliteLike;\n\nexport const REACTOR_STORE = {\n label: \"reactor-storage\",\n parsers: \"none\",\n} as const;\n\nexport const READ_STORE = {\n label: \"read-storage\",\n parsers: \"utc-timestamps\",\n} as const;\n\n/** A host's two stores, opening side by side. */\nexport interface StoresOpening {\n reactor: PGliteLike;\n readModel: PGliteLike;\n /** Rejects with the first store's failure, once the other has closed. */\n failed: Promise<never>;\n close(): Promise<void>;\n}\n\n/**\n * Starts both stores at once, so the wait is the slower of the two rather than\n * their sum. A store left by a crash spends seconds recovering in its thread.\n * If one can't open, the other is closed, not left recovering for nobody.\n */\nexport function openStoresTogether(\n openReactor: () => PGliteLike,\n openReadModel: () => PGliteLike,\n): StoresOpening {\n const reactor = openReactor();\n let readModel: PGliteLike;\n try {\n readModel = openReadModel();\n } catch (error) {\n void reactor.close().catch(() => undefined);\n throw error;\n }\n const close = async () => {\n await Promise.allSettled([reactor.close(), readModel.close()]);\n };\n const stays = () => new Promise<never>(() => undefined);\n const failed = Promise.race([\n reactor.waitReady.then(stays),\n readModel.waitReady.then(stays),\n ]).catch(async (error: unknown) => {\n await close();\n throw error;\n });\n failed.catch(() => undefined);\n return { reactor, readModel, failed, close };\n}\n\n/**\n * The factory for one PGlite store: in a worker thread when `threaded` (and a\n * worker script exists here), else in the main thread as before. Either way\n * the store runs DurableNodeFs over its dir with the same fsync choice, and a\n * wasm abort takes the fatal shutdown.\n */\nexport async function createPgliteStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n if (options.threaded) {\n if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);\n options.logger.warn(\n `${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`,\n );\n }\n return mainThreadStoreFactory(options);\n}\n\nfunction threadedStoreFactory(options: PgliteStoreOptions): PgliteStoreFactory {\n const { label, major, parsers, inMemory, logger, proc } = options;\n const settings = options.settings ?? {};\n const memoryLimitMb =\n settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;\n const module = pgliteModuleSpec(major);\n return (dir) => {\n const store = new ThreadedPGlite({\n store: {\n label,\n dataDir: inMemory ? null : dir,\n module,\n durableFs: inMemory\n ? null\n : {\n fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),\n ...(settings.maintenance ?? DEFAULT_MAINTENANCE),\n },\n parsers,\n },\n memoryLimitMb,\n logger,\n });\n routePgliteWorkerFailures(store, logger, proc);\n logger.info(\n `${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`,\n );\n // Opening a large store (loading the data dir, a crash-recovery sweep)\n // can take a while before the first query answers: say so while it lasts.\n const opening = startProgressHeartbeat({\n logger,\n label: `${label}: opening the store`,\n });\n store.waitReady.then(\n () => opening.stop(),\n () => opening.stop(\"failed\"),\n );\n return store;\n };\n}\n\nasync function mainThreadStoreFactory(\n options: PgliteStoreOptions,\n): Promise<PgliteStoreFactory> {\n const { label, major, inMemory, logger, proc } = options;\n const { PGlite } = await loadPGliteModule(major);\n const durableFs = inMemory\n ? null\n : await loadDurableFsFactory(major, logger, proc, options.settings);\n const base: PGliteOptions =\n options.parsers === \"utc-timestamps\" ? { parsers: PGLITE_UTC_PARSERS } : {};\n return (dir) => {\n logger.info(\n `${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`,\n );\n return durableFs === null\n ? new PGlite(base)\n : new PGlite({ ...base, fs: durableFs(dir) });\n };\n}\n\nfunction where(inMemory: boolean, dir: string): string {\n return inMemory ? \", in memory [PH_PGLITE_IN_MEMORY=1]\" : ` at ${dir}`;\n}\n","import {\n DEFAULT_SIGNATURE_POLICY,\n isSignaturePolicy,\n type SignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\n/**\n * What new documents are created as, from CREATE_SIGNATURE_POLICY. Without a\n * signer this switchboard cannot write to a v2-required document, so it falls\n * back to legacy and says so.\n */\nexport function resolveCreateSignaturePolicy(\n env: NodeJS.ProcessEnv,\n options: SignerFallbackOptions,\n): SignaturePolicy {\n const raw = env.CREATE_SIGNATURE_POLICY?.trim();\n let policy: SignaturePolicy = DEFAULT_SIGNATURE_POLICY;\n if (raw) {\n if (!isSignaturePolicy(raw)) {\n throw new Error(\n `CREATE_SIGNATURE_POLICY must be \"legacy\" or \"v2-required\", got \"${raw}\"`,\n );\n }\n policy = raw;\n }\n return createSignaturePolicyFor(policy, options);\n}\n\ntype SignerFallbackOptions = {\n hasSigner: boolean;\n logger?: Pick<ILogger, \"warn\">;\n};\n\n/** The requested policy, or legacy when it needs a signer this switchboard lacks. */\nexport function createSignaturePolicyFor(\n policy: SignaturePolicy,\n options: SignerFallbackOptions,\n): SignaturePolicy {\n if (policy === \"v2-required\" && !options.hasSigner) {\n options.logger?.warn(\n \"No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.\",\n );\n return \"legacy\";\n }\n return policy;\n}\n","import type { FactorySpec, SignerConfig } from \"@powerhousedao/reactor\";\nimport {\n createRenownTrustPolicy,\n DEFAULT_KEYPAIR_PATH,\n DEFAULT_RENOWN_URL,\n NodeKeyStorage,\n RenownBuilder,\n RenownCryptoBuilder,\n resolveSwitchboardEndpoint,\n type IRenown,\n type RenownTrustPolicyOptions,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { childLogger } from \"document-model\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\n\nconst logger = childLogger([\"switchboard\", \"renown\"]);\n\nexport interface RenownOptions {\n /** Path to the keypair file. Defaults to .ph/.keypair.json in cwd */\n keypairPath?: string;\n /** If true, won't generate a new keypair if none exists */\n requireExisting?: boolean;\n /** Base url of the Renown instance to use */\n baseUrl?: string;\n /** Renown user storage; defaults to .ph/.renown.json under `userDataDir`, else renown's own default. */\n storagePath?: string;\n /** The relocated `.ph` root (PH_USER_DATA_DIR at the edge). */\n userDataDir?: string;\n}\n\n/**\n * Initialize Renown for the Switchboard instance.\n * This allows Switchboard to authenticate with remote services\n * using the same identity established during `ph login`.\n */\nexport async function initRenown(\n options: RenownOptions = {},\n): Promise<IRenown | null> {\n const {\n keypairPath,\n requireExisting = false,\n baseUrl = DEFAULT_RENOWN_URL,\n userDataDir,\n storagePath = userDataDir\n ? join(\n resolvePhDir(undefined, { PH_USER_DATA_DIR: userDataDir }),\n \".renown.json\",\n )\n : undefined,\n } = options;\n\n const keyStorage = new NodeKeyStorage(keypairPath, {\n logger,\n });\n\n // Check if we have an existing keypair\n const existingKeyPair = await keyStorage.loadKeyPair();\n\n if (!existingKeyPair && requireExisting) {\n throw new Error(\n \"No existing keypair found and requireExisting is true. \" +\n 'Run \"ph login\" to create one.',\n );\n }\n\n if (!existingKeyPair) {\n logger.info(\"No existing keypair found. A new one will be generated.\");\n }\n\n const renownCrypto = await new RenownCryptoBuilder()\n .withKeyPairStorage(keyStorage)\n .build();\n\n // keyPath too: the builder's default key storage mkdirs <cwd>/.ph.\n const renown = await new RenownBuilder(\"switchboard\", {\n ...(storagePath ? { storagePath } : {}),\n ...(keypairPath ? { keyPath: keypairPath } : {}),\n })\n .withCrypto(renownCrypto)\n .withBaseUrl(baseUrl)\n .build();\n\n logger.info(\"Switchboard identity initialized: @did\", renownCrypto.did);\n\n return renown;\n}\n\n/**\n * Get the signer config for the given renown instance.\n *\n * @param renown - The renown instance\n * @param keypairPath - Where `initRenown` loaded the key from\n */\nexport function getRenownSignerConfig(\n renown: IRenown,\n keypairPath?: string,\n): SignerConfig {\n return {\n signer: renown.signer,\n workerSigner: getRenownWorkerSignerSpec(renown, keypairPath),\n };\n}\n\n/**\n * What a pooled executor worker imports to sign as this switchboard: it\n * reloads the key `initRenown` stored, and takes the user known at boot.\n */\nexport function getRenownWorkerSignerSpec(\n renown: IRenown,\n keypairPath?: string,\n): FactorySpec {\n const { signer } = renown;\n const user = signer.user;\n return {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createNodeRenownSigner\",\n },\n initArgs: {\n appName: signer.app?.name ?? \"switchboard\",\n keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),\n ...(signer.app?.key ? { did: signer.app.key } : {}),\n ...(user\n ? {\n user: {\n address: user.address,\n networkId: user.networkId,\n chainId: user.chainId,\n },\n }\n : {}),\n },\n };\n}\n\n/**\n * What a host with `authEnforcement` off installs: a delegated signer is\n * verified from what it carries, and every other signer is accepted as the\n * default would. No lookup, so it needs no network, at boot or after.\n */\nexport function getDelegationTrustPolicyConfig(\n renown: IRenown | null,\n): Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\"> {\n const ownSigner = renown?.signer;\n const self = ownIdentity(renown);\n return {\n trustPolicy: createRenownTrustPolicy({ delegationOnly: true, ownSigner }),\n workerTrustPolicy: {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createRenownTrustPolicy\",\n },\n initArgs: { delegationOnly: true, ...(self ? { self } : {}) },\n },\n };\n}\n\n/** Where switchboard reads the credentials binding keys to wallets. */\nexport type RenownTrustSource =\n | { source: \"remote\"; renownUrl?: string; switchboardUrl?: string }\n | { source: \"self\"; request: SwitchboardRequestFn };\n\n/**\n * Admits a key as a signer for an address a Renown credential binds it to; a\n * `self` source has no worker spec. In process, the switchboard's own key is\n * matched against its current user; the worker spec carries the user known now.\n */\nexport async function getRenownTrustPolicyConfig(\n trustSource: RenownTrustSource,\n renown: IRenown | null,\n): Promise<Pick<SignerConfig, \"trustPolicy\" | \"workerTrustPolicy\">> {\n const ownSigner = renown?.signer;\n if (trustSource.source === \"self\") {\n return {\n trustPolicy: createRenownTrustPolicy({\n switchboard: trustSource.request,\n ownSigner,\n }),\n };\n }\n\n const switchboardUrl = await resolveSwitchboardEndpoint({\n switchboardUrl: trustSource.switchboardUrl,\n baseUrl: trustSource.renownUrl,\n });\n const options = {\n ...(switchboardUrl ? { switchboard: switchboardUrl } : {}),\n ...(trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}),\n } satisfies RenownTrustPolicyOptions;\n const self = ownIdentity(renown);\n return {\n trustPolicy: createRenownTrustPolicy({ ...options, ownSigner }),\n workerTrustPolicy: {\n module: {\n filePath: createRequire(import.meta.url).resolve(\"@renown/sdk/node\"),\n exportName: \"createRenownTrustPolicy\",\n },\n initArgs: { ...options, ...(self ? { self } : {}) },\n },\n };\n}\n\nfunction ownIdentity(\n renown: IRenown | null,\n): RenownTrustPolicyOptions[\"self\"] | undefined {\n const key = renown?.signer.app?.key;\n if (!key) {\n return undefined;\n }\n const user = renown.signer.user;\n return {\n key,\n user: {\n address: user?.address ?? \"\",\n networkId: user?.networkId ?? \"\",\n chainId: user?.chainId ?? 0,\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * One process per PGlite store. PGlite is an in-process Postgres with no\n * postmaster to arbitrate: two processes opening the same data dir are two\n * writers on one PGDATA, which tears the store (it then aborts at the next\n * checkpoint or refuses to reopen). Hosts share one `.ph` tree by design\n * (`ph run vetra`, `ph run cli`, `ph run desktop`, classic `ph vetra` /\n * `ph switchboard` all use `.ph/reactor-storage` + `.ph/read-storage`), and the\n * per-host run records cannot see each other — so the guard lives here,\n * below every host: the switchboard takes a lock per store dir before\n * opening it.\n *\n * The lock is a SIBLING file (`<dir>.lock`), not a file inside the data dir:\n * initdb refuses a non-empty directory. A lock whose owner is dead (a\n * hard-killed process) is stale and taken over; the owner releases it on\n * exit. The same process may re-acquire its own lock (in-process restarts).\n */\nexport interface StoreLockOwner {\n pid: number;\n startedAt: string;\n command: string;\n}\n\nexport class StoreInUseError extends Error {\n constructor(\n readonly dir: string,\n readonly owner: StoreLockOwner,\n ) {\n super(\n `The PGlite store ${dir} is in use by another process (pid ${owner.pid}, since ${owner.startedAt}: ${owner.command}). ` +\n \"Two processes on one PGlite store corrupt it. Stop that process first, or point this one at a different store.\",\n );\n this.name = \"StoreInUseError\";\n }\n}\n\nconst lockPathOf = (dir: string) => `${path.resolve(dir)}.lock`;\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nfunction readOwner(file: string): StoreLockOwner | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as StoreLockOwner;\n } catch {\n return undefined;\n }\n}\n\nconst held = new Set<string>();\nlet exitHookInstalled = false;\n\nfunction releaseAll(): void {\n for (const file of held) {\n const owner = readOwner(file);\n if (owner?.pid === process.pid) {\n try {\n fs.rmSync(file);\n } catch {\n // already gone\n }\n }\n }\n held.clear();\n}\n\n/** Take the lock for each store dir, or throw StoreInUseError naming the\n * live owner. Idempotent within one process. */\nexport function acquireStoreLocks(\n dirs: readonly string[],\n isPidAlive: (pid: number) => boolean = isAlive,\n): void {\n const mine: StoreLockOwner = {\n pid: process.pid,\n startedAt: new Date().toISOString(),\n command: process.argv.slice(1).join(\" \").slice(0, 200),\n };\n for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {\n const file = lockPathOf(dir);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const owner = readOwner(file);\n if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) {\n throw new StoreInUseError(dir, owner);\n }\n // free, stale (dead owner) or already ours: write our claim\n fs.writeFileSync(file, `${JSON.stringify(mine)}\\n`);\n held.add(file);\n }\n if (!exitHookInstalled) {\n exitHookInstalled = true;\n process.on(\"exit\", releaseAll);\n }\n}\n\n/** Release this process's store locks (tests; orderly shutdown). */\nexport function releaseStoreLocks(): void {\n releaseAll();\n}\n","#!/usr/bin/env node\nimport { metrics, trace } from \"@opentelemetry/api\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { ReactorInstrumentation } from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport {\n CatchUpPriority,\n computeProcessorTiming,\n DriveCollectionId,\n EventBus,\n IN_MEMORY_PGLITE_STORAGE_FACTS,\n PGLITE_PATH_STORAGE_FACTS,\n POSTGRES_STORAGE_FACTS,\n REACTOR_SCHEMA,\n ReactorBuilder,\n ReactorClientBuilder,\n createHybridProjectionCoordinatorFactory,\n instrumentPgPool,\n MemoryTelemetry,\n parseDriveUrl,\n ProcessorTimingSettings,\n parseKeyframeSettings,\n type Database,\n type InProcessReactorClientModule,\n type InProcessReactorModule,\n type IStoreMaintenance,\n type JwtHandler,\n type KeyframeSettings,\n type PoolInstrumentation,\n type ReactorStorageFacts,\n UnsupportedStoredProtocolError,\n withProgressHeartbeat,\n} from \"@powerhousedao/reactor\";\nimport {\n createHeapSnapshotWriter,\n HttpPackageLoader,\n ImportPackageLoader,\n memoryFileSink,\n NodeMemorySampler,\n PackageManagementService,\n PackagesSubgraph,\n initializeAndStartAPI,\n NodeEventLoopDelay,\n RequestLoadRecorder,\n reportFailure,\n resolveRenownConfig,\n runDetached,\n telemetryDir,\n type CanonicalDocumentId,\n type ClientInitializerDependencies,\n type CredentialVerifier,\n type DocumentPermissionDatabase,\n type IPackageLoader,\n type PgliteFactory,\n type ResolvedRenownConfig,\n} from \"@powerhousedao/reactor-api\";\nimport { httpsHooksPath } from \"@powerhousedao/reactor-api/https-hooks\";\nimport {\n disableWasmWrapperTiering,\n maintenanceOf,\n pgliteWorkerEntryPath,\n ThreadedPGlite,\n type PGliteLike,\n} from \"@powerhousedao/reactor-api/pglite-node\";\nimport type { VitePackageLoader } from \"@powerhousedao/reactor-api/vite\";\nimport { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport {\n createReactorDriveWriteStrategy,\n DriveNodeView,\n NodeProcessor,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n ReactorDriveClient,\n type ReactorDriveDatabase,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n createReactorDriveResolvers,\n REACTOR_DRIVE_SUBGRAPH_NAME,\n reactorDriveSubgraphTypeDefs,\n} from \"@powerhousedao/reactor-drive/subgraph\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n createLocalCredentialVerifier,\n RENOWN_READ_MODEL_SUBGRAPH,\n type CredentialCheck,\n type IRenown,\n type SwitchboardRequestFn,\n} from \"@renown/sdk/node\";\nimport { childLogger, setLogLevel, type ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\nimport { Kysely, PostgresDialect } from \"kysely\";\nimport { backfillPermissionTables } from \"./permissions-backfill.mjs\";\nimport { register } from \"node:module\";\nimport type http from \"node:http\";\nimport net from \"node:net\";\nimport path from \"path\";\nimport { Pool } from \"pg\";\nimport type { ViteDevServer } from \"vite\";\nimport { registerAttachmentRoutes } from \"./attachments/index.js\";\nimport {\n parseOAuthApps,\n type OAuthAppConfig,\n} from \"./workflow/oauth-apps-config.js\";\nimport {\n registerAttachmentReferenceReadModel,\n registerAttachmentReferenceReadModelOnModule,\n} from \"./attachment-reference-read-model.mjs\";\nimport { installFatalErrorShutdown, raiseSigterm } from \"./fatal-shutdown.mjs\";\nimport {\n resolvePrivacy,\n startPrivacy,\n type ResolvedPrivacy,\n type RunningPrivacy,\n} from \"./privacy.mjs\";\nimport { applySwitchboardReactorDefaults } from \"./builder-defaults.mjs\";\nimport {\n createSwitchboardPluginHost,\n type SwitchboardPluginHost,\n} from \"./plugin-host.mjs\";\nimport {\n assertProjectionWorkerSupported,\n resolveProjectionWorkerOptions,\n} from \"./projection-worker.mjs\";\nimport {\n buildWorkerDbConfig,\n keepImportableSources,\n resolveWorkerModelSources,\n resolveWorkerPoolOptions,\n} from \"./worker-pool.mjs\";\nimport { initProfilerFromEnv } from \"./profiler.js\";\nimport { switchboardConfigFromEnv } from \"./config/from-env.js\";\nimport { startProcessorTimingLog } from \"./processor-timing-log.mjs\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigSchema,\n type SwitchboardConfig,\n type SwitchboardConfigInput,\n} from \"./config/schema.js\";\nimport {\n WORKFLOW_PACKAGE_NAME,\n WORKFLOW_TELEMETRY_SCOPE,\n composeWorkflowRuntime,\n modelManifestSource,\n assertWorkflowPackageLoadable,\n isWorkflowSingletonConflict,\n retryWorkflowSingleton,\n workflowSingletonLossHandler,\n type WorkflowSingletonRetry,\n type ComposedWorkflowRuntime,\n type ModelManifestSource,\n} from \"./workflow-runtime.mjs\";\nimport {\n ClosablePGliteDialect,\n reactorPgliteDialectOptions,\n} from \"./pglite-dialect.js\";\nimport { runPglitePreflight } from \"./pglite-preflight.js\";\nimport {\n createPgliteStoreFactory,\n openStoresTogether,\n READ_STORE,\n REACTOR_STORE,\n terminateOnPoisoned,\n vacuumFullTimingOf,\n type PgliteStoreSettings,\n type StoresOpening,\n} from \"./pglite-store.mjs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\nimport { reactorFeatureFlagsOf } from \"./reactor-feature-flags.mjs\";\nimport { createSignaturePolicyFor } from \"./create-signature-policy.mjs\";\nimport { workerPoolIssues } from \"./boot-preconditions.mjs\";\nimport { renownLayers } from \"./renown-layers.mjs\";\nimport {\n getDelegationTrustPolicyConfig,\n getRenownSignerConfig,\n getRenownTrustPolicyConfig,\n initRenown,\n} from \"./renown.js\";\nimport type {\n StartServerOptions,\n SwitchboardDeps,\n SwitchboardReactor,\n} from \"./types.js\";\nimport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\nimport { ensureDrive, isPostgresUrl } from \"./utils.mjs\";\nimport { acquireStoreLocks } from \"./store-lock.mjs\";\nimport {\n defaultStoreDirs,\n resolvePhDir,\n} from \"@powerhousedao/shared/clis/ph-dir\";\nimport { isDotenvDisabled } from \"@powerhousedao/shared/clis/project-env\";\n\nconst defaultLogger = childLogger([\"switchboard\"]);\n\n// Edges map process.env after importing this, so the cwd .env is in it by then.\nif (!isDotenvDisabled()) dotenv.config();\n\n/** Process-wide settings an edge applies once, before its first `startSwitchboard`. */\nexport function initSwitchboardProcess(\n options: Pick<SwitchboardConfigInput, \"logLevel\"> = {},\n): void {\n setLogLevel(options.logLevel ?? \"info\");\n}\n\n// Module hooks are process-wide; registering them per server would stack them.\nlet httpsHooksRegistered = false;\nfunction registerHttpsHooks(): void {\n if (httpsHooksRegistered) return;\n httpsHooksRegistered = true;\n register(httpsHooksPath, import.meta.url);\n}\n\n// How many ports forward from the requested one we will try before giving up.\nconst PORT_FALLBACK_ATTEMPTS = 20;\n\n// Retired with the snapshot store; PGlite writes through NodeFS now.\nlet flushIntervalWarned = false;\nfunction warnIgnoredFlushInterval(logger: ILogger): void {\n if (flushIntervalWarned) return;\n if (process.env.PGLITE_FLUSH_INTERVAL_MS === undefined) return;\n flushIntervalWarned = true;\n logger.warn(\n \"PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.\",\n );\n}\n\n/**\n * Attempt to bind a throwaway TCP server to the given port. Resolves true if\n * the port is free, false if the OS reports it in use. Any other error is\n * surfaced so we don't silently mask real issues (permissions, bad host, …).\n */\nexport async function isPortAvailable(port: number): Promise<boolean> {\n try {\n // `::` is dual-stack on most systems, so it sees IPv6 and IPv4 listeners.\n return await probePort(port, \"::\");\n } catch (error) {\n // A host without IPv6, e.g. a container, can only probe IPv4.\n if (!isNoIpv6Error(error)) throw portProbeError(port, error);\n try {\n return await probePort(port, \"0.0.0.0\");\n } catch (ipv4Error) {\n throw portProbeError(port, ipv4Error);\n }\n }\n}\n\nconst isNoIpv6Error = (error: unknown) =>\n [\"EAFNOSUPPORT\", \"EADDRNOTAVAIL\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n );\n\nconst portProbeError = (port: number, error: unknown) =>\n new Error(\n `Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n\nfunction probePort(port: number, host: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const tester = net.createServer();\n tester.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" || err.code === \"EACCES\") {\n resolve(false);\n } else {\n reject(err);\n }\n });\n tester.once(\"listening\", () => {\n tester.close(() => resolve(true));\n });\n tester.listen({ port, host });\n });\n}\n\n/** The powerhouse.config.json this run reads, defaulting to the cwd copy. */\nfunction resolveConfigPath(configFile: string | undefined): string {\n return configFile ?? path.join(process.cwd(), \"powerhouse.config.json\");\n}\n\n/**\n * The config file's `workflows.oauthApps`, client file paths made absolute\n * from the config file's folder. An unreadable file or a malformed entry\n * means none: a missing app is reported when a sign-in asks for it.\n */\nfunction readConfigOAuthApps(\n configPath: string,\n logger: ILogger,\n): OAuthAppConfig[] {\n let raw: unknown;\n try {\n raw = (getConfig(configPath) as { workflows?: { oauthApps?: unknown } })\n .workflows?.oauthApps;\n } catch {\n return [];\n }\n return parseOAuthApps(\n raw,\n path.dirname(path.resolve(configPath)),\n (id, relay) =>\n logger.warn(\n `workflows.oauthApps \"${id}\": relay ${JSON.stringify(relay)} is not an object with clientId, redirectUri and tokenUrl; ignored`,\n ),\n );\n}\n\n// An unreadable config file means \"not configured\", not a boot failure:\n// workflows are opt-in.\n/** `PH_KEYFRAMES` (or a caller's layer) wins whole over the project config. */\nexport function resolveKeyframes(\n configured: SwitchboardConfig[\"storage\"][\"keyframes\"],\n fromFile: unknown,\n configPath: string,\n): KeyframeSettings | undefined {\n if (configured) return configured;\n return fromFile === undefined\n ? undefined\n : parseKeyframeSettings(fromFile, `${configPath} reactor.keyframes`);\n}\n\nfunction readConfigWorkflowsEnabled(configPath: string): boolean {\n try {\n return getConfig(configPath).workflows?.enabled ?? false;\n } catch {\n return false;\n }\n}\n\nasync function resolveServerPort(\n requested: number,\n strictPort: boolean,\n logger: ILogger,\n): Promise<number> {\n // 0 asks the OS for a free port at bind time: nothing to probe.\n if (requested === 0 || strictPort) return requested;\n for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {\n const candidate = requested + i;\n if (await isPortAvailable(candidate)) {\n if (candidate !== requested) {\n logger.info(\n `Port ${requested} is in use. Falling back to port ${candidate}.`,\n );\n }\n return candidate;\n }\n }\n // Couldn't find a free port in the window; let the caller surface the\n // original EADDRINUSE when the real bind attempts runs.\n return requested;\n}\n\n/**\n * The reactor's storage handle, plus the pool instrumentation when that\n * storage is Postgres. The PGlite branch has no `pg.Pool` at all, so the\n * instrumentation is absent rather than optional-by-convention.\n */\ntype ReactorStorage = {\n kysely: Kysely<Database>;\n poolInstrumentation: PoolInstrumentation | undefined;\n storageFacts: ReactorStorageFacts;\n /** Absent on Postgres, where the host does not own the connection. */\n storeMaintenance?: IStoreMaintenance;\n};\n\nexport async function createReactorKysely(opts: {\n reactorDbUrl: string | undefined;\n reactorPgliteDir: string | null;\n reactorPgliteMajor: SupportedPgMajor | null;\n inMemory: boolean;\n /** Called only on the Postgres branch, the one with a host pool. */\n hostPoolSize: () => number;\n /** Open the PGlite store in its own worker thread. */\n pgliteWorkers: boolean;\n pgliteSettings?: PgliteStoreSettings;\n /** The store, when it's already opening. */\n openingStore?: PGliteLike;\n logger: ILogger;\n}): Promise<ReactorStorage> {\n const {\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n hostPoolSize,\n pgliteWorkers,\n pgliteSettings,\n openingStore,\n logger,\n } = opts;\n\n if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {\n const connectionString = reactorDbUrl.includes(\"?\")\n ? reactorDbUrl\n : `${reactorDbUrl}?sslmode=disable`;\n const poolSize = hostPoolSize();\n const pool = new Pool({ connectionString, max: poolSize });\n // Named to match the reactor's own convention for the pools it opens\n // itself (`reactor-worker-N`, `projection-shard-N`).\n const poolInstrumentation = instrumentPgPool(pool, \"reactor-host\");\n logger.info(\n `Using PostgreSQL for reactor storage (host pool max ${poolSize})`,\n );\n return {\n kysely: new Kysely<Database>({ dialect: new PostgresDialect({ pool }) }),\n poolInstrumentation,\n storageFacts: POSTGRES_STORAGE_FACTS,\n };\n }\n\n if (!reactorPgliteDir || reactorPgliteMajor === null) {\n throw new Error(\"Reactor PGLite directory not resolved\");\n }\n const pglite =\n openingStore ??\n (\n await createPgliteStoreFactory({\n ...REACTOR_STORE,\n major: reactorPgliteMajor,\n inMemory,\n threaded: pgliteWorkers,\n settings: pgliteSettings,\n logger,\n })\n )(reactorPgliteDir);\n const dialectOptions =\n pglite instanceof ThreadedPGlite\n ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite)\n : reactorPgliteDialectOptions(logger);\n return {\n kysely: new Kysely<Database>({\n dialect: new ClosablePGliteDialect(pglite, dialectOptions),\n }),\n poolInstrumentation: undefined,\n storageFacts: inMemory\n ? IN_MEMORY_PGLITE_STORAGE_FACTS\n : PGLITE_PATH_STORAGE_FACTS,\n storeMaintenance:\n pglite instanceof ThreadedPGlite\n ? pglite\n : maintenanceOf(pglite as { fs?: unknown }),\n };\n}\n\nexport interface PgliteStorageDirs {\n /** Read-model store: a Postgres URL or a PGlite dir. */\n readModelPath: string;\n /** Reactor store: a Postgres URL or a PGlite dir. */\n reactorPath: string;\n /** PGlite dir for the reactor, null for Postgres or a caller-owned reactor. */\n reactorPgliteDir: string | null;\n /** PGlite dir for the read model, null for Postgres. */\n readModelPgliteDir: string | null;\n /** The PGlite dirs for the pre-flight, as before (not deduplicated). */\n pgliteDirs: string[];\n /** Set when BOTH stores are PGlite on one dir (see resolvePgliteStorageDirs). */\n sharedPgliteDir: string | null;\n}\n\n/**\n * Where the two stores live — the classic resolution, relocated verbatim.\n * Classic layout: `./.ph/reactor-storage` for the reactor and\n * `.ph/read-storage` for the read model (the same names inside\n * `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names\n * the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone\n * both stores share one location. That is the long-standing contract of\n * `--db-path` and fine for one Postgres database, but for PGlite it is two\n * postmasters on one data dir — reported via `sharedPgliteDir` so the caller\n * warns. Not refused: changing that contract is a separate decision.\n */\nexport function resolvePgliteStorageDirs(opts: {\n dbPath: string | undefined;\n reactorDbUrl: string | undefined;\n /** The caller passed its own reactor — the reactor-side dir is unused. */\n callerReactor: boolean;\n /** The relocated `.ph` root (PH_USER_DATA_DIR at the edge). */\n userDataDir?: string;\n phDir?: string;\n}): PgliteStorageDirs {\n const { dbPath, reactorDbUrl, callerReactor } = opts;\n const defaults = defaultStoreDirs(\n { PH_USER_DATA_DIR: opts.userDataDir },\n opts.phDir,\n );\n const readModelPath = dbPath || defaults.readModel;\n const reactorPath = reactorDbUrl || defaults.reactor;\n const reactorPgliteDir = callerReactor\n ? null\n : !reactorDbUrl || !isPostgresUrl(reactorDbUrl)\n ? reactorPath\n : null;\n const readModelPgliteDir =\n !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;\n const sharedPgliteDir =\n reactorPgliteDir !== null &&\n readModelPgliteDir !== null &&\n path.resolve(reactorPgliteDir) === path.resolve(readModelPgliteDir)\n ? path.resolve(reactorPgliteDir)\n : null;\n const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter(\n (d): d is string => d !== null,\n );\n return {\n readModelPath,\n reactorPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n };\n}\n\n/** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */\nexport function deriveAttachmentServiceConfig(\n options: Pick<StartServerOptions, \"attachmentServiceUrl\" | \"https\">,\n serverPort: number,\n renown: IRenown | null,\n): { remoteUrl: string; jwtHandler: JwtHandler | undefined } {\n const protocol = options.https ? \"https\" : \"http\";\n const remoteUrl =\n options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`;\n const jwtHandler: JwtHandler | undefined = renown\n ? async (url: string) =>\n renown.user\n ? renown.getBearerToken({ expiresIn: 10, aud: url })\n : undefined\n : undefined;\n return { remoteUrl, jwtHandler };\n}\n\n/** Sentry starts only under SENTRY_DSN (observability.mts), and is a lot to load. */\nasync function captureInSentry(error: unknown): Promise<void> {\n if (!process.env.SENTRY_DSN) return;\n const Sentry = await import(\"@sentry/node\");\n Sentry.captureException(error);\n}\n\nasync function initServer(\n requestedPort: number,\n options: StartServerOptions,\n config: SwitchboardConfig,\n renown: IRenown | null,\n renownConfig: ResolvedRenownConfig,\n reportError: (error: unknown) => void,\n /** Filled in once the stores start, for a boot that fails after that. */\n opening: { stores?: StoresOpening },\n) {\n const {\n dev,\n packages = [],\n remoteDrives = [],\n logger = defaultLogger,\n } = options;\n\n // R2 plugin pipeline (FEATURE_PLUGIN_HOST_ENABLED): flag off, the inline\n // path below runs byte-identically; flag on, carved subsystems run as\n // built-in plugins through the hook moments marked along this function.\n const pluginHost: SwitchboardPluginHost | null = config.features.pluginHost\n ? createSwitchboardPluginHost(\n {\n logger,\n options: options as unknown as Record<string, unknown>,\n config,\n renown,\n },\n options.pluginComposition,\n )\n : null;\n if (pluginHost) {\n options = await pluginHost.transformOptions(options);\n // Presence is activation: whatever no plugin (or explicit option) set\n // stays OFF. The mcp/workflows plugins set these true at\n // transformServerOptions; their absence must actually deactivate.\n options.mcp ??= false;\n options.workflows = {\n ...options.workflows,\n enabled: options.workflows?.enabled === true,\n };\n }\n logger.level = config.logLevel;\n const dbPath = config.storage.readModel.url;\n const reactorDbUrl = config.storage.reactor.url;\n const inMemory = config.storage.inMemory;\n const pgliteSettings: PgliteStoreSettings = {\n fsync: config.storage.pglite.fsync,\n maintenance: vacuumFullTimingOf(config.storage.pglite.vacuumFull),\n workerMemoryMb: config.storage.pglite.workerMemoryMb,\n };\n // Postgres URLs or local PGlite dirs under the project's .ph tree. When\n // the caller passes in a reactor, the reactor-side PGLite dir is unused —\n // the caller owns its own storage. Only the read-model dir is still needed\n // by reactor-api itself. Refuses one PGlite dir for both stores.\n const {\n readModelPath,\n reactorPgliteDir,\n readModelPgliteDir,\n pgliteDirs,\n sharedPgliteDir,\n } = resolvePgliteStorageDirs({\n dbPath,\n reactorDbUrl,\n callerReactor: options.reactor !== undefined,\n userDataDir: config.storage.userDataDir,\n });\n if (sharedPgliteDir !== null) {\n logger.warn(\n `The reactor and read-model PGlite stores share one directory (${sharedPgliteDir}): ` +\n \"two PGlite instances on one data dir can abort at the first checkpoint and leave the store unopenable. \" +\n \"Set PH_REACTOR_DATABASE_URL to a separate directory, or leave dbPath unset for the classic \" +\n \"./.ph/reactor-storage + .ph/read-storage layout.\",\n );\n }\n\n // PGLite pre-flight: convert legacy single-file snapshot stores, clear\n // stale lock and WAL temp files, then detect PG_VERSION and migrate or\n // warn. Under PH_FORCE_PG_VERSION the dirs are wiped instead.\n // One process per PGlite store, before anything (the pre-flight included)\n // touches it: hosts share one .ph tree, so a second `ph run …` / `ph vetra`\n // in the same project must fail here instead of tearing the store.\n if (!inMemory) acquireStoreLocks(pgliteDirs);\n warnIgnoredFlushInterval(logger);\n const detectedMajors = await runPglitePreflight({\n dirs: pgliteDirs,\n forcePgVersion: options.forcePgVersion,\n migratePglite: options.migratePglite,\n inMemory,\n logger,\n });\n\n function resolvePgliteMajorForDir(dir: string): SupportedPgMajor {\n if (options.forcePgVersion !== undefined) return options.forcePgVersion;\n const detected = detectedMajors.get(dir);\n if (detected === undefined) return CURRENT_PG_MAJOR;\n if (!isSupportedMajor(detected)) {\n throw new Error(\n `Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`,\n );\n }\n return detected;\n }\n\n const reactorPgliteMajor = reactorPgliteDir\n ? resolvePgliteMajorForDir(reactorPgliteDir)\n : null;\n const readModelPgliteMajor = readModelPgliteDir\n ? resolvePgliteMajorForDir(readModelPgliteDir)\n : null;\n\n const inspectionThrottle =\n config.inspection.callsPerMinute === undefined\n ? {}\n : { callsPerMinute: config.inspection.callsPerMinute };\n // The env is empty: the edges mapped it into the config.\n let workerPool = resolveWorkerPoolOptions(options.workerPool, {});\n if (workerPool && options.reactor) {\n logger.warn(\n \"Worker pool configuration ignored: the caller-provided reactor owns its own executor\",\n );\n workerPool = null;\n }\n if (workerPool) {\n const issue = workerPoolIssues({\n dev: dev === true,\n workers: workerPool.numWorkers,\n projectionWorker: false,\n reactorDbUrl,\n authEnforcement: config.protocol.featureFlags.authEnforcement,\n renownSource: renownConfig.source,\n }).at(0);\n if (issue) throw new Error(issue);\n }\n\n const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(\n options.unsupportedStoredDocuments,\n {},\n );\n\n let projectionWorker = resolveProjectionWorkerOptions(\n options.projectionWorker,\n {},\n );\n if (projectionWorker && options.reactor) {\n logger.warn(\n \"Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator\",\n );\n projectionWorker = null;\n }\n if (projectionWorker) {\n assertProjectionWorkerSupported({ dev: dev === true, reactorDbUrl });\n }\n\n // The reactor-api owns its own PGlite/HTTP/WS resources but has no shutdown\n // path of its own; we register `api.dispose` as a reactor shutdown hook so\n // those resources drain inside the reactor's SIGINT chain. The reference\n // is forward — `initializeClient` runs (and registers the hook) before\n // `initializeAndStartAPI` returns the api — so the closure reads `apiRef`\n // at hook-fire time, not at registration time.\n const apiRef: { current: { dispose: () => Promise<void> } | undefined } = {\n current: undefined,\n };\n let driveNodeView: DriveNodeView | undefined;\n\n // HTTP registry package loading\n const configPath = resolveConfigPath(options.configFile);\n const fileConfig = getConfig(configPath);\n const registryUrl = options.registryUrl ?? fileConfig.packageRegistryUrl;\n const registryPackages = config.packages.registryPackages;\n const dynamicModelLoading = options.dynamicModelLoading === true;\n let httpLoader: HttpPackageLoader | undefined;\n\n if (registryUrl) {\n // Register HTTP/HTTPS module loader hooks for dynamic package imports\n registerHttpsHooks();\n httpLoader = new HttpPackageLoader({\n registryUrl,\n cacheDir: path.join(\n resolvePhDir(undefined, {\n PH_USER_DATA_DIR: config.storage.userDataDir,\n }),\n \"registry-packages\",\n ),\n });\n for (const name of registryPackages) {\n if (!packages.includes(name)) {\n packages.push(name);\n }\n }\n }\n\n // Registry packages import from the on-disk cache, which workers can read.\n const registryPackageNames = new Set(registryPackages.filter(Boolean));\n const resolveRegistryModels = async (\n identifier: string,\n ): Promise<string | null> =>\n httpLoader && registryPackageNames.has(identifier)\n ? ((await httpLoader.cachePackage(identifier)).entries.documentModels ??\n null)\n : null;\n\n const reactorLogger = logger.child([\"reactor\"]);\n // Latched: dropWriteReady reports the fatal once per dropped job.\n let projectionWorkerFatalFired = false;\n const onProjectionWorkerFatal = (shardId: string, reason: Error) => {\n if (projectionWorkerFatalFired) {\n return;\n }\n projectionWorkerFatalFired = true;\n reactorLogger.error(\n `Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`,\n reason,\n );\n // SIGTERM takes the builder's withSignalHandlers() path: kill, hooks, db.\n raiseSigterm();\n };\n // Resolved in startSwitchboard, which owns the flag mechanism; initServer\n // only reads the answer.\n const workflowsEnabled = options.workflows?.enabled === true;\n // Resolved before the reactor is built: a bad secret fails the boot early.\n // Flag-on, the privacy plugin owns this resolve (same fail-fast timing, in\n // transformServerOptions above).\n const privacyConfig = pluginHost\n ? ({ enabled: false } as ResolvedPrivacy)\n : resolvePrivacy(options.privacy, {});\n\n // Through the package manager like any other, so one route carries the\n // models, the subgraphs and the piece.\n if (workflowsEnabled) {\n await assertWorkflowPackageLoadable();\n if (!packages.includes(WORKFLOW_PACKAGE_NAME)) {\n packages.push(WORKFLOW_PACKAGE_NAME);\n }\n }\n\n // Set only when we build the reactor ourselves; a caller-provided one keeps\n // its own lifecycle and must not be torn down here.\n let ownedReactorModule: InProcessReactorClientModule | undefined;\n // Paces an owned reactor's processor backfills; fed by this server's load.\n const catchUpPriority = new CatchUpPriority(\n config.protocol.catchUpPriority === \"dynamic\"\n ? { mode: \"dynamic\" }\n : { mode: \"fixed\", level: config.protocol.catchUpPriority },\n );\n const processorTiming = new ProcessorTimingSettings({\n level: config.protocol.processorTiming,\n windowMs: config.protocol.processorTimingWindowMs,\n slowBatchMs: config.protocol.processorSlowBatchMs,\n });\n const memoryTelemetry = createMemoryTelemetry(config, reactorLogger);\n // The models workers and workflow pieces import; only on a reactor built here.\n let workerModels: ModelManifestSource | undefined;\n // Bound once the api serves the renown read model; see `localCredentialCheck`.\n let localRenownRequest: SwitchboardRequestFn | undefined;\n const initializeClient = async (\n documentModels: DocumentModelModule[],\n {\n attachmentReferenceWriter,\n upgradeManifests,\n readModelDb,\n }: ClientInitializerDependencies,\n ) => {\n // When the caller hands us a pre-built reactor module, reuse it\n // instead of constructing one. The caller owns the reactor lifecycle\n // and must call `switchboard.shutdown()` from their own teardown to\n // drain /graphql, MCP, attachments, etc.\n if (options.reactor) {\n const attachmentReferenceProjection =\n await registerAttachmentReferenceReadModelOnModule(\n options.reactor,\n attachmentReferenceWriter,\n );\n if (options.reactor.reactorModule) {\n const instrumentation = new ReactorInstrumentation(\n options.reactor.reactorModule,\n );\n instrumentation.start();\n reactorLogger.info(\n \"Reactor metrics instrumentation started (using caller-provided reactor)\",\n );\n }\n return {\n module: options.reactor,\n attachmentReferenceProjection,\n };\n }\n\n const {\n kysely: baseKysely,\n poolInstrumentation,\n storageFacts,\n storeMaintenance,\n } = await createReactorKysely({\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n hostPoolSize: () => config.workers.hostPoolSize,\n pgliteWorkers: options.pgliteWorkers === true,\n pgliteSettings,\n openingStore: opening.stores?.reactor,\n logger,\n });\n\n const maxSkipThreshold = config.protocol.maxSkipThreshold;\n const hasSkipThreshold = maxSkipThreshold !== undefined;\n if (hasSkipThreshold) {\n logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);\n }\n\n // Flip these per document-sharing fleet, never per node: replay decisions\n // are consensus outcomes, so nodes that disagree on the flags diverge.\n const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =\n reactorFeatureFlagsOf(config.protocol.featureFlags);\n if (enabledFeatureFlags.length > 0) {\n logger.info(\n `Reactor feature flags enabled: ${enabledFeatureFlags.join(\", \")}`,\n );\n }\n if (reactorFeatureFlags.undoV3 === false) {\n logger.info(\"Reactor undoV3 is off: new documents take base-reducer 2\");\n }\n\n const reactorBuilder = new ReactorBuilder()\n .withEventBus(new EventBus())\n .withKysely(baseKysely)\n .withStorageFacts(storageFacts)\n .withFeatures({\n legacyProcessorIds: config.protocol.legacyProcessorIds,\n })\n .withUnsupportedStoredDocuments(unsupportedStoredDocuments)\n .withCatchUpPriority(catchUpPriority)\n .withProcessorTiming(processorTiming)\n .withMemoryTelemetry(memoryTelemetry);\n\n const keyframes = resolveKeyframes(\n config.storage.keyframes,\n fileConfig.reactor?.keyframes,\n configPath,\n );\n if (keyframes) {\n logger.info(\n `Keyframes: default ${JSON.stringify(keyframes.default ?? {})}, ${Object.keys(keyframes.types ?? {}).length} document type(s) with their own rule`,\n );\n reactorBuilder.withKeyframes(keyframes);\n }\n if (storeMaintenance) {\n reactorBuilder.withStoreMaintenance(storeMaintenance);\n }\n\n // Feeds `module.pools`, which ReactorInstrumentation reads to emit\n // reactor.db.pool.{acquire.wait_duration,size,idle,waiting}. Without this\n // the host pool is the one pool the reactor opens that nobody can see.\n // Note the gauges observe pg-pool only: behind a transaction-mode\n // pgbouncer, `waiting` can read 0 while requests queue in the pooler.\n if (poolInstrumentation) {\n reactorBuilder.withInstrumentedPool(poolInstrumentation);\n }\n\n const clientBuilder = new ReactorClientBuilder().withReactorBuilder(\n reactorBuilder,\n );\n\n // Subpath import keeps vetra's React editors out of the node bundle.\n const vetraDocumentModels: DocumentModelModule[] = dev\n ? (\n Object.values(\n await import(\"@powerhousedao/vetra/document-models\"),\n ) as unknown[]\n ).filter(\n (m): m is DocumentModelModule =>\n typeof m === \"object\" &&\n m !== null &&\n \"documentModel\" in m &&\n \"reducer\" in m,\n )\n : [];\n\n applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {\n signalHandlers: options.signalHandlers,\n documentModels: [...documentModels, ...vetraDocumentModels],\n upgradeManifests,\n // Always: an explicit undoV3 false enables nothing but must still reach\n // the reactor.\n executorConfig: {\n ...(hasSkipThreshold ? { maxSkipThreshold } : {}),\n featureFlags: reactorFeatureFlags,\n },\n documentModelLoader:\n httpLoader && dynamicModelLoading\n ? httpLoader.documentModelLoader\n : undefined,\n logger: reactorLogger,\n signer: renown\n ? getRenownSignerConfig(renown, options.identity?.keypairPath)\n : undefined,\n createSignaturePolicy: createSignaturePolicyFor(\n config.protocol.createSignaturePolicy,\n { hasSigner: renown !== null, logger },\n ),\n trustPolicy: reactorFeatureFlags.authEnforcement\n ? await getRenownTrustPolicyConfig(\n renownConfig.source === \"self\"\n ? {\n source: \"self\",\n request: (query, variables) =>\n localRenownRequest\n ? localRenownRequest(query, variables)\n : Promise.reject(\n new Error(\n \"The local renown read model is not bound yet\",\n ),\n ),\n }\n : {\n source: \"remote\",\n renownUrl: renownConfig.url,\n switchboardUrl: renownConfig.switchboardUrl,\n },\n renown,\n )\n : getDelegationTrustPolicyConfig(renown),\n });\n\n // File sources give workers and workflow pieces importable paths for the\n // models registered above; the builder dedupes them.\n if (workerPool || projectionWorker || workflowsEnabled) {\n const sources = await resolveWorkerModelSources(packages, reactorLogger, {\n resolveRemote: resolveRegistryModels,\n });\n // Workers need every model; workflow pieces can do without a broken one.\n reactorBuilder.withDocumentModelSources(\n workerPool || projectionWorker\n ? sources\n : await keepImportableSources(sources, reactorLogger),\n );\n }\n workerModels = modelManifestSource(reactorBuilder);\n\n if (workerPool) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: worker pool enabled without a reactor database URL\",\n );\n }\n // The builder fails the boot if a model lacks an importable source.\n reactorBuilder.withWorkerPool({\n numWorkers: workerPool.numWorkers,\n db: buildWorkerDbConfig(reactorDbUrl, workerPool),\n });\n reactorLogger.info(\n `Executor worker pool enabled: ${workerPool.numWorkers} worker threads${\n workerPool.mode === \"auto\" ? \" (auto-sized from cores)\" : \"\"\n }`,\n );\n }\n\n reactorBuilder.withReadModelFactory(\n async ({\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const nodeProcessor = new NodeProcessor(\n baseKysely as unknown as Kysely<unknown>,\n REACTOR_SCHEMA,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n );\n await nodeProcessor.init();\n return nodeProcessor;\n },\n );\n\n registerAttachmentReferenceReadModel(reactorBuilder, {\n baseKysely: baseKysely as unknown as Kysely<unknown>,\n attachmentReferenceWriter,\n });\n\n if (projectionWorker) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: projection worker enabled without a reactor database URL\",\n );\n }\n const db = {\n ...buildWorkerDbConfig(reactorDbUrl, {\n dbPoolSizePerWorker: projectionWorker.dbPoolSize,\n acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5000,\n }),\n applicationName: \"switchboard-projection\",\n };\n reactorBuilder.withReadModelCoordinatorFactory(\n createHybridProjectionCoordinatorFactory({\n shardCount: 1,\n poolSize: projectionWorker.dbPoolSize,\n db,\n onFatal: onProjectionWorkerFatal,\n }),\n );\n reactorLogger.info(\n `Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`,\n );\n }\n\n reactorBuilder.withShutdownHook(async () => {\n if (apiRef.current) await apiRef.current.dispose();\n });\n\n const reactorDriveSchemaDb = baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<ReactorDriveDatabase>;\n const nodeView = new DriveNodeView(reactorDriveSchemaDb);\n driveNodeView = nodeView;\n clientBuilder\n .withDriveNodeSource(nodeView)\n .withDriveWriteStrategy(\n REACTOR_DRIVE_DOCUMENT_TYPE,\n createReactorDriveWriteStrategy,\n );\n\n let module: InProcessReactorClientModule;\n try {\n module = await withProgressHeartbeat(\n {\n logger,\n label:\n \"Starting the reactor (migrations, document view, indexer, processors)\",\n },\n () => clientBuilder.buildModule(),\n );\n } catch (error) {\n try {\n await baseKysely.destroy();\n } catch (destroyError) {\n logger.error(\n \"Aborting boot: reactor database destroy failed: @error\",\n destroyError,\n );\n }\n if (UnsupportedStoredProtocolError.isError(error)) {\n throw new StoredDocumentsRefusedError(error);\n }\n throw error;\n }\n\n if (module.reactorModule) {\n const instrumentation = new ReactorInstrumentation(module.reactorModule);\n instrumentation.start();\n reactorLogger.info(\"Reactor metrics instrumentation started\");\n memoryTelemetry.addGauge(\"otel\", () => instrumentation.stats());\n }\n\n const reactorDriveClient = new ReactorDriveClient({\n read: module.read,\n write: module.write,\n readModel: nodeView,\n });\n\n ownedReactorModule = module;\n if (options.fatalErrorShutdown) {\n installFatalErrorShutdown(logger);\n }\n\n // The permission tables live in the reactor store (reactor migration 029,\n // applied by buildModule above); move what the read-model store still\n // holds before the permission service serves a check. A reactor-api that\n // predates the move hands over no read-model store and keeps its tables\n // there, so nothing is moved.\n const permissionsDb = baseKysely.withSchema(REACTOR_SCHEMA);\n try {\n if (readModelDb) {\n await withProgressHeartbeat(\n { logger, label: \"Moving the permission tables\" },\n () =>\n backfillPermissionTables(\n readModelDb,\n permissionsDb as unknown as Kysely<unknown>,\n logger,\n ),\n );\n }\n } catch (error) {\n logger.error(\n \"Aborting boot: permission tables backfill failed: @error\",\n error,\n );\n try {\n await module.reactorModule?.shutdown();\n } catch (shutdownError) {\n logger.error(\n \"Aborting boot: reactor shutdown failed: @error\",\n shutdownError,\n );\n }\n throw error;\n }\n\n return {\n module,\n reactorDriveClient,\n driveNodes: nodeView,\n attachmentReferenceProjection: { status: \"available\" as const },\n permissionsDb:\n permissionsDb as unknown as Kysely<DocumentPermissionDatabase>,\n };\n };\n\n // Tear down a partially booted stack in the reactor's own order: reactor\n // first, then the api's HTTP/WS/db handles, then the database pool. An\n // owned reactor goes through its module's shutdown, so the other hooks run\n // too and a later signal joins this teardown instead of repeating it.\n const abortBoot = async (api: { dispose: () => Promise<void> }) => {\n let disposed: Promise<void> | undefined;\n const disposeApi = () => (disposed ??= api.dispose());\n apiRef.current = { dispose: disposeApi };\n const owned = ownedReactorModule;\n if (owned?.reactorModule) {\n try {\n await owned.reactorModule.shutdown();\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n } else if (owned) {\n try {\n await owned.reactor.kill().completed;\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n }\n // Already done by the shutdown hook unless the reactor failed to stop.\n try {\n await disposeApi();\n } catch (error) {\n logger.error(\"Aborting boot: api dispose failed: @error\", error);\n }\n };\n\n // Reading credentials from this switchboard's own reactor needs the GraphQL\n // manager, which only exists once the api is up: bind the check afterwards.\n let localCredentialCheck: CredentialCheck | undefined;\n const verifyCredential: CredentialVerifier | undefined =\n renownConfig.source === \"self\"\n ? (params) =>\n localCredentialCheck\n ? localCredentialCheck(params)\n : Promise.reject(\n new Error(\"The local renown read model is not bound yet\"),\n )\n : undefined;\n\n let defaultDriveUrl: undefined | string = undefined;\n\n // TODO get path from powerhouse config\n const basePath = process.cwd();\n\n const reporting = { logger, report: reportError };\n\n // import Vite loader only if dev mode is enabled\n let vite: ViteDevServer | undefined;\n let viteLoader: VitePackageLoader | undefined;\n if (dev) {\n const { VitePackageLoader, createViteLogger, startViteServer } =\n await import(\"@powerhousedao/reactor-api/vite\");\n vite = await startViteServer(process.cwd(), createViteLogger(logger));\n // Packages switchboard brings, like the workflow package, resolve from\n // here when the project does not install them itself.\n viteLoader = VitePackageLoader.build(vite, {\n resolveFrom: [import.meta.url],\n reportError,\n });\n }\n\n // Vetra is builder-only and bundled (not CDN-loadable); lazy-load its\n // processor only in dev, where builder tooling runs (e.g. `ph vetra`).\n const vetraProcessorFactory = dev\n ? (await import(\"@powerhousedao/vetra/processors\")).processorFactory\n : undefined;\n\n // get paths to local document models\n if (!options.disableLocalPackages) {\n packages.push(basePath);\n }\n\n // create loaders\n const packageLoaders: IPackageLoader[] = [];\n if (viteLoader) {\n packageLoaders.push(viteLoader);\n } else {\n packageLoaders.push(new ImportPackageLoader());\n }\n if (httpLoader) {\n packageLoaders.push(httpLoader);\n for (const name of registryPackages) {\n if (!packages.includes(name)) {\n packages.push(name);\n }\n }\n }\n\n const apiLogger = logger.child([\"reactor-api\"]);\n // When the read-model store is on disk, hand reactor-api a factory that\n // constructs the matching PGLite (current or legacy) for the detected\n // PG_VERSION. reactor-api calls the factory synchronously, so the legacy\n // module is preloaded above.\n let pgliteFactory: PgliteFactory | undefined;\n let storeFailed: (error: unknown) => void = () => undefined;\n const storesFailed = new Promise<never>((_, reject) => {\n storeFailed = reject;\n });\n storesFailed.catch(() => undefined);\n if (readModelPgliteDir && readModelPgliteMajor !== null) {\n const storeOptions = {\n inMemory,\n threaded: options.pgliteWorkers === true,\n settings: pgliteSettings,\n logger,\n };\n const openReadStore = await createPgliteStoreFactory({\n ...storeOptions,\n ...READ_STORE,\n major: readModelPgliteMajor,\n });\n // With a thread each, the stores needn't take turns. Two on one dir must,\n // and in the main thread nothing would overlap.\n const openReactorStore =\n storeOptions.threaded &&\n pgliteWorkerEntryPath !== null &&\n sharedPgliteDir === null &&\n reactorPgliteDir &&\n reactorPgliteMajor !== null\n ? await createPgliteStoreFactory({\n ...storeOptions,\n ...REACTOR_STORE,\n major: reactorPgliteMajor,\n })\n : undefined;\n pgliteFactory = (connectionString) => {\n const dir = connectionString ?? readModelPgliteDir;\n if (\n !openReactorStore ||\n !reactorPgliteDir ||\n dir !== readModelPgliteDir\n ) {\n return openReadStore(dir);\n }\n // Here, not any sooner: reactor-api refuses what it won't run before it\n // reaches for this store, and a refused boot touches neither.\n opening.stores ??= openStoresTogether(\n () => openReactorStore(reactorPgliteDir),\n () => openReadStore(dir),\n );\n opening.stores.failed.catch(storeFailed);\n return opening.stores.readModel;\n };\n }\n\n const startingApi = initializeAndStartAPI(\n initializeClient,\n {\n port: requestedPort,\n dbPath: readModelPath,\n pgliteFactory,\n https: options.https,\n packageLoaders: packageLoaders.length > 0 ? packageLoaders : undefined,\n packages: packages,\n processorConfig: options.processorConfig,\n ...(renown ? { hostSigner: renown.signer } : {}),\n processors: vetraProcessorFactory\n ? { \"@powerhousedao/vetra\": [vetraProcessorFactory] }\n : {},\n configFile: configPath,\n server: {\n basePath: config.server.basePath,\n gatewayAdapter: config.server.gatewayAdapter,\n publicUrl: config.server.publicUrl,\n host: config.server.host,\n },\n auth: {\n ...authSectionOf(config.auth),\n stateDir: resolvePhDir(\n undefined,\n config.storage.userDataDir\n ? { PH_USER_DATA_DIR: config.storage.userDataDir }\n : process.env,\n ),\n },\n attachments: { storage: config.attachments.storage },\n mcp: options.mcp ?? true,\n inspection:\n options.inspection === false\n ? false\n : { throttle: inspectionThrottle, admin: config.inspection.admin },\n logger: apiLogger,\n reportError,\n enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,\n hostValidation: options.hostValidation,\n // The final update before readiness picks up everything added until then.\n hostRefreshesSupergraph: true,\n // Already resolved for this reactor's own identity; reuse it so an\n // invalid RENOWN_SOURCE is reported once, not once per resolution.\n renown: renownConfig,\n verifyCredential,\n },\n \"switchboard\",\n );\n // A store that can't open ends the boot now, with its own error, rather\n // than as a closed store's error once something reaches for the other one.\n const api = await Promise.race([startingApi, storesFailed]);\n apiRef.current = api;\n const serverPort = api.port;\n\n if (renownConfig.source === \"self\") {\n const { graphqlManager: manager } = api;\n // Credentials are checked from the first request, before the router update\n // that readiness waits for: a package's read model gets its handler now.\n if (\n !manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH) &&\n manager.getSubgraphByName(RENOWN_READ_MODEL_SUBGRAPH)\n ) {\n try {\n await manager.updateRouter(true);\n } catch (error) {\n await abortBoot(api);\n throw error;\n }\n }\n // Refuse to serve rather than 401 every request: the read model comes from\n // a loaded package, so a missing one is a deployment mistake.\n if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {\n await abortBoot(api);\n throw new Error(\n 'Renown credential verification is set to \"self\" (auth.renown.source ' +\n `or RENOWN_SOURCE) but no loaded package serves the ` +\n `\"${RENOWN_READ_MODEL_SUBGRAPH}\" subgraph. Install one ` +\n \"(@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.\",\n );\n }\n localRenownRequest = (query, variables) =>\n manager.executeSubgraphQuery(\n RENOWN_READ_MODEL_SUBGRAPH,\n query,\n variables,\n );\n localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, {\n onError: (error) =>\n logger.error(\"Renown read model query failed: @error\", error),\n });\n logger.info(\n \"Renown credentials will be verified against this switchboard's own \" +\n \"renown read model\",\n );\n }\n\n // R2.3: flag-on, the attachments plugin owns the route mount + service\n // creation at onHttpMounting; flag-off runs the inline path.\n let attachmentService:\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n if (pluginHost) {\n pluginHost.ctx.api = api;\n pluginHost.ctx.serverPort = serverPort;\n await pluginHost.observe(\"onHttpMounting\");\n attachmentService = pluginHost.ctx.attachmentService as\n | ReturnType<typeof createRemoteAttachmentService>\n | undefined;\n } else {\n registerAttachmentRoutes(api, { config: config.attachments });\n attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(options, serverPort, renown),\n );\n }\n\n if (process.env.SENTRY_DSN) {\n // Register Sentry error handler after all routes are established.\n // The adapter calls the framework-specific Sentry setup internally.\n api.httpAdapter.setupSentryErrorHandler(await import(\"@sentry/node\"));\n }\n\n // The framework wiring takes the halves; `client` (the facade) stays for\n // the consumers that have not moved.\n const { client, read, write, graphqlManager, documentModelRegistry } = api;\n\n const lateSubgraphs: Promise<unknown>[] = [];\n if (pluginHost) {\n pluginHost.ctx.client = client;\n pluginHost.ctx.read = read;\n pluginHost.ctx.write = write;\n pluginHost.ctx.graphqlManager = graphqlManager;\n pluginHost.ctx.lateSubgraphs = lateSubgraphs;\n pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;\n await pluginHost.observe(\"onReactorReady\");\n }\n\n // The workflow runtime is a switchboard component: composed from what the\n // api handed back, registered like any other late subgraph.\n let workflows: ComposedWorkflowRuntime | undefined;\n let workflowsRetry: WorkflowSingletonRetry | undefined;\n const composeWorkflows = () =>\n composeWorkflowRuntime({\n reactorClient: client,\n clientModule: options.reactor ?? ownedReactorModule,\n relationalDb: api.relationalDb,\n // A Postgres read model outlives the pod; a key file beside it would not.\n secretsKeyFile: readModelPgliteDir === null ? false : undefined,\n // The stable half of the default singleton owner name. Absolute, so\n // two Switchboards in different working directories differ.\n storageId:\n readModelPgliteDir === null\n ? readModelPath\n : path.resolve(readModelPath),\n attachments: createAttachmentClient(api.attachments.service),\n attachmentAccess: api.attachmentAccess,\n // The workflow package's own HTTP namespace: its webhook endpoints live\n // under it, not under the reactor's.\n webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,\n http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),\n // The host's option, else the config file's: under uniform runners the\n // plugins own the workflows switch and the classic config read is skipped.\n oauthApps:\n options.workflows?.oauthApps ??\n readConfigOAuthApps(resolveConfigPath(options.configFile), logger),\n authorizationService: api.authorizationService,\n // The manager that serves this reactor's subgraphs: a piece's index read\n // runs through it in process, as the run's user.\n indexQueries: api.graphqlManager,\n // The manager that already loads this reactor's packages: the project it\n // runs in is one of them, so its own pieces arrive with the rest.\n pieces: api.packageManager,\n pieceRegistryUrl: registryUrl,\n models: workerModels,\n // The piece pool leaves the reactor's threads their share of the cores.\n reactorThreads:\n (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),\n logger: logger.child([\"workflow-runtime\"]),\n exclusiveJournal: readModelPgliteDir !== null,\n onSingletonLost: workflowSingletonLossHandler(logger),\n // The providers observability.mts registered before this module loaded.\n telemetry: {\n tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),\n meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE),\n },\n });\n const registerWorkflowSubgraph = (composed: ComposedWorkflowRuntime) => {\n const WorkflowRuntimeSubgraph = composed.subgraph;\n const workflowSubgraph = new WorkflowRuntimeSubgraph({\n readClient: read,\n reactorClient: client,\n http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),\n relationalDb: api.relationalDb,\n analyticsStore: undefined as never,\n graphqlManager,\n syncManager: api.syncManager,\n authorizationService: graphqlManager.getAuthorizationService(),\n path: graphqlManager.getBasePath(),\n attachments: api.attachmentClientProvider,\n });\n return graphqlManager\n .registerSubgraphInstance(workflowSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register workflow-runtime subgraph: @error\",\n );\n });\n };\n if (!pluginHost && workflowsEnabled) {\n try {\n workflows = await composeWorkflows();\n } catch (error) {\n // Without the claim this host must not run workflows, but everything\n // else it serves still works, so it boots without the runtime.\n if (!isWorkflowSingletonConflict(error)) throw error;\n logger.warn(\n `Workflows are enabled but another live process (\"${error.owner ?? \"unknown\"}\") ` +\n `holds the workflow singleton until ${error.expiresAt ?? \"unknown\"}. ` +\n \"This Switchboard has booted WITHOUT the workflow runtime: no \" +\n \"trigger of any kind fires here, and the workflow GraphQL face is \" +\n \"absent. Everything else serves normally. Stop the other owner, or \" +\n \"set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the \" +\n \"slot that owns workflows. This Switchboard retries the claim and \" +\n \"starts workflows once the lease comes free.\",\n );\n workflowsRetry = retryWorkflowSingleton({\n compose: composeWorkflows,\n onComposed: async (composed) => {\n try {\n await composed.start();\n } catch (error) {\n // Hands the lease back so a retry or another replica can claim it.\n try {\n await composed.stop();\n } catch (stopError) {\n logger.error(\n \"Stopping the late workflow runtime failed: @error\",\n stopError,\n );\n }\n throw error;\n }\n logger.info(\"Workflow runtime started\");\n workflows = composed;\n await registerWorkflowSubgraph(composed);\n // Past boot nothing else rebuilds the router, so a subgraph\n // registered now is not served until this runs.\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n );\n }\n },\n logger,\n });\n }\n }\n if (workflows) {\n lateSubgraphs.push(registerWorkflowSubgraph(workflows));\n const runtime = workflows;\n await withProgressHeartbeat(\n { logger, label: \"Starting the workflow runtime\" },\n () => runtime.start(),\n );\n logger.info(\"Workflow runtime started\");\n api.inspection?.facts.setWorkflows(true);\n }\n\n // Plugins register their subgraphs here (push into lateSubgraphs, or mount\n // directly like privacy). The call site carries the inline privacy block's\n // failure semantics: stop workflows, abort the partial boot, rethrow.\n if (pluginHost) {\n pluginHost.ctx.workflowsOrchestration = {\n enabled: options.workflows?.enabled === true,\n composeWorkflows,\n registerWorkflowSubgraph,\n updateRouter: () => graphqlManager.updateRouter(true),\n reportMountFailure: (error: unknown) =>\n reportFailure(\n reporting,\n error,\n \"Mounting the late workflow-runtime subgraph failed: @error\",\n ),\n setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true),\n };\n try {\n await pluginHost.observe(\"onSubgraphsRegistering\");\n } catch (error) {\n await (\n pluginHost.ctx.workflowsRetry as WorkflowSingletonRetry | undefined\n )?.stop();\n await (\n pluginHost.ctx.workflows as ComposedWorkflowRuntime | undefined\n )?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n let privacy: RunningPrivacy | undefined;\n if (!pluginHost && privacyConfig.enabled) {\n // The caller's reactor signs with a signer only the caller knows.\n const signer = options.reactor\n ? options.privacy?.signer\n : (options.privacy?.signer ?? renown?.signer);\n try {\n privacy = await startPrivacy({\n config: privacyConfig,\n reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,\n signer,\n authorizationService: api.authorizationService,\n documentPermissionService: api.documentPermissionService,\n graphqlManager,\n reactorClient: client,\n logger: logger.child([\"privacy\"]),\n });\n } catch (error) {\n await workflowsRetry?.stop();\n await workflows?.stop();\n await abortBoot(api);\n throw error;\n }\n }\n\n // Ahead of the api: the runtime's store lives in the read-model database\n // that dispose closes, and its children outlive the reactor otherwise.\n // Memoized: the reactor's shutdown hook and a caller can both reach it.\n const stopCatchUpLoad = ownedReactorModule\n ? feedCatchUpPriority(catchUpPriority, api.httpServer)\n : () => {};\n const stopTimingLog = startOwnedTimingLog(\n ownedReactorModule?.reactorModule,\n processorTiming,\n config.protocol.processorTimingLogMs,\n reactorLogger,\n );\n if (ownedReactorModule?.reactorModule && config.telemetry.memory.enabled) {\n memoryTelemetry.start();\n }\n let apiDrained: Promise<void> | undefined;\n const drainApi = () =>\n (apiDrained ??= (async () => {\n stopCatchUpLoad();\n stopTimingLog();\n memoryTelemetry.stop();\n if (pluginHost) await pluginHost.observe(\"onShutdown\");\n await privacy?.stop();\n await workflowsRetry?.stop();\n await workflows?.stop();\n await api.dispose();\n })());\n apiRef.current = { dispose: drainApi };\n // An owned reactor's shutdown drains the api through the hook above, in the\n // signal path's order: kill, hooks, database. A caller's reactor is the\n // caller's to stop, so only the api is drained.\n const ownedReactor = ownedReactorModule?.reactorModule;\n const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;\n\n // Wire up dynamic package management if HTTP loader is configured\n if (httpLoader) {\n const packageManagementService = new PackageManagementService({\n defaultRegistryUrl: registryUrl,\n httpLoader,\n documentModelRegistry,\n packageManager: api.packageManager,\n });\n\n packageManagementService.setOnModelsChanged(() => {\n graphqlManager\n .regenerateDocumentModelSubgraphs()\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to regenerate document model subgraphs: @error\",\n );\n });\n });\n\n const packagesSubgraph = new PackagesSubgraph({\n relationalDb: undefined as never,\n analyticsStore: undefined as never,\n readClient: read,\n reactorClient: client,\n graphqlManager,\n syncManager: api.syncManager,\n path: graphqlManager.getBasePath(),\n authorizationService: graphqlManager.getAuthorizationService(),\n packageManagementService,\n http: graphqlManager.scopeForPackage(\"@powerhousedao/switchboard\"),\n attachments: api.attachmentClientProvider,\n });\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(packagesSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register packages subgraph: @error\",\n );\n }),\n );\n }\n\n if (driveNodeView) {\n graphqlManager.setAdditionalContextFields({\n readModel: driveNodeView,\n });\n\n const authorizationService = graphqlManager.getAuthorizationService();\n const reactorDriveSubgraph = {\n name: REACTOR_DRIVE_SUBGRAPH_NAME,\n path: graphqlManager.getBasePath(),\n resolvers: createReactorDriveResolvers({\n reactorClient: client,\n readModel: driveNodeView,\n hostCanRead: (documentId, address) =>\n authorizationService.canRead(\n documentId as CanonicalDocumentId,\n address,\n ),\n }),\n typeDefs: reactorDriveSubgraphTypeDefs,\n readClient: read,\n reactorClient: client,\n relationalDb: undefined as never,\n };\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(reactorDriveSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n reportFailure(\n reporting,\n error,\n \"Failed to register reactor-drive subgraph: @error\",\n );\n }),\n );\n }\n\n // Create default drive if provided\n if (options.drive) {\n if (!renown) {\n throw new Error(\"Cannot create default drive without Renown identity\");\n }\n\n defaultDriveUrl = await ensureDrive(\n client,\n options.drive,\n serverPort,\n logger,\n );\n }\n\n // Ready once this server serves its own drives. Remote drives stay out: they\n // replicate from another server, which may be down.\n void runDetached(\n \"Marking the API ready\",\n async () => {\n await Promise.allSettled(lateSubgraphs);\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Final router update before readiness failed: @error\",\n );\n }\n try {\n await options.readyAfter;\n } catch (error) {\n reportFailure(\n reporting,\n error,\n \"Not ready: the drives seeded after start failed: @error\",\n );\n return;\n }\n api.readiness.markReady();\n },\n reporting,\n );\n\n // add vite middleware after express app is initialized if applicable\n if (vite) {\n api.httpAdapter.mountRawMiddleware(vite.middlewares);\n }\n\n // Connect to remote drives AFTER packages are loaded\n if (remoteDrives.length > 0) {\n for (const remoteDriveUrl of remoteDrives) {\n let driveId: string | undefined;\n\n try {\n const { syncManager } = api;\n const parsed = parseDriveUrl(remoteDriveUrl);\n driveId = parsed.driveId;\n const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {\n type: \"gql\",\n parameters: { url: parsed.graphqlEndpoint },\n });\n logger.debug(\"Remote drive @remoteDriveUrl synced\", remoteDriveUrl);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"already exists\")\n ) {\n logger.debug(\n \"Remote drive already added: @remoteDriveUrl\",\n remoteDriveUrl,\n );\n driveId = remoteDriveUrl.split(\"/\").pop();\n } else {\n logger.error(\n \"Failed to connect to remote drive @remoteDriveUrl: @error\",\n remoteDriveUrl,\n error,\n );\n }\n } finally {\n // Construct local URL once in finally block\n if (!defaultDriveUrl && driveId) {\n const protocol = options.https ? \"https\" : \"http\";\n defaultDriveUrl = `${protocol}://localhost:${serverPort}/d/${driveId}`;\n }\n }\n }\n }\n\n // Drives exist (default created, remotes attached) — the barrier after the\n // future core drive seeding (R2 step 2 replaces the two blocks above).\n if (pluginHost) await pluginHost.observe(\"onDrivesReady\");\n\n return {\n defaultDriveUrl,\n api,\n reactor: client,\n attachmentService,\n attachmentReferenceProjection: api.attachmentReferenceProjection,\n // Read live: losing the singleton turns it unavailable.\n get workflowTriggers() {\n return (\n workflows ??\n (pluginHost?.ctx.workflows as ComposedWorkflowRuntime | undefined)\n )?.triggers;\n },\n workflowsEnabled,\n modelManifest: () => workerModels?.modelManifest() ?? [],\n privacy: (() => {\n const running =\n privacy ?? (pluginHost?.ctx.privacy as RunningPrivacy | undefined);\n return running ? { erasure: running.erasure } : undefined;\n })(),\n mcpEnabled: options.mcp !== false,\n inspectionEnabled: options.inspection !== false,\n inspector: api.inspection?.inspector,\n renown,\n port: serverPort,\n shutdown,\n };\n}\n\n/**\n * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.\n *\n * If `options.reactor` is provided, the switchboard reuses it instead of\n * building its own — the caller then owns the reactor's lifecycle and is\n * responsible for invoking `SwitchboardReactor.shutdown()` from their own\n * teardown / SIGINT path. The switchboard will not reach into the caller's\n * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources\n * dangling until the process exits.\n *\n * When `options.reactor` is omitted, the switchboard builds and owns the\n * reactor. `shutdown()` on the returned handle then runs the reactor\n * module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains\n * the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the\n * reactor database. It does not exit the process. It is the same memoized\n * teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling\n * it twice, or receiving a signal around it, tears down once.\n */\nexport const startSwitchboard = async (\n input: SwitchboardConfigInput = {},\n deps: SwitchboardDeps = {},\n): Promise<SwitchboardReactor> => {\n assertConfigShape(input);\n const configPath = resolveConfigPath(input.configFile);\n const fileConfig = getConfig(configPath);\n // The file's auth lies under the env and the caller, as under the env vars.\n const config = switchboardConfigSchema.parse(\n mergeSwitchboardConfig(\n {\n auth: {\n enabled: fileConfig.auth?.enabled,\n admins: fileConfig.auth?.admins,\n },\n },\n input,\n ),\n );\n const logger = deps.logger ?? defaultLogger;\n if (disableWasmWrapperTiering()) {\n logger.info(\"Wasm wrapper tier-up off on Node 24 (nodejs/node#66366)\");\n }\n // Here as well as in index.mts, so a host embedding the server is profiled.\n if (process.env.PYROSCOPE_SERVER_ADDRESS) {\n await initProfilerFromEnv(process.env).catch((error: unknown) =>\n logger.error(\"Error starting profiler: @error\", error),\n );\n }\n const serverPort = await resolveServerPort(\n config.server.port,\n config.server.strictPort,\n logger,\n );\n\n const options = serverOptionsOf(config, deps);\n // CLASSIC resolution of the carved subsystems' switches — flag-on, the\n // plugins own these (presence is activation): an ABSENT plugin can actually\n // deactivate its subsystem (initServer normalizes unset values to off after\n // transformServerOptions). An explicit config value always wins on both\n // paths. The inspection switch is a core capability (not carved).\n if (!config.features.pluginHost) {\n options.mcp = config.features.mcp ?? true;\n options.workflows = {\n enabled:\n config.features.workflows ?? readConfigWorkflowsEnabled(configPath),\n };\n }\n // This switchboard's own identity authenticates against the same Renown\n // instance it verifies incoming credentials against, unless told otherwise.\n const renownConfig = resolveRenownConfig(\n renownLayers(fileConfig.auth?.renown, config.auth.renown),\n {},\n logger,\n );\n const userDataDir = config.storage.userDataDir;\n options.identity = {\n ...options.identity,\n baseUrl: options.identity?.baseUrl ?? renownConfig.url,\n // Under a relocated .ph tree the identity lives in the user's .ph tree\n // with the stores, never in the install dir. Unset: unchanged — renown's\n // own `<cwd>/.ph/.keypair.json` default applies.\n keypairPath:\n options.identity?.keypairPath ??\n (userDataDir\n ? path.join(\n resolvePhDir(undefined, { PH_USER_DATA_DIR: userDataDir }),\n \".keypair.json\",\n )\n : undefined),\n };\n\n logger.info(\n \"Feature flags: @flags\",\n JSON.stringify(\n {\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,\n MCP_ENABLED: options.mcp,\n INSPECTION_ENABLED: options.inspection,\n PH_PGLITE_WORKERS: options.pgliteWorkers,\n PH_WORKFLOWS_ENABLED: options.workflows?.enabled,\n },\n null,\n 2,\n ),\n );\n\n // Initialize Renown if identity options are provided or keypair exists\n let renown: IRenown | null = null;\n try {\n renown = await initRenown({ ...options.identity, userDataDir });\n } catch (e) {\n logger.warn(\"Failed to initialize ConnectCrypto: @error\", e);\n if (options.identity.requireExisting) {\n throw new Error(\n 'Identity required but failed to initialize. Run \"ph login\" first.',\n { cause: e },\n );\n }\n }\n\n const reportError =\n deps.reportError ??\n ((error: unknown) => {\n void captureInSentry(error);\n });\n const opening: { stores?: StoresOpening } = {};\n try {\n return await initServer(\n serverPort,\n options,\n config,\n renown,\n renownConfig,\n reportError,\n opening,\n );\n } catch (e) {\n await opening.stores?.close();\n await captureInSentry(e);\n if (StoredDocumentsRefusedError.isError(e)) {\n logger.error(e.message);\n } else {\n logger.error(\"App crashed: @error\", e);\n }\n throw e;\n }\n};\n\n// Parsing strips unknown keys, so a caller still passing the old options would boot on defaults.\nfunction assertConfigShape(input: SwitchboardConfigInput): void {\n const unknown = Object.keys(input).filter(\n (key) => !(key in switchboardConfigSchema.shape),\n );\n if (unknown.length > 0) {\n throw new Error(\n `startSwitchboard(config, deps) got unknown config keys: ${unknown.join(\", \")}. ` +\n \"It takes the @powerhousedao/switchboard/config shape; runtime objects go in deps.\",\n );\n }\n}\n\n/** The options view plugins transform, from the config and deps. */\nfunction serverOptionsOf(\n config: SwitchboardConfig,\n deps: SwitchboardDeps,\n): StartServerOptions {\n const { executor, projection } = config.workers;\n return {\n reactor: deps.reactor,\n fatalErrorShutdown: deps.fatalErrorShutdown,\n signalHandlers: deps.signalHandlers,\n readyAfter: deps.readyAfter,\n pluginComposition: deps.pluginComposition,\n logger: deps.logger,\n registryUrl: config.packages.registryUrl,\n configFile: config.configFile,\n port: config.server.port,\n strictPort: config.server.strictPort,\n dev: config.server.dev,\n dbPath: config.storage.readModel.url,\n drive: config.drive as StartServerOptions[\"drive\"],\n packages: [...config.packages.list],\n remoteDrives: [...config.remoteDrives],\n https: config.server.https,\n identity: config.identity,\n attachmentServiceUrl: config.attachments.serviceUrl,\n mcp: config.features.mcp,\n inspection: config.inspection.enabled,\n pgliteWorkers: config.storage.pglite.workers,\n workflows:\n config.features.workflows === undefined\n ? undefined\n : { enabled: config.features.workflows },\n privacy: {\n enabled: config.features.privacy.enabled,\n deploymentSecret: config.features.privacy.deploymentSecret,\n intervalMs: config.features.privacy.intervalMs,\n deadlineMs: config.features.privacy.deadlineMs,\n markerGraceMs: config.features.privacy.markerGraceMs,\n purgeTimeoutMs: config.features.privacy.purgeTimeoutMs,\n signer: deps.privacySigner,\n },\n processorConfig: config.processorConfig,\n disableLocalPackages: config.packages.disableLocal,\n enableDocumentModelSubgraphs: config.features.documentModelSubgraphs,\n dynamicModelLoading: config.packages.dynamic,\n hostValidation: config.packages.hostValidation,\n migratePglite: config.storage.migratePglite,\n forcePgVersion: config.storage.forcePgVersion,\n workerPool: {\n numWorkers: executor.count,\n dbPoolSizePerWorker: executor.poolSize,\n acquireTimeoutMs: executor.acquireTimeoutMs,\n },\n projectionWorker: {\n enabled: projection.enabled,\n dbPoolSize: projection.poolSize,\n },\n unsupportedStoredDocuments: config.protocol.unsupportedStoredDocuments,\n };\n}\n\n/** reactor-api's auth section; renown is resolved here, not there. */\nfunction authSectionOf(auth: SwitchboardConfig[\"auth\"]) {\n const { renown: _renown, ...section } = auth;\n return section;\n}\n\nexport {\n applySwitchboardReactorDefaults,\n type SwitchboardReactorDefaultsOptions,\n} from \"./builder-defaults.mjs\";\nexport * from \"./types.js\";\nexport {\n StoredDocumentsRefusedError,\n resolveUnsupportedStoredDocuments,\n} from \"./unsupported-stored-documents.mjs\";\n\nif (import.meta.main) {\n const config = switchboardConfigFromEnv(process.env);\n initSwitchboardProcess(config);\n await startSwitchboard(config, { fatalErrorShutdown: true });\n}\n\n/** Off in config, no timers or observers exist; a lever can still start it. */\nfunction createMemoryTelemetry(\n config: SwitchboardConfig,\n logger: ILogger,\n): MemoryTelemetry {\n const { memory, dir, heapSnapshotDir } = config.telemetry;\n const directory = dir ?? telemetryDir();\n return new MemoryTelemetry({\n sampler: new NodeMemorySampler(),\n config: {\n enabled: memory.enabled,\n intervalMs: memory.intervalMs,\n outputs: memory.outputs,\n filePath: memory.file.path,\n fileMaxMb: memory.file.maxMb,\n fileKeep: memory.file.keep,\n ringSize: memory.ringSize,\n consoleIntervalMs: memory.consoleIntervalMs,\n workers: memory.workers,\n windowMin: memory.windowMin,\n },\n fileSink: (settings) =>\n memoryFileSink(settings, { dir: directory, logger }),\n heapSnapshot: createHeapSnapshotWriter({\n dir: heapSnapshotDir ?? directory,\n }),\n logger,\n });\n}\n\n/** For a host with no ph-cli display: the slowest processors, through the log. */\nfunction startOwnedTimingLog(\n module: InProcessReactorModule | undefined,\n settings: ProcessorTimingSettings,\n intervalMs: number,\n logger: ILogger,\n): () => void {\n if (!module || intervalMs <= 0) return () => {};\n return startProcessorTimingLog({\n intervalMs,\n read: () =>\n computeProcessorTiming(\n module.processorManager.getAll(),\n module.catchUp.status(),\n settings.level,\n settings.windowMs,\n ),\n log: (line) => logger.info(\"@Line\", line),\n });\n}\n\n/**\n * Feeds the priority this server's request load and main-thread event-loop\n * delay, and ticks its controller every second. Returns the stop.\n */\nfunction feedCatchUpPriority(\n priority: CatchUpPriority,\n server: http.Server,\n): () => void {\n const recorder = new RequestLoadRecorder({\n eventLoopDelay: new NodeEventLoopDelay(),\n });\n recorder.attach(server);\n priority.setLoadSource(recorder);\n const stopTicking = priority.startTicking();\n return () => {\n stopTicking();\n priority.setLoadSource(undefined);\n recorder.stop();\n };\n}\n"],"names":["logger","logger","fs","fs","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAI,UAAU;AAId,eAAsB,oBAAoB,KAAyB;CACjE,IAAI,WAAW,CAAC,IAAI,0BAA0B;CAC9C,UAAU;CACV,MAAM,EACJ,0BAA0B,eAC1B,4BAA4B,SAC5B,gBAAgB,eAChB,oBAAoB,mBACpB,wBAAwB,aACxB,wBAAwB,gBACtB;CAoBJ,OAAO,aAAa;EAjBlB;EACA;EACA;EACA;EAGA,MAAM;GACJ,oBAAoB;GACpB,wBAAwB;GACxB,gBAAgB;EAClB;EAEA,MAAM;GACJ,uBAAuB;GACvB,YAAY;EACd;CAEw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