@happyvertical/smrt-app-runtime 0.55.21 → 0.55.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/dist/chunks/{src-D7cM0zHW.js → src-vP6GV99v.js} +6 -3
- package/dist/chunks/src-vP6GV99v.js.map +1 -0
- package/dist/deployed-runtime.d.ts +1 -0
- package/dist/deployed-runtime.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +5 -5
- package/dist/sveltekit.js +1 -1
- package/package.json +8 -8
- package/dist/chunks/src-D7cM0zHW.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-D7cM0zHW.js","names":["copy"],"sources":["../../src/deployed-runtime.ts","../../src/direct-membership.ts","../../src/plain-data.ts","../../src/local-mcp-tokens.ts","../../src/application-identity.ts","../../src/error-code.ts","../../src/stale-reclaim.ts","../../src/operation-lock.ts","../../src/provider-readiness.ts","../../src/runtime-diagnostics.ts","../../src/state-root.ts","../../src/writer-lease.ts","../../src/index.ts"],"sourcesContent":["/**\n * Application-side composition for public self-hosted and managed-cloud\n * runtimes. Provider credentials and vendor clients remain in their owning\n * adapters; this module validates the selected seams, owns the PostgreSQL\n * connection lifecycle, and exposes orchestration-safe diagnostics.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport {\n type ApplicationRuntimeProfile,\n type AssetStorageProvider,\n type AuthenticationProvider,\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n type SecretProvider,\n} from '@happyvertical/smrt-config';\nimport {\n ScheduleRunner,\n type ScheduleRunnerConfig,\n TaskRunner,\n type TaskRunnerConfig,\n} from '@happyvertical/smrt-jobs';\nimport { SessionService } from '@happyvertical/smrt-users';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\nexport type DeployedApplicationRuntimeProfile = Exclude<\n ApplicationRuntimeProfile,\n 'local'\n>;\n\nexport type PublicAuthenticationProvider = Exclude<\n AuthenticationProvider,\n 'owner-bootstrap'\n>;\n\nexport type DeployedRuntimeComponent =\n | 'database'\n | 'authentication'\n | 'assets'\n | 'secrets';\n\n/**\n * A provider-owned readiness boundary.\n *\n * The callback should prove that required configuration is present and that\n * the provider is usable. It must not return credentials or secret values.\n */\nexport interface DeployedProviderBinding<Provider extends string> {\n readonly provider: Provider;\n readonly readiness: () => Promise<void>;\n}\n\n/** PostgreSQL connection factory. URLs and credentials stay in this adapter. */\nexport interface DeployedDatabaseBinding {\n readonly engine: 'postgres';\n readonly connect: () => Promise<DatabaseInterface>;\n readonly readiness?: (db: DatabaseInterface) => Promise<void>;\n /**\n * Provider-owned cleanup boundary, required before a connection is opened.\n * Keeping cleanup on the binding also covers malformed connection handles.\n */\n readonly close: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedApplicationRuntimeOptions {\n readonly profile: DeployedApplicationRuntimeProfile;\n /** Validated selector overrides; never put credentials in this object. */\n readonly providers?: RuntimeProviderOverrides;\n readonly database: DeployedDatabaseBinding;\n readonly authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n readonly assets: DeployedProviderBinding<AssetStorageProvider>;\n readonly secrets: DeployedProviderBinding<SecretProvider>;\n /** Explicit, idempotent application migration hook. */\n readonly prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedProviderDiagnostic {\n readonly provider: string;\n readonly configured: true;\n}\n\nexport interface DeployedRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly providers: {\n readonly database: DeployedProviderDiagnostic;\n readonly authentication: DeployedProviderDiagnostic;\n readonly assets: DeployedProviderDiagnostic;\n readonly secrets: DeployedProviderDiagnostic;\n };\n readonly tenancy: {\n readonly mode: 'single-tenant' | 'multi-tenant';\n readonly context: 'defaulted' | 'required';\n readonly isolation: 'application' | 'database-rls';\n readonly rootTenantFallback: 'disabled';\n };\n readonly workers: {\n readonly topology: 'external' | 'scalable';\n readonly taskProcess: 'separate';\n readonly scheduleProcess: 'separate';\n readonly replicas: 'operator-managed' | 'horizontal';\n };\n readonly secretValuesIncluded: false;\n}\n\nexport interface DeployedRuntimeHealth {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'healthy' | 'stopped';\n}\n\nexport interface DeployedComponentReadiness {\n readonly status: 'ready' | 'not-ready';\n}\n\nexport interface DeployedRuntimeReadiness {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'ready' | 'not-ready';\n readonly components: Readonly<\n Record<DeployedRuntimeComponent, DeployedComponentReadiness>\n >;\n readonly secretValuesIncluded: false;\n}\n\nexport type DeployedRuntimeErrorCode =\n | 'invalid_configuration'\n | 'provider_mismatch'\n | 'provider_unavailable'\n | 'tenant_context_required'\n | 'tenant_context_unauthorized'\n | 'runtime_stopped';\n\n/** Stable failure that never includes a provider's underlying error text. */\nexport class DeployedRuntimeError extends Error {\n constructor(\n readonly code: DeployedRuntimeErrorCode,\n message: string,\n readonly component?: DeployedRuntimeComponent,\n ) {\n super(message);\n this.name = 'DeployedRuntimeError';\n }\n}\n\n/** Startup failure that retains the only safe retry path for database cleanup. */\nexport class DeployedRuntimeCleanupError extends DeployedRuntimeError {\n private cleaned = false;\n private cleanupAttempt?: Promise<void>;\n\n constructor(private readonly cleanup: () => Promise<void>) {\n super(\n 'provider_unavailable',\n \"The database connection could not be closed after startup failed; retry cleanup and inspect the provider's private logs.\",\n 'database',\n );\n this.name = 'DeployedRuntimeCleanupError';\n }\n\n async retryCleanup(): Promise<void> {\n if (this.cleaned) return;\n if (!this.cleanupAttempt) {\n this.cleanupAttempt = Promise.resolve()\n .then(() => this.cleanup())\n .then(() => {\n this.cleaned = true;\n })\n .catch(() => {\n throw this;\n })\n .finally(() => {\n this.cleanupAttempt = undefined;\n });\n }\n return this.cleanupAttempt;\n }\n}\n\n/** Session fields that carry tenant-authorization provenance. */\nexport type SessionTenantAuthorizationEvidence = Pick<\n NonNullable<Awaited<ReturnType<SessionService['loadSessionContext']>>>,\n 'membership' | 'tenantAuthorization'\n>;\n\n/**\n * The single rule for whether a loaded session may act in its tenant.\n *\n * True only for a verified ACTIVE direct membership whose id is the resolved\n * authorization (and is not inherited), or — with no direct membership — a\n * resolved authorization inherited from a named ancestor tenant. Accessor\n * failures propagate so callers can fail closed.\n */\nexport function isSessionTenantAuthorized(\n context: SessionTenantAuthorizationEvidence,\n): boolean {\n const membership = context.membership;\n const authorization = context.tenantAuthorization;\n const membershipId = authorization?.membershipId;\n const validMembershipId =\n typeof membershipId === 'string' && membershipId.trim().length > 0;\n if (membership?.isActive() === true) {\n return (\n validMembershipId &&\n membership.id === membershipId &&\n authorization?.inheritedFromTenantId === null\n );\n }\n if (membership === null) {\n return (\n validMembershipId &&\n typeof authorization?.inheritedFromTenantId === 'string' &&\n authorization.inheritedFromTenantId.trim().length > 0\n );\n }\n return false;\n}\n\nexport interface DeployedApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createTaskWorker(config?: TaskRunnerConfig): Promise<TaskRunner>;\n createScheduleWorker(config?: ScheduleRunnerConfig): Promise<ScheduleRunner>;\n diagnostics(): DeployedRuntimeDiagnostics;\n health(): DeployedRuntimeHealth;\n readiness(): Promise<DeployedRuntimeReadiness>;\n close(): Promise<void>;\n}\n\ninterface ValidatedBindings {\n database: DeployedDatabaseBinding;\n authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n assets: DeployedProviderBinding<AssetStorageProvider>;\n secrets: DeployedProviderBinding<SecretProvider>;\n}\n\n/**\n * Initialize a self-hosted or cloud application composition.\n *\n * Configuration and provider identity are validated before a connection is\n * opened. Provider readiness and database migrations complete before the\n * runtime is returned. A failed initialization closes the acquired connection.\n */\nexport async function initializeDeployedApplicationRuntime(\n options: DeployedApplicationRuntimeOptions,\n): Promise<DeployedApplicationRuntime> {\n const resolvedRuntime = resolveDeployedRuntime(options);\n const bindings = validateBindings(options, resolvedRuntime);\n const prepareDatabase = snapshotPrepareDatabase(options);\n\n await checkProvider('authentication', () =>\n bindings.authentication.readiness(),\n );\n await checkProvider('assets', () => bindings.assets.readiness());\n await checkProvider('secrets', () => bindings.secrets.readiness());\n\n let db: DatabaseInterface | undefined;\n try {\n db = await bindings.database.connect();\n } catch {\n throw unavailable('database');\n }\n let validDatabase = false;\n try {\n validDatabase = isDatabaseInterface(db);\n } catch {\n // Treat throwing accessors on an untrusted handle as malformed.\n }\n if (!validDatabase) {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'invalid_configuration',\n 'The database adapter did not return a valid database connection.',\n 'database',\n ),\n );\n }\n try {\n await checkDatabase(bindings.database, db);\n } catch (error) {\n await cleanupAfterStartupFailure(bindings.database, db, error);\n }\n try {\n await prepareDatabase?.(db);\n } catch {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'provider_unavailable',\n 'The PostgreSQL migration step failed; inspect the application migration logs.',\n 'database',\n ),\n );\n }\n\n return new InitializedDeployedApplicationRuntime(\n db,\n resolvedRuntime,\n bindings,\n );\n}\n\nfunction resolveDeployedRuntime(\n options: DeployedApplicationRuntimeOptions,\n): ResolvedApplicationRuntime {\n let plainOptions = false;\n try {\n plainOptions = isPlainRecord(options);\n } catch {\n // Proxies and throwing prototype traps are invalid options.\n }\n if (!plainOptions) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options must be an object.',\n );\n }\n let profile: unknown;\n let providers: RuntimeProviderOverrides | undefined;\n try {\n profile = options.profile;\n providers = options.providers;\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options could not be read safely.',\n );\n }\n if (profile !== 'self-hosted' && profile !== 'cloud') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime initialization requires the self-hosted or cloud profile.',\n );\n }\n try {\n return resolveApplicationRuntime({ profile, providers });\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime provider options could not be read safely.',\n );\n }\n}\n\nfunction validateBindings(\n options: DeployedApplicationRuntimeOptions,\n runtime: ResolvedApplicationRuntime,\n): ValidatedBindings {\n const databaseSource = readBindingOption(options, 'database', 'database');\n const database = requireObjectBinding<DeployedDatabaseBinding>(\n databaseSource,\n 'database',\n );\n let engine: unknown;\n let connect: unknown;\n let readiness: unknown;\n let close: unknown;\n try {\n engine = database.engine;\n connect = database.connect;\n readiness = database.readiness;\n close = database.close;\n } catch {\n throw invalidBinding('database');\n }\n requireFunction(connect, 'database', 'connect');\n requireOptionalFunction(readiness, 'database', 'readiness');\n requireFunction(close, 'database', 'close');\n if (engine !== runtime.providers.database.engine) {\n throw mismatch('database', runtime.providers.database.engine);\n }\n const databaseSnapshot: DeployedDatabaseBinding = Object.freeze({\n engine: engine as 'postgres',\n connect: bindCallback(\n connect as DeployedDatabaseBinding['connect'],\n database,\n 'database',\n ),\n readiness:\n typeof readiness === 'function'\n ? bindCallback(\n readiness as NonNullable<DeployedDatabaseBinding['readiness']>,\n database,\n 'database',\n )\n : undefined,\n close: bindCallback(\n close as DeployedDatabaseBinding['close'],\n database,\n 'database',\n ),\n });\n\n const authentication = requireProviderBinding(\n readBindingOption(options, 'authentication', 'authentication'),\n 'authentication',\n runtime.providers.authentication.provider,\n ) as DeployedProviderBinding<PublicAuthenticationProvider>;\n const assets = requireProviderBinding(\n readBindingOption(options, 'assets', 'assets'),\n 'assets',\n runtime.providers.assets.provider,\n ) as DeployedProviderBinding<AssetStorageProvider>;\n const secrets = requireProviderBinding(\n readBindingOption(options, 'secrets', 'secrets'),\n 'secrets',\n runtime.providers.secrets.provider,\n ) as DeployedProviderBinding<SecretProvider>;\n\n return {\n database: databaseSnapshot,\n authentication,\n assets,\n secrets,\n };\n}\n\nfunction snapshotPrepareDatabase(\n options: DeployedApplicationRuntimeOptions,\n): DeployedApplicationRuntimeOptions['prepareDatabase'] {\n let prepareDatabase: unknown;\n try {\n prepareDatabase = options.prepareDatabase;\n } catch {\n throw invalidBinding('database');\n }\n requireOptionalFunction(prepareDatabase, 'database', 'prepareDatabase');\n return typeof prepareDatabase === 'function'\n ? bindCallback(\n prepareDatabase as NonNullable<\n DeployedApplicationRuntimeOptions['prepareDatabase']\n >,\n options,\n 'database',\n )\n : undefined;\n}\n\nfunction readBindingOption(\n options: DeployedApplicationRuntimeOptions,\n field: 'database' | 'authentication' | 'assets' | 'secrets',\n component: DeployedRuntimeComponent,\n): unknown {\n try {\n return options[field];\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireProviderBinding(\n value: unknown,\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n expectedProvider: string,\n): DeployedProviderBinding<string> {\n const binding = requireObjectBinding<DeployedProviderBinding<string>>(\n value,\n component,\n );\n let provider: unknown;\n let readiness: unknown;\n try {\n provider = binding.provider;\n readiness = binding.readiness;\n } catch {\n throw invalidBinding(component);\n }\n if (provider !== expectedProvider) {\n throw mismatch(component, expectedProvider);\n }\n requireFunction(readiness, component, 'readiness');\n return Object.freeze({\n provider: provider as string,\n readiness: bindCallback(\n readiness as DeployedProviderBinding<string>['readiness'],\n binding,\n component,\n ),\n });\n}\n\nfunction requireObjectBinding<T>(\n value: unknown,\n component: DeployedRuntimeComponent,\n): T {\n let valid = false;\n try {\n valid =\n typeof value === 'object' && value !== null && !Array.isArray(value);\n } catch {\n // Revoked proxies and throwing shape traps are invalid bindings.\n }\n if (!valid) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding is required.`,\n component,\n );\n }\n return value as T;\n}\n\nfunction invalidBinding(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding could not be read safely.`,\n component,\n );\n}\n\nfunction bindCallback<T>(\n callback: T,\n receiver: unknown,\n component: DeployedRuntimeComponent,\n): T {\n try {\n return Reflect.apply(\n Function.prototype.bind,\n callback as (...args: never[]) => unknown,\n [receiver],\n ) as T;\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (typeof value !== 'function') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider requires a ${field} callback.`,\n component,\n );\n }\n}\n\nfunction requireOptionalFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (value !== undefined) requireFunction(value, component, field);\n}\n\nfunction mismatch(\n component: DeployedRuntimeComponent,\n expectedProvider: string,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_mismatch',\n `The ${component} binding does not match the selected ${expectedProvider} provider.`,\n component,\n );\n}\n\nfunction unavailable(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_unavailable',\n `The ${component} provider is not ready; inspect that provider's private logs.`,\n component,\n );\n}\n\nasync function checkProvider(\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n check: () => Promise<void>,\n): Promise<void> {\n try {\n await check();\n } catch {\n throw unavailable(component);\n }\n}\n\nasync function checkDatabase(\n binding: DeployedDatabaseBinding,\n db: DatabaseInterface,\n): Promise<void> {\n try {\n await binding.readiness?.(db);\n const result = await db.query(\n \"SELECT current_setting('server_version_num') AS smrt_postgres_version\",\n );\n if (!isValidPostgresProbe(result)) throw new Error('invalid probe');\n } catch {\n throw unavailable('database');\n }\n}\n\nclass InitializedDeployedApplicationRuntime\n implements DeployedApplicationRuntime\n{\n private state: 'running' | 'closing' | 'close-failed' | 'stopped' = 'running';\n private closeAttempt?: Promise<void>;\n private readonly pendingReadinessChecks = new Set<Promise<unknown>>();\n private readonly pendingSessionRestorations = new Set<Promise<unknown>>();\n private readonly pendingWorkerInitializations = new Set<Promise<unknown>>();\n private readonly pendingWorkerOperations = new Set<Promise<unknown>>();\n private readonly lifecycleOperationContext = new AsyncLocalStorage<symbol>();\n private readonly activeLifecycleOperations = new Set<symbol>();\n private readonly workerCleanups = new Set<() => Promise<void>>();\n private readonly sessionService: SessionService;\n private sessionServiceReady?: Promise<void>;\n private readonly snapshot: DeployedRuntimeDiagnostics;\n\n constructor(\n readonly db: DatabaseInterface,\n readonly resolvedRuntime: ResolvedApplicationRuntime,\n private readonly bindings: ValidatedBindings,\n ) {\n this.snapshot = createDiagnostics(resolvedRuntime);\n this.sessionService = new SessionService({ db });\n }\n\n async restoreSession(sessionId: string) {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.restoreSessionWhileRunning(sessionId),\n );\n this.pendingSessionRestorations.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingSessionRestorations.delete(operation);\n }\n }\n\n private async restoreSessionWhileRunning(sessionId: string) {\n let context: Awaited<ReturnType<SessionService['loadSessionContext']>>;\n try {\n await this.initializeSessionService();\n context = await this.sessionService.loadSessionContext(sessionId);\n } catch {\n throw unavailable('authentication');\n }\n this.assertRunning();\n if (\n context &&\n this.resolvedRuntime.providers.tenancy.context === 'required'\n ) {\n let tenantId: unknown;\n try {\n tenantId = context.tenantId;\n } catch {\n throw unavailable('authentication');\n }\n if (typeof tenantId !== 'string' || tenantId.trim().length === 0) {\n throw new DeployedRuntimeError(\n 'tenant_context_required',\n 'The authenticated session does not include the required tenant context.',\n 'authentication',\n );\n }\n let tenantAuthorized = false;\n try {\n tenantAuthorized = isSessionTenantAuthorized(context);\n } catch {\n throw unavailable('authentication');\n }\n if (!tenantAuthorized) {\n throw new DeployedRuntimeError(\n 'tenant_context_unauthorized',\n 'The authenticated session is not authorized for its tenant context.',\n 'authentication',\n );\n }\n }\n return context;\n }\n\n async createTaskWorker(config: TaskRunnerConfig = {}): Promise<TaskRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeTaskWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n async createScheduleWorker(\n config: ScheduleRunnerConfig = {},\n ): Promise<ScheduleRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeScheduleWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n diagnostics(): DeployedRuntimeDiagnostics {\n return this.snapshot;\n }\n\n health(): DeployedRuntimeHealth {\n return Object.freeze({\n schemaVersion: 1 as const,\n profile: this.resolvedRuntime\n .profile as DeployedApplicationRuntimeProfile,\n status:\n this.state === 'running' ? ('healthy' as const) : ('stopped' as const),\n });\n }\n\n async readiness(): Promise<DeployedRuntimeReadiness> {\n if (this.state !== 'running')\n return createStoppedReadiness(this.resolvedRuntime.profile);\n\n const operation = this.beginLifecycleOperation(() =>\n this.checkReadinessWhileRunning(),\n );\n this.pendingReadinessChecks.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingReadinessChecks.delete(operation);\n }\n }\n\n private async checkReadinessWhileRunning(): Promise<DeployedRuntimeReadiness> {\n const results = await Promise.all([\n probe(() => checkDatabase(this.bindings.database, this.db)),\n probe(() => this.bindings.authentication.readiness()),\n probe(() => this.bindings.assets.readiness()),\n probe(() => this.bindings.secrets.readiness()),\n ]);\n if (this.state !== 'running') {\n return createStoppedReadiness(this.resolvedRuntime.profile);\n }\n const [database, authentication, assets, secrets] = results;\n return freezeReadiness(\n this.resolvedRuntime.profile,\n { database, authentication, assets, secrets },\n results.every((result) => result.status === 'ready'),\n );\n }\n\n async close(): Promise<void> {\n const operationToken = this.lifecycleOperationContext.getStore();\n const requestedFromLifecycleOperation =\n operationToken !== undefined &&\n this.activeLifecycleOperations.has(operationToken);\n if (this.state === 'stopped') return;\n if (this.closeAttempt) {\n if (requestedFromLifecycleOperation) return;\n return this.closeAttempt;\n }\n\n this.state = 'closing';\n const pendingOperations = [\n ...this.pendingReadinessChecks,\n ...this.pendingSessionRestorations,\n ...this.pendingWorkerInitializations,\n ...this.pendingWorkerOperations,\n ];\n const shutdownToken = Symbol('deployed-runtime-shutdown');\n this.activeLifecycleOperations.add(shutdownToken);\n const attempt = Promise.resolve()\n .then(() =>\n this.lifecycleOperationContext.run(shutdownToken, async () => {\n await Promise.allSettled(pendingOperations);\n await this.cleanupWorkers();\n await this.closeConnection();\n }),\n )\n .finally(() => {\n this.activeLifecycleOperations.delete(shutdownToken);\n });\n this.closeAttempt = attempt.finally(() => {\n this.closeAttempt = undefined;\n });\n if (requestedFromLifecycleOperation) {\n // The lifecycle callback cannot await the shutdown pipeline without\n // deadlocking on itself. It receives an acknowledgement instead, but the\n // internally owned attempt still needs a rejection observer until an\n // outside caller can retry the failed cleanup.\n void this.closeAttempt.catch(() => undefined);\n return;\n }\n return this.closeAttempt;\n }\n\n private async initializeTaskWorker(\n config: TaskRunnerConfig,\n ): Promise<TaskRunner> {\n let runner: TaskRunner | undefined;\n try {\n runner = new TaskRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async initializeScheduleWorker(\n config: ScheduleRunnerConfig,\n ): Promise<ScheduleRunner> {\n let runner: ScheduleRunner | undefined;\n try {\n runner = new ScheduleRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async stopOrRetainUnreturnedWorker(runner: {\n stop(): Promise<void>;\n }): Promise<void> {\n const cleanup = () => runner.stop();\n try {\n await cleanup();\n } catch {\n this.workerCleanups.add(cleanup);\n }\n }\n\n private retainWorker<Runner extends TaskRunner | ScheduleRunner>(\n runner: Runner,\n ): Runner {\n const start = runner.start.bind(runner);\n const stop = runner.stop.bind(runner);\n let operationTail = Promise.resolve();\n const queueOperation = (callback: () => Promise<void>): Promise<void> => {\n const previous = operationTail;\n const operation = this.beginLifecycleOperation(async () => {\n await previous;\n await callback();\n });\n operationTail = operation.catch(() => undefined);\n this.pendingWorkerOperations.add(operation);\n void operation.then(\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n );\n return operation;\n };\n const ownedStart = async (): Promise<void> => {\n this.assertRunning();\n return queueOperation(async () => {\n this.assertRunning();\n try {\n await start();\n this.assertRunning();\n } catch {\n // A runner can reject after it has made itself live (for example,\n // when a runner:started listener throws). Keep this cleanup inside\n // the tracked lifecycle operation so shutdown cannot call stop()\n // concurrently on the same runner.\n if (this.state === 'running') {\n try {\n await stop();\n } catch {\n // The runtime-owned cleanup is already retained in workerCleanups.\n }\n }\n if (this.state !== 'running') this.assertRunning();\n throw unavailable('database');\n }\n });\n };\n const ownedStop = (): Promise<void> =>\n queueOperation(async () => {\n try {\n await stop();\n } catch {\n throw unavailable('database');\n }\n });\n Object.defineProperties(runner, {\n start: {\n configurable: false,\n enumerable: false,\n value: ownedStart,\n writable: false,\n },\n stop: {\n configurable: false,\n enumerable: false,\n value: ownedStop,\n writable: false,\n },\n });\n this.workerCleanups.add(ownedStop);\n return runner;\n }\n\n private async cleanupWorkers(): Promise<void> {\n const cleanups = [...this.workerCleanups];\n const results = await Promise.allSettled(\n cleanups.map((cleanup) => Promise.resolve().then(cleanup)),\n );\n let cleanupFailed = false;\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n const cleanup = cleanups[index];\n if (cleanup) this.workerCleanups.delete(cleanup);\n } else cleanupFailed = true;\n }\n if (cleanupFailed) {\n this.state = 'close-failed';\n throw unavailable('database');\n }\n }\n\n private initializeSessionService(): Promise<void> {\n if (!this.sessionServiceReady) {\n this.sessionServiceReady = this.sessionService\n .initialize()\n .catch((error) => {\n this.sessionServiceReady = undefined;\n throw error;\n });\n }\n return this.sessionServiceReady;\n }\n\n private beginLifecycleOperation<T>(operation: () => Promise<T>): Promise<T> {\n const token = Symbol('deployed-runtime-operation');\n this.activeLifecycleOperations.add(token);\n return Promise.resolve()\n .then(() => this.lifecycleOperationContext.run(token, operation))\n .finally(() => {\n this.activeLifecycleOperations.delete(token);\n });\n }\n\n private async closeConnection(): Promise<void> {\n try {\n await this.bindings.database.close(this.db);\n this.state = 'stopped';\n } catch {\n this.state = 'close-failed';\n throw new DeployedRuntimeError(\n 'provider_unavailable',\n \"The database connection could not be closed; inspect the provider's private logs.\",\n 'database',\n );\n }\n }\n\n private assertRunning(): void {\n if (this.state !== 'running') {\n throw new DeployedRuntimeError(\n 'runtime_stopped',\n 'The deployed application runtime has already stopped.',\n );\n }\n }\n}\n\nfunction createDiagnostics(\n runtime: ResolvedApplicationRuntime,\n): DeployedRuntimeDiagnostics {\n const provider = (value: string): DeployedProviderDiagnostic =>\n Object.freeze({ provider: value, configured: true as const });\n return deepFreeze({\n schemaVersion: 1 as const,\n runtime,\n providers: {\n database: provider(runtime.providers.database.engine),\n authentication: provider(runtime.providers.authentication.provider),\n assets: provider(runtime.providers.assets.provider),\n secrets: provider(runtime.providers.secrets.provider),\n },\n tenancy: {\n mode: runtime.providers.tenancy.mode as 'single-tenant' | 'multi-tenant',\n context: runtime.providers.tenancy.context,\n isolation: runtime.providers.tenancy.isolation,\n rootTenantFallback: 'disabled' as const,\n },\n workers: {\n topology: runtime.providers.jobs.topology as 'external' | 'scalable',\n taskProcess: 'separate' as const,\n scheduleProcess: 'separate' as const,\n replicas:\n runtime.providers.jobs.topology === 'scalable'\n ? ('horizontal' as const)\n : ('operator-managed' as const),\n },\n secretValuesIncluded: false as const,\n });\n}\n\nasync function probe(\n check: () => Promise<void>,\n): Promise<DeployedComponentReadiness> {\n try {\n await check();\n return Object.freeze({ status: 'ready' as const });\n } catch {\n return Object.freeze({ status: 'not-ready' as const });\n }\n}\n\nfunction createStoppedReadiness(\n profile: ApplicationRuntimeProfile,\n): DeployedRuntimeReadiness {\n const stopped = Object.freeze({ status: 'not-ready' as const });\n return freezeReadiness(\n profile,\n {\n database: stopped,\n authentication: stopped,\n assets: stopped,\n secrets: stopped,\n },\n false,\n );\n}\n\nfunction freezeReadiness(\n profile: ApplicationRuntimeProfile,\n components: Record<DeployedRuntimeComponent, DeployedComponentReadiness>,\n ready: boolean,\n): DeployedRuntimeReadiness {\n return deepFreeze({\n schemaVersion: 1 as const,\n profile: profile as DeployedApplicationRuntimeProfile,\n status: ready ? ('ready' as const) : ('not-ready' as const),\n components,\n secretValuesIncluded: false as const,\n });\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDatabaseInterface(value: unknown): value is DatabaseInterface {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { query?: unknown }).query === 'function'\n );\n}\n\nfunction isValidPostgresProbe(\n value: unknown,\n): value is { rows: Array<{ smrt_postgres_version: string }> } {\n if (typeof value !== 'object' || value === null) return false;\n const rows = (value as { rows?: unknown }).rows;\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n const row = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n const version = (row as { smrt_postgres_version?: unknown })\n .smrt_postgres_version;\n return typeof version === 'string' && /^\\d+$/.test(version);\n}\n\nasync function cleanupAfterStartupFailure(\n binding: DeployedDatabaseBinding,\n db: unknown,\n startupError: unknown,\n): Promise<never> {\n const cleanup = () => binding.close(db as DatabaseInterface);\n try {\n await cleanup();\n } catch {\n throw new DeployedRuntimeCleanupError(cleanup);\n }\n throw startupError;\n}\n\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value && typeof value === 'object') {\n if (seen.has(value)) return value;\n seen.add(value);\n if (!Object.isFrozen(value)) Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child, seen);\n }\n }\n return value;\n}\n","/**\n * Tenant-binding permission resolution for bearer principals (#3413 review\n * F1, I1). The authentication adapter states how a principal's tenant\n * authority may be established:\n *\n * - `direct`: only the principal's own active membership row in exactly its\n * tenant (local owner tokens, the default hosted resolver).\n * - `direct-or-inherited`: the session step's rule\n * ({@link isSessionTenantAuthorized}): that direct row, or, when no direct\n * row exists at all, authority inherited from an active inheritable\n * ancestor membership (hosted application-owned mappings).\n *\n * The direct row, when it exists, is pinned into `PermissionResolver`, so\n * inheritance never substitutes for a suspended or pending direct row; in\n * `direct` mode it never substitutes for a deleted one either.\n *\n * @internal\n */\n\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport type {\n MembershipCollection,\n PermissionResolver,\n} from '@happyvertical/smrt-users';\nimport { isSessionTenantAuthorized } from './deployed-runtime.js';\n\n/** How a bound principal's tenant authority may be established. */\nexport type TenantBindingMode = 'direct' | 'direct-or-inherited';\n\n/** The authorizing membership and the live permissions it grants. */\nexport interface BoundMembershipPermissions {\n readonly membershipId: string;\n readonly inheritedFromTenantId: string | null;\n readonly permissions: ReadonlySet<string>;\n}\n\n/**\n * Resolve `userId`'s live permissions in `tenantId` under `binding`, or\n * `null` when that mode does not authorize the principal there.\n */\nexport async function resolveBoundMembershipPermissions(options: {\n readonly memberships: MembershipCollection;\n readonly resolver: PermissionResolver;\n readonly userId: string;\n readonly tenantId: string;\n readonly binding: TenantBindingMode;\n}): Promise<BoundMembershipPermissions | null> {\n const { memberships, resolver, userId, tenantId, binding } = options;\n // Keyed by the explicit user and tenant only; the ambient (cookie) tenant\n // filter must not hide or substitute the row.\n const direct = await withSystemContext(() =>\n memberships.findByUserAndTenant(userId, tenantId),\n );\n if (direct) {\n if (\n direct.userId !== userId ||\n direct.tenantId !== tenantId ||\n !direct.isActive()\n ) {\n return null;\n }\n } else if (binding !== 'direct-or-inherited') {\n return null;\n }\n // Pin the raw lookup: a direct row authorizes alone; `null` asserts that\n // no direct row exists and lets the resolver consider inheritance.\n const resolved = await resolver.resolvePermissions(userId, tenantId, {\n membership: direct ?? null,\n });\n const authorized = isSessionTenantAuthorized({\n membership: direct ?? null,\n tenantAuthorization: {\n membershipId: resolved.membershipId,\n inheritedFromTenantId: resolved.inheritedFromTenantId,\n },\n });\n if (!authorized || !resolved.membershipId) return null;\n return {\n membershipId: resolved.membershipId,\n inheritedFromTenantId: resolved.inheritedFromTenantId,\n permissions: resolved.permissions,\n };\n}\n","/**\n * Hardened copies of caller-supplied plain data (#3413 review N1).\n *\n * Every copy is built from own data properties only, into null-prototype\n * objects and fresh dense arrays, and deep-frozen. It rejects, at every\n * depth: the keys `__proto__`, `constructor` and `prototype`; accessor\n * properties (getters are never invoked); objects whose prototype is not\n * `Object.prototype` or `null` (class instances, objects inheriting data);\n * arrays that are sparse, subclassed or carry extra own keys; functions; and\n * nesting deeper than {@link MAX_PLAIN_DATA_DEPTH}. Non-enumerable own\n * properties are dropped.\n *\n * @internal\n */\n\n/** Keys that can rewrite a prototype or impersonate a constructor. */\nexport const FORBIDDEN_DATA_KEYS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n/** Deepest accepted nesting. */\nexport const MAX_PLAIN_DATA_DEPTH = 8;\n\n/** Thrown for input that is not acceptable plain data. */\nexport class PlainDataError extends Error {\n override readonly name = 'PlainDataError';\n}\n\n/** Deep-frozen copy of `value`, or a {@link PlainDataError}. */\nexport function deepFrozenPlainCopy(value: unknown, depth = 0): unknown {\n if (typeof value === 'function') {\n throw new PlainDataError('may contain only plain data');\n }\n if (value === null || typeof value !== 'object') return value;\n if (depth > MAX_PLAIN_DATA_DEPTH) {\n throw new PlainDataError('is nested too deeply');\n }\n if (Array.isArray(value)) {\n if (Object.getPrototypeOf(value) !== Array.prototype) {\n throw new PlainDataError('may contain only plain arrays');\n }\n const length = value.length;\n for (const key of Reflect.ownKeys(value)) {\n if (key === 'length') continue;\n if (\n typeof key !== 'string' ||\n !/^(?:0|[1-9][0-9]*)$/u.test(key) ||\n Number(key) >= length\n ) {\n throw new PlainDataError('may contain only plain arrays');\n }\n }\n const copy: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n const descriptor = Reflect.getOwnPropertyDescriptor(value, index);\n if (!descriptor || !('value' in descriptor)) {\n throw new PlainDataError('may contain only dense data arrays');\n }\n Object.defineProperty(copy, index, {\n value: deepFrozenPlainCopy(descriptor.value, depth + 1),\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n return Object.freeze(copy);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new PlainDataError('may contain only plain data');\n }\n const copy = Object.create(null) as Record<PropertyKey, unknown>;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === 'string' && FORBIDDEN_DATA_KEYS.has(key)) {\n throw new PlainDataError(`may not contain the key ${key}`);\n }\n const descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n if (!descriptor?.enumerable) continue;\n if (!('value' in descriptor)) {\n throw new PlainDataError('may not contain accessor properties');\n }\n Object.defineProperty(copy, key, {\n value: deepFrozenPlainCopy(descriptor.value, depth + 1),\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n return Object.freeze(copy);\n}\n\n/** Own data value of `key` on a copy made by {@link deepFrozenPlainCopy}. */\nexport function ownValue(record: object, key: PropertyKey): unknown {\n return Object.hasOwn(record, key)\n ? (record as Record<PropertyKey, unknown>)[key]\n : undefined;\n}\n","/**\n * Owner-minted bearer tokens for local MCP clients (`local` profile only).\n *\n * A token is a random 256-bit value with a fixed prefix. The runtime stores\n * only a domain-separated HMAC of it (keyed by the local application secret)\n * in the runtime-owned `_smrt_local_mcp_tokens` system table, alongside the\n * owner's user and tenant, the granted scopes and the expiry. The plaintext\n * is returned exactly once, by `issue()`.\n *\n * A token never carries more authority than its owner holds *now*: `issue()`\n * refuses scopes the owner does not currently hold, and `verify()` returns\n * the token's scopes intersected with the owner's live permissions from its\n * active direct membership in the bound tenant (inherited authority never\n * substitutes for it; no such membership, an inactive user, a revoked or an\n * expired token all yield `null`). Routes should still bind the principal with\n * `runtime.runAsPrincipal`, which applies the same intersection inside the\n * request permission context.\n */\n\nimport { createHmac, randomBytes, randomUUID } from 'node:crypto';\nimport {\n MembershipCollection,\n PermissionResolver,\n UserCollection,\n UserStatus,\n} from '@happyvertical/smrt-users';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { resolveBoundMembershipPermissions } from './direct-membership.js';\nimport { deepFrozenPlainCopy, ownValue, PlainDataError } from './plain-data.js';\n\n/** Runtime-owned system table; ignored by schema diff, parity and portability. */\nexport const LOCAL_MCP_TOKEN_TABLE = '_smrt_local_mcp_tokens';\n/** Prefix of every local MCP token (aids secret scanning). */\nexport const LOCAL_MCP_TOKEN_PREFIX = 'smrt_mcp_';\n/** Default token lifetime: 30 days. */\nexport const DEFAULT_LOCAL_MCP_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n/** Longest token lifetime: 365 days. There is no non-expiring token. */\nexport const MAX_LOCAL_MCP_TOKEN_TTL_SECONDS = 365 * 24 * 60 * 60;\n\nconst MAX_SCOPES = 64;\nconst MAX_SCOPE_LENGTH = 128;\nconst MAX_LABEL_LENGTH = 80;\nconst SCOPE_PATTERN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/u;\nconst TOKEN_PATTERN = /^smrt_mcp_[A-Za-z0-9_-]{43}$/u;\nconst TOKEN_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;\n/** Domain separation from the owner-bootstrap HMAC sharing the same secret. */\nconst HMAC_DOMAIN = 'smrt.local-mcp-token.v1\\0';\n\n/** Input for {@link LocalMcpTokenStore.issue}. */\nexport interface IssueLocalMcpTokenInput {\n /** Permission slugs the token may use. Each must be held by the owner. */\n readonly scopes: readonly string[];\n /**\n * Lifetime in whole seconds, 60..{@link MAX_LOCAL_MCP_TOKEN_TTL_SECONDS}.\n * Defaults to {@link DEFAULT_LOCAL_MCP_TOKEN_TTL_SECONDS}.\n */\n readonly expiresInSeconds?: number;\n /** Operator note shown by `list()` (printable, at most 80 characters). */\n readonly label?: string;\n}\n\n/** The one-time result of {@link LocalMcpTokenStore.issue}. */\nexport interface IssuedLocalMcpToken {\n /** Public token id used by `list()`/`revoke()`; not a credential. */\n readonly id: string;\n /** The bearer credential. Shown once; only its HMAC is stored. */\n readonly token: string;\n readonly scopes: readonly string[];\n readonly label: string | null;\n readonly createdAt: string;\n readonly expiresAt: string;\n}\n\n/** Lifecycle state of a stored token. */\nexport type LocalMcpTokenStatus = 'active' | 'expired' | 'revoked';\n\n/** Secret-free token metadata returned by {@link LocalMcpTokenStore.list}. */\nexport interface LocalMcpTokenRecord {\n readonly id: string;\n readonly scopes: readonly string[];\n readonly label: string | null;\n readonly createdAt: string;\n readonly expiresAt: string;\n readonly revokedAt: string | null;\n readonly status: LocalMcpTokenStatus;\n}\n\n/**\n * Brand on every principal `verify()` returns. It is an enumerable symbol, so\n * a spread copy keeps it and `runAsPrincipal` can refuse any attempt to widen\n * the binding of a token-derived principal.\n *\n * @internal\n */\nexport const LOCAL_MCP_TOKEN_PRINCIPAL: unique symbol = Symbol.for(\n '@happyvertical/smrt-app-runtime/local-mcp-token-principal',\n);\n\n/**\n * A verified token principal, structurally an MCP app principal. `scopes`\n * are the token scopes the owner still holds in `tenantId`. The object is\n * frozen (its `scopes` array too) and always binds `direct`: passed straight to `runAsPrincipal`, it\n * is authorized only by the owner's active direct membership in `tenantId`.\n * A copy that sets any other `tenantBinding` is rejected, not ignored.\n */\nexport interface LocalMcpTokenPrincipal {\n readonly id: string;\n readonly tenantId: string;\n readonly kind: 'human';\n /** Frozen: token scopes ∩ live permissions at verification. */\n readonly scopes: readonly string[];\n readonly tenantBinding: 'direct';\n /** @internal Token provenance brand; see {@link LOCAL_MCP_TOKEN_PRINCIPAL}. */\n readonly [LOCAL_MCP_TOKEN_PRINCIPAL]: true;\n}\n\n/** True for a principal derived from a verified local MCP token. */\nexport function isLocalMcpTokenPrincipal(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[LOCAL_MCP_TOKEN_PRINCIPAL] === true\n );\n}\n\n/** Owner-scoped local MCP token operations. */\nexport interface LocalMcpTokenStore {\n /** Mint a token bound to the local owner's user and tenant. */\n issue(input: IssueLocalMcpTokenInput): Promise<IssuedLocalMcpToken>;\n /** Every stored token, newest first, without token values or hashes. */\n list(): Promise<LocalMcpTokenRecord[]>;\n /** Revoke a token by id. Repeating it is a no-op. Unknown ids throw. */\n revoke(id: string): Promise<'revoked' | 'already-revoked'>;\n /**\n * Resolve a presented token to its principal, or `null` (fail closed) for\n * a malformed, unknown, revoked or expired token, or an owner whose user or\n * membership is no longer active.\n */\n verify(token: string): Promise<LocalMcpTokenPrincipal | null>;\n}\n\n/** @internal Collaborators supplied by the local runtime. */\nexport interface LocalMcpTokenStoreDependencies {\n readonly db: DatabaseInterface;\n /** Read the local application secret (validated custody). */\n readonly readSecret: () => Promise<string>;\n readonly now: () => Date;\n /** The active local owner, or `null` before owner setup. */\n readonly findOwner: (\n db: DatabaseInterface,\n ) => Promise<{ userId: string; tenantId: string } | null>;\n /** Build the stable, secret-free runtime error. */\n readonly fail: (\n code: 'invalid_scope' | 'owner_unavailable' | 'invalid_configuration',\n message: string,\n ) => Error;\n}\n\ninterface TokenRow {\n id?: unknown;\n user_id?: unknown;\n tenant_id?: unknown;\n scopes?: unknown;\n label?: unknown;\n created_at?: unknown;\n expires_at?: unknown;\n revoked_at?: unknown;\n}\n\n/** Create the runtime-owned token table if it does not exist. */\nexport async function ensureLocalMcpTokenTable(\n db: DatabaseInterface,\n): Promise<void> {\n await db.query(\n `CREATE TABLE IF NOT EXISTS ${LOCAL_MCP_TOKEN_TABLE} (\n id TEXT PRIMARY KEY,\n token_hash TEXT NOT NULL UNIQUE,\n user_id TEXT NOT NULL,\n tenant_id TEXT NOT NULL,\n scopes TEXT NOT NULL,\n label TEXT NULL,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n revoked_at TEXT NULL\n )`,\n );\n}\n\n/** @internal Build the store over an open local database. */\nexport function createLocalMcpTokenStore(\n deps: LocalMcpTokenStoreDependencies,\n): LocalMcpTokenStore {\n const { db, now, fail } = deps;\n let keyPromise: Promise<Buffer> | undefined;\n const hashKey = (): Promise<Buffer> => {\n keyPromise ??= deps\n .readSecret()\n .then((secret) =>\n createHmac('sha256', secret.trim()).update(HMAC_DOMAIN).digest(),\n )\n .catch((error: unknown) => {\n keyPromise = undefined;\n throw error;\n });\n return keyPromise;\n };\n const hashToken = async (token: string): Promise<string> =>\n createHmac('sha256', await hashKey())\n .update(token)\n .digest('hex');\n\n let resolverPromise: Promise<PermissionResolver> | undefined;\n /**\n * Live permissions from the owner's active *direct* membership in exactly\n * this tenant (pinned; inheritance never substitutes), or `null`.\n */\n const livePermissions = async (\n userId: string,\n tenantId: string,\n ): Promise<ReadonlySet<string> | null> => {\n resolverPromise ??= PermissionResolver.create({ db }).catch(\n (error: unknown) => {\n resolverPromise = undefined;\n throw error;\n },\n );\n const resolved = await resolveBoundMembershipPermissions({\n memberships: await MembershipCollection.create({ db }),\n resolver: await resolverPromise,\n userId,\n tenantId,\n binding: 'direct',\n });\n return resolved?.permissions ?? null;\n };\n\n return Object.freeze({\n async issue(input: IssueLocalMcpTokenInput): Promise<IssuedLocalMcpToken> {\n // Own plain data only: inherited or poisoned fields never set scopes,\n // lifetime or label.\n let fields: object;\n try {\n fields = deepFrozenPlainCopy(input ?? {}) as object;\n } catch (error) {\n if (!(error instanceof PlainDataError)) throw error;\n throw fail(\n 'invalid_configuration',\n `MCP token input ${error.message}.`,\n );\n }\n if (fields === null || typeof fields !== 'object') {\n throw fail(\n 'invalid_configuration',\n 'MCP token input must be an object.',\n );\n }\n const scopes = normalizeScopes(\n ownValue(fields, 'scopes') as readonly string[] | undefined,\n fail,\n );\n const ttl =\n (ownValue(fields, 'expiresInSeconds') as number | undefined) ??\n DEFAULT_LOCAL_MCP_TOKEN_TTL_SECONDS;\n if (\n !Number.isSafeInteger(ttl) ||\n ttl < 60 ||\n ttl > MAX_LOCAL_MCP_TOKEN_TTL_SECONDS\n ) {\n throw fail(\n 'invalid_configuration',\n 'MCP token lifetime must be between one minute and 365 days.',\n );\n }\n const label = normalizeLabel(\n ownValue(fields, 'label') as string | undefined,\n fail,\n );\n const owner = await deps.findOwner(db);\n if (!owner) {\n throw fail(\n 'owner_unavailable',\n 'No local owner exists yet; finish owner setup before issuing MCP tokens.',\n );\n }\n const held = await livePermissions(owner.userId, owner.tenantId);\n const missing = scopes.filter((scope) => !held?.has(scope));\n if (missing.length > 0) {\n throw fail(\n 'invalid_scope',\n `The local owner does not hold: ${missing.join(', ')}.`,\n );\n }\n await ensureLocalMcpTokenTable(db);\n const token = `${LOCAL_MCP_TOKEN_PREFIX}${randomBytes(32).toString('base64url')}`;\n const id = randomUUID();\n const created = now();\n const createdAt = created.toISOString();\n const expiresAt = new Date(created.getTime() + ttl * 1000).toISOString();\n await db.query(\n `INSERT INTO ${LOCAL_MCP_TOKEN_TABLE}\n (id, token_hash, user_id, tenant_id, scopes, label, created_at, expires_at, revoked_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)`,\n id,\n await hashToken(token),\n owner.userId,\n owner.tenantId,\n JSON.stringify(scopes),\n label,\n createdAt,\n expiresAt,\n );\n return Object.freeze({\n id,\n token,\n scopes: Object.freeze([...scopes]),\n label,\n createdAt,\n expiresAt,\n });\n },\n\n async list(): Promise<LocalMcpTokenRecord[]> {\n await ensureLocalMcpTokenTable(db);\n const result = await db.query(\n `SELECT id, scopes, label, created_at, expires_at, revoked_at\n FROM ${LOCAL_MCP_TOKEN_TABLE}\n ORDER BY created_at DESC, id`,\n );\n const current = now().getTime();\n return (result.rows as TokenRow[]).map((row) => {\n const expiresAt = String(row.expires_at);\n const revokedAt =\n row.revoked_at == null ? null : String(row.revoked_at);\n const status: LocalMcpTokenStatus = revokedAt\n ? 'revoked'\n : Date.parse(expiresAt) > current\n ? 'active'\n : 'expired';\n return Object.freeze({\n id: String(row.id),\n scopes: Object.freeze(parseScopes(row.scopes) ?? []),\n label: row.label == null ? null : String(row.label),\n createdAt: String(row.created_at),\n expiresAt,\n revokedAt,\n status,\n });\n });\n },\n\n async revoke(id: string): Promise<'revoked' | 'already-revoked'> {\n if (typeof id !== 'string' || !TOKEN_ID_PATTERN.test(id)) {\n throw fail('invalid_configuration', 'Unknown MCP token id.');\n }\n await ensureLocalMcpTokenTable(db);\n const updated = await db.query(\n `UPDATE ${LOCAL_MCP_TOKEN_TABLE}\n SET revoked_at = ?\n WHERE id = ? AND revoked_at IS NULL\n RETURNING id`,\n now().toISOString(),\n id,\n );\n if (updated.rows.length > 0) return 'revoked';\n const existing = await db.query(\n `SELECT id FROM ${LOCAL_MCP_TOKEN_TABLE} WHERE id = ? LIMIT 1`,\n id,\n );\n if (existing.rows.length === 0) {\n throw fail('invalid_configuration', 'Unknown MCP token id.');\n }\n return 'already-revoked';\n },\n\n async verify(token: string): Promise<LocalMcpTokenPrincipal | null> {\n // Reject garbage before any secret read or database access.\n if (typeof token !== 'string' || !TOKEN_PATTERN.test(token)) return null;\n const result = await db.query(\n `SELECT id, user_id, tenant_id, scopes, expires_at, revoked_at\n FROM ${LOCAL_MCP_TOKEN_TABLE}\n WHERE token_hash = ?\n LIMIT 1`,\n await hashToken(token),\n );\n const row = result.rows[0] as TokenRow | undefined;\n if (!row || row.revoked_at != null) return null;\n const expiresAt = Date.parse(String(row.expires_at));\n if (!Number.isFinite(expiresAt) || expiresAt <= now().getTime()) {\n return null;\n }\n const userId = row.user_id;\n const tenantId = row.tenant_id;\n const scopes = parseScopes(row.scopes);\n if (\n typeof userId !== 'string' ||\n userId.length === 0 ||\n typeof tenantId !== 'string' ||\n tenantId.length === 0 ||\n !scopes\n ) {\n return null;\n }\n const users = await UserCollection.create({ db });\n const user = await users.get({ id: userId });\n if (!user || user.status !== UserStatus.ACTIVE) return null;\n const held = await livePermissions(userId, tenantId);\n if (!held) return null;\n return Object.freeze({\n id: userId,\n tenantId,\n kind: 'human' as const,\n // A frozen copy: mutating it can never widen a later binding.\n scopes: Object.freeze(scopes.filter((scope) => held.has(scope))),\n tenantBinding: 'direct' as const,\n [LOCAL_MCP_TOKEN_PRINCIPAL]: true as const,\n });\n },\n });\n}\n\nfunction normalizeScopes(\n value: readonly string[] | undefined,\n fail: LocalMcpTokenStoreDependencies['fail'],\n): string[] {\n if (!Array.isArray(value) || value.length === 0) {\n throw fail('invalid_scope', 'An MCP token needs at least one scope.');\n }\n if (value.length > MAX_SCOPES) {\n throw fail('invalid_scope', 'An MCP token may carry at most 64 scopes.');\n }\n for (const scope of value) {\n if (\n typeof scope !== 'string' ||\n scope.length > MAX_SCOPE_LENGTH ||\n !SCOPE_PATTERN.test(scope)\n ) {\n throw fail('invalid_scope', 'Invalid MCP token scope.');\n }\n }\n return [...new Set(value)].sort();\n}\n\nfunction normalizeLabel(\n value: string | undefined,\n fail: LocalMcpTokenStoreDependencies['fail'],\n): string | null {\n if (value === undefined) return null;\n const label = typeof value === 'string' ? value.trim() : '';\n if (\n label.length === 0 ||\n label.length > MAX_LABEL_LENGTH ||\n // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point.\n /[\\u0000-\\u001f\\u007f]/u.test(label)\n ) {\n throw fail(\n 'invalid_configuration',\n 'An MCP token label must be 1-80 printable characters.',\n );\n }\n return label;\n}\n\nfunction parseScopes(value: unknown): string[] | null {\n if (typeof value !== 'string') return null;\n try {\n const parsed = JSON.parse(value) as unknown;\n return Array.isArray(parsed) &&\n parsed.every((scope) => typeof scope === 'string')\n ? (parsed as string[])\n : null;\n } catch {\n return null;\n }\n}\n","/**\n * Canonical application identity shared by the web process, operator commands,\n * and generated operational surfaces.\n *\n * Every process that manages the same application must derive the same app ID\n * and the same configuration fingerprint, so these helpers live next to\n * `validateApplicationId()` / `encodeApplicationId()` rather than in copied\n * template scripts.\n */\n\nimport { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { ResolvedApplicationRuntime } from '@happyvertical/smrt-config';\nimport { encodeApplicationId, validateApplicationId } from './index.js';\n\nexport interface ResolveApplicationIdOptions {\n /** Directory containing the application's `package.json`. Defaults to cwd. */\n sourceRoot?: string;\n /** Package name to encode instead of reading `package.json`. */\n packageName?: string;\n /** Explicit, strictly validated app ID (for example `SMRT_APP_ID`). */\n explicitId?: string;\n}\n\n/**\n * Resolve one stable application identity.\n *\n * An explicit ID is validated with {@link validateApplicationId}; otherwise\n * the package name is encoded with {@link encodeApplicationId}.\n */\nexport function resolveApplicationId(\n options: ResolveApplicationIdOptions = {},\n): string {\n if (options.explicitId) return validateApplicationId(options.explicitId);\n let packageName = options.packageName;\n if (packageName === undefined) {\n const sourceRoot = options.sourceRoot ?? process.cwd();\n packageName = (\n JSON.parse(readFileSync(join(sourceRoot, 'package.json'), 'utf8')) as {\n name?: unknown;\n }\n ).name as string | undefined;\n }\n if (typeof packageName !== 'string' || packageName.trim() === '') {\n throw new Error('package.json must declare a non-empty package name.');\n }\n return encodeApplicationId(packageName);\n}\n\nfunction databaseTargetIdentity(value: string | undefined): string | null {\n if (!value) return null;\n try {\n const target = new URL(value);\n const sslMode = target.searchParams.get('sslmode');\n target.username = '';\n target.password = '';\n target.search = '';\n target.hash = '';\n if (sslMode) target.searchParams.set('sslmode', sslMode);\n return target.toString();\n } catch {\n return resolve(value);\n }\n}\n\n/**\n * Runtime selection the fingerprint covers. Structural so operator tooling\n * can fingerprint a resolved runtime it loaded itself; a\n * {@link ResolvedApplicationRuntime} always satisfies it.\n */\nexport interface FingerprintRuntime {\n readonly profile: string;\n readonly providers: unknown;\n}\n\n/**\n * Secret-safe identity used to reject stale managed processes after profile,\n * provider, database-target, or listener configuration changes.\n *\n * Credentials, query strings, and fragments of `DATABASE_URL` are excluded;\n * only `sslmode` survives. The digest is stable for identical inputs so a\n * process manager and the web process can compare it.\n */\nexport function runtimeConfigurationFingerprint(\n runtime: FingerprintRuntime,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n return createHash('sha256')\n .update(\n JSON.stringify({\n profile: runtime.profile,\n providers: runtime.providers,\n databaseTarget: databaseTargetIdentity(environment.DATABASE_URL),\n host: environment.HOST || null,\n port: environment.PORT || null,\n origin: environment.ORIGIN || null,\n backgroundJobs: environment.SMRT_BACKGROUND_JOBS === 'true',\n readinessModules: {\n authentication: environment.SMRT_AUTH_READINESS_MODULE || null,\n assets: environment.SMRT_ASSETS_READINESS_MODULE || null,\n secrets: environment.SMRT_SECRETS_READINESS_MODULE || null,\n },\n mcpAuthorization: {\n resource: environment.SMRT_MCP_RESOURCE || null,\n issuer: environment.SMRT_MCP_ISSUER || null,\n jwksUri: environment.SMRT_MCP_JWKS_URI || null,\n scopes: environment.SMRT_MCP_SCOPES || null,\n },\n }),\n )\n .digest('hex');\n}\n","/** Read a Node `code` from an unknown thrown value. Internal helper. */\nexport function errorCode(error: unknown): string | undefined {\n return error &&\n typeof error === 'object' &&\n 'code' in error &&\n typeof (error as { code: unknown }).code === 'string'\n ? (error as { code: string }).code\n : undefined;\n}\n","/**\n * Serialized removal of stale `operation.lock` / `writer.lease` files.\n *\n * Deciding a lock is stale (owner pid gone) and unlinking it are two steps,\n * and POSIX has no \"unlink if unchanged\". Two reclaimers that both observed\n * the same dead owner could otherwise interleave so that the slower one\n * unlinks the live lock the faster one just created (#3371 review R1).\n *\n * Every reclamation therefore runs under an exclusive SQLite transaction on\n * a dedicated mutex database next to the lock. The kernel releases that lock\n * when its holder dies, so the mutex itself can never go stale, and nothing\n * on the lock path is renamed or replaced. Under the mutex the reclaimer\n * re-reads the lock and only unlinks the exact record it judged stale, after\n * re-checking that its owner is still gone. Acquisition stays a plain\n * `O_EXCL` create, so record formats are unchanged and readable by the\n * template's original scripts.\n */\n\nimport { chmodSync, lstatSync, readFileSync, rmSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\nimport { errorCode } from './error-code.js';\n\n/** Mutex database file created in the lock's (private) state directory. */\nexport const RECLAIM_MUTEX_FILE = '.smrt-lock-reclaim.sqlite';\n\n/** How long a reclaimer waits for another process's reclamation. */\nconst RECLAIM_WAIT_MS = 2_000;\n\n/** Outcome of {@link reclaimStaleRecord}. */\nexport type ReclaimOutcome =\n /** The observed stale record was removed by this call. */\n | 'removed'\n /** The lock no longer exists (another reclaimer removed it). */\n | 'gone'\n /** The lock now holds a different record, or its owner is live: untouched. */\n | 'changed';\n\nfunction withReclaimMutex<T>(stateRoot: string, callback: () => T): T {\n const mutexPath = join(stateRoot, RECLAIM_MUTEX_FILE);\n try {\n const details = lstatSync(mutexPath);\n if (details.isSymbolicLink() || !details.isFile()) {\n throw new Error('The application lock reclaim mutex is unsafe.');\n }\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error;\n }\n const database = new DatabaseSync(mutexPath, { timeout: RECLAIM_WAIT_MS });\n try {\n try {\n chmodSync(mutexPath, 0o600);\n } catch {\n // Best effort: the state directory itself is already mode 0700.\n }\n try {\n database.exec('BEGIN EXCLUSIVE');\n } catch {\n throw new Error(\n 'Another process is reclaiming a stale application lock; retry the operation.',\n );\n }\n try {\n return callback();\n } finally {\n database.exec('ROLLBACK');\n }\n } finally {\n database.close();\n }\n}\n\n/**\n * Remove `path` only if it still contains exactly `observed` and\n * `isStale(observed)` still holds, serialized against every other reclaimer.\n */\nexport function reclaimStaleRecord(\n path: string,\n observed: string,\n isStale: (contents: string) => boolean,\n): ReclaimOutcome {\n return withReclaimMutex(dirname(path), () => {\n let current: string;\n try {\n current = readFileSync(path, 'utf8');\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return 'gone';\n throw error;\n }\n if (current !== observed || !isStale(current)) return 'changed';\n rmSync(path);\n return 'removed';\n });\n}\n","/**\n * Exclusive operator-operation lock (`<state>/operation.lock`).\n *\n * Ported from the template's `scripts/smrt-operation-lock.mjs`: the same\n * file, record shape, and messages. Stale-owner reclamation is serialized\n * through `stale-reclaim.ts` so it can never remove a live lock.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport {\n closeSync,\n mkdirSync,\n openSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { errorCode } from './error-code.js';\nimport { reclaimStaleRecord } from './stale-reclaim.js';\n\n/** Held lock handed to the operation callback. */\nexport interface OperationLock {\n /** Per-acquisition nonce; a managed writer presents it to join the operation. */\n readonly instance: string;\n /** Lock file path. */\n readonly path: string;\n}\n\n/** True when `pid` names a live process, including one owned by another user. */\nexport function processExists(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // A permission boundary still proves that the process exists.\n const code = errorCode(error);\n return code === 'EPERM' || code === 'EACCES';\n }\n}\n\n/** Owner pid of a lock record, or `null` when it cannot be verified. */\nexport function lockOwnerPid(contents: string): number | null {\n try {\n const pid = (JSON.parse(contents) as { pid?: unknown } | null)?.pid;\n return Number.isSafeInteger(pid) && (pid as number) >= 1\n ? (pid as number)\n : null;\n } catch {\n return null;\n }\n}\n\n/** True when an operation-lock record names an owner that no longer exists. */\nexport function isStaleOperationLock(contents: string): boolean {\n const pid = lockOwnerPid(contents);\n return pid !== null && !processExists(pid);\n}\n\n/**\n * Run `callback` while holding the application's exclusive operation lock.\n *\n * A lock whose owner process is gone is reclaimed; an unverifiable lock fails\n * closed. The lock is only removed when it is still this acquisition's own.\n */\nexport async function withOperationLock<T>(\n stateRoot: string,\n operation: string,\n callback: (lock: OperationLock) => Promise<T> | T,\n): Promise<T> {\n mkdirSync(stateRoot, { recursive: true, mode: 0o700 });\n const path = join(stateRoot, 'operation.lock');\n const instance = randomBytes(16).toString('hex');\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n descriptor = openSync(path, 'wx', 0o600);\n try {\n writeFileSync(\n descriptor,\n `${JSON.stringify({ schemaVersion: 1, pid: process.pid, operation, instance })}\\n`,\n );\n } catch (error) {\n closeSync(descriptor);\n descriptor = undefined;\n rmSync(path, { force: true });\n throw error;\n }\n break;\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n let observed: string | null = null;\n try {\n observed = readFileSync(path, 'utf8');\n } catch {\n // A lock that cannot be read has no provable owner.\n }\n const ownerPid = observed === null ? null : lockOwnerPid(observed);\n if (ownerPid === null) {\n throw new Error(\n 'An application operation lock exists but cannot be verified; inspect the private state directory.',\n );\n }\n if (processExists(ownerPid)) {\n throw new Error(\n `Another application operation is active (process ${ownerPid}).`,\n );\n }\n // Removed only under the reclaim mutex, and only if it is still this\n // exact dead owner's record; a replaced lock is retried, never unlinked.\n reclaimStaleRecord(path, observed as string, isStaleOperationLock);\n }\n }\n if (descriptor === undefined) {\n throw new Error('The application operation lock could not be acquired.');\n }\n try {\n return await callback({ instance, path });\n } finally {\n closeSync(descriptor);\n // Do not unlink a replacement lock if an operator repaired this one while\n // the operation was active.\n try {\n const current = JSON.parse(readFileSync(path, 'utf8')) as {\n pid?: unknown;\n instance?: unknown;\n };\n if (current.pid === process.pid && current.instance === instance) {\n rmSync(path, { force: true });\n }\n } catch {\n // A missing or externally repaired lock is not ours to remove.\n }\n }\n}\n","/**\n * Provider-owned readiness probes for deployed profiles.\n *\n * Ported from the template's `scripts/smrt-provider-readiness.mjs`. The\n * module named by the environment setting is resolved from the application\n * (not from this CLI package), because it is the application's installed\n * provider adapter.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { existsSync, realpathSync } from 'node:fs';\nimport { registerHooks } from 'node:module';\nimport { dirname, isAbsolute, join, resolve, sep } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\n\n/** Provider components with a readiness module setting. */\nexport type ReadinessComponent = 'authentication' | 'assets' | 'secrets';\n\n/** Environment variable naming each component's readiness module. */\nexport const PROVIDER_READINESS_SETTINGS: Readonly<\n Record<ReadinessComponent, string>\n> = Object.freeze({\n authentication: 'SMRT_AUTH_READINESS_MODULE',\n assets: 'SMRT_ASSETS_READINESS_MODULE',\n secrets: 'SMRT_SECRETS_READINESS_MODULE',\n});\n\n/** Context handed to the provider's probe. */\nexport interface ReadinessContext {\n profile: string;\n provider: string;\n}\n\n/** Options for {@link createProviderReadinessProbe}. */\nexport interface ProviderReadinessOptions {\n /** Application root the module is resolved from. Defaults to `process.cwd()`. */\n sourceRoot?: string;\n /** Environment to read the setting from. Defaults to `process.env`. */\n environment?: Record<string, string | undefined>;\n}\n\n/**\n * Locate an installed package the way an ES module in `sourceRoot` would:\n * the nearest `node_modules/<name>` walking up from the application. Unlike\n * CommonJS resolution this never consults `NODE_PATH`, which package-manager\n * bin shims point at the CLI's own dependency store.\n */\nexport function findInstalledPackage(\n sourceRoot: string,\n packageName: string,\n): string | null {\n let directory = resolve(sourceRoot);\n for (;;) {\n const candidate = join(directory, 'node_modules', packageName);\n if (existsSync(join(candidate, 'package.json'))) return candidate;\n const parent = dirname(directory);\n if (parent === directory) return null;\n directory = parent;\n }\n}\n\nfunction packageNameOf(specifier: string): string {\n const parts = specifier.split('/');\n return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];\n}\n\n/** Evaluated by Node itself; exposes `import.meta.resolve` to the hook. */\nconst RESOLVER_MODULE =\n 'data:text/javascript,export default (s) => import.meta.resolve(s)';\n\n/**\n * Resolve a bare specifier exactly as an ES module located at `sourceRoot`\n * would, using Node's own ESM resolver (exports/imports maps, condition\n * order, PATTERN_KEY_COMPARE, null targets, invalid-target rejection).\n *\n * Node 26 still flags `import.meta.resolve(specifier, parent)`, so a\n * synchronous `module.registerHooks()` resolve hook re-parents one unique\n * token onto the application's `package.json` and delegates to the default\n * resolver; the hook is removed before this returns.\n */\nasync function resolveFromApplication(\n specifier: string,\n sourceRoot: string,\n): Promise<string> {\n const parentURL = pathToFileURL(\n join(resolve(sourceRoot), 'package.json'),\n ).href;\n const token = `smrt-app-readiness-${randomUUID()}`;\n const hooks = registerHooks({\n resolve(requested, context, nextResolve) {\n return requested === token\n ? nextResolve(specifier, { ...context, parentURL })\n : nextResolve(requested, context);\n },\n });\n try {\n // A data: module is evaluated by Node itself, so its import.meta.resolve\n // runs through the hook (and not through a test runner's resolver).\n const resolver = (await import(/* @vite-ignore */ RESOLVER_MODULE)) as {\n default: (value: string) => string;\n };\n return resolver.default(token);\n } finally {\n hooks.deregister();\n }\n}\n\n/**\n * Resolve a readiness module specifier the way the application would.\n *\n * URLs (`data:`, `file:`) are imported as given; absolute paths become file\n * URLs; relative paths resolve against the application root; bare package\n * specifiers resolve through Node's ESM resolver from the application root\n * (as the template's in-app `import()` did) and must land inside the\n * package installed in the application's own `node_modules` chain.\n */\nexport async function resolveReadinessModule(\n specifier: string,\n sourceRoot: string,\n): Promise<string> {\n if (/^[a-z][a-z0-9+.-]*:/i.test(specifier) && !isAbsolute(specifier)) {\n return specifier;\n }\n if (isAbsolute(specifier)) return pathToFileURL(specifier).href;\n if (specifier.startsWith('./') || specifier.startsWith('../')) {\n return pathToFileURL(resolve(sourceRoot, specifier)).href;\n }\n const installed = findInstalledPackage(sourceRoot, packageNameOf(specifier));\n if (!installed) {\n throw new Error(`${specifier} is not installed in the application.`);\n }\n const packageRoot = realpathSync(installed);\n const resolvedUrl = await resolveFromApplication(specifier, sourceRoot);\n const resolvedPath = realpathSync(fileURLToPath(resolvedUrl));\n if (\n resolvedPath !== packageRoot &&\n !resolvedPath.startsWith(`${packageRoot}${sep}`)\n ) {\n throw new Error(\n `${specifier} resolved outside its installed package; refusing to load it.`,\n );\n }\n return pathToFileURL(resolvedPath).href;\n}\n\n/**\n * Build a provider-owned readiness probe. The installed adapter module must\n * export `checkReadiness()` (or a default function) and return `true` or\n * `{ ready: true }` only after checking its real backing service.\n */\nexport function createProviderReadinessProbe(\n component: ReadinessComponent,\n context: ReadinessContext,\n options: ProviderReadinessOptions = {},\n): () => Promise<void> {\n return async () => {\n const setting = PROVIDER_READINESS_SETTINGS[component];\n const environment = options.environment ?? process.env;\n const specifier = environment[setting];\n if (!specifier) {\n throw new Error(\n `${setting} must name an installed provider readiness module.`,\n );\n }\n // The specifier is operator configuration resolved from the app root at\n // runtime; a bundler must leave it alone.\n const module = (await import(\n /* @vite-ignore */ await resolveReadinessModule(\n specifier,\n options.sourceRoot ?? process.cwd(),\n )\n )) as { checkReadiness?: unknown; default?: unknown };\n const probe = module.checkReadiness || module.default;\n if (typeof probe !== 'function') {\n throw new Error(`${setting} does not export a readiness probe.`);\n }\n const result = (await probe({ component, ...context })) as\n | boolean\n | { ready?: unknown }\n | null\n | undefined;\n if (\n result !== true &&\n (typeof result !== 'object' || result === null || result.ready !== true)\n ) {\n throw new Error(`${component} provider readiness check failed.`);\n }\n };\n}\n","import { createHash } from 'node:crypto';\n\nimport type { ApplicationRuntimeProfile } from '@happyvertical/smrt-config';\n\nexport const RUNTIME_DIAGNOSTICS_SCHEMA_VERSION = 1 as const;\nexport const MAX_RUNTIME_DIAGNOSTIC_TOOLS = 64;\nexport const MAX_RUNTIME_DIAGNOSTIC_ERRORS = 8;\nexport const RUNTIME_WORKER_FRESHNESS_SECONDS = 120;\n\nconst CAPABILITY_IDS = [\n 'asset-storage',\n 'authentication',\n 'background-jobs',\n 'database',\n 'paid-capabilities',\n 'secret-storage',\n] as const;\n\nconst ERROR_CODES = [\n 'authentication_unavailable',\n 'database_unavailable',\n 'migration_required',\n 'provider_unavailable',\n 'runtime_stopped',\n 'worker_stale',\n] as const;\n\nconst PROHIBITED_IDENTIFIER_PARTS = new Set([\n 'authorization',\n 'cookie',\n 'constructor',\n 'credential',\n 'email',\n 'hash',\n 'key',\n 'log',\n 'logs',\n 'password',\n 'path',\n 'record',\n 'prototype',\n 'secret',\n 'session',\n 'stack',\n 'tenant',\n 'token',\n 'url',\n 'user',\n]);\n\ntype CapabilityId = (typeof CAPABILITY_IDS)[number];\ntype CapabilityStatus = 'available' | 'disabled' | 'unavailable' | 'unknown';\ntype RuntimeDiagnosticErrorCode =\n | (typeof ERROR_CODES)[number]\n | 'runtime_error';\ntype WorkerTopology = 'embedded' | 'external' | 'inline' | 'scalable';\n\n/**\n * Versioned public diagnostics returned only after application authorization.\n * Every field is a fixed allowlist projection; this is intentionally not a\n * cleaned or serialized form of either private runtime diagnostics object.\n */\nexport interface RuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly profile: ApplicationRuntimeProfile | 'unknown';\n readonly health: 'healthy' | 'degraded' | 'stopped' | 'unknown';\n readonly schema: {\n readonly status: 'ready' | 'not-ready' | 'unknown';\n readonly migrations: 'current' | 'failed' | 'pending' | 'unknown';\n };\n readonly capabilities: readonly {\n readonly id: CapabilityId;\n readonly status: CapabilityStatus;\n }[];\n readonly tools: {\n readonly names: readonly string[];\n readonly count: number;\n readonly digest: string;\n };\n readonly operationalDifferences: {\n readonly backgroundJobs: 'disabled' | 'enabled';\n readonly workerTopology: WorkerTopology;\n };\n readonly worker: {\n readonly topology: WorkerTopology;\n readonly liveness: 'alive' | 'not-required' | 'stale' | 'unknown';\n readonly heartbeatAt: string | null;\n readonly observedAt: string;\n };\n readonly recentErrors: readonly {\n readonly code: RuntimeDiagnosticErrorCode;\n readonly at: string;\n }[];\n}\n\nexport interface RuntimeDiagnosticsProjectionInput {\n readonly profile?: unknown;\n readonly health?: unknown;\n readonly schema?: unknown;\n readonly capabilities?: unknown;\n readonly toolNames?: unknown;\n readonly worker?: unknown;\n readonly recentErrors?: unknown;\n /** Required explicit clock seam; the projector never reads the process clock. */\n readonly observedAt?: unknown;\n}\n\n/**\n * Project private local/deployed state into the deterministic public contract.\n * Unknown, oversized, nested, accessor-backed, or prohibited values are never\n * copied. Invalid error codes become `runtime_error` at ingestion.\n */\nexport function projectRuntimeDiagnostics(\n input: RuntimeDiagnosticsProjectionInput,\n): RuntimeDiagnostics {\n const source = plainRecord(input);\n const observedAtValue = read(source, 'observedAt');\n const observedAtMilliseconds = timestampMilliseconds(observedAtValue);\n const observedAt = coarseTimestamp(observedAtValue) ?? EPOCH;\n const profile = runtimeProfile(read(source, 'profile'));\n const worker = projectWorker(\n read(source, 'worker'),\n observedAt,\n observedAtMilliseconds,\n );\n const capabilities = projectCapabilities(read(source, 'capabilities'));\n const tools = canonicalTools(read(source, 'toolNames'));\n\n return deepFreeze({\n schemaVersion: RUNTIME_DIAGNOSTICS_SCHEMA_VERSION,\n profile,\n health: oneOf(read(source, 'health'), HEALTH_VALUES, 'unknown'),\n schema: projectSchema(read(source, 'schema')),\n capabilities,\n tools: {\n names: tools,\n count: tools.length,\n digest: createHash('sha256').update(tools.join('\\n')).digest('hex'),\n },\n operationalDifferences: {\n backgroundJobs:\n capabilityStatus(capabilities, 'background-jobs') === 'available'\n ? 'enabled'\n : 'disabled',\n workerTopology: worker.topology,\n },\n worker,\n recentErrors: projectErrors(read(source, 'recentErrors')),\n });\n}\n\nconst EPOCH = '1970-01-01T00:00:00.000Z';\nconst PROFILES = ['local', 'self-hosted', 'cloud', 'unknown'] as const;\nconst HEALTH_VALUES = ['healthy', 'degraded', 'stopped', 'unknown'] as const;\nconst SCHEMA_VALUES = ['ready', 'not-ready', 'unknown'] as const;\nconst MIGRATION_VALUES = ['current', 'failed', 'pending', 'unknown'] as const;\nconst CAPABILITY_VALUES = [\n 'available',\n 'disabled',\n 'unavailable',\n 'unknown',\n] as const;\nconst WORKER_TOPOLOGIES = [\n 'embedded',\n 'external',\n 'inline',\n 'scalable',\n] as const;\n\nfunction runtimeProfile(value: unknown): ApplicationRuntimeProfile | 'unknown' {\n return oneOf(value, PROFILES, 'unknown');\n}\n\nfunction projectSchema(value: unknown): RuntimeDiagnostics['schema'] {\n const source = plainRecord(value);\n return {\n status: oneOf(read(source, 'status'), SCHEMA_VALUES, 'unknown'),\n migrations: oneOf(read(source, 'migrations'), MIGRATION_VALUES, 'unknown'),\n };\n}\n\nfunction projectCapabilities(\n value: unknown,\n): RuntimeDiagnostics['capabilities'] {\n const source = plainRecord(value);\n return CAPABILITY_IDS.map((id) => ({\n id,\n status: oneOf(read(source, id), CAPABILITY_VALUES, 'unknown'),\n }));\n}\n\nfunction canonicalTools(value: unknown): readonly string[] {\n const names = new Set<string>();\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_TOOLS * 4,\n )) {\n if (typeof candidate !== 'string' || !isPublicIdentifier(candidate)) {\n continue;\n }\n names.add(candidate);\n }\n return [...names].sort().slice(0, MAX_RUNTIME_DIAGNOSTIC_TOOLS);\n}\n\nfunction isPublicIdentifier(value: string): boolean {\n if (\n value.length < 1 ||\n value.length > 80 ||\n !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value)\n ) {\n return false;\n }\n const parts = value.split(/[._-]/);\n return !parts.some((part) => PROHIBITED_IDENTIFIER_PARTS.has(part));\n}\n\nfunction projectWorker(\n value: unknown,\n observedAt: string,\n observedAtMilliseconds: number | null,\n): RuntimeDiagnostics['worker'] {\n const source = plainRecord(value);\n const topology = oneOf(read(source, 'topology'), WORKER_TOPOLOGIES, 'inline');\n const required = read(source, 'required') === true;\n const heartbeatValue = read(source, 'heartbeatAt');\n const heartbeatMilliseconds = timestampMilliseconds(heartbeatValue);\n const heartbeatAt = coarseTimestamp(heartbeatValue);\n let liveness: RuntimeDiagnostics['worker']['liveness'] = 'not-required';\n if (required) {\n liveness = 'unknown';\n if (heartbeatMilliseconds !== null && observedAtMilliseconds !== null) {\n const ageSeconds =\n (observedAtMilliseconds - heartbeatMilliseconds) / 1_000;\n if (ageSeconds >= 0) {\n liveness =\n ageSeconds <= RUNTIME_WORKER_FRESHNESS_SECONDS ? 'alive' : 'stale';\n }\n }\n }\n return { topology, liveness, heartbeatAt, observedAt };\n}\n\nfunction projectErrors(value: unknown): RuntimeDiagnostics['recentErrors'] {\n const errors: Array<RuntimeDiagnostics['recentErrors'][number]> = [];\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_ERRORS * 4,\n )) {\n const source = plainRecord(candidate);\n const at = coarseTimestamp(read(source, 'at'));\n if (!at) continue;\n const rawCode = read(source, 'code');\n const code: RuntimeDiagnosticErrorCode = ERROR_CODES.includes(\n rawCode as (typeof ERROR_CODES)[number],\n )\n ? (rawCode as (typeof ERROR_CODES)[number])\n : 'runtime_error';\n errors.push({ code, at });\n }\n return errors\n .sort((left, right) =>\n left.at === right.at\n ? left.code.localeCompare(right.code)\n : right.at.localeCompare(left.at),\n )\n .slice(0, MAX_RUNTIME_DIAGNOSTIC_ERRORS);\n}\n\nfunction capabilityStatus(\n capabilities: RuntimeDiagnostics['capabilities'],\n id: CapabilityId,\n): CapabilityStatus {\n return (\n capabilities.find((capability) => capability.id === id)?.status ?? 'unknown'\n );\n}\n\nfunction coarseTimestamp(value: unknown): string | null {\n const milliseconds = timestampMilliseconds(value);\n if (milliseconds === null) return null;\n const minute = Math.floor(milliseconds / 60_000) * 60_000;\n return new Date(minute).toISOString();\n}\n\nfunction timestampMilliseconds(value: unknown): number | null {\n try {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const milliseconds =\n value instanceof Date ? value.getTime() : Date.parse(value);\n return Number.isFinite(milliseconds) ? milliseconds : null;\n } catch {\n return null;\n }\n}\n\nfunction oneOf<\n const Values extends readonly string[],\n Fallback extends Values[number],\n>(value: unknown, values: Values, fallback: Fallback): Values[number] {\n return typeof value === 'string' && values.includes(value as Values[number])\n ? (value as Values[number])\n : fallback;\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | null {\n try {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return null;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction read(source: Record<string, unknown> | null, key: string): unknown {\n try {\n if (!source || !Object.hasOwn(source, key)) {\n return undefined;\n }\n return source[key];\n } catch {\n return undefined;\n }\n}\n\nfunction safeArrayItems(value: unknown, maximum: number): readonly unknown[] {\n try {\n if (!Array.isArray(value)) return [];\n const length = Math.min(value.length, maximum);\n if (!Number.isSafeInteger(length) || length < 0) return [];\n const items: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n try {\n items.push(value[index]);\n } catch {\n items.push(undefined);\n }\n }\n return items;\n } catch {\n return [];\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object') {\n Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n if (child && typeof child === 'object' && !Object.isFrozen(child)) {\n deepFreeze(child);\n }\n }\n }\n return value;\n}\n","/**\n * Private, app-bound state root shared by the running web process and the\n * `smrt app` operator commands (`writer.lease`, `operation.lock`, onboarding\n * handoff files).\n *\n * The path is derived from the canonical application/data identity so every\n * process managing one database root shares one lock domain. Moved here from\n * `@happyvertical/smrt-cli/app` (which re-exports it) so the web process does\n * not depend on the CLI package; files, names, and error messages are\n * unchanged from the template's former `scripts/smrt-runtime-identity.mjs`.\n */\n\nimport { createHash } from 'node:crypto';\nimport {\n closeSync,\n constants,\n lstatSync,\n mkdirSync,\n openSync,\n realpathSync,\n rmSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { join, parse, resolve } from 'node:path';\nimport { errorCode } from './error-code.js';\nimport { resolveLocalRuntimePaths, validateApplicationId } from './index.js';\n\n/** Inputs for the state-root resolvers. */\nexport interface ApplicationStateRootOptions {\n appId: string;\n dataDirectory?: string;\n sourceRoot?: string;\n /** Testable platform override. */\n platformName?: NodeJS.Platform | string;\n /** Testable home-directory override. */\n homeDirectory?: string;\n /** Testable environment override. */\n environment?: Record<string, string | undefined>;\n}\n\n/**\n * State is derived from the canonical application/data identity. It is not an\n * independent override because every process and operator command must share\n * one lock domain for a given database root.\n */\nexport function resolveApplicationStateRoot(\n options: ApplicationStateRootOptions,\n): string {\n const paths = resolveLocalRuntimePaths({\n appId: options.appId,\n dataDirectory: options.dataDirectory,\n sourceRoot: options.sourceRoot,\n });\n const platformName = options.platformName || platform();\n const homeDirectory = options.homeDirectory || homedir();\n const environment = options.environment || process.env;\n const stateBase =\n platformName === 'darwin'\n ? join(homeDirectory, 'Library', 'Application Support')\n : platformName === 'win32'\n ? environment.LOCALAPPDATA || homeDirectory\n : environment.XDG_STATE_HOME || join(homeDirectory, '.local', 'state');\n const dataIdentity = createHash('sha256')\n .update(resolve(paths.root))\n .digest('hex')\n .slice(0, 12);\n return resolve(stateBase, `.${options.appId}-${dataIdentity}-state`);\n}\n\nfunction isInside(parent: string, child: string): boolean {\n const relative = child.slice(parent.length);\n return (\n child === parent ||\n (child.startsWith(parent) &&\n (relative.startsWith('/') || relative.startsWith('\\\\')))\n );\n}\n\n/** Owner check seam; production uses the real process uid. */\nexport interface StateCustodyOptions {\n /**\n * Testable uid override (e.g. to prove a foreign owner is rejected). It can\n * only substitute a uid; it cannot disable the ownership check.\n */\n currentUid?: number;\n}\n\n/**\n * Create or verify the private, app-bound state/lock directory.\n */\nexport function prepareApplicationStateRoot(\n options: ApplicationStateRootOptions & StateCustodyOptions,\n): string {\n const sourceRoot = realpathSync(resolve(options.sourceRoot || process.cwd()));\n const stateRoot = resolveApplicationStateRoot(options);\n if (isInside(sourceRoot, stateRoot) || isInside(stateRoot, sourceRoot)) {\n throw new Error('Application state must remain outside the source tree.');\n }\n const currentUid = options.currentUid ?? process.getuid?.();\n let component = parse(stateRoot).root;\n for (const part of stateRoot\n .slice(component.length)\n .split(/[\\\\/]+/)\n .filter(Boolean)) {\n component = join(component, part);\n try {\n const details = lstatSync(component);\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw new Error(\n `Application state path component is unsafe: ${component}`,\n );\n }\n const sharedStickyRoot =\n details.uid === 0 && (details.mode & 0o1000) !== 0;\n if (\n currentUid !== undefined &&\n ((details.uid !== currentUid && details.uid !== 0) ||\n ((details.mode & 0o022) !== 0 && !sharedStickyRoot))\n ) {\n throw new Error(\n `Application state path lacks trusted custody: ${component}`,\n );\n }\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error;\n try {\n mkdirSync(component, { mode: 0o700 });\n } catch (mkdirError) {\n if (errorCode(mkdirError) !== 'EEXIST') throw mkdirError;\n }\n const created = lstatSync(component);\n if (\n created.isSymbolicLink() ||\n !created.isDirectory() ||\n (currentUid !== undefined && created.uid !== currentUid) ||\n (created.mode & 0o777) !== 0o700\n ) {\n throw new Error(\n `Application state path component is unsafe: ${component}`,\n );\n }\n }\n }\n const rootDetails = lstatSync(stateRoot);\n if (\n rootDetails.isSymbolicLink() ||\n !rootDetails.isDirectory() ||\n (currentUid !== undefined && rootDetails.uid !== currentUid) ||\n (rootDetails.mode & 0o777) !== 0o700\n ) {\n throw new Error(\n 'Application state root must be current-user-owned mode 0700.',\n );\n }\n const markerPath = join(\n stateRoot,\n `.smrt-state-${validateApplicationId(options.appId)}`,\n );\n let descriptor: number | undefined;\n try {\n descriptor = openSync(\n markerPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n );\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n const marker = lstatSync(markerPath);\n if (\n marker.isSymbolicLink() ||\n !marker.isFile() ||\n marker.size !== 0 ||\n (currentUid !== undefined && marker.uid !== currentUid) ||\n (marker.mode & 0o777) !== 0o600\n ) {\n throw new Error('Application state marker is unsafe.');\n }\n } finally {\n if (descriptor !== undefined) closeSync(descriptor);\n }\n return stateRoot;\n}\n\n/**\n * Hand-off files `smrt app setup` / `recover` leave in the private state root.\n * They hold the loopback `/setup?token=` URL, so they are spent once the owner\n * claim commits.\n */\nexport const ONBOARDING_HANDOFF_FILES: readonly string[] = Object.freeze([\n 'onboarding.json',\n 'onboarding-launch.html',\n]);\n\n/**\n * Remove the onboarding hand-off files from `stateRoot`. Missing files are\n * fine. Call only after the owner claim transaction has committed.\n */\nexport function removeOnboardingHandoff(stateRoot: string): void {\n for (const file of ONBOARDING_HANDOFF_FILES) {\n rmSync(join(stateRoot, file), { force: true });\n }\n}\n","/**\n * Single-writer lease (`<state>/writer.lease`).\n *\n * Ported from the template's `scripts/smrt-writer-lease.mjs`. The running web\n * server takes the same lease, so the file, record shape, and operation-lock\n * admission rule stay byte-compatible. Stale-owner reclamation (of the lease\n * and of a dead operation lock) is serialized through `stale-reclaim.ts`.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport {\n closeSync,\n mkdirSync,\n openSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { errorCode } from './error-code.js';\nimport { isStaleOperationLock, processExists } from './operation-lock.js';\nimport { reclaimStaleRecord } from './stale-reclaim.js';\n\n/** Persisted writer-lease record. */\nexport interface WriterLeaseRecord {\n schemaVersion: 1;\n pid: number;\n instance: string;\n}\n\n/** Held writer lease. `release()` is idempotent. */\nexport interface WriterLease {\n release(): void;\n}\n\n/** Options for {@link acquireWriterLease}. */\nexport interface AcquireWriterLeaseOptions {\n /** Instance of the operation lock this writer was started under, if any. */\n operationInstance?: string;\n}\n\nfunction validateRecord(record: unknown): WriterLeaseRecord {\n const candidate = record as Partial<WriterLeaseRecord> | null;\n if (\n candidate?.schemaVersion !== 1 ||\n !Number.isSafeInteger(candidate.pid) ||\n (candidate.pid as number) < 1 ||\n typeof candidate.instance !== 'string' ||\n !/^[a-f0-9]{32}$/.test(candidate.instance)\n ) {\n throw new Error('The application writer lease is malformed.');\n }\n return candidate as WriterLeaseRecord;\n}\n\nfunction readRecord(pathOrDescriptor: string | number): WriterLeaseRecord {\n return validateRecord(JSON.parse(readFileSync(pathOrDescriptor, 'utf8')));\n}\n\n/** True when a lease record names a writer that no longer exists. */\nfunction isStaleWriterLease(contents: string): boolean {\n try {\n return !processExists(validateRecord(JSON.parse(contents)).pid);\n } catch {\n return false;\n }\n}\n\n/**\n * Return the live writer lease, removing a lease whose owner is gone.\n */\nexport function readActiveWriterLease(\n stateRoot: string,\n): WriterLeaseRecord | null {\n const path = join(stateRoot, 'writer.lease');\n for (let attempt = 0; attempt < 4; attempt += 1) {\n let observed: string;\n let record: WriterLeaseRecord;\n try {\n observed = readFileSync(path, 'utf8');\n record = validateRecord(JSON.parse(observed));\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return null;\n throw new Error(\n 'The application writer lease cannot be verified; inspect the private state directory.',\n );\n }\n if (processExists(record.pid)) return record;\n // Removed only under the reclaim mutex, and only if it is still this\n // exact dead writer's record; a replaced lease is re-read, never unlinked.\n const outcome = reclaimStaleRecord(path, observed, isStaleWriterLease);\n if (outcome !== 'changed') return null;\n }\n throw new Error(\n 'The application writer lease changed repeatedly and cannot be verified.',\n );\n}\n\n/**\n * Acquire the application's single-writer lease.\n *\n * A live operator operation blocks the writer unless the writer presents that\n * operation's own lock instance (a managed `start`); a dead operation lock is\n * reclaimed.\n */\nexport function acquireWriterLease(\n stateRoot: string,\n options: AcquireWriterLeaseOptions = {},\n): WriterLease {\n mkdirSync(stateRoot, { recursive: true, mode: 0o700 });\n const path = join(stateRoot, 'writer.lease');\n const active = readActiveWriterLease(stateRoot);\n if (active?.pid === process.pid) return { release() {} };\n if (active) {\n throw new Error(\n `Another application writer is active (process ${active.pid}).`,\n );\n }\n const instance = randomBytes(16).toString('hex');\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n descriptor = openSync(path, 'wx', 0o600);\n writeFileSync(\n descriptor,\n `${JSON.stringify({ schemaVersion: 1, pid: process.pid, instance })}\\n`,\n );\n break;\n } catch (error) {\n if (descriptor !== undefined) {\n closeSync(descriptor);\n descriptor = undefined;\n }\n if (errorCode(error) === 'EEXIST') {\n const owner = readActiveWriterLease(stateRoot);\n if (!owner && attempt === 0) continue;\n throw new Error(\n `Another application writer is active${owner ? ` (process ${owner.pid})` : ''}.`,\n );\n }\n rmSync(path, { force: true });\n throw error;\n }\n }\n if (descriptor === undefined) {\n throw new Error('The application writer lease could not be acquired.');\n }\n closeSync(descriptor);\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n process.removeListener('exit', release);\n try {\n const current = readRecord(path);\n if (current.pid === process.pid && current.instance === instance) {\n rmSync(path, { force: true });\n }\n } catch {\n // A missing or externally repaired lease is not ours to remove.\n }\n };\n const operationPath = join(stateRoot, 'operation.lock');\n let observedOperation: string | null = null;\n try {\n observedOperation = readFileSync(operationPath, 'utf8');\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n release();\n throw error;\n }\n }\n if (observedOperation !== null) {\n let operation: { pid?: unknown; instance?: unknown } | null;\n try {\n operation = JSON.parse(observedOperation);\n } catch {\n operation = null;\n }\n if (\n !operation ||\n !Number.isSafeInteger(operation.pid) ||\n (operation.pid as number) < 1 ||\n typeof operation.instance !== 'string'\n ) {\n release();\n throw new Error('The application operation lock cannot be verified.');\n }\n if (!processExists(operation.pid as number)) {\n let outcome: ReturnType<typeof reclaimStaleRecord>;\n try {\n outcome = reclaimStaleRecord(\n operationPath,\n observedOperation,\n isStaleOperationLock,\n );\n } catch (error) {\n release();\n throw error;\n }\n if (outcome === 'changed') {\n release();\n throw new Error('The application operation lock changed unexpectedly.');\n }\n } else if (operation.instance !== options.operationInstance) {\n release();\n throw new Error(\n 'An application operation is active; wait for it to finish before starting a writer.',\n );\n }\n }\n process.once('exit', release);\n return { release };\n}\n","/**\n * Safe, private, single-owner application runtime for the `local` profile.\n *\n * This Node-only subpath owns the small amount of operational composition that\n * does not belong in a generated application: user-owned paths, restrictive\n * local secret material, SQLite tuning, owner bootstrap, and an optional\n * embedded job runner. Domain schema preparation remains an explicit startup\n * step supplied by the application migration layer.\n */\n\nimport { execFile } from 'node:child_process';\nimport { createHash, createHmac, randomBytes } from 'node:crypto';\nimport {\n constants,\n type FileHandle,\n link,\n lstat,\n mkdir,\n open,\n readdir,\n realpath,\n rmdir,\n unlink,\n} from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { isAbsolute, parse, relative, resolve, sep } from 'node:path';\nimport { promisify } from 'node:util';\nimport { Worker } from 'node:worker_threads';\nimport {\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n} from '@happyvertical/smrt-config';\nimport { TaskRunner, type TaskRunnerConfig } from '@happyvertical/smrt-jobs';\nimport { Person, ProfileTypeCollection } from '@happyvertical/smrt-profiles';\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport {\n DEFAULT_ROLE_SLUGS,\n MembershipCollection,\n MembershipStatus,\n RoleCollection,\n SessionCollection,\n SessionService,\n TenantService,\n UserCollection,\n UserStatus,\n} from '@happyvertical/smrt-users';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\nimport {\n createLocalMcpTokenStore,\n ensureLocalMcpTokenTable,\n type LocalMcpTokenStore,\n} from './local-mcp-tokens.js';\n\nexport * from './application-identity.js';\nexport * from './deployed-runtime.js';\nexport {\n DEFAULT_LOCAL_MCP_TOKEN_TTL_SECONDS,\n type IssuedLocalMcpToken,\n type IssueLocalMcpTokenInput,\n isLocalMcpTokenPrincipal,\n LOCAL_MCP_TOKEN_PREFIX,\n LOCAL_MCP_TOKEN_PRINCIPAL,\n LOCAL_MCP_TOKEN_TABLE,\n type LocalMcpTokenPrincipal,\n type LocalMcpTokenRecord,\n type LocalMcpTokenStatus,\n type LocalMcpTokenStore,\n MAX_LOCAL_MCP_TOKEN_TTL_SECONDS,\n} from './local-mcp-tokens.js';\nexport * from './operation-lock.js';\nexport * from './provider-readiness.js';\nexport * from './runtime-diagnostics.js';\nexport * from './stale-reclaim.js';\nexport * from './state-root.js';\nexport * from './writer-lease.js';\n\nconst DEFAULT_BIND_HOST = '127.0.0.1';\nconst DEFAULT_BOOTSTRAP_TTL_SECONDS = 10 * 60;\nconst MAX_BOOTSTRAP_TTL_SECONDS = 15 * 60;\nconst DEFAULT_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;\nconst BOOTSTRAP_TABLE = '_smrt_local_owner_bootstrap';\nconst SECRET_FILE_NAME = 'application.secret';\nconst DATABASE_FILE_NAME = 'application.sqlite';\nconst ROOT_MARKER_PREFIX = '.smrt-local-runtime-';\nconst PREFLIGHT_RETRY_LIMIT = 4;\nconst INITIALIZATION_LOCK_TIMEOUT_MS = 120_000;\nconst INITIALIZATION_LOCK_WORKER = `\n const { parentPort, workerData } = require('node:worker_threads');\n let database;\n let transaction;\n (async () => {\n try {\n const { getDatabase } = await import(workerData.sqlModuleUrl);\n database = await getDatabase({\n type: 'sqlite',\n url: workerData.path,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: workerData.custodyRoot,\n },\n transactionQueueTimeout: workerData.timeout,\n });\n if (!database.beginTransaction) {\n throw new Error('Secure SQLite does not expose beginTransaction().');\n }\n await database.query('PRAGMA busy_timeout = ' + workerData.timeout);\n transaction = await database.beginTransaction();\n parentPort.postMessage({ type: 'acquired' });\n } catch (error) {\n try { await database?.close?.(); } catch {}\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n return;\n }\n parentPort.once('message', async (message) => {\n if (message?.type !== 'release') return;\n let releaseError;\n try { await transaction.rollback(); } catch (error) { releaseError = String(error); }\n try { await database.close?.(); } catch (error) { releaseError ??= String(error); }\n parentPort.postMessage({ type: 'released', error: releaseError });\n parentPort.close();\n });\n })().catch((error) => {\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n });\n`;\nconst execFileAsync = promisify(execFile);\n\n/** Paths owned by the local user, outside the source tree by default. */\nexport interface LocalRuntimePaths {\n readonly root: string;\n readonly database: string;\n readonly assets: string;\n readonly secrets: string;\n readonly applicationSecret: string;\n}\n\nexport interface ResolveLocalRuntimePathsOptions {\n /** Stable application identifier, e.g. `lolaus`. */\n appId: string;\n /** Explicit user-owned data directory. Defaults to the OS application-data directory. */\n dataDirectory?: string;\n /** Source checkout to protect from accidental data placement. Defaults to cwd. */\n sourceRoot?: string;\n /** Testable default-root and filesystem case-sensitivity override. */\n platform?: NodeJS.Platform;\n /** Testable home-directory override. */\n homeDirectory?: string;\n /** Testable environment override. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface LocalApplicationRuntimeOptions\n extends ResolveLocalRuntimePathsOptions {\n /** Actual HTTP bind host. Owner bootstrap refuses non-loopback values. */\n bindHost?: string;\n /**\n * Explicit application migration/schema hook, invoked before identity access.\n * It must be idempotent; runtime code never synthesizes application tables.\n */\n prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n /** Local profile provider overrides (only validated local combinations survive). */\n providers?: RuntimeProviderOverrides;\n /** Short-lived bootstrap token lifetime. Range: 1..900 seconds. */\n bootstrapTtlSeconds?: number;\n /** Normal authenticated session lifetime in whole seconds. Minimum 1. */\n sessionTtlSeconds?: number;\n /** Explicit opt-in for persisted background work. Default false. */\n backgroundJobs?: boolean;\n /** Explicit opt-in for application-defined paid capabilities. Default false. */\n paidCapabilities?: boolean;\n /** Testable clock. */\n now?: () => Date;\n}\n\n/**\n * Claim the secure local database root before a standalone migration command\n * opens SQLite. This does not create application schema or bootstrap records.\n */\nexport async function prepareLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let failure: unknown;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n await db.close?.();\n db = undefined;\n } catch (error) {\n failure = db ? await closeDatabaseAfterFailure(db, error) : error;\n db = undefined;\n }\n try {\n await initializationLock.release();\n } catch (releaseError) {\n failure = failure\n ? preservePrimaryFailure(\n failure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local database storage preparation and initialization-lock release both failed.',\n )\n : releaseError;\n }\n if (failure) throw failure;\n return paths;\n}\n\n/**\n * Verify an already-initialized local database root without creating or\n * changing any filesystem/database artifact. Operator read/copy/import paths\n * use this boundary before opening SQLite outside the runtime bootstrap.\n */\nexport async function validateLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const canonicalSourceRoot = await realpath(sourceRoot);\n await validateRootMarker(\n resolve(paths.root, `${ROOT_MARKER_PREFIX}${appId}`),\n canonicalSourceRoot,\n );\n await validateExistingPathChain(paths.database, canonicalSourceRoot, 'file');\n const database = await lstat(paths.database);\n const currentUid = process.getuid?.();\n if (\n database.isSymbolicLink() ||\n !database.isFile() ||\n (currentUid !== undefined && database.uid !== currentUid) ||\n (database.mode & 0o777) !== 0o600\n ) {\n throw unsafeFilesystemEntry(\n `Local application database must be a current-user-owned mode-0600 file: ${paths.database}`,\n );\n }\n return paths;\n}\n\n/** Options for {@link openLocalMcpTokenStore}. */\nexport interface OpenLocalMcpTokenStoreOptions\n extends ResolveLocalRuntimePathsOptions {\n /** Testable clock. */\n now?: () => Date;\n}\n\n/** A {@link LocalMcpTokenStore} over its own connection; call `close()`. */\nexport interface OpenedLocalMcpTokenStore extends LocalMcpTokenStore {\n close(): Promise<void>;\n}\n\n/**\n * Open the local MCP token store of an already-initialized application for\n * an operator command (`smrt app token`). It validates the existing storage\n * custody exactly like `validateLocalDatabaseStorage()` and opens SQLite\n * without running migrations or owner bootstrap. It does not take the writer\n * lease: issuing or revoking a token while the web process runs is the\n * expected use, and revocation takes effect on the next request.\n */\nexport async function openLocalMcpTokenStore(\n options: OpenLocalMcpTokenStoreOptions,\n): Promise<OpenedLocalMcpTokenStore> {\n const paths = await validateLocalDatabaseStorage(options);\n const canonicalSourceRoot = await realpath(\n resolve(options.sourceRoot ?? process.cwd()),\n );\n // Uncached: `close()` must never close a connection another caller in\n // this process (for example the web runtime) shares.\n const db = await getDatabase({\n type: 'sqlite',\n url: paths.database,\n cache: false,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: paths.root,\n },\n });\n try {\n await tuneLocalSqlite(db);\n await ensureLocalMcpTokenTable(db);\n } catch (error) {\n throw await closeDatabaseAfterFailure(db, error);\n }\n const store = localMcpTokenStore(\n db,\n paths,\n canonicalSourceRoot,\n options.now ?? (() => new Date()),\n );\n return Object.freeze({\n issue: store.issue,\n list: store.list,\n revoke: store.revoke,\n verify: store.verify,\n close: async () => {\n await db.close?.();\n },\n });\n}\n\nfunction localMcpTokenStore(\n db: DatabaseInterface,\n paths: LocalRuntimePaths,\n canonicalSourceRoot: string,\n now: () => Date,\n): LocalMcpTokenStore {\n return createLocalMcpTokenStore({\n db,\n now,\n readSecret: () =>\n validateApplicationSecret(paths.applicationSecret, canonicalSourceRoot),\n findOwner: findExistingOwner,\n fail: (code, message) => new LocalRuntimeError(code, message),\n });\n}\n\nexport interface LocalOwnerBootstrapInvitation {\n /** Plaintext is returned exactly when a new claim is issued; it is never persisted. */\n readonly token: string;\n readonly expiresAt: string;\n}\n\nexport interface LocalRuntimeInitialization {\n readonly runtime: LocalApplicationRuntime;\n readonly bootstrap: LocalOwnerBootstrapInvitation | null;\n readonly diagnostics: LocalRuntimeDiagnostics;\n}\n\nexport interface ClaimLocalOwnerInput {\n token: string;\n name: string;\n email: string;\n tenantName?: string;\n userAgent?: string;\n ipAddress?: string;\n}\n\nexport interface LocalOwnerClaimResult {\n readonly profileId: string;\n readonly userId: string;\n readonly tenantId: string;\n readonly membershipId: string;\n readonly sessionId: string;\n}\n\nexport type LocalBootstrapStatus =\n | 'available'\n | 'expired'\n | 'claimed'\n | 'unavailable';\n\n/** Secret-free, machine-readable local runtime state. */\nexport interface LocalRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly bind: {\n readonly host: string;\n readonly loopback: true;\n };\n readonly paths: LocalRuntimePaths;\n readonly storage: {\n readonly database: 'sqlite-file';\n readonly assets: 'user-owned-directory';\n readonly secrets: 'mode-0600-local-file';\n };\n readonly bootstrap: {\n readonly status: LocalBootstrapStatus;\n readonly expiresAt: string | null;\n readonly tokenValuesIncluded: false;\n readonly tokenHashesIncluded: false;\n };\n readonly tenancy: {\n readonly mode: 'real-default-tenant';\n readonly ui: 'hidden';\n };\n readonly jobs: {\n readonly topology: 'inline' | 'embedded';\n readonly backgroundEnabled: boolean;\n };\n readonly paidCapabilitiesEnabled: boolean;\n readonly secretValuesIncluded: false;\n}\n\nexport type LocalRuntimeErrorCode =\n | 'bootstrap_claimed'\n | 'bootstrap_expired'\n | 'bootstrap_invalid'\n | 'bootstrap_unavailable'\n | 'capability_disabled'\n | 'invalid_configuration'\n | 'invalid_scope'\n | 'migration_failed'\n | 'owner_unavailable'\n | 'unsafe_public_exposure';\n\n/**\n * Fixed, secret-free surface for a failed application migration.\n *\n * A migration driver message is a likely carrier of a connection string,\n * credential, filesystem path, or environment value, so the caller's text is\n * never surfaced. The original error is retained as a non-enumerable `cause`\n * for private logs only.\n */\nexport const MIGRATION_FAILED_MESSAGE =\n 'The application migration step failed; run pnpm app:setup and inspect the private migration logs.';\n\n/** Stable, secret-free local-runtime failure. */\nexport class LocalRuntimeError extends Error {\n constructor(\n readonly code: LocalRuntimeErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'LocalRuntimeError';\n }\n}\n\ninterface BootstrapRow {\n expires_at?: unknown;\n consumed_at?: unknown;\n}\n\ninterface ExistingOwner {\n userId: string;\n tenantId: string;\n}\n\n/**\n * Resolve deterministic user-owned paths and reject source-tree placement.\n */\nexport function resolveLocalRuntimePaths(\n options: ResolveLocalRuntimePathsOptions,\n): LocalRuntimePaths {\n const appId = validateApplicationId(options.appId);\n const runtimePlatform = options.platform ?? platform();\n const runtimeHome = options.homeDirectory ?? homedir();\n const env = options.env ?? process.env;\n const defaultRoot = defaultApplicationDataRoot(\n runtimePlatform,\n runtimeHome,\n env,\n );\n const root = resolve(options.dataDirectory ?? resolve(defaultRoot, appId));\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n\n if (\n sameFilesystemPath(root, runtimeHome, runtimePlatform) ||\n sameFilesystemPath(root, parse(root).root, runtimePlatform) ||\n isInside(sourceRoot, root, runtimePlatform) ||\n isInside(root, sourceRoot, runtimePlatform)\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Local application data must be a dedicated directory that does not overlap the source tree.',\n );\n }\n\n return Object.freeze({\n root,\n database: resolve(root, DATABASE_FILE_NAME),\n assets: resolve(root, 'assets'),\n secrets: resolve(root, 'secrets'),\n applicationSecret: resolve(root, 'secrets', SECRET_FILE_NAME),\n });\n}\n\n/**\n * Initialize or reopen a local application runtime.\n *\n * A plaintext bootstrap token is returned only when this call creates a new\n * invitation. Existing unexpired invitations remain valid but cannot be read\n * back because only their HMAC is stored.\n */\nexport async function initializeLocalApplicationRuntime(\n options: LocalApplicationRuntimeOptions,\n): Promise<LocalRuntimeInitialization> {\n const bindHost = normalizeLoopbackHost(options.bindHost ?? DEFAULT_BIND_HOST);\n const bootstrapTtlSeconds = validateBootstrapTtl(\n options.bootstrapTtlSeconds ?? DEFAULT_BOOTSTRAP_TTL_SECONDS,\n );\n const sessionTtlSeconds = validateSessionTtl(\n options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS,\n );\n const resolvedRuntime = resolveApplicationRuntime({\n profile: 'local',\n providers: options.providers,\n });\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let initialization: LocalRuntimeInitialization | undefined;\n let initializationFailure: unknown;\n let initializationFailed = false;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n const { canonicalSourceRoot } = acquired;\n await prepareLocalFilesystem(paths, canonicalSourceRoot);\n await tuneLocalSqlite(db);\n try {\n await options.prepareDatabase?.(db);\n } catch (migrationFailure) {\n throw migrationFailed(migrationFailure);\n }\n await ensureBootstrapTable(db);\n await ensureLocalMcpTokenTable(db);\n\n const runtime = new InitializedLocalApplicationRuntime({\n db,\n paths,\n bindHost,\n resolvedRuntime,\n bootstrapTtlSeconds,\n sessionTtlSeconds,\n backgroundJobs: options.backgroundJobs === true,\n paidCapabilities: options.paidCapabilities === true,\n now: options.now ?? (() => new Date()),\n canonicalSourceRoot,\n });\n const bootstrap = await runtime.ensureBootstrapInvitation();\n initialization = {\n runtime,\n bootstrap,\n diagnostics: await runtime.diagnostics(),\n };\n } catch (error) {\n initializationFailed = true;\n initializationFailure = db\n ? await closeDatabaseAfterFailure(db, error)\n : error;\n db = undefined;\n }\n\n try {\n await initializationLock.release();\n } catch (releaseError) {\n if (initializationFailed) {\n initializationFailure = preservePrimaryFailure(\n initializationFailure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local runtime initialization and initialization-lock release both failed.',\n );\n } else if (db) {\n initializationFailed = true;\n initializationFailure = await closeDatabaseAfterFailure(db, releaseError);\n db = undefined;\n } else {\n initializationFailed = true;\n initializationFailure = releaseError;\n }\n }\n\n if (initializationFailed) throw initializationFailure;\n if (!initialization) {\n throw new Error('Local runtime initialization completed without a result.');\n }\n return initialization;\n}\n\ninterface LocalApplicationRuntimeState {\n db: DatabaseInterface;\n paths: LocalRuntimePaths;\n bindHost: string;\n resolvedRuntime: ResolvedApplicationRuntime;\n bootstrapTtlSeconds: number;\n sessionTtlSeconds: number;\n backgroundJobs: boolean;\n paidCapabilities: boolean;\n now: () => Date;\n canonicalSourceRoot: string;\n}\n\n/** Initialized local runtime used by server startup and onboarding handlers. */\nexport interface LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null>;\n rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation>;\n claimOwner(input: ClaimLocalOwnerInput): Promise<LocalOwnerClaimResult>;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createEmbeddedJobRunner(config?: TaskRunnerConfig): Promise<TaskRunner>;\n diagnostics(): Promise<LocalRuntimeDiagnostics>;\n /**\n * Owner-minted bearer tokens for local MCP clients. Always present on a\n * runtime returned by {@link initializeLocalApplicationRuntime}; optional\n * only so structural test doubles stay valid. Absent means \"no tokens\":\n * callers fail closed.\n */\n readonly mcpTokens?: LocalMcpTokenStore;\n}\n\nclass InitializedLocalApplicationRuntime implements LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n readonly mcpTokens: LocalMcpTokenStore;\n private readonly bootstrapTtlSeconds: number;\n private readonly sessionTtlSeconds: number;\n private readonly now: () => Date;\n private readonly canonicalSourceRoot: string;\n\n constructor(state: LocalApplicationRuntimeState) {\n this.db = state.db;\n this.paths = state.paths;\n this.bindHost = state.bindHost;\n this.resolvedRuntime = state.resolvedRuntime;\n this.bootstrapTtlSeconds = state.bootstrapTtlSeconds;\n this.sessionTtlSeconds = state.sessionTtlSeconds;\n this.backgroundJobsEnabled = state.backgroundJobs;\n this.paidCapabilitiesEnabled = state.paidCapabilities;\n this.now = state.now;\n this.canonicalSourceRoot = state.canonicalSourceRoot;\n this.mcpTokens = localMcpTokenStore(\n state.db,\n state.paths,\n state.canonicalSourceRoot,\n state.now,\n );\n }\n\n /**\n * Issue the first short-lived owner invitation when none is active.\n * Repeated startup never rotates an unexpired token or duplicates an owner.\n */\n async ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null> {\n if (await findExistingOwner(this.db)) return null;\n const current = await readBootstrapRow(this.db);\n if (current?.consumed_at != null) return null;\n const now = this.now();\n const currentExpiry = parseStoredDate(current?.expires_at);\n if (\n current &&\n current.consumed_at == null &&\n currentExpiry !== null &&\n currentExpiry.getTime() > now.getTime()\n ) {\n return null;\n }\n return this.issueBootstrapInvitation(false);\n }\n\n /** Explicit recovery when an installer lost the one-time plaintext token. */\n async rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation> {\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const invitation = await this.issueBootstrapInvitation(true);\n if (!invitation) {\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'A local owner bootstrap invitation could not be issued.',\n );\n }\n return invitation;\n }\n\n /**\n * Consume a bootstrap token and atomically create normal identity/RBAC/session\n * records. The token transition and every record write share one transaction.\n */\n async claimOwner(\n input: ClaimLocalOwnerInput,\n ): Promise<LocalOwnerClaimResult> {\n validateOwnerInput(input);\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if (typeof this.db.transaction !== 'function') {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'Owner bootstrap requires a database adapter with transaction support.',\n );\n }\n\n const tokenHash = await this.hashBootstrapToken(input.token);\n const now = this.now();\n const nowIso = now.toISOString();\n // A token that cannot claim is rejected before seeding, so a wrong,\n // replayed, or expired token stays read-only and never pays for a\n // catalog-wide write (#3323). This is a preflight only: the conditional\n // UPDATE in the claim transaction below remains the single authority.\n if (!(await isBootstrapTokenClaimable(this.db, tokenHash, nowIso))) {\n await throwBootstrapClaimFailure(this.db, now);\n }\n // Generated write routes require `<collection>.<action>` grants (#2977),\n // so the owner role must hold the default role matrix over the manifest\n // permission catalog, not only the role itself. Seeding is idempotent and\n // additive, and commits in its own transaction before the claim\n // transaction.\n const roles = await RoleCollection.create({ db: this.db });\n await roles.seedSystemRoles({ seedPermissions: true });\n return this.db.transaction(async (tx) => {\n const claimed = await tx.query(\n `UPDATE ${BOOTSTRAP_TABLE}\n SET consumed_at = ?\n WHERE slot = 1\n AND token_hash = ?\n AND consumed_at IS NULL\n AND expires_at > ?\n RETURNING expires_at`,\n nowIso,\n tokenHash,\n nowIso,\n );\n if (claimed.rows.length === 0) {\n await throwBootstrapClaimFailure(tx, now);\n }\n\n const concurrentOwner = await findExistingOwner(tx);\n if (concurrentOwner) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n\n return createLocalOwnerRecords(tx, input, this.sessionTtlSeconds);\n });\n }\n\n /** Restore the normal server-side session created by owner bootstrap. */\n async restoreSession(sessionId: string) {\n const service = new SessionService({ db: this.db });\n await service.initialize();\n return service.loadSessionContext(sessionId);\n }\n\n /**\n * Create an in-process persisted-job runner. Background work is default-off\n * and must be explicitly enabled by runtime configuration.\n */\n async createEmbeddedJobRunner(\n config: TaskRunnerConfig = {},\n ): Promise<TaskRunner> {\n if (!this.backgroundJobsEnabled) {\n throw new LocalRuntimeError(\n 'capability_disabled',\n 'Background jobs are disabled; enable them explicitly for this local application.',\n );\n }\n if (this.resolvedRuntime.providers.jobs.topology !== 'embedded') {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'An embedded runner requires the local embedded job topology.',\n );\n }\n const runner = new TaskRunner({\n concurrency: 1,\n retention: false,\n ...config,\n });\n await runner.initialize(this.db);\n return runner;\n }\n\n /** Return a deterministic snapshot that never reads secret file contents. */\n async diagnostics(): Promise<LocalRuntimeDiagnostics> {\n const owner = await findExistingOwner(this.db);\n const bootstrap = await readBootstrapRow(this.db);\n const now = this.now();\n const expiresAt = parseStoredDate(bootstrap?.expires_at);\n let status: LocalBootstrapStatus = 'unavailable';\n if (owner || bootstrap?.consumed_at != null) status = 'claimed';\n else if (expiresAt && expiresAt.getTime() > now.getTime())\n status = 'available';\n else if (expiresAt) status = 'expired';\n\n return Object.freeze({\n schemaVersion: 1,\n runtime: this.resolvedRuntime,\n bind: Object.freeze({ host: this.bindHost, loopback: true as const }),\n paths: this.paths,\n storage: Object.freeze({\n database: 'sqlite-file' as const,\n assets: 'user-owned-directory' as const,\n secrets: 'mode-0600-local-file' as const,\n }),\n bootstrap: Object.freeze({\n status,\n expiresAt: expiresAt?.toISOString() ?? null,\n tokenValuesIncluded: false as const,\n tokenHashesIncluded: false as const,\n }),\n tenancy: Object.freeze({\n mode: 'real-default-tenant' as const,\n ui: 'hidden' as const,\n }),\n jobs: Object.freeze({\n topology: this.resolvedRuntime.providers.jobs.topology as\n | 'inline'\n | 'embedded',\n backgroundEnabled: this.backgroundJobsEnabled,\n }),\n paidCapabilitiesEnabled: this.paidCapabilitiesEnabled,\n secretValuesIncluded: false as const,\n });\n }\n\n private async issueBootstrapInvitation(\n replaceActive: boolean,\n ): Promise<LocalOwnerBootstrapInvitation | null> {\n const token = randomBytes(32).toString('base64url');\n const tokenHash = await this.hashBootstrapToken(token);\n const now = this.now();\n const expiresAt = new Date(now.getTime() + this.bootstrapTtlSeconds * 1000);\n const stored = await this.db.query(\n `INSERT INTO ${BOOTSTRAP_TABLE}\n (slot, token_hash, expires_at, consumed_at, created_at)\n VALUES (1, ?, ?, NULL, ?)\n ON CONFLICT(slot) DO UPDATE SET\n token_hash = excluded.token_hash,\n expires_at = excluded.expires_at,\n consumed_at = NULL,\n created_at = excluded.created_at\n WHERE ${BOOTSTRAP_TABLE}.consumed_at IS NULL\n AND (? = 1 OR ${BOOTSTRAP_TABLE}.expires_at <= ?)\n RETURNING token_hash`,\n tokenHash,\n expiresAt.toISOString(),\n now.toISOString(),\n replaceActive ? 1 : 0,\n now.toISOString(),\n );\n const persistedHash = (\n stored.rows[0] as { token_hash?: unknown } | undefined\n )?.token_hash;\n if (persistedHash !== tokenHash) return null;\n return Object.freeze({ token, expiresAt: expiresAt.toISOString() });\n }\n\n private async hashBootstrapToken(token: string): Promise<string> {\n const secret = await validateApplicationSecret(\n this.paths.applicationSecret,\n this.canonicalSourceRoot,\n );\n return createHmac('sha256', secret.trim()).update(token).digest('hex');\n }\n}\n\nasync function createLocalOwnerRecords(\n db: DatabaseInterface,\n input: ClaimLocalOwnerInput,\n sessionTtlSeconds: number,\n): Promise<LocalOwnerClaimResult> {\n const profileTypes = await ProfileTypeCollection.create({ db });\n const personType = await withSystemContext(() =>\n profileTypes.getOrCreateGlobalBySlug('person', {\n name: 'Person',\n description: 'An individual person',\n }),\n );\n const person = new Person({\n db,\n typeId: requireId(personType.id, 'Person profile type'),\n tenantId: null,\n name: input.name.trim(),\n email: input.email.trim(),\n });\n await person.initialize();\n await person.save();\n\n const users = await UserCollection.create({ db });\n const user = await users.create({\n profileId: requireId(person.id, 'Person'),\n email: input.email.trim(),\n status: UserStatus.ACTIVE,\n lastLoginAt: new Date(),\n });\n await user.save();\n\n const tenantService = new TenantService(\n { db },\n {\n mode: 'required',\n maxTenants: 1,\n defaultName: input.tenantName?.trim() || 'My Workspace',\n },\n );\n await tenantService.initialize();\n const { tenant, membership } = await tenantService.createTenantWithOwnership(\n requireId(user.id, 'User'),\n input.tenantName?.trim() || 'My Workspace',\n { slug: 'default' },\n );\n\n const sessions = await SessionCollection.create({ db });\n const session = await sessions.createSession({\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n ttl: sessionTtlSeconds,\n userAgent: input.userAgent,\n ipAddress: input.ipAddress,\n data: { localOwner: true },\n });\n\n return Object.freeze({\n profileId: requireId(person.id, 'Person'),\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n membershipId: requireId(membership.id, 'Membership'),\n sessionId: requireId(session.id, 'Session'),\n });\n}\n\nasync function findExistingOwner(\n db: DatabaseInterface,\n): Promise<ExistingOwner | null> {\n const roles = await RoleCollection.create({ db });\n const ownerRole = await roles.findSystemRoleBySlug(DEFAULT_ROLE_SLUGS.OWNER);\n if (!ownerRole?.id) return null;\n const memberships = await MembershipCollection.create({ db });\n const ownerMemberships = await memberships.findByRole(ownerRole.id);\n const active = ownerMemberships.find(\n (membership) =>\n membership.status === MembershipStatus.ACTIVE &&\n typeof membership.userId === 'string' &&\n typeof membership.tenantId === 'string',\n );\n return active\n ? { userId: active.userId as string, tenantId: active.tenantId as string }\n : null;\n}\n\nasync function throwBootstrapClaimFailure(\n db: DatabaseInterface,\n now: Date,\n): Promise<never> {\n const row = await readBootstrapRow(db);\n if (!row) {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'No local owner bootstrap invitation is available.',\n );\n }\n if (row.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const expiresAt = parseStoredDate(row.expires_at);\n if (!expiresAt || expiresAt.getTime() <= now.getTime()) {\n throw new LocalRuntimeError(\n 'bootstrap_expired',\n 'The local owner bootstrap invitation has expired.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'The local owner bootstrap token is invalid.',\n );\n}\n\nasync function isBootstrapTokenClaimable(\n db: DatabaseInterface,\n tokenHash: string,\n nowIso: string,\n): Promise<boolean> {\n const result = await db.query(\n `SELECT 1 AS claimable\n FROM ${BOOTSTRAP_TABLE}\n WHERE slot = 1\n AND token_hash = ?\n AND consumed_at IS NULL\n AND expires_at > ?\n LIMIT 1`,\n tokenHash,\n nowIso,\n );\n return result.rows.length > 0;\n}\n\nasync function readBootstrapRow(\n db: DatabaseInterface,\n): Promise<BootstrapRow | null> {\n const result = await db.query(\n `SELECT expires_at, consumed_at\n FROM ${BOOTSTRAP_TABLE}\n WHERE slot = 1\n LIMIT 1`,\n );\n return (result.rows[0] as BootstrapRow | undefined) ?? null;\n}\n\nasync function ensureBootstrapTable(db: DatabaseInterface): Promise<void> {\n await db.query(\n `CREATE TABLE IF NOT EXISTS ${BOOTSTRAP_TABLE} (\n slot INTEGER PRIMARY KEY CHECK (slot = 1),\n token_hash TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n consumed_at TEXT NULL,\n created_at TEXT NOT NULL\n )`,\n );\n}\n\nasync function tuneLocalSqlite(db: DatabaseInterface): Promise<void> {\n await db.query('PRAGMA foreign_keys = ON');\n await db.query('PRAGMA journal_mode = WAL');\n await db.query('PRAGMA synchronous = FULL');\n await db.query('PRAGMA busy_timeout = 5000');\n}\n\ninterface PreparedLocalRoot {\n createdDirectories: string[];\n pendingMarker: string | null;\n pendingMarkerCreatedByAttempt: boolean;\n finalMarker: string;\n}\n\ninterface LocalInitializationLock {\n release(): Promise<void>;\n}\n\nasync function preflightLocalApplicationRoot(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n for (let attempt = 0; attempt < PREFLIGHT_RETRY_LIMIT; attempt += 1) {\n try {\n await preflightLocalApplicationRootOnce(root, sourceRoot, appId);\n return;\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n if (attempt === PREFLIGHT_RETRY_LIMIT - 1) {\n throw unsafeFilesystemEntry(\n 'Local application data changed repeatedly during read-only preflight.',\n error,\n );\n }\n await new Promise<void>((resolveRetry) => setImmediate(resolveRetry));\n }\n }\n}\n\nasync function preflightLocalApplicationRootOnce(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime storage requires a numeric current-user identity.',\n );\n }\n if (\n isInside(canonicalSourceRoot, root) ||\n isInside(root, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n\n let rootExists = true;\n for (const component of absolutePathComponents(root)) {\n let details: Awaited<ReturnType<typeof lstat>>;\n try {\n details = await lstat(component);\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n rootExists = false;\n break;\n }\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n const sharedStickyRoot = details.uid === 0 && (details.mode & 0o1000) !== 0;\n if (\n (details.uid !== currentUid && details.uid !== 0) ||\n ((details.mode & 0o022) !== 0 && !sharedStickyRoot)\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path ancestry does not have trusted-parent custody: ${component}`,\n );\n }\n await assertNoPermissiveDarwinAcl(component);\n }\n\n if (!rootExists) return;\n const rootDetails = await lstat(root);\n if (rootDetails.uid !== currentUid || (rootDetails.mode & 0o777) !== 0o700) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${root}`,\n );\n }\n await preflightDedicatedRoot(root, canonicalSourceRoot, appId);\n}\n\nasync function preflightDedicatedRoot(\n root: string,\n canonicalSourceRoot: string,\n appId: string,\n): Promise<void> {\n const finalMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(root);\n const finalMarkerName = finalMarker.slice(root.length + 1);\n const pendingMarkerName = pendingMarker.slice(root.length + 1);\n const hasFinalMarker = entries.includes(finalMarkerName);\n const hasPendingMarker = entries.includes(pendingMarkerName);\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return;\n }\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarkerName,\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return;\n }\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n}\n\nasync function assertNoPermissiveDarwinAcl(path: string): Promise<void> {\n if (platform() !== 'darwin') return;\n let listing: string;\n try {\n const result = await execFileAsync('/bin/ls', ['-lde', '--', path], {\n encoding: 'utf8',\n env: { ...process.env, LC_ALL: 'C' },\n });\n listing = result.stdout;\n } catch (error) {\n throw unsafeFilesystemEntry(\n `Local runtime could not inspect macOS access controls: ${path}`,\n error,\n );\n }\n for (const line of listing.split('\\n')) {\n if (!/^\\s*\\d+:/.test(line)) continue;\n const entry = line.match(/^\\s*\\d+:\\s+.+\\s+(allow|deny)\\s+\\S.*$/);\n if (entry?.[1] !== 'deny') {\n throw unsafeFilesystemEntry(\n `Local runtime path contains a permissive macOS access control list: ${path}`,\n );\n }\n }\n}\n\nasync function acquireLocalDatabase(\n paths: LocalRuntimePaths,\n sourceRoot: string,\n appId: string,\n): Promise<{\n canonicalSourceRoot: string;\n db: DatabaseInterface;\n}> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const createdDirectories = await ensureSafeDirectoryTree(\n paths.root,\n canonicalSourceRoot,\n true,\n );\n const prepared = await prepareDedicatedRoot(\n paths.root,\n canonicalSourceRoot,\n appId,\n createdDirectories,\n );\n let db: DatabaseInterface | undefined;\n try {\n db = await getDatabase({\n type: 'sqlite',\n url: paths.database,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: paths.root,\n },\n });\n await enforcePrivateDatabaseMode(paths.database, canonicalSourceRoot);\n } catch (error) {\n if (db) throw await closeDatabaseAfterFailure(db, error);\n if (prepared.pendingMarkerCreatedByAttempt) {\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n await removeCreatedDirectories(createdDirectories);\n }\n throw error;\n }\n if (!db) {\n throw new Error('Local runtime database acquisition returned no database.');\n }\n\n // Once SQLite acquisition succeeds, the database is an authoritative\n // artifact. Keep the pending marker through every promotion failure so a\n // later startup can resume rather than seeing an unmarked populated root.\n try {\n await publishRootMarker(prepared.finalMarker, canonicalSourceRoot);\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n } catch (error) {\n throw await closeDatabaseAfterFailure(db, error);\n }\n return { canonicalSourceRoot, db };\n}\n\nasync function enforcePrivateDatabaseMode(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const database = await openSafeFile(\n path,\n constants.O_RDWR,\n 0o600,\n 'Local application database',\n canonicalSourceRoot,\n );\n try {\n await database.chmod(0o600);\n await database.sync();\n } finally {\n await database.close();\n }\n}\n\nasync function closeDatabaseAfterFailure(\n db: DatabaseInterface,\n primaryFailure: unknown,\n): Promise<unknown> {\n try {\n await db.close?.();\n } catch (cleanupFailure) {\n return preservePrimaryFailure(\n primaryFailure,\n cleanupFailure,\n 'databaseCleanupError',\n 'Local runtime initialization and database cleanup both failed.',\n );\n }\n return primaryFailure;\n}\n\nfunction migrationFailed(cause: unknown): LocalRuntimeError {\n const failure = new LocalRuntimeError(\n 'migration_failed',\n MIGRATION_FAILED_MESSAGE,\n );\n Object.defineProperty(failure, 'cause', {\n value: cause,\n configurable: true,\n });\n return failure;\n}\n\nfunction preservePrimaryFailure(\n primaryFailure: unknown,\n secondaryFailure: unknown,\n secondaryProperty: string,\n aggregateMessage: string,\n): unknown {\n if (primaryFailure instanceof Error) {\n try {\n Object.defineProperty(primaryFailure, secondaryProperty, {\n value: secondaryFailure,\n configurable: true,\n });\n } catch {\n // A frozen application error must remain primary even when secondary\n // failure context cannot be attached to it.\n }\n return primaryFailure;\n }\n return new AggregateError(\n [primaryFailure, secondaryFailure],\n aggregateMessage,\n );\n}\n\nasync function prepareLocalFilesystem(\n paths: LocalRuntimePaths,\n canonicalSourceRoot: string,\n): Promise<void> {\n await ensureSafeDirectoryTree(paths.assets, canonicalSourceRoot);\n await ensureSafeDirectoryTree(paths.secrets, canonicalSourceRoot);\n await ensureApplicationSecret(paths.applicationSecret, canonicalSourceRoot);\n}\n\nasync function prepareDedicatedRoot(\n path: string,\n canonicalSourceRoot: string,\n appId: string,\n createdDirectories: string[],\n): Promise<PreparedLocalRoot> {\n const finalMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(path);\n const hasFinalMarker = entries.includes(finalMarker.slice(path.length + 1));\n const hasPendingMarker = entries.includes(\n pendingMarker.slice(path.length + 1),\n );\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return {\n createdDirectories,\n pendingMarker: hasPendingMarker ? pendingMarker : null,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarker.slice(path.length + 1),\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n const pendingMarkerCreatedByAttempt = await publishRootMarker(\n pendingMarker,\n canonicalSourceRoot,\n );\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt,\n finalMarker,\n };\n}\n\nasync function acquireInitializationLock(\n root: string,\n): Promise<LocalInitializationLock> {\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime initialization locks require a numeric current-user identity.',\n );\n }\n const canonicalTemporaryRoot = await realpath('/tmp');\n const lockRoot = resolve(canonicalTemporaryRoot, `.smrt-${currentUid}`);\n try {\n await mkdir(lockRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const lockRootDetails = await lstat(lockRoot);\n if (\n !lockRootDetails.isDirectory() ||\n lockRootDetails.isSymbolicLink() ||\n lockRootDetails.uid !== currentUid ||\n (lockRootDetails.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime lock directory must be current-user-owned with mode 0700: ${lockRoot}`,\n );\n }\n const lockKey = createHash('sha256')\n .update(normalizeFilesystemIdentity(root))\n .digest('hex')\n .slice(0, 32);\n const custodyRoot = resolve(lockRoot, lockKey);\n try {\n await mkdir(custodyRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const path = resolve(custodyRoot, 'initialization.sqlite');\n return acquireInitializationDatabaseLease(path, custodyRoot);\n}\n\nasync function acquireInitializationDatabaseLease(\n path: string,\n custodyRoot: string,\n): Promise<LocalInitializationLock> {\n const worker = new Worker(INITIALIZATION_LOCK_WORKER, {\n eval: true,\n workerData: {\n path,\n custodyRoot,\n timeout: INITIALIZATION_LOCK_TIMEOUT_MS,\n sqlModuleUrl: import.meta.resolve('@happyvertical/sql'),\n },\n });\n const acquisitionFailure = (cause: unknown) => {\n const failure = new LocalRuntimeError(\n 'invalid_configuration',\n 'Could not acquire the local runtime initialization lease within two minutes.',\n );\n Object.defineProperty(failure, 'cause', { value: cause });\n return failure;\n };\n let workerError: unknown;\n const exited = new Promise<never>((_resolve, reject) => {\n worker.once('error', (error) => {\n workerError = error;\n });\n worker.once('exit', (code) => {\n reject(\n acquisitionFailure(\n workerError ??\n new Error(`Initialization lock worker exited ${code}.`),\n ),\n );\n });\n });\n const acquired = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; message?: string }) => {\n if (message.type === 'acquired') {\n worker.off('message', onMessage);\n resolvePromise();\n } else if (message.type === 'error') {\n worker.off('message', onMessage);\n reject(acquisitionFailure(new Error(message.message)));\n }\n };\n worker.on('message', onMessage);\n });\n await Promise.race([acquired, exited]);\n\n let released = false;\n return {\n release: async () => {\n if (released) return;\n released = true;\n const releaseCompleted = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; error?: string }) => {\n if (message.type !== 'released') return;\n worker.off('message', onMessage);\n if (message.error) reject(new Error(message.error));\n else resolvePromise();\n };\n worker.on('message', onMessage);\n worker.postMessage({ type: 'release' });\n });\n try {\n await Promise.race([releaseCompleted, exited]);\n } finally {\n await worker.terminate();\n }\n },\n };\n}\n\nasync function ensureSafeDirectoryTree(\n path: string,\n canonicalSourceRoot: string,\n dedicatedRoot = false,\n): Promise<string[]> {\n const components = absolutePathComponents(path);\n const createdDirectories: string[] = [];\n for (const component of components) {\n let created = false;\n try {\n const details = await lstat(component);\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n try {\n await mkdir(component, { mode: 0o700 });\n created = true;\n createdDirectories.push(component);\n } catch (mkdirError) {\n // A concurrent initializer may have created the component. It is still\n // opened and validated without following links below.\n if (!isFileAlreadyExists(mkdirError)) throw mkdirError;\n }\n }\n\n const directory = await openSafeDirectory(component, canonicalSourceRoot);\n try {\n await assertCanonicalEntry(component, canonicalSourceRoot);\n if (component === path && dedicatedRoot && !created) {\n await assertExistingDedicatedRoot(\n directory,\n component,\n canonicalSourceRoot,\n );\n }\n if (created || (component === path && !dedicatedRoot)) {\n await directory.chmod(0o700);\n }\n } finally {\n await directory.close();\n }\n }\n await validateExistingPathChain(path, canonicalSourceRoot, 'directory');\n return createdDirectories;\n}\n\nasync function assertExistingDedicatedRoot(\n directory: FileHandle,\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (\n isInside(canonicalSourceRoot, canonical) ||\n isInside(canonical, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must be a dedicated directory that does not overlap the canonical source tree.',\n );\n }\n\n const details = await directory.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${path}`,\n );\n }\n}\n\nasync function publishRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<boolean> {\n let marker: FileHandle | undefined;\n let created = false;\n try {\n marker = await openSafeFile(\n path,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n created = true;\n await marker.sync();\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n } finally {\n await marker?.close();\n }\n await validateRootMarker(path, canonicalSourceRoot);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n return created;\n}\n\nasync function validateRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const marker = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n try {\n const details = await marker.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 0\n ) {\n throw unsafeFilesystemEntry(\n `Local application root marker must be an empty current-user-owned mode-0600 file: ${path}`,\n );\n }\n } finally {\n await marker.close();\n }\n}\n\nasync function removeMarkerIfPresent(\n path: string | null,\n canonicalSourceRoot: string,\n): Promise<void> {\n if (path === null) return;\n try {\n await validateRootMarker(path, canonicalSourceRoot);\n await unlink(path);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n }\n}\n\nasync function removeCreatedDirectories(paths: string[]): Promise<void> {\n for (const path of paths.toReversed()) {\n try {\n await rmdir(path);\n } catch (error) {\n if (!isMissingFile(error) && !isDirectoryNotEmpty(error)) throw error;\n }\n }\n}\n\nasync function ensureApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directoryPath = resolve(path, '..');\n const temporaryPath = resolve(\n directoryPath,\n `.${SECRET_FILE_NAME}.tmp-${randomBytes(16).toString('hex')}`,\n );\n let temporary: FileHandle | undefined;\n let failure: unknown;\n try {\n temporary = await openSafeFile(\n temporaryPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Temporary application secret',\n canonicalSourceRoot,\n );\n await temporary.writeFile(\n `${randomBytes(32).toString('base64url')}\\n`,\n 'utf8',\n );\n await temporary.sync();\n await temporary.close();\n temporary = undefined;\n\n try {\n await link(temporaryPath, path);\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n\n await validateApplicationSecret(path, canonicalSourceRoot);\n await syncDirectory(directoryPath, canonicalSourceRoot);\n } catch (error) {\n failure = error;\n }\n try {\n await temporary?.close();\n } catch (error) {\n failure ??= error;\n }\n try {\n await unlink(temporaryPath);\n } catch (error) {\n if (!isMissingFile(error)) failure ??= error;\n }\n if (failure !== undefined) throw failure;\n await removeStaleSecretTemps(directoryPath);\n}\n\nasync function validateApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<string> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const file = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Application secret',\n canonicalSourceRoot,\n );\n try {\n const details = await file.stat();\n const currentUid = process.getuid?.();\n const secret = await file.readFile('utf8');\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 44 ||\n !/^[A-Za-z0-9_-]{43}\\n$/.test(secret)\n ) {\n throw unsafeFilesystemEntry(\n 'Application secret must be a complete current-user-owned mode-0600 value in the expected format.',\n );\n }\n return secret;\n } finally {\n await file.close();\n }\n}\n\nasync function syncDirectory(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directory = await openSafeDirectory(path, canonicalSourceRoot);\n try {\n await directory.sync();\n } finally {\n await directory.close();\n }\n}\n\nasync function removeStaleSecretTemps(directoryPath: string): Promise<void> {\n const prefix = `.${SECRET_FILE_NAME}.tmp-`;\n for (const entry of await readdir(directoryPath)) {\n if (!entry.startsWith(prefix)) continue;\n try {\n await unlink(resolve(directoryPath, entry));\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n }\n }\n}\n\nasync function openSafeDirectory(path: string, canonicalSourceRoot: string) {\n let directory: FileHandle | undefined;\n try {\n directory = await open(\n path,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,\n );\n await validateOpenHandlePath(\n directory,\n path,\n 'directory',\n canonicalSourceRoot,\n );\n return directory;\n } catch (error) {\n await directory?.close();\n if (error instanceof LocalRuntimeError) throw error;\n throw unsafeFilesystemEntry(\n `Could not safely open local runtime directory: ${path}`,\n error,\n );\n }\n}\n\nasync function openSafeFile(\n path: string,\n flags: number,\n mode: number,\n label: string,\n canonicalSourceRoot: string,\n) {\n let file: FileHandle | undefined;\n try {\n file = await open(path, flags | constants.O_NOFOLLOW, mode);\n await validateOpenHandlePath(file, path, 'file', canonicalSourceRoot);\n return file;\n } catch (error) {\n await file?.close();\n if (error instanceof LocalRuntimeError || isFileAlreadyExists(error)) {\n throw error;\n }\n throw unsafeFilesystemEntry(\n `${label} could not be opened without following symbolic links.`,\n error,\n );\n }\n}\n\nasync function validateOpenHandlePath(\n handle: FileHandle,\n path: string,\n expectedType: 'directory' | 'file',\n canonicalSourceRoot: string,\n): Promise<void> {\n const opened = await handle.stat();\n const current = await lstat(path);\n const expectedDirectory = expectedType === 'directory';\n if (\n current.isSymbolicLink() ||\n (expectedDirectory ? !opened.isDirectory() : !opened.isFile()) ||\n (expectedDirectory ? !current.isDirectory() : !current.isFile()) ||\n opened.dev !== current.dev ||\n opened.ino !== current.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed while it was being opened: ${path}`,\n );\n }\n await validateExistingPathChain(path, canonicalSourceRoot, expectedType);\n const afterValidation = await lstat(path);\n if (\n afterValidation.isSymbolicLink() ||\n opened.dev !== afterValidation.dev ||\n opened.ino !== afterValidation.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed during validation: ${path}`,\n );\n }\n}\n\nasync function validateExistingPathChain(\n path: string,\n canonicalSourceRoot: string,\n leafType: 'directory' | 'file',\n): Promise<void> {\n const components = absolutePathComponents(path);\n for (const [index, component] of components.entries()) {\n const details = await lstat(component);\n const expectedFile = index === components.length - 1 && leafType === 'file';\n if (\n details.isSymbolicLink() ||\n (expectedFile ? !details.isFile() : !details.isDirectory())\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path contains an unsafe component: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n }\n}\n\nasync function assertCanonicalEntry(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (!sameFilesystemPath(canonical, path)) {\n throw unsafeFilesystemEntry(\n `Local runtime path must not be redirected: ${path}`,\n );\n }\n if (isInside(canonicalSourceRoot, canonical)) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n}\n\nfunction absolutePathComponents(path: string): string[] {\n const absolute = resolve(path);\n const root = parse(absolute).root;\n const parts = absolute.slice(root.length).split(sep).filter(Boolean);\n const components = [root];\n for (const part of parts) {\n components.push(resolve(components.at(-1) as string, part));\n }\n return components;\n}\n\nfunction requireNoFollowSupport(): void {\n if (\n typeof constants.O_NOFOLLOW !== 'number' ||\n constants.O_NOFOLLOW === 0 ||\n typeof constants.O_DIRECTORY !== 'number' ||\n constants.O_DIRECTORY === 0\n ) {\n throw unsafeFilesystemEntry(\n 'This platform cannot safely initialize local storage without no-follow filesystem support.',\n );\n }\n}\n\nfunction sameFilesystemPath(\n left: string,\n right: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n return (\n normalizeFilesystemIdentity(left, runtimePlatform) ===\n normalizeFilesystemIdentity(right, runtimePlatform)\n );\n}\n\nfunction usesCaseInsensitivePathGuards(\n runtimePlatform: NodeJS.Platform,\n): boolean {\n return runtimePlatform === 'win32' || runtimePlatform === 'darwin';\n}\n\nfunction normalizeFilesystemIdentity(\n value: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): string {\n const normalized = resolve(value);\n return usesCaseInsensitivePathGuards(runtimePlatform)\n ? normalized.toLowerCase()\n : normalized;\n}\n\nfunction unsafeFilesystemEntry(message: string, cause?: unknown) {\n const error = new LocalRuntimeError('invalid_configuration', message);\n if (cause !== undefined)\n Object.defineProperty(error, 'cause', { value: cause });\n return error;\n}\n\nfunction validateBootstrapTtl(value: number): number {\n if (\n !Number.isInteger(value) ||\n value < 1 ||\n value > MAX_BOOTSTRAP_TTL_SECONDS\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n `Owner bootstrap TTL must be an integer from 1 to ${MAX_BOOTSTRAP_TTL_SECONDS} seconds.`,\n );\n }\n return value;\n}\n\nfunction validateSessionTtl(value: number): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Session TTL must be a whole number of seconds greater than or equal to 1.',\n );\n }\n return value;\n}\n\nfunction validateOwnerInput(input: ClaimLocalOwnerInput): void {\n if (!input.token || !input.name.trim() || !input.email.trim()) {\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'Owner bootstrap requires a token, name, and email address.',\n );\n }\n}\n\nfunction normalizeLoopbackHost(value: string): string {\n const host = value\n .trim()\n .toLowerCase()\n .replace(/^\\[|\\]$/g, '');\n if (host === '::1') return host;\n const octets = host.split('.');\n if (\n octets.length === 4 &&\n octets.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255) &&\n Number(octets[0]) === 127\n ) {\n return host;\n }\n throw new LocalRuntimeError(\n 'unsafe_public_exposure',\n 'Owner bootstrap is restricted to a loopback IP literal. Use ::1 or 127.0.0.0/8.',\n );\n}\n\n/** Validate an explicit runtime identity. */\nexport function validateApplicationId(value: string): string {\n const appId = value.trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9.-]{0,62}$/.test(appId)) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'appId must contain only lowercase letters, digits, dots, or hyphens.',\n );\n }\n return appId;\n}\n\n/** Encode a package/project identity into a collision-resistant runtime ID. */\nexport function encodeApplicationId(value: string): string {\n const source = value.trim().toLowerCase();\n if (/^[a-z0-9][a-z0-9.-]{0,62}$/.test(source)) return source;\n const digest = createHash('sha256')\n .update(value.trim())\n .digest('hex')\n .slice(0, 10);\n const slug =\n source\n .replace(/[^a-z0-9.-]+/g, '-')\n .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')\n .slice(0, 52)\n .replace(/[^a-z0-9]+$/g, '') || 'app';\n return validateApplicationId(`${slug}-${digest}`);\n}\n\nfunction defaultApplicationDataRoot(\n runtimePlatform: NodeJS.Platform,\n runtimeHome: string,\n env: NodeJS.ProcessEnv,\n): string {\n if (runtimePlatform === 'darwin') {\n return resolve(runtimeHome, 'Library', 'Application Support');\n }\n if (runtimePlatform === 'win32') {\n return resolve(env.LOCALAPPDATA ?? env.APPDATA ?? runtimeHome);\n }\n return resolve(env.XDG_DATA_HOME ?? resolve(runtimeHome, '.local', 'share'));\n}\n\nfunction isInside(\n parent: string,\n child: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n const normalizedParent = normalizeFilesystemIdentity(parent, runtimePlatform);\n const normalizedChild = normalizeFilesystemIdentity(child, runtimePlatform);\n const path = relative(normalizedParent, normalizedChild);\n return path === '' || (!path.startsWith('..') && !isAbsolute(path));\n}\n\nfunction parseStoredDate(value: unknown): Date | null {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireId(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${label} was not persisted with an id.`);\n }\n return value;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n );\n}\n\nfunction hasMissingFileCause(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'cause' in error &&\n isMissingFile((error as { cause?: unknown }).cause)\n );\n}\n\nfunction isFileAlreadyExists(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n );\n}\n\nfunction isDirectoryNotEmpty(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOTEMPTY'\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwIO,IAAM,uBAAN,cAAmC,MAAM;CAC9C,YACW,MACT,SACS,WACT;EACA,MAAM,OAAO;EAJJ,KAAA,OAAA;EAEA,KAAA,YAAA;EAGT,KAAK,OAAO;CACd;CANW;CAEA;AAKb;AAGO,IAAM,8BAAN,cAA0C,qBAAqB;CAIpE,YAA6B,SAA8B;EACzD,MACE,wBACA,4HACA,UACF;EAL2B,KAAA,UAAA;EAM3B,KAAK,OAAO;CACd;CAP6B;CAHrB,UAAU;CACV;CAWR,MAAM,eAA8B;EAClC,IAAI,KAA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