@powerhousedao/host-core 6.2.3-dev.72 → 6.2.3-dev.74

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/drives.ts","../src/reactor-config.ts","../src/backend-projection.ts","../src/connect-projection.ts","../src/expect-host.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport {\n DRIVE_ICON_MAX_BYTES,\n resolveImageRef,\n} from \"@powerhousedao/shared/connect/image-ref\";\nimport { projectDriveIdWith, type DriveDeclaration } from \"./drive-schema.js\";\n\n/**\n * R1 — core drive declarations. A reactor without drives is not a running\n * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):\n * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins\n * CONTRIBUTE declarations into the same merged list (Contributions.drives);\n * `--explain drives` prints the merged set with provenance.\n *\n * The declaration schema lives in drive-schema.ts (platform-neutral); this\n * module is the node half: resolution (image refs read files), seeding and\n * the node:crypto-bound project drive id.\n */\n\nexport {\n driveDeclarationSchema,\n drivesSchema,\n type DriveDeclaration,\n} from \"./drive-schema.js\";\n\nconst sha256Hex = (input: string): string =>\n crypto.createHash(\"sha256\").update(input).digest(\"hex\");\n\nexport function projectDriveId(projectRoot: string, slug: string): string {\n return projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\n\nexport interface ResolvedDrive {\n kind: \"local\" | \"remote\";\n id: string;\n slug: string;\n name: string;\n icon?: string;\n preferredEditor?: string;\n sharingType: \"public\" | \"private\" | \"shared\";\n availableOffline: boolean;\n remoteUrl?: string;\n}\n\nexport function resolveDriveDeclaration(\n projectRoot: string,\n decl: DriveDeclaration,\n): ResolvedDrive {\n const id = decl.projectHash\n ? projectDriveId(projectRoot, decl.slug)\n : (decl.id ?? decl.slug);\n // Hash-derived drives serve under the hashed slug too (classic parity:\n // the vetra drive's slug IS its hashed id) — unless only the id is hashed.\n const slug = decl.projectHash === true ? id : decl.slug;\n if (decl.remote) {\n return {\n kind: \"remote\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n remoteUrl: decl.remote.url,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n }\n return {\n kind: \"local\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n // A project path becomes a data URI here (the icon lives in synced drive\n // state, so it is size-capped); URLs and data URIs pass through.\n icon: resolveImageRef(projectRoot, decl.icon, {\n maxBytes: DRIVE_ICON_MAX_BYTES,\n warn: (m) => console.warn(m),\n }),\n preferredEditor: decl.preferredEditor,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n}\n\n/* ------------------------------------------------------------------ seeding */\n\n/** The minimal client surface the seeder needs — runners adapt their reactor\n * clients (IReactorClient, addDefaultDrive-style helpers) onto it. */\nexport interface DriveSeederClient {\n /** Return the existing drive's id for a slug, or undefined. */\n findDriveBySlug(slug: string): Promise<string | undefined>;\n /** Create a local drive; preferredEditor lands on header.meta. */\n createDrive(drive: ResolvedDrive): Promise<void>;\n /** Attach a remote drive by URL (idempotent on the client side). */\n attachRemoteDrive(url: string): Promise<void>;\n}\n\nexport interface SeedResult {\n created: string[];\n existing: string[];\n attached: string[];\n}\n\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n * recreated, never mutated — preserveStrategy refinements live here later). */\nexport async function seedDrives(\n client: DriveSeederClient,\n drives: readonly ResolvedDrive[],\n): Promise<SeedResult> {\n const result: SeedResult = { created: [], existing: [], attached: [] };\n for (const drive of drives) {\n if (drive.kind === \"remote\") {\n await client.attachRemoteDrive(drive.remoteUrl!);\n result.attached.push(drive.slug);\n continue;\n }\n const existing = await client.findDriveBySlug(drive.slug);\n if (existing !== undefined) {\n result.existing.push(drive.slug);\n continue;\n }\n await client.createDrive(drive);\n result.created.push(drive.slug);\n }\n return result;\n}\n\n/* ------------------------------------------------------------------ explain */\n\nexport interface DrivePlanEntry {\n drive: ResolvedDrive;\n /** \"host\" for host.js declarations; a plugin name for contributions. */\n source: string;\n}\n\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n * host file wins on conflicts (it is the most explicit source). */\nexport function mergeDrivePlan(\n projectRoot: string,\n hostDeclared: readonly DriveDeclaration[],\n contributed: readonly { declaration: DriveDeclaration; source: string }[],\n): DrivePlanEntry[] {\n const plan = new Map<string, DrivePlanEntry>();\n for (const { declaration, source } of contributed) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source });\n }\n for (const declaration of hostDeclared) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source: \"host\" });\n }\n return [...plan.values()];\n}\n\nexport function explainDrivePlan(plan: readonly DrivePlanEntry[]): string {\n if (plan.length === 0) return \"(no drives declared)\";\n const lines = plan.map(({ drive, source }) => {\n const kind =\n drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n const editor = drive.preferredEditor\n ? ` editor=${drive.preferredEditor}`\n : \"\";\n return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n });\n return [\"drives:\", ...lines].join(\"\\n\");\n}\n","/**\n * The shared `reactor` host-config block and its projections onto today's\n * Switchboard env / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\nexport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorPackageConfig,\n ReactorProtocol,\n ReactorRemoteConfig,\n ReactorStorageConfig,\n} from \"./host-schemas.js\";\n\n/** The single primary backend for phase-2 projection (multi-backend routing is\n * track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\nexport interface SwitchboardReactorProjection {\n /** Env the switchboard server reads at boot. Only keys the block sets. */\n env: Record<string, string>;\n /** Options passed to startSwitchboard (DB path). */\n options: { dbPath?: string };\n}\n\n/** Project the reactor block onto the switchboard's env + options. */\nexport function projectReactorToSwitchboard(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorProjection {\n const env = protocolEnv(reactor?.protocol);\n const backend = primaryBackend(reactor);\n const options: { dbPath?: string } = {};\n\n if (backend?.storage) {\n const s = backend.storage;\n const dbUrl = s.kind === \"postgres\" ? s.url : s.dataDir;\n if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;\n }\n if (backend?.readModel?.url) options.dbPath = backend.readModel.url;\n if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = \"true\";\n if (reactor?.workflows !== undefined) {\n env.PH_WORKFLOWS_ENABLED = reactor.workflows ? \"1\" : \"0\";\n }\n return { env, options };\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind>([\n \"in-process\",\n \"worker\",\n]);\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return primaryBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: { reactorWorker?: boolean; reactorClient?: ReactorClientMode };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (legacy) + instance.reactorClient (the explicit 4-way selector),\n * workflows → app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const backend = primaryBackend(reactor);\n const mode = reactorClientMode(reactor);\n if (backend?.kind !== undefined || mode !== undefined) {\n connect.instance = {\n ...(backend?.kind !== undefined\n ? { reactorWorker: backend.kind === \"worker\" }\n : {}),\n ...(mode !== undefined ? { reactorClient: mode } : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value. An env var that merely matches, or is unset, is fine (phase-2\n * transition keeps an operator's explicit env as an escape hatch unless it\n * disagrees with the protocol — see the WBS precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n if (!protocol) return;\n const expected = protocolEnv(protocol);\n for (const [varName, hostValue] of Object.entries(expected)) {\n const envValue = env[varName];\n if (envValue !== undefined && envValue !== hostValue) {\n throw new Error(\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n );\n }\n }\n}\n","import type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind,\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set<ReactorBackendKind>([\"in-process\", \"worker\"]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' urls, placement order — what the routing client dials. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n","import type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n","import {\n backendToDescriptor,\n isStructuralMultiReactor,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorStorageConfig,\n RunnerKind,\n} from \"./host-schemas.js\";\nimport { reactorClientMode, type ReactorClientMode } from \"./reactor-config.js\";\nimport { envSitesOf, outputSitesOf, refKey } from \"./resolve/declared.js\";\nimport type { CompoundPlan } from \"./resolve/plan.js\";\nimport type { OutputPath } from \"./tokens.js\";\n\n/**\n * What a host amounts to once its pipeline has run (typed-host-configs G2,\n * 2.2): the reactor-client shape its backends select, the drives it serves\n * or attaches, the producers whose outputs it consumes and, for a compound,\n * the start order and each member's expectation. Pure and platform-neutral:\n * the caller runs load → declared validation → resolve → resolved\n * validation (and plugin contribution discovery) and hands over the\n * results. The returned value is JSON-only, so it can be pinned in a test\n * table or shipped to another process (a future reactor-monitor).\n */\n\n/** One backend, in placement-primary-first order. */\nexport interface ExpectedBackend {\n name: string;\n kind: ReactorBackendKind;\n storage?: ReactorStorageConfig[\"kind\"];\n /** The RESOLVED storage dir (`\"${userData}\"` sugar and `$env` applied). */\n dataDir?: string;\n /** Why a provisioned reactor (a browser tab, reactor-monitor) cannot be\n * built from this backend (`backendToDescriptor`): e.g. postgres storage\n * is server-side only, a remote backend needs `remote.url`. Absent when\n * it can. A switchboard's own backend may legitimately carry one. */\n provisionError?: string;\n}\n\n/** One drive of the merged plan: plugin contributions first, then the\n * host's own declarations (the host wins a slug). Identity is the DECLARED\n * slug: a `projectHash` drive reports the flag, not a hashed id, so the\n * expectation does not depend on where the project lives. */\nexport interface ExpectedDrive {\n slug: string;\n kind: \"local\" | \"remote\";\n /** \"host\" for `reactor.drives`; the plugin name for a contribution. */\n source: string;\n /** A remote drive's resolved URL. */\n url?: string;\n id?: string;\n projectHash?: boolean | \"id\";\n}\n\n/** One `$output` token in the declared host. */\nexport interface ConsumedOutput {\n /** Host path of the token (`reactor.backends.sb.remote.url`). */\n at: string;\n host: string;\n member?: string;\n path: OutputPath;\n}\n\nexport interface HostExpectation {\n name: string;\n kind: RunnerKind;\n /** The verb this host runs at: `runner.defaultVerb ?? \"run\"` standalone;\n * for a compound member, its own effective verb under the compound's. */\n verb: string;\n /** Reactor hosts with backends: `reactorClientMode`. */\n clientMode?: ReactorClientMode;\n /** Reactor hosts: local AND remote backends (Connect's routing client). */\n multiReactor?: boolean;\n backends?: ExpectedBackend[];\n /** The resolved URLs of the remote backends, placement order. */\n remotes?: string[];\n drives?: ExpectedDrive[];\n /** Producers its own tokens read (`host` or `host#member`), sorted. */\n dependsOn: string[];\n consumes: ConsumedOutput[];\n /** `$env` names its own tokens read, sorted (values are not recorded). */\n env: string[];\n /** Compound: member keys in start order. */\n startOrder?: string[];\n /** Compound: each member's expectation. */\n members?: Record<string, MemberExpectation>;\n}\n\nexport interface MemberExpectation extends Omit<\n HostExpectation,\n \"startOrder\" | \"members\"\n> {\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** Member keys this member consumes (it starts after them), sorted. */\n after: string[];\n}\n\n/** A drive a plugin contributes, as plugin contribution discovery reports\n * it (`resolvePluginContributions`). */\nexport interface ContributedDriveInput {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface ExpectHostInput {\n kind: RunnerKind;\n /** The host as declared (tokens in place); a compound member's draft\n * (its host.js with the wrapper applied). */\n declared: Record<string, unknown>;\n /** The resolved (and parsed) host. Default: `declared`. */\n resolved?: Record<string, unknown>;\n /** Drives the host's plugins contribute at its verb. */\n contributed?: readonly ContributedDriveInput[];\n /** Compound: its members, any order (the plan orders them). */\n members?: readonly MemberInput[];\n /** Compound: the dependency plan (`planCompound`). */\n plan?: CompoundPlan;\n}\n\nexport interface MemberInput extends Omit<ExpectHostInput, \"members\" | \"plan\"> {\n key: string;\n host: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction runnerOf(host: Record<string, unknown>): Record<string, unknown> {\n return isRecord(host.runner) ? host.runner : {};\n}\n\nfunction defaultVerbOf(host: Record<string, unknown>): string | undefined {\n const verb = runnerOf(host).defaultVerb;\n return typeof verb === \"string\" ? verb : undefined;\n}\n\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb: string, member: Record<string, unknown>) {\n return compoundVerb === \"run\"\n ? (defaultVerbOf(member) ?? \"run\")\n : compoundVerb;\n}\n\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor: ReactorConfig): [string, ReactorBackend][] {\n const backends = Object.entries(reactor.backends ?? {});\n const primary = reactor.placement?.primary;\n const first = backends.filter(([name]) => name === primary);\n return [...first, ...backends.filter(([name]) => name !== primary)];\n}\n\nfunction expectBackend(\n name: string,\n backend: ReactorBackend,\n reactor: ReactorConfig,\n): ExpectedBackend {\n const out: ExpectedBackend = { name, kind: backend.kind };\n if (backend.storage) out.storage = backend.storage.kind;\n if (typeof backend.storage?.dataDir === \"string\") {\n out.dataDir = backend.storage.dataDir;\n }\n try {\n backendToDescriptor(name, backend, reactor.protocol);\n } catch (error) {\n out.provisionError = error instanceof Error ? error.message : String(error);\n }\n return out;\n}\n\nfunction expectDrive(\n declaration: Record<string, unknown>,\n source: string,\n): ExpectedDrive | undefined {\n if (typeof declaration.slug !== \"string\") return undefined;\n const remote = isRecord(declaration.remote) ? declaration.remote : undefined;\n const drive: ExpectedDrive = {\n slug: declaration.slug,\n kind: remote ? \"remote\" : \"local\",\n source,\n };\n if (remote && typeof remote.url === \"string\") drive.url = remote.url;\n if (typeof declaration.id === \"string\") drive.id = declaration.id;\n const projectHash = declaration.projectHash;\n if (typeof projectHash === \"boolean\" || projectHash === \"id\") {\n drive.projectHash = projectHash;\n }\n return drive;\n}\n\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n * `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive: ExpectedDrive): string {\n return drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n\n/** Contributions first, then host declarations; keyed by served slug, the\n * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(\n reactor: ReactorConfig | undefined,\n contributed: readonly ContributedDriveInput[],\n): ExpectedDrive[] {\n const plan = new Map<string, ExpectedDrive>();\n for (const { declaration, source } of contributed) {\n const drive = expectDrive(declaration, source);\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n for (const declaration of reactor?.drives ?? []) {\n const drive = expectDrive(declaration, \"host\");\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n return [...plan.values()];\n}\n\n/** Token facts of the host's OWN fields (a compound's `children` are its\n * members' own). */\nfunction tokenFacts(\n declared: Record<string, unknown>,\n kind: RunnerKind,\n): Pick<HostExpectation, \"dependsOn\" | \"consumes\" | \"env\"> {\n const own =\n kind === \"compound\"\n ? Object.fromEntries(\n Object.entries(declared).filter(([key]) => key !== \"children\"),\n )\n : declared;\n const sites = outputSitesOf(own);\n const consumes = sites.map(({ path, ref, outputPath }): ConsumedOutput => ({\n at: path,\n host: ref.host,\n ...(ref.member !== undefined ? { member: ref.member } : {}),\n path: outputPath,\n }));\n return {\n dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n consumes,\n env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort(),\n };\n}\n\nfunction expectOwn(\n input: Omit<ExpectHostInput, \"members\" | \"plan\">,\n verb: string,\n): HostExpectation {\n const resolved = input.resolved ?? input.declared;\n const expectation: HostExpectation = {\n name: typeof resolved.name === \"string\" ? resolved.name : \"\",\n kind: input.kind,\n verb,\n ...tokenFacts(input.declared, input.kind),\n };\n if (input.kind !== \"reactor\") return expectation;\n\n const reactor = isRecord(resolved.reactor)\n ? (resolved.reactor as ReactorConfig)\n : undefined;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) expectation.clientMode = mode;\n expectation.multiReactor = isStructuralMultiReactor(reactor);\n const backends = reactor ? orderedBackends(reactor) : [];\n if (reactor && backends.length > 0) {\n expectation.backends = backends.map(([name, backend]) =>\n expectBackend(name, backend, reactor),\n );\n expectation.remotes = backends.flatMap(([, backend]) =>\n backend.kind === \"remote\" && typeof backend.remote?.url === \"string\"\n ? [backend.remote.url]\n : [],\n );\n }\n expectation.drives = drivePlan(reactor, input.contributed ?? []);\n return expectation;\n}\n\n/**\n * The expectation for one host. A reactor host's comes from its resolved\n * reactor block and contributed drives; a compound's lists its members in\n * plan order, each with the verb it runs at under the compound's own verb\n * and the members it starts after.\n */\nexport function expectHost(input: ExpectHostInput): HostExpectation {\n const verb = defaultVerbOf(input.declared) ?? \"run\";\n const expectation = expectOwn(input, verb);\n if (input.kind !== \"compound\" || !input.members) return expectation;\n\n const order = input.plan?.order ?? input.members.map((m) => m.key);\n const edges = input.plan?.edges ?? [];\n const byKey = new Map(input.members.map((m) => [m.key, m]));\n const members: Record<string, MemberExpectation> = {};\n for (const key of order) {\n const member = byKey.get(key);\n if (!member) continue;\n members[key] = {\n host: member.host,\n ...expectOwn(member, memberVerb(verb, member.declared)),\n after: [\n ...new Set(\n edges.filter((e) => e.consumer === key).map((e) => e.producer),\n ),\n ].sort(),\n };\n }\n expectation.startOrder = order.filter((key) => byKey.has(key));\n expectation.members = members;\n return expectation;\n}\n"],"mappings":";;;;AAyBA,MAAM,aAAa,UACjB,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAExD,SAAgB,eAAe,aAAqB,MAAsB;CACxE,OAAO,mBAAmB,WAAW,aAAa,IAAI;AACxD;AAcA,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mjs","names":[],"sources":["../src/spawn-host.ts","../src/check-host.ts","../src/drives.ts","../src/reactor-config.ts","../src/backend-projection.ts","../src/connect-projection.ts","../src/expect-host.ts"],"sourcesContent":["import { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadHost } from \"./host-loader.js\";\nimport { clearRunRecord, listRunRecords } from \"./run-record.js\";\nimport type { RunRecord } from \"./run-record-schema.js\";\nimport {\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface SpawnHostOptions {\n projectRoot: string;\n /** Folder name under hosts/. */\n host: string;\n /** The child's PH_USER_DATA_DIR (created if missing). */\n dataDir: string;\n verb?: string;\n /** Merged over the clean base env; may not set PH_USER_DATA_DIR. */\n env?: Record<string, string>;\n /** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */\n cli?: string;\n readyTimeoutMs?: number;\n stopTimeoutMs?: number;\n /** Before ready: stop and reject. After: stop. */\n signal?: AbortSignal;\n onOutput?: (stream: \"stdout\" | \"stderr\", chunk: string) => void;\n /** Appends both streams. */\n logFile?: string;\n}\n\nexport interface HostExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n /** SIGKILL after stopTimeoutMs. */\n forced: boolean;\n}\n\nexport interface SpawnedHost {\n pid: number;\n dataDir: string;\n record: RunRecord;\n outputs: Record<string, unknown> | undefined;\n members: RunRecord[\"members\"];\n /** Resolves (never rejects) when the child exits. */\n exited: Promise<HostExit>;\n /** SIGTERM, SIGKILL after stopTimeoutMs, clear a leftover record. */\n stop(): Promise<HostExit>;\n}\n\nexport type SpawnHostPhase = \"exited\" | \"timeout\" | \"aborted\";\n\nexport class SpawnHostError extends Error {\n constructor(\n message: string,\n readonly phase: SpawnHostPhase,\n readonly outputTail: string,\n readonly exit?: HostExit,\n ) {\n super(\n outputTail ? `${message}\\n--- output tail ---\\n${outputTail}` : message,\n );\n this.name = \"SpawnHostError\";\n }\n}\n\nconst READY_TIMEOUT_MS = 120_000;\nconst STOP_TIMEOUT_MS = 30_000;\nconst POLL_MS = 100;\nconst TAIL_BYTES = 8 * 1024;\n// A grandchild may hold the pipes open past the child's exit.\nconst CLOSE_WAIT_MS = 1_000;\n\nconst BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"TMPDIR\"];\nconst WIN32_ENV_KEYS = [\n \"SystemRoot\",\n \"USERPROFILE\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"TEMP\",\n \"TMP\",\n \"ComSpec\",\n \"PATHEXT\",\n];\n\n/** The child's whole env: no other `process.env` key reaches it. */\nfunction childEnv(\n dataDir: string,\n env: Record<string, string> = {},\n): Record<string, string> {\n if (\"PH_USER_DATA_DIR\" in env) {\n throw new Error(\n \"spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.\",\n );\n }\n const keys =\n process.platform === \"win32\"\n ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS]\n : BASE_ENV_KEYS;\n const base: Record<string, string> = {};\n for (const key of keys) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n return {\n ...base,\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_USER_DATA_DIR: dataDir,\n PH_NO_TELEMETRY: \"1\",\n PH_NO_DOTENV: \"1\",\n ...env,\n };\n}\n\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\n/** Readiness waits for a record; refuse a host/verb that writes none. */\nasync function assertWritesRecord(\n projectRoot: string,\n host: string,\n verb: string | undefined,\n): Promise<void> {\n if (verb !== undefined && ONE_SHOT_VERBS.has(verb)) {\n throw new Error(\n `spawnHost: \"${verb}\" is a one-shot verb; it writes no run record to wait for.`,\n );\n }\n const loaded = await loadHost(projectRoot, host);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n if (runner.kind === \"compound\") {\n const config = (loaded.host as { config?: { runtimeRecord?: unknown } })\n .config;\n if (config?.runtimeRecord === false) {\n throw new Error(\n `spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`,\n );\n }\n return;\n }\n if (!isSchemaLike(runner.outputsSchema)) {\n throw new Error(\n `spawnHost: hosts/${host} runs \"${specifier}\", which exports no outputsSchema, so it writes no run record to wait for.`,\n );\n }\n}\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\n// Children still running when this process exits get SIGTERM, so a launcher\n// that exits without stop() leaves no host behind.\nconst live = new Set<ChildProcess>();\nlet exitHookInstalled = false;\nfunction track(child: ChildProcess): void {\n live.add(child);\n child.once(\"exit\", () => live.delete(child));\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n process.once(\"exit\", () => {\n for (const running of live) running.kill(\"SIGTERM\");\n });\n}\n\n/**\n * `ph run <host> [verb]` as a child; ready when its run record appears.\n *\n * The child shares this process's group, so a terminal Ctrl-C reaches both.\n * It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the\n * project's `.env` anyway.\n */\nexport async function spawnHost(\n options: SpawnHostOptions,\n): Promise<SpawnedHost> {\n const projectRoot = path.resolve(options.projectRoot);\n const dataDir = path.resolve(options.dataDir);\n const env = childEnv(dataDir, options.env);\n const readerEnv = { PH_USER_DATA_DIR: dataDir };\n const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;\n const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;\n const { signal } = options;\n\n if (signal?.aborted) {\n throw new SpawnHostError(\"spawnHost: aborted before start.\", \"aborted\", \"\");\n }\n await assertWritesRecord(projectRoot, options.host, options.verb);\n const cli = options.cli ?? resolvePhCliEntry(projectRoot);\n fs.mkdirSync(dataDir, { recursive: true });\n\n const log = options.logFile\n ? fs.createWriteStream(options.logFile, { flags: \"a\" })\n : undefined;\n let tail = \"\";\n log?.on(\"error\", (error) => {\n tail = (tail + `logFile: ${error.message}\\n`).slice(-TAIL_BYTES);\n });\n const args = [cli, \"run\", options.host];\n if (options.verb !== undefined) args.push(options.verb);\n const child = spawn(process.execPath, args, {\n cwd: projectRoot,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n track(child);\n\n const onChunk = (stream: \"stdout\" | \"stderr\") => (chunk: string) => {\n tail = (tail + chunk).slice(-TAIL_BYTES);\n log?.write(chunk);\n try {\n options.onOutput?.(stream, chunk);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n tail = (tail + `onOutput: ${message}\\n`).slice(-TAIL_BYTES);\n }\n };\n child.stdout.setEncoding(\"utf8\").on(\"data\", onChunk(\"stdout\"));\n child.stderr.setEncoding(\"utf8\").on(\"data\", onChunk(\"stderr\"));\n\n let forced = false;\n let exit: HostExit | undefined;\n const exited = new Promise<HostExit>((resolve) => {\n const done = (code: number | null, sig: NodeJS.Signals | null) => {\n if (exit) return;\n exit = { code, signal: sig, forced };\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(exit);\n };\n child.once(\"exit\", done);\n child.once(\"error\", (error) => {\n tail = (tail + `${error.message}\\n`).slice(-TAIL_BYTES);\n if (child.pid === undefined) done(null, null);\n });\n });\n\n // After the last chunk: stdio may still flush past \"exit\".\n const closed = new Promise<void>((resolve) => {\n child.once(\"close\", () => {\n log?.end();\n resolve();\n });\n });\n\n const pid = child.pid;\n const ownRecords = () =>\n pid === undefined\n ? []\n : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);\n\n const kill = (sig: NodeJS.Signals) => {\n if (pid === undefined) return;\n try {\n process.kill(pid, sig);\n } catch {\n // already gone\n }\n };\n const clearOwnRecords = () => {\n for (const record of ownRecords()) {\n clearRunRecord(projectRoot, record.host, readerEnv);\n }\n };\n\n let stopping: Promise<HostExit> | undefined;\n const stop = (): Promise<HostExit> => {\n stopping ??= (async () => {\n if (!exit) {\n kill(\"SIGTERM\");\n let timer: NodeJS.Timeout | undefined;\n const timedOut = await Promise.race([\n exited.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), stopTimeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (timedOut) {\n forced = true;\n kill(\"SIGKILL\");\n }\n }\n const result = await exited;\n // A killed child skips its exit handler's record clear.\n clearOwnRecords();\n return result;\n })();\n return stopping;\n };\n\n function onAbort() {\n void stop();\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = Date.now() + readyTimeoutMs;\n for (;;) {\n const aborted = signal?.aborted ?? false;\n // Before the record: a child killed after writing it leaves it behind.\n if (exit && !aborted) {\n clearOwnRecords();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CLOSE_WAIT_MS);\n }),\n ]);\n clearTimeout(timer);\n const how =\n exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;\n throw new SpawnHostError(\n `spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`,\n \"exited\",\n tail,\n exit,\n );\n }\n const record = aborted ? undefined : ownRecords().at(0);\n if (record) {\n return {\n pid: record.pid,\n dataDir,\n record,\n outputs: record.outputs,\n members: record.members,\n exited,\n stop,\n };\n }\n if (aborted || Date.now() >= deadline) {\n const phase: SpawnHostPhase = aborted ? \"aborted\" : \"timeout\";\n const stopped = await stop();\n throw new SpawnHostError(\n phase === \"aborted\"\n ? `spawnHost: aborted before ph run ${options.host} was ready.`\n : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`,\n phase,\n tail,\n stopped,\n );\n }\n await Promise.race([sleep(POLL_MS), exited]);\n }\n}\n","import {\n compoundStartVerb,\n memberVerbOf,\n prepareMember,\n takesCspRegistrySync,\n type PreparedMember,\n} from \"./compound.js\";\nimport { isBuiltinEnvName, substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport type { CheckStage, HostIssue } from \"./host-issues.js\";\nimport type { ChildWrapper, CompoundWiring } from \"./host-schemas.js\";\nimport {\n checkOutputPaths,\n checkTokenSites,\n envSitesOf,\n outputRefsOf,\n outputSitesOf,\n type OutputRef,\n type OutputsSchemaLookup,\n} from \"./resolve/declared.js\";\nimport {\n loadProducers,\n processResolveEnv,\n producerOutputsSchemas,\n runnerOutputsSchema,\n} from \"./resolve/node.js\";\nimport { memberForRef, planCompound } from \"./resolve/plan.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport {\n resolveHostOutputs,\n TokenResolutionError,\n unsetEnvMessage,\n type DeferredToken,\n type OutputSource,\n type SelfMembers,\n} from \"./resolve/resolve.js\";\nimport { isPlainObject } from \"./resolve/walk.js\";\nimport {\n getVerb,\n hostSchemaIssues,\n kindShapeIssues,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n type HostSchemaLike,\n type RunnerIssue,\n type RunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface CheckHostOptions {\n projectRoot: string;\n /** The environment `ph run` would resolve against; `process.env` is never read. */\n env: Readonly<Record<string, string | undefined>>;\n /** Default `run`, as `ph run <name>`. */\n verb?: string;\n /** Producers' outputs. Absent: `$output` tokens are checked declared-only. */\n outputs?: OutputSource;\n}\n\nexport interface CheckDeferred extends DeferredToken {\n file: string;\n}\n\nexport interface CheckHostResult {\n issues: HostIssue[];\n /** `$output` tokens left unresolved because no `outputs` were given. */\n deferred: CheckDeferred[];\n}\n\n/** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */\nexport async function checkHost(\n name: string,\n options: CheckHostOptions,\n): Promise<CheckHostResult> {\n const result: CheckHostResult = { issues: [], deferred: [] };\n const file = `hosts/${name}/host.js`;\n const issue = issuer(result, file);\n const verb = options.verb ?? \"run\";\n let host: Record<string, unknown> & { runner: { module: string } };\n let runner: RunnerModule;\n try {\n host = (await loadHost(options.projectRoot, name)).host;\n runner = await resolveRunnerModule(options.projectRoot, host.runner.module);\n } catch (error) {\n issue(\"load\", \"\", error);\n return result;\n }\n const specifier = host.runner.module;\n\n if (runner.kind === \"compound\") {\n await checkCompound(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n });\n return result;\n }\n\n const refs = outputRefsOf(host);\n const producers = await loadProducers(options.projectRoot, refs);\n await checkSubject(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n outputsSchemaOf: producerOutputsSchemas(producers),\n self: \"outputs\",\n });\n return result;\n}\n\ninterface Subject {\n file: string;\n host: Record<string, unknown>;\n runner: RunnerModule;\n specifier: string;\n verb: string;\n}\n\ninterface ReactorSubject extends Subject {\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup;\n /** Whose `$output` tokens stay in place when no outputs are given. */\n self: SelfMembers | \"outputs\";\n /** A compound member's wiring, applied before resolved validation. */\n patch?: (host: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Declared validation; returns whether its tokens and its shape passed. */\nfunction checkDeclared(\n result: CheckHostResult,\n subject: Subject,\n outputsSchemaOf?: (ref: OutputRef) => OutputsSchemaLookup,\n): { tokens: boolean; shape: boolean } {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n try {\n getVerb(runner, specifier, subject.verb);\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n const tokenIssues = [\n ...findRemovedForms(host),\n ...checkTokenSites(host),\n ...(outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []),\n ];\n for (const i of tokenIssues) issue(\"declared\", i);\n const shapeIssues = runner.declaredHostSchema\n ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true)\n : kindShapeIssues(runner.kind, specifier, host);\n for (const i of shapeIssues) issue(\"declared\", i);\n return { tokens: tokenIssues.length === 0, shape: shapeIssues.length === 0 };\n}\n\nfunction schemaIssuesOf(\n runner: RunnerModule,\n schema: HostSchemaLike,\n specifier: string,\n host: unknown,\n allowTokens: boolean,\n): RunnerIssue[] {\n const checked = hostSchemaIssues(runner, schema, specifier, host, {\n tokens: allowTokens ? \"allow\" : \"forbid\",\n });\n return [...checked.issues, ...(checked.schemaIssues ?? [])];\n}\n\nasync function checkSubject(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: ReactorSubject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { runner, specifier, file } = subject;\n const declared = checkDeclared(result, subject, subject.outputsSchemaOf);\n const resolveEnv = processResolveEnv(options.projectRoot, options.env);\n const patch = subject.patch ?? ((host) => host);\n\n // A one-shot verb (build) resolves nothing; its verb gets the declared host.\n if (ONE_SHOT_VERBS.has(subject.verb)) {\n if (!declared.tokens || !declared.shape) return;\n const host = patch(\n substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}),\n );\n const schema = runner.declaredHostSchema ?? runner.hostSchema;\n for (const i of schemaIssuesOf(runner, schema, specifier, host, true)) {\n issue(\"resolved\", i);\n }\n return;\n }\n\n const unset = envSitesOf(subject.host).filter(\n (site) =>\n !site.optional &&\n !isBuiltinEnvName(site.name) &&\n options.env[site.name] === undefined,\n );\n for (const site of unset) {\n issue(\"resolve\", { path: site.path, message: unsetEnvMessage(site.name) });\n }\n if (!declared.tokens || unset.length > 0) return;\n\n let resolved: Record<string, unknown>;\n let deferred: DeferredToken[] = [];\n try {\n if (options.outputs) {\n resolved = resolveHostOutputs(subject.host, {\n outputs: options.outputs,\n ...resolveEnv,\n });\n } else {\n const partial = resolveHostOutputs(subject.host, resolveEnv, {\n deferSelf: subject.self,\n });\n resolved = partial.host;\n deferred = partial.deferred;\n }\n } catch (error) {\n if (error instanceof TokenResolutionError && error.detail) {\n issue(\"resolve\", {\n path: error.detail.path,\n message: error.detail.reason,\n });\n } else {\n issue(\"resolve\", \"\", error);\n }\n return;\n }\n result.deferred.push(...deferred.map((d) => ({ ...d, file })));\n if (!declared.shape) return;\n\n const allow = deferred.length > 0;\n const schema = allow\n ? (runner.declaredHostSchema ?? runner.hostSchema)\n : runner.hostSchema;\n const checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), {\n tokens: allow ? \"allow\" : \"forbid\",\n });\n const resolvedIssues = [...checked.issues, ...(checked.schemaIssues ?? [])];\n for (const i of resolvedIssues) issue(\"resolved\", i);\n if (resolvedIssues.length > 0 || !runner.checkBoot) return;\n\n try {\n const boot = await runner.checkBoot(checked.data, {\n projectRoot: options.projectRoot,\n verb: subject.verb,\n env: options.env,\n file,\n });\n for (const i of boot) issue(\"boot\", { ...i, path: i.path ?? \"\" });\n } catch (error) {\n issue(\"boot\", \"\", error);\n }\n}\n\nasync function checkCompound(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: Subject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n const declared = checkDeclared(result, subject);\n if (!declared.tokens || !declared.shape) return;\n // Without a declared schema, checkDeclared checked the kind shape only.\n if (!runner.declaredHostSchema) {\n const own = schemaIssuesOf(\n runner,\n runner.hostSchema,\n specifier,\n host,\n true,\n );\n for (const i of own) issue(\"resolved\", i);\n if (own.length > 0) return;\n }\n\n const children = (\n isPlainObject(host.children) ? host.children : {}\n ) as Record<string, ChildWrapper>;\n const wiring = (\n isPlainObject(host.config) ? host.config : {}\n ) as CompoundWiring;\n // The generic compound's mapping; a runner with its own (desktop's\n // `serve`) is checked as if it were generic.\n const verb = compoundStartVerb(\n subject.verb,\n host.runner as { defaultVerb?: string },\n );\n\n const prepared: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n try {\n prepared.push(await prepareMember(options.projectRoot, key, member));\n } catch (error) {\n issuer(result, `hosts/${member.host}/host.js`)(\"load\", \"\", error);\n }\n }\n const members = Object.entries(children).map(([key, m]) => ({\n key,\n host: m.host,\n }));\n if (prepared.length === members.length) {\n try {\n planCompound(\n prepared.map((m) => ({\n key: m.key,\n host: m.member.host,\n refs: outputSitesOf(m.draft).map(({ ref, path }) => ({\n ref,\n path,\n })),\n })),\n wiring.startOrder,\n );\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n }\n\n const byKey = new Map(prepared.map((m) => [m.key, m]));\n const outputsSchemaOf = (ref: OutputRef): OutputsSchemaLookup => {\n const target = memberForRef(ref, members);\n if (\"error\" in target) return { error: target.error };\n const producer = byKey.get(target.key);\n return producer\n ? runnerOutputsSchema(\n producer.runner,\n producer.specifier,\n `member \"${target.key}\"`,\n )\n : { error: `names member \"${target.key}\", which was not prepared.` };\n };\n for (const m of prepared) {\n const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);\n await checkSubject(result, options, {\n file: m.file,\n host: m.draft,\n runner: m.runner,\n specifier: m.specifier,\n verb: memberVerbOf(verb, m.draft.runner),\n outputsSchemaOf,\n self: { members },\n ...(csp\n ? {\n patch: (resolved) => ({\n ...resolved,\n runner: { ...(resolved.runner as object), cspRegistrySync: true },\n }),\n }\n : {}),\n });\n }\n}\n\nfunction issuer(result: CheckHostResult, file: string) {\n return (\n stage: CheckStage,\n found: RunnerIssue | string,\n error?: unknown,\n ): void => {\n if (typeof found !== \"string\") {\n const { path, message, hint } = found;\n result.issues.push({\n stage,\n file,\n path,\n message,\n ...(hint ? { hint } : {}),\n });\n return;\n }\n const text = error instanceof Error ? error.message : String(error);\n const [message, hint] = text.split(\"\\n Hint: \");\n result.issues.push({\n stage,\n file,\n path: found,\n message,\n ...(hint ? { hint } : {}),\n });\n };\n}\n","import crypto from \"node:crypto\";\nimport {\n DRIVE_ICON_MAX_BYTES,\n resolveImageRef,\n} from \"@powerhousedao/shared/connect/image-ref\";\nimport { projectDriveIdWith, type DriveDeclaration } from \"./drive-schema.js\";\n\n/**\n * R1 — core drive declarations. A reactor without drives is not a running\n * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):\n * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins\n * CONTRIBUTE declarations into the same merged list (Contributions.drives);\n * `--explain drives` prints the merged set with provenance.\n *\n * The declaration schema lives in drive-schema.ts (platform-neutral); this\n * module is the node half: resolution (image refs read files), seeding and\n * the node:crypto-bound project drive id.\n */\n\nexport {\n driveDeclarationSchema,\n drivesSchema,\n type DriveDeclaration,\n} from \"./drive-schema.js\";\n\nconst sha256Hex = (input: string): string =>\n crypto.createHash(\"sha256\").update(input).digest(\"hex\");\n\nexport function projectDriveId(projectRoot: string, slug: string): string {\n return projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\n\nexport interface ResolvedDrive {\n kind: \"local\" | \"remote\";\n id: string;\n slug: string;\n name: string;\n icon?: string;\n preferredEditor?: string;\n sharingType: \"public\" | \"private\" | \"shared\";\n availableOffline: boolean;\n remoteUrl?: string;\n}\n\nexport function resolveDriveDeclaration(\n projectRoot: string,\n decl: DriveDeclaration,\n): ResolvedDrive {\n const id = decl.projectHash\n ? projectDriveId(projectRoot, decl.slug)\n : (decl.id ?? decl.slug);\n // Hash-derived drives serve under the hashed slug too (classic parity:\n // the vetra drive's slug IS its hashed id) — unless only the id is hashed.\n const slug = decl.projectHash === true ? id : decl.slug;\n if (decl.remote) {\n return {\n kind: \"remote\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n remoteUrl: decl.remote.url,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n }\n return {\n kind: \"local\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n // A project path becomes a data URI here (the icon lives in synced drive\n // state, so it is size-capped); URLs and data URIs pass through.\n icon: resolveImageRef(projectRoot, decl.icon, {\n maxBytes: DRIVE_ICON_MAX_BYTES,\n warn: (m) => console.warn(m),\n }),\n preferredEditor: decl.preferredEditor,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n}\n\n/* ------------------------------------------------------------------ seeding */\n\n/** The minimal client surface the seeder needs — runners adapt their reactor\n * clients (IReactorClient, addDefaultDrive-style helpers) onto it. */\nexport interface DriveSeederClient {\n /** Return the existing drive's id for a slug, or undefined. */\n findDriveBySlug(slug: string): Promise<string | undefined>;\n /** Create a local drive; preferredEditor lands on header.meta. */\n createDrive(drive: ResolvedDrive): Promise<void>;\n /** Attach a remote drive by URL (idempotent on the client side). */\n attachRemoteDrive(url: string): Promise<void>;\n}\n\nexport interface SeedResult {\n created: string[];\n existing: string[];\n attached: string[];\n}\n\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n * recreated, never mutated — preserveStrategy refinements live here later). */\nexport async function seedDrives(\n client: DriveSeederClient,\n drives: readonly ResolvedDrive[],\n): Promise<SeedResult> {\n const result: SeedResult = { created: [], existing: [], attached: [] };\n for (const drive of drives) {\n if (drive.kind === \"remote\") {\n await client.attachRemoteDrive(drive.remoteUrl!);\n result.attached.push(drive.slug);\n continue;\n }\n const existing = await client.findDriveBySlug(drive.slug);\n if (existing !== undefined) {\n result.existing.push(drive.slug);\n continue;\n }\n await client.createDrive(drive);\n result.created.push(drive.slug);\n }\n return result;\n}\n\n/* ------------------------------------------------------------------ explain */\n\nexport interface DrivePlanEntry {\n drive: ResolvedDrive;\n /** \"host\" for host.js declarations; a plugin name for contributions. */\n source: string;\n}\n\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n * host file wins on conflicts (it is the most explicit source). */\nexport function mergeDrivePlan(\n projectRoot: string,\n hostDeclared: readonly DriveDeclaration[],\n contributed: readonly { declaration: DriveDeclaration; source: string }[],\n): DrivePlanEntry[] {\n const plan = new Map<string, DrivePlanEntry>();\n for (const { declaration, source } of contributed) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source });\n }\n for (const declaration of hostDeclared) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source: \"host\" });\n }\n return [...plan.values()];\n}\n\nexport function explainDrivePlan(plan: readonly DrivePlanEntry[]): string {\n if (plan.length === 0) return \"(no drives declared)\";\n const lines = plan.map(({ drive, source }) => {\n const kind =\n drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n const editor = drive.preferredEditor\n ? ` editor=${drive.preferredEditor}`\n : \"\";\n return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n });\n return [\"drives:\", ...lines].join(\"\\n\");\n}\n","/**\n * The shared `reactor` host-config block and its projections onto today's\n * Switchboard env / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\nexport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorPackageConfig,\n ReactorProtocol,\n ReactorRemoteConfig,\n ReactorStorageConfig,\n} from \"./host-schemas.js\";\n\n/** The single primary backend for phase-2 projection (multi-backend routing is\n * track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\nexport interface SwitchboardReactorProjection {\n /** Env the switchboard server reads at boot. Only keys the block sets. */\n env: Record<string, string>;\n /** Options passed to startSwitchboard (DB path). */\n options: { dbPath?: string };\n}\n\n/** Project the reactor block onto the switchboard's env + options. */\nexport function projectReactorToSwitchboard(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorProjection {\n const env = protocolEnv(reactor?.protocol);\n const backend = primaryBackend(reactor);\n const options: { dbPath?: string } = {};\n\n if (backend?.storage) {\n const s = backend.storage;\n const dbUrl = s.kind === \"postgres\" ? s.url : s.dataDir;\n if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;\n }\n if (backend?.readModel?.url) options.dbPath = backend.readModel.url;\n if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = \"true\";\n if (reactor?.workflows !== undefined) {\n env.PH_WORKFLOWS_ENABLED = reactor.workflows ? \"1\" : \"0\";\n }\n return { env, options };\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind>([\n \"in-process\",\n \"worker\",\n]);\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return primaryBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: { reactorWorker?: boolean; reactorClient?: ReactorClientMode };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (legacy) + instance.reactorClient (the explicit 4-way selector),\n * workflows → app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const backend = primaryBackend(reactor);\n const mode = reactorClientMode(reactor);\n if (backend?.kind !== undefined || mode !== undefined) {\n connect.instance = {\n ...(backend?.kind !== undefined\n ? { reactorWorker: backend.kind === \"worker\" }\n : {}),\n ...(mode !== undefined ? { reactorClient: mode } : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n * message naming the var, the host value and the env value. An env var that\n * merely matches, or is unset, is fine. */\nexport function protocolConflicts(\n protocol: ReactorProtocol | undefined,\n env: Readonly<Record<string, string | undefined>>,\n hostFile = \"the host file\",\n): string[] {\n if (!protocol) return [];\n return Object.entries(protocolEnv(protocol)).flatMap(\n ([varName, hostValue]) => {\n const envValue = env[varName];\n if (envValue === undefined || envValue === hostValue) return [];\n return [\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n ];\n },\n );\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value (phase-2 transition keeps an operator's explicit env as an\n * escape hatch unless it disagrees with the protocol — see the WBS\n * precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n const conflict = protocolConflicts(protocol, env, hostFile).at(0);\n if (conflict) throw new Error(conflict);\n}\n","import type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind,\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set<ReactorBackendKind>([\"in-process\", \"worker\"]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' urls, placement order — what the routing client dials. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n","import type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n","import {\n backendToDescriptor,\n isStructuralMultiReactor,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorStorageConfig,\n RunnerKind,\n} from \"./host-schemas.js\";\nimport { reactorClientMode, type ReactorClientMode } from \"./reactor-config.js\";\nimport { envSitesOf, outputSitesOf, refKey } from \"./resolve/declared.js\";\nimport type { CompoundPlan } from \"./resolve/plan.js\";\nimport type { OutputPath } from \"./tokens.js\";\n\n/**\n * What a host amounts to once its pipeline has run (typed-host-configs G2,\n * 2.2): the reactor-client shape its backends select, the drives it serves\n * or attaches, the producers whose outputs it consumes and, for a compound,\n * the start order and each member's expectation. Pure and platform-neutral:\n * the caller runs load → declared validation → resolve → resolved\n * validation (and plugin contribution discovery) and hands over the\n * results. The returned value is JSON-only, so it can be pinned in a test\n * table or shipped to another process (a future reactor-monitor).\n */\n\n/** One backend, in placement-primary-first order. */\nexport interface ExpectedBackend {\n name: string;\n kind: ReactorBackendKind;\n storage?: ReactorStorageConfig[\"kind\"];\n /** The RESOLVED storage dir (`\"${userData}\"` sugar and `$env` applied). */\n dataDir?: string;\n /** Why a provisioned reactor (a browser tab, reactor-monitor) cannot be\n * built from this backend (`backendToDescriptor`): e.g. postgres storage\n * is server-side only, a remote backend needs `remote.url`. Absent when\n * it can. A switchboard's own backend may legitimately carry one. */\n provisionError?: string;\n}\n\n/** One drive of the merged plan: plugin contributions first, then the\n * host's own declarations (the host wins a slug). Identity is the DECLARED\n * slug: a `projectHash` drive reports the flag, not a hashed id, so the\n * expectation does not depend on where the project lives. */\nexport interface ExpectedDrive {\n slug: string;\n kind: \"local\" | \"remote\";\n /** \"host\" for `reactor.drives`; the plugin name for a contribution. */\n source: string;\n /** A remote drive's resolved URL. */\n url?: string;\n id?: string;\n projectHash?: boolean | \"id\";\n}\n\n/** One `$output` token in the declared host. */\nexport interface ConsumedOutput {\n /** Host path of the token (`reactor.backends.sb.remote.url`). */\n at: string;\n host: string;\n member?: string;\n path: OutputPath;\n}\n\nexport interface HostExpectation {\n name: string;\n kind: RunnerKind;\n /** The verb this host runs at: `runner.defaultVerb ?? \"run\"` standalone;\n * for a compound member, its own effective verb under the compound's. */\n verb: string;\n /** Reactor hosts with backends: `reactorClientMode`. */\n clientMode?: ReactorClientMode;\n /** Reactor hosts: local AND remote backends (Connect's routing client). */\n multiReactor?: boolean;\n backends?: ExpectedBackend[];\n /** The resolved URLs of the remote backends, placement order. */\n remotes?: string[];\n drives?: ExpectedDrive[];\n /** Producers its own tokens read (`host` or `host#member`), sorted. */\n dependsOn: string[];\n consumes: ConsumedOutput[];\n /** `$env` names its own tokens read, sorted (values are not recorded). */\n env: string[];\n /** Compound: member keys in start order. */\n startOrder?: string[];\n /** Compound: each member's expectation. */\n members?: Record<string, MemberExpectation>;\n}\n\nexport interface MemberExpectation extends Omit<\n HostExpectation,\n \"startOrder\" | \"members\"\n> {\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** Member keys this member consumes (it starts after them), sorted. */\n after: string[];\n}\n\n/** A drive a plugin contributes, as plugin contribution discovery reports\n * it (`resolvePluginContributions`). */\nexport interface ContributedDriveInput {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface ExpectHostInput {\n kind: RunnerKind;\n /** The host as declared (tokens in place); a compound member's draft\n * (its host.js with the wrapper applied). */\n declared: Record<string, unknown>;\n /** The resolved (and parsed) host. Default: `declared`. */\n resolved?: Record<string, unknown>;\n /** Drives the host's plugins contribute at its verb. */\n contributed?: readonly ContributedDriveInput[];\n /** Compound: its members, any order (the plan orders them). */\n members?: readonly MemberInput[];\n /** Compound: the dependency plan (`planCompound`). */\n plan?: CompoundPlan;\n}\n\nexport interface MemberInput extends Omit<ExpectHostInput, \"members\" | \"plan\"> {\n key: string;\n host: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction runnerOf(host: Record<string, unknown>): Record<string, unknown> {\n return isRecord(host.runner) ? host.runner : {};\n}\n\nfunction defaultVerbOf(host: Record<string, unknown>): string | undefined {\n const verb = runnerOf(host).defaultVerb;\n return typeof verb === \"string\" ? verb : undefined;\n}\n\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb: string, member: Record<string, unknown>) {\n return compoundVerb === \"run\"\n ? (defaultVerbOf(member) ?? \"run\")\n : compoundVerb;\n}\n\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor: ReactorConfig): [string, ReactorBackend][] {\n const backends = Object.entries(reactor.backends ?? {});\n const primary = reactor.placement?.primary;\n const first = backends.filter(([name]) => name === primary);\n return [...first, ...backends.filter(([name]) => name !== primary)];\n}\n\nfunction expectBackend(\n name: string,\n backend: ReactorBackend,\n reactor: ReactorConfig,\n): ExpectedBackend {\n const out: ExpectedBackend = { name, kind: backend.kind };\n if (backend.storage) out.storage = backend.storage.kind;\n if (typeof backend.storage?.dataDir === \"string\") {\n out.dataDir = backend.storage.dataDir;\n }\n try {\n backendToDescriptor(name, backend, reactor.protocol);\n } catch (error) {\n out.provisionError = error instanceof Error ? error.message : String(error);\n }\n return out;\n}\n\nfunction expectDrive(\n declaration: Record<string, unknown>,\n source: string,\n): ExpectedDrive | undefined {\n if (typeof declaration.slug !== \"string\") return undefined;\n const remote = isRecord(declaration.remote) ? declaration.remote : undefined;\n const drive: ExpectedDrive = {\n slug: declaration.slug,\n kind: remote ? \"remote\" : \"local\",\n source,\n };\n if (remote && typeof remote.url === \"string\") drive.url = remote.url;\n if (typeof declaration.id === \"string\") drive.id = declaration.id;\n const projectHash = declaration.projectHash;\n if (typeof projectHash === \"boolean\" || projectHash === \"id\") {\n drive.projectHash = projectHash;\n }\n return drive;\n}\n\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n * `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive: ExpectedDrive): string {\n return drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n\n/** Contributions first, then host declarations; keyed by served slug, the\n * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(\n reactor: ReactorConfig | undefined,\n contributed: readonly ContributedDriveInput[],\n): ExpectedDrive[] {\n const plan = new Map<string, ExpectedDrive>();\n for (const { declaration, source } of contributed) {\n const drive = expectDrive(declaration, source);\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n for (const declaration of reactor?.drives ?? []) {\n const drive = expectDrive(declaration, \"host\");\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n return [...plan.values()];\n}\n\n/** Token facts of the host's OWN fields (a compound's `children` are its\n * members' own). */\nfunction tokenFacts(\n declared: Record<string, unknown>,\n kind: RunnerKind,\n): Pick<HostExpectation, \"dependsOn\" | \"consumes\" | \"env\"> {\n const own =\n kind === \"compound\"\n ? Object.fromEntries(\n Object.entries(declared).filter(([key]) => key !== \"children\"),\n )\n : declared;\n const sites = outputSitesOf(own);\n const consumes = sites.map(({ path, ref, outputPath }): ConsumedOutput => ({\n at: path,\n host: ref.host,\n ...(ref.member !== undefined ? { member: ref.member } : {}),\n path: outputPath,\n }));\n return {\n dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n consumes,\n env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort(),\n };\n}\n\nfunction expectOwn(\n input: Omit<ExpectHostInput, \"members\" | \"plan\">,\n verb: string,\n): HostExpectation {\n const resolved = input.resolved ?? input.declared;\n const expectation: HostExpectation = {\n name: typeof resolved.name === \"string\" ? resolved.name : \"\",\n kind: input.kind,\n verb,\n ...tokenFacts(input.declared, input.kind),\n };\n if (input.kind !== \"reactor\") return expectation;\n\n const reactor = isRecord(resolved.reactor)\n ? (resolved.reactor as ReactorConfig)\n : undefined;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) expectation.clientMode = mode;\n expectation.multiReactor = isStructuralMultiReactor(reactor);\n const backends = reactor ? orderedBackends(reactor) : [];\n if (reactor && backends.length > 0) {\n expectation.backends = backends.map(([name, backend]) =>\n expectBackend(name, backend, reactor),\n );\n expectation.remotes = backends.flatMap(([, backend]) =>\n backend.kind === \"remote\" && typeof backend.remote?.url === \"string\"\n ? [backend.remote.url]\n : [],\n );\n }\n expectation.drives = drivePlan(reactor, input.contributed ?? []);\n return expectation;\n}\n\n/**\n * The expectation for one host. A reactor host's comes from its resolved\n * reactor block and contributed drives; a compound's lists its members in\n * plan order, each with the verb it runs at under the compound's own verb\n * and the members it starts after.\n */\nexport function expectHost(input: ExpectHostInput): HostExpectation {\n const verb = defaultVerbOf(input.declared) ?? \"run\";\n const expectation = expectOwn(input, verb);\n if (input.kind !== \"compound\" || !input.members) return expectation;\n\n const order = input.plan?.order ?? input.members.map((m) => m.key);\n const edges = input.plan?.edges ?? [];\n const byKey = new Map(input.members.map((m) => [m.key, m]));\n const members: Record<string, MemberExpectation> = {};\n for (const key of order) {\n const member = byKey.get(key);\n if (!member) continue;\n members[key] = {\n host: member.host,\n ...expectOwn(member, memberVerb(verb, member.declared)),\n after: [\n ...new Set(\n edges.filter((e) => e.consumer === key).map((e) => e.producer),\n ),\n ].sort(),\n };\n }\n expectation.startOrder = order.filter((key) => byKey.has(key));\n expectation.members = members;\n return expectation;\n}\n"],"mappings":";;;;;;;;;AAuDA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CACA;CAJX,YACE,SACA,OACA,YACA,MACA;EACA,MACE,aAAa,GAAG,QAAQ,yBAAyB,eAAe,OAClE;EANS,KAAA,QAAA;EACA,KAAA,aAAA;EACA,KAAA,OAAA;EAKT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,UAAU;AAGhB,MAAM,gBAAgB;AAEtB,MAAM,gBAAgB;CAAC;CAAQ;CAAQ;AAAQ;AAC/C,MAAM,iBAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,SACP,SACA,MAA8B,CAAC,GACP;CACxB,IAAI,sBAAsB,KACxB,MAAM,IAAI,MACR,uEACF;CAEF,MAAM,OACJ,QAA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AI,CAAC,QAAQ;EACb,QAAQ,OAAO;GACb,MAAM,OAAO;GACb,GAAG,UAAU,QAAQ,WAAW,MAAM,OAAO,QAAQ,CAAC;GACtD,OAAO,CACL,GAAG,IAAI,IACL,MAAM,QAAQ,MAAM,EAAE,aAAa,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,QAAQ,CAC/D,CACF,CAAC,CAAC,KAAK;EACT;CACF;CACA,YAAY,aAAa,MAAM,QAAQ,QAAQ,MAAM,IAAI,GAAG,CAAC;CAC7D,YAAY,UAAU;CACtB,OAAO;AACT"}
@@ -50,12 +50,16 @@ interface ConnectReactorProjection {
50
50
  * (legacy) + instance.reactorClient (the explicit 4-way selector),
51
51
  * workflows → app.workflowsEnabled. */
52
52
  export declare function projectReactorToConnect(reactor: ReactorConfig | undefined): ConnectReactorProjection;
53
+ /** Each pre-set env var that CONTRADICTS the host's protocol block, as a
54
+ * message naming the var, the host value and the env value. An env var that
55
+ * merely matches, or is unset, is fine. */
56
+ export declare function protocolConflicts(protocol: ReactorProtocol | undefined, env: Readonly<Record<string, string | undefined>>, hostFile?: string): string[];
53
57
  /**
54
58
  * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
55
59
  * the host's protocol block, fail loudly naming the var, the host value, and
56
- * the env value. An env var that merely matches, or is unset, is fine (phase-2
57
- * transition keeps an operator's explicit env as an escape hatch unless it
58
- * disagrees with the protocol — see the WBS precedence note).
60
+ * the env value (phase-2 transition keeps an operator's explicit env as an
61
+ * escape hatch unless it disagrees with the protocol — see the WBS
62
+ * precedence note).
59
63
  */
60
64
  export declare function assertProtocolConsistency(protocol: ReactorProtocol | undefined, env: Record<string, string | undefined>, hostFile?: string): void;
61
65
  //#endregion
@@ -338,7 +342,15 @@ interface ResolveSources {
338
342
  where?: string;
339
343
  }
340
344
  export declare class TokenResolutionError extends Error {
341
- constructor(message: string);
345
+ /** The host path that failed and the reason, without the file prefix. */
346
+ readonly detail?: {
347
+ path: string;
348
+ reason: string;
349
+ };
350
+ constructor(message: string, detail?: {
351
+ path: string;
352
+ reason: string;
353
+ });
342
354
  }
343
355
  /**
344
356
  * The `$map` elements an issue path (from resolved validation of a resolved
@@ -378,8 +390,9 @@ interface DeferredResolution<T> {
378
390
  interface ResolveOptions {
379
391
  /** Resolving a COMPOUND's own fields: tokens that read one of its members
380
392
  * are deferred until those members have started (see
381
- * `DeferredResolution`); `children` is left for the members. */
382
- deferSelf: SelfMembers;
393
+ * `DeferredResolution`); `children` is left for the members. `"outputs"`
394
+ * defers every `$output` (its `members` are the producers' ref keys). */
395
+ deferSelf: SelfMembers | "outputs";
383
396
  }
384
397
  /**
385
398
  * Resolve every token in a declared host (or any JSON-shaped value): the
@@ -1 +1 @@
1
- {"version":3,"file":"projection.d.mts","names":[],"sources":["../src/reactor-config.ts","../src/backend-projection.ts","../src/connect-projection.ts","../src/run-record-schema.ts","../src/resolve/declared.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/resolve/removed-forms.ts","../src/resolve/sources.ts","../src/resolve/walk.ts","../src/expect-host.ts"],"mappings":";;;;;;;wBA4BgB,eACd,SAAS,4BACR;;;wBA2Ba,YACd,UAAU,8BACT;UAiBc;;EAEf,KAAK;;EAEL;IAAW;;;;wBAIG,4BACd,SAAS,4BACR;;;KAoBS;;;;;;;;;;wBAgBI,kBACd,SAAS,4BACR;UAYc;;EAEf;IACE,UAAU;IACV;MAAa;MAAyB,gBAAgB;;IACtD;MAAQ;;;;;;;;wBAQI,wBACd,SAAS,4BACR;;;;;;;;wBA0Ba,0BACd,UAAU,6BACV,KAAK,oCACL;;;;;;;;;;;;;;KCjKU;EACN;;EACA;;EACA;EAAc;;UAEH;EACf;EACA;EACA,UAAU;EACV;IAAa;IAAiB;IAAkB;;EAChD;IACE;IACA;IACA;IACA;;EAEF;IAAW;;;;;;wBAgCG,oBACd,cACA,SAAS,gBACT,WAAW,kBACV;;;wBA2Ba,sBACd,SAAS,4BACR;;;;;;;wBAsBa,yBACd,SAAS;;wBAW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AU;;EAEV;;;;EAIA,OAAO,SAAS,eAAe;;UAuYhB;;;;EAIf,WAAW;;;;;;;;;;;;;;wBAeG,mBAAmB,GAAG,MAAM,GAAG,SAAS,iBAAiB;wBACzD,mBAAmB,GACjC,MAAM,GACN,SAAS,gBACT,SAAS,iBACR,mBAAmB;;;;;;;;;UCvnBL;;EAEf;EACA;;;;wBA+Dc,iBAAiB,gBAAgB;;;;;;;;;;wBChEjC,qBACd;EAAoB;EAAa;KACjC,SAAS,8BACT,kBACA,UAAU,+BACT;;;;;;;;;;;;KCCS;;UASK;;EAEf,MAAM;;EAEN;;EAEA,OAAO;;UAGQ;;;EAGf,MAAM;EACN,KAAK;;EAEL,OAAO;EACP,UAAU;;;EAGV,iBAAiB;;;wBAcH,WAAW;;;;;wBAmBX,kBAAkB,iBAAiB;;wBA+DnC,cAAc;;;wBAuDd,aAAa,GAAG,OAAO,IAAI;;;wBAe3B,cAAc,GAAG,OAAO,IAAI;;;;;;;;;;;;;;UCvL3B;EACf;EACA,MAAM;EACN,UAAU;;EAEV;;;;;EAKA;;;;;;UAOe;EACf;EACA;;EAEA;;EAEA;EACA;EACA;;;UAIe;;EAEf;EACA;EACA;EACA,MAAM;;UAGS;EACf;EACA,MAAM;;;EAGN;;EAEA,aAAa;;EAEb;EACA,WAAW;;EAEX;EACA,SAAS;;EAET;EACA,UAAU;;EAEV;;EAEA;;EAEA,UAAU,eAAe;;UAGV,0BAA0B,KACzC;;EAIA;;EAEA;;;;UAKe;EACf,aAAa;EACb;;UAGe;EACf,MAAM;;;EAGN,UAAU;;EAEV,WAAW;;EAEX,uBAAuB;;EAEvB,mBAAmB;;EAEnB,OAAO;;UAGQ,oBAAoB,KAAK;EACxC;EACA;;;;;;;;wBAgKc,WAAW,OAAO,kBAAkB"}
1
+ {"version":3,"file":"projection.d.mts","names":[],"sources":["../src/reactor-config.ts","../src/backend-projection.ts","../src/connect-projection.ts","../src/run-record-schema.ts","../src/resolve/declared.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/resolve/removed-forms.ts","../src/resolve/sources.ts","../src/resolve/walk.ts","../src/expect-host.ts"],"mappings":";;;;;;;wBA4BgB,eACd,SAAS,4BACR;;;wBA2Ba,YACd,UAAU,8BACT;UAiBc;;EAEf,KAAK;;EAEL;IAAW;;;;wBAIG,4BACd,SAAS,4BACR;;;KAoBS;;;;;;;;;;wBAgBI,kBACd,SAAS,4BACR;UAYc;;EAEf;IACE,UAAU;IACV;MAAa;MAAyB,gBAAgB;;IACtD;MAAQ;;;;;;;;wBAQI,wBACd,SAAS,4BACR;;;;wBAsBa,kBACd,UAAU,6BACV,KAAK,SAAS,qCACd;;;;;;;;wBAuBc,0BACd,UAAU,6BACV,KAAK,oCACL;;;;;;;;;;;;;;KCvLU;EACN;;EACA;;EACA;EAAc;;UAEH;EACf;EACA;EACA,UAAU;EACV;IAAa;IAAiB;IAAkB;;EAChD;IACE;IACA;IACA;IACA;;EAEF;IAAW;;;;;;wBAgCG,oBACd,cACA,SAAS,gBACT,WAAW,kBACV;;;wBA2Ba,sBACd,SAAS,4BACR;;;;;;;wBAsBa,yBACd,SAAS;;wBAWK,kBACd,SAAS;;;;;;;;;;wBCxGK,sBACX,QAAQ,4BACV;;;;;;;;wBAqBa,eAAe,kBAAkB;UAahC;;;EAGf;;EAEA,0BAA0B;;EAE1B;;;;;;;;wBASc,yBACd,OAAO,uBACN,KAAK;;;qBCxEK,uBAAqB,EAAA;;;;;;;;;GAOhC,EAAA,KAAA;qBAEW,iBAAe,EAAA;;;;;;;;;;;;;;;;;;;;;;;GAc1B,EAAA,KAAA;KAEU,YAAY,EAAE,aAAa;KAC3B,kBAAkB,EAAE,aAAa;;;;;;;;;;;;;UClB5B;EACf;EACA;;UAGe;;EAEf;EACA;;wBAqBc,OAAO,KAAK;;wBAKZ,aAAa,gBAAgB;;;wBAY7B,cACd;EACG;EAAc,KAAK;EAAW,YAAY;;;wBAW/B,WACd;EACG;EAAc;EAAc;;;;;;wBAuEjB,gBAAg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BAmBX,kBAAkB,iBAAiB;;wBA+DnC,cAAc;;;wBAuDd,aAAa,GAAG,OAAO,IAAI;;;wBAe3B,cAAc,GAAG,OAAO,IAAI;;;;;;;;;;;;;;UCvL3B;EACf;EACA,MAAM;EACN,UAAU;;EAEV;;;;;EAKA;;;;;;UAOe;EACf;EACA;;EAEA;;EAEA;EACA;EACA;;;UAIe;;EAEf;EACA;EACA;EACA,MAAM;;UAGS;EACf;EACA,MAAM;;;EAGN;;EAEA,aAAa;;EAEb;EACA,WAAW;;EAEX;EACA,SAAS;;EAET;EACA,UAAU;;EAEV;;EAEA;;EAEA,UAAU,eAAe;;UAGV,0BAA0B,KACzC;;EAIA;;EAEA;;;;UAKe;EACf,aAAa;EACb;;UAGe;EACf,MAAM;;;EAGN,UAAU;;EAEV,WAAW;;EAEX,uBAAuB;;EAEvB,mBAAmB;;EAEnB,OAAO;;UAGQ,oBAAoB,KAAK;EACxC;EACA;;;;;;;;wBAgKc,WAAW,OAAO,kBAAkB"}
@@ -1,4 +1,4 @@
1
- import { B as tokenSchema, E as TOKEN_ESCAPE_KEY, t as substituteBuiltinEnv, x as runnerKindSchema, z as tokenKeyOf } from "./env-substitution-Dj3pdsut.mjs";
1
+ import { B as tokenKeyOf, D as TOKEN_ESCAPE_KEY, S as runnerKindSchema, V as tokenSchema, n as substituteBuiltinEnv, t as isBuiltinEnvName } from "./env-substitution-BjpuE5fm.mjs";
2
2
  import { z } from "zod";
3
3
  //#region src/reactor-config.ts
4
4
  /** The single primary backend for phase-2 projection (multi-backend routing is
@@ -84,20 +84,27 @@ function projectReactorToConnect(reactor) {
84
84
  if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
85
85
  return { connect };
86
86
  }
87
+ /** Each pre-set env var that CONTRADICTS the host's protocol block, as a
88
+ * message naming the var, the host value and the env value. An env var that
89
+ * merely matches, or is unset, is fine. */
90
+ function protocolConflicts(protocol, env, hostFile = "the host file") {
91
+ if (!protocol) return [];
92
+ return Object.entries(protocolEnv(protocol)).flatMap(([varName, hostValue]) => {
93
+ const envValue = env[varName];
94
+ if (envValue === void 0 || envValue === hostValue) return [];
95
+ return [`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`];
96
+ });
97
+ }
87
98
  /**
88
99
  * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
89
100
  * the host's protocol block, fail loudly naming the var, the host value, and
90
- * the env value. An env var that merely matches, or is unset, is fine (phase-2
91
- * transition keeps an operator's explicit env as an escape hatch unless it
92
- * disagrees with the protocol — see the WBS precedence note).
101
+ * the env value (phase-2 transition keeps an operator's explicit env as an
102
+ * escape hatch unless it disagrees with the protocol — see the WBS
103
+ * precedence note).
93
104
  */
94
105
  function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
95
- if (!protocol) return;
96
- const expected = protocolEnv(protocol);
97
- for (const [varName, hostValue] of Object.entries(expected)) {
98
- const envValue = env[varName];
99
- if (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);
100
- }
106
+ const conflict = protocolConflicts(protocol, env, hostFile).at(0);
107
+ if (conflict) throw new Error(conflict);
101
108
  }
102
109
  //#endregion
103
110
  //#region src/backend-projection.ts
@@ -919,11 +926,18 @@ function planCompound(members, startOrder) {
919
926
  //#endregion
920
927
  //#region src/resolve/resolve.ts
921
928
  var TokenResolutionError = class extends Error {
922
- constructor(message) {
929
+ /** The host path that failed and the reason, without the file prefix. */
930
+ detail;
931
+ constructor(message, detail) {
923
932
  super(message);
924
933
  this.name = "TokenResolutionError";
934
+ if (detail) this.detail = detail;
925
935
  }
926
936
  };
937
+ /** Why a required `$env` cannot resolve. */
938
+ function unsetEnvMessage(name) {
939
+ return `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: "${name}", optional: true } } to omit the property when unset).`;
940
+ }
927
941
  /** A resolved `{ $env: { name, optional: true } }` whose variable is unset,
928
942
  * or an `$output`/`$item` reading an absent optional field: its enclosing
929
943
  * property is omitted. */
@@ -1023,6 +1037,10 @@ var Resolver = class {
1023
1037
  host: operand.host,
1024
1038
  member: operand.member
1025
1039
  } : { host: operand.host };
1040
+ if (this.self === "outputs") {
1041
+ keys.add(refKey(ref));
1042
+ continue;
1043
+ }
1026
1044
  if (!this.self.members.some((m) => m.host === ref.host)) continue;
1027
1045
  const target = memberForRef(ref, this.self.members);
1028
1046
  if ("error" in target) this.fail([...trail, ...site.path], `in a compound ${target.error}`);
@@ -1033,7 +1051,11 @@ var Resolver = class {
1033
1051
  fail(trail, message, scope = []) {
1034
1052
  const where = this.sources.where ? `${this.sources.where}: ` : "";
1035
1053
  const inside = scope.length ? ` (rendering $map element ${scope.map(elementText).join(" › ")})` : "";
1036
- throw new TokenResolutionError(`${where}\`${formatPath(trail)}\` ${message}${inside}`);
1054
+ const path = formatPath(trail);
1055
+ throw new TokenResolutionError(`${where}\`${path}\` ${message}${inside}`, {
1056
+ path,
1057
+ reason: `${message}${inside}`
1058
+ });
1037
1059
  }
1038
1060
  value(value, trail, scope = []) {
1039
1061
  if (typeof value === "string") return this.sources.builtins ? substituteBuiltinEnv(value, this.sources.builtins) : value;
@@ -1058,7 +1080,7 @@ var Resolver = class {
1058
1080
  }
1059
1081
  const out = {};
1060
1082
  for (const [key, child] of Object.entries(value)) {
1061
- if (this.self && trail.length === 0 && key === "children") {
1083
+ if (typeof this.self === "object" && trail.length === 0 && key === "children") {
1062
1084
  out[key] = child;
1063
1085
  continue;
1064
1086
  }
@@ -1184,7 +1206,15 @@ var Resolver = class {
1184
1206
  const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);
1185
1207
  if (!this.sources.outputs) return this.fail(trail, `reads ${describeToken(token)}, but no outputs are available here.`, scope);
1186
1208
  const lookup = this.sources.outputs.lookup(ref);
1187
- if (lookup.status === "unavailable") throw new TokenResolutionError(`${this.sources.where ? `${this.sources.where}: ` : ""}${lookup.message}\n (needed by \`${formatPath(trail)}\`: ${describeToken(token)})`);
1209
+ if (lookup.status === "unavailable") {
1210
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
1211
+ const path = formatPath(trail);
1212
+ const reason = `${lookup.message}\n (needed by \`${path}\`: ${describeToken(token)})`;
1213
+ throw new TokenResolutionError(`${where}${reason}`, {
1214
+ path,
1215
+ reason
1216
+ });
1217
+ }
1188
1218
  const hit = walkPath(lookup.outputs, path);
1189
1219
  if (!hit.ok) {
1190
1220
  if (lookup.schema !== void 0 && isOptionalField(lookup.schema, path, hit.at)) return this.omit("an absent optional output");
@@ -1203,11 +1233,11 @@ var Resolver = class {
1203
1233
  const name = optional ? operand.name : operand;
1204
1234
  if (typeof name !== "string") return this.fail(trail, "is a malformed $env token.", scope);
1205
1235
  const builtins = this.sources.builtins;
1206
- if ((name === "userData" || name === "projectRoot") && builtins?.[name]) return builtins[name];
1236
+ if (isBuiltinEnvName(name) && builtins?.[name]) return builtins[name];
1207
1237
  const value = this.sources.env?.[name];
1208
1238
  if (value !== void 0) return value;
1209
1239
  if (optional) return this.omit("an optional $env").value;
1210
- return this.fail(trail, `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: "${name}", optional: true } } to omit the property when unset).`, scope);
1240
+ return this.fail(trail, unsetEnvMessage(name), scope);
1211
1241
  }
1212
1242
  concat(parts, trail, scope = []) {
1213
1243
  if (!Array.isArray(parts)) return this.fail(trail, "is a malformed $concat token.", scope);
@@ -1500,6 +1530,6 @@ function expectHost(input) {
1500
1530
  return expectation;
1501
1531
  }
1502
1532
  //#endregion
1503
- export { PlanError, TokenResolutionError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, checkOutputPaths, checkTokenSites, collectTokenSites, compoundOutputSource, describeMapElements, describeToken, envSitesOf, expectHost, findRemovedForms, formatPath, isStructuralMultiReactor, memberForRef, mergeDefaultDrives, outputRefsOf, outputSitesOf, planCompound, primaryBackend, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolEnv, reactorClientMode, rebaseDriveUrl, refKey, remoteBackendUrls, renderTokens, resolveHostOutputs, runRecordMemberSchema, runRecordSchema, schemaAtPath, unwrapEscapes };
1533
+ export { PlanError, TokenResolutionError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, checkOutputPaths, checkTokenSites, collectTokenSites, compoundOutputSource, describeMapElements, describeToken, envSitesOf, expectHost, findRemovedForms, formatPath, isStructuralMultiReactor, memberForRef, mergeDefaultDrives, outputRefsOf, outputSitesOf, planCompound, primaryBackend, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolConflicts, protocolEnv, reactorClientMode, rebaseDriveUrl, refKey, remoteBackendUrls, renderTokens, resolveHostOutputs, runRecordMemberSchema, runRecordSchema, schemaAtPath, unwrapEscapes };
1504
1534
 
1505
1535
  //# sourceMappingURL=projection.mjs.map