@leitwerk-dev/server 0.5.12 → 0.5.13
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/dist/{app-DWWNqFtH.d.ts → app-JFOsYwET.d.ts} +2 -0
- package/dist/app-WPJIIDUW.js +8 -0
- package/dist/{chunk-65CBLH7U.js → chunk-CHK7ZFJS.js} +11 -3
- package/dist/chunk-CHK7ZFJS.js.map +1 -0
- package/dist/{chunk-I3CCVPXY.js → chunk-KR2Q3NLJ.js} +2 -2
- package/dist/{chunk-C2K2AM5X.js → chunk-YZ2L5YN7.js} +2 -2
- package/dist/config/config-loader.d.ts.map +1 -1
- package/dist/config/config-types.d.ts +2 -0
- package/dist/config/config-types.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/main.js +3 -3
- package/dist/testing.js +1 -1
- package/package.json +12 -12
- package/src/commit-message-policy.ts +3 -3
- package/src/config/config-loader.ts +7 -1
- package/src/config/config-types.ts +2 -0
- package/dist/app-VLQCV5WS.js +0 -8
- package/dist/chunk-65CBLH7U.js.map +0 -1
- /package/dist/{app-VLQCV5WS.js.map → app-WPJIIDUW.js.map} +0 -0
- /package/dist/{chunk-I3CCVPXY.js.map → chunk-KR2Q3NLJ.js.map} +0 -0
- /package/dist/{chunk-C2K2AM5X.js.map → chunk-YZ2L5YN7.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/config-loader.ts","../src/auth/api-token-policy.ts","../src/auth/oidc-evidence.ts","../src/commit-message-policy.ts","../src/docker-registry-credentials.ts","../src/process-storage-size.ts","../src/skills/skill-id.ts","../src/config/kubernetes-docker-isolation.ts","../src/config/url-policy.ts","../src/db/database.ts","../src/db/schema.ts","../src/db/schema-ddl.ts","../src/db/credential-cipher.ts","../src/db/repositories.ts","../src/db/api-token-repo.ts","../src/db/execution-inspection-repo.ts","../src/db/publication-repo.ts","../src/db/scoped-settings-repo.ts","../src/db/repo-helpers.ts","../src/db/startup-observation-repo.ts","../src/db/turn-summary-repo.ts","../src/db/auth-repo.ts","../src/db/external-write-log-repo.ts","../src/db/future-execution-repo.ts","../src/db/launch-run-repo.ts","../src/db/launcher-recent-value-repo.ts","../src/db/mapped-llm-run-repo.ts","../src/db/pending-external-source-fire-repo.ts","../src/db/process-event-repo.ts","../src/db/process-handoff-dedup-key-repo.ts","../src/db/process-input-repo.ts","../src/db/process-instance-repo.ts","../src/launch-title.ts","../src/db/process-leaf-outcome-snapshot-repo.ts","../src/db/history-window.ts","../src/db/process-project-repo.ts","../src/db/process-question-request-repo.ts","../src/db/process-relation-repo.ts","../src/db/process-skill-repo.ts","../src/pi-resources/resource-collector.ts","../src/db/process-title-job-repo.ts","../src/db/process-tool-approval-request-repo.ts","../src/db/process-turn-annotation-repo.ts","../src/db/process-turn-record-repo.ts","../src/db/provider-credential-repo.ts","../src/db/session-transfer-repo.ts","../src/auth/auth-tokens.ts","../src/db/skill-repo.ts","../src/skills/skill-dependencies.ts","../src/skills/skill-frontmatter.ts","../src/db/ticket-destination-recent-repo.ts","../src/db/turn-start-record-repo.ts","../src/db/worker-lease-repo.ts","../src/turn-progress.ts","../src/process-model-policy/construct.ts","../src/process-graph.ts","../src/process-model-policy/evaluate.ts","../src/process-model-policy/requirements.ts","../src/process-model-policy/types.ts","../src/process-model-policy/fingerprint.ts","../src/process-model-policy/input.ts","../src/process-model-policy/integrity.ts","../src/process-model-policy/launch.ts","../src/process-model-policy/project.ts","../src/process-model-policy-presenter.ts","../src/process-model-policy/stable-availability.ts","../src/process-model-policy/index.ts","../src/launch-pipeline.ts","../src/pi-resources/bundle-cache.ts","../src/model-providers/provider-boundary-utils.ts","../src/pi-resources/bundle-pin-lifecycle.ts","../src/pi-resources/assemble.ts","../src/process-operator-attention.ts","../src/process-execution.ts","../src/worker-runtime-profile-selection.ts","../src/process-engine/turn-start-preflight.ts","../src/model-providers/provider-options.ts","../src/process-operation-coordinator.ts","../src/process-session-store.ts","../src/pi-session-tree.ts","../src/instance-tree.ts","../src/process-turn-trace.ts","../src/session-transfer-service.ts","../src/supervisor/worker-storage-layout.ts","../src/process-ui-snapshot-presenter.ts","../src/external-source-reporting.ts","../src/future-execution-presenter.ts","../src/process-action-presenter.ts","../src/physical-worker-starts.ts","../src/process-engine/writes/writes.ts","../src/process-engine/turn-wait-state.ts","../src/process-inspection.ts","../src/process-instance-tree-presenter.ts","../src/process-turn-navigation.ts","../src/routes/process-route-helpers.ts","../src/process-engine/internal-failures.ts","../src/auth/fastify-auth.ts","../src/startup-retry-policy.ts","../src/startup-evidence.ts","../src/session-summary-projection.ts","../src/primary-path-snapshot.ts","../src/ws/broadcast.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { copiedUnknownRecordSchema as unknownRecordSchema } from \"@leitwerk-dev/domain\";\nimport { modelPolicyIdentifiersSchema, modelRequirementsSchema } from \"@leitwerk-dev/protocol\";\nimport { DEFAULT_SESSION_TRANSFER_LIMITS } from \"@leitwerk-dev/session-transfer\";\nimport { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport {\n\tdockerNetworkSchema,\n\tdockerRegistryCredentialSchema,\n\tipAddressSchema as kubernetesHostAliasIpSchema,\n} from \"@leitwerk-dev/worker-protocol\";\nimport { createDefu } from \"defu\";\nimport * as v from \"valibot\";\nimport { parse as parseYaml } from \"yaml\";\nimport { resolveApiTokenPolicy } from \"../auth/api-token-policy.js\";\nimport { policyErrors } from \"../auth/oidc-evidence.js\";\nimport { normalizeRepositoryLocator } from \"../commit-message-policy.js\";\nimport { resolveDockerRegistryCredentials } from \"../docker-registry-credentials.js\";\nimport { isValidStorageSize } from \"../process-storage-size.js\";\nimport { SAFE_SKILL_ID_PATTERN } from \"../skills/skill-id.js\";\nimport type { LeitwerkConfig } from \"./config-types.js\";\nimport { resolveKubernetesDockerIsolation } from \"./kubernetes-docker-isolation.js\";\nimport { isHttpsOrLoopbackHttpUrl, isValidHttpUrl, parseHttpUrl } from \"./url-policy.js\";\n\nconst DEFAULT_SEARCH_PATHS = [\"./leitwerk.yaml\", \"~/.leitwerk/leitwerk.yaml\"];\nconst REDACTED_LOG_VALUE = \"<redacted>\";\nconst SENSITIVE_CONFIG_KEY_PATTERN =\n\t/(token|secret|password|passphrase|api[_-]?key|private[_-]?key|known[_-]?hosts|webhook)/i;\nconst storageSizeSchema = v.pipe(\n\tv.string(),\n\tv.check(\n\t\t(value) => isValidStorageSize(value),\n\t\t\"Must be a positive storage quantity (for example, 128Mi or 1Gi)\",\n\t),\n);\nconst positiveSafeInteger = v.pipe(\n\tv.number(),\n\tv.integer(),\n\tv.minValue(1),\n\tv.maxValue(Number.MAX_SAFE_INTEGER),\n);\n\n/** @public */\nexport interface ConfigLoadResult {\n\t/** @public */\n\tok: true;\n\t/** @public */\n\tconfig: LeitwerkConfig;\n\t/** @internal */\n\tfilePath: string;\n}\n\n/** @public */\nexport interface ConfigLoadError {\n\t/** @public */\n\tok: false;\n\t/** @public */\n\terror: string;\n}\n\ntype ConfigIssue = {\n\tpath: string;\n\tmessage: string;\n};\n\nfunction expandHome(p: string): string {\n\tif (p.startsWith(\"~/\")) {\n\t\tconst home = process.env.HOME ?? process.env.USERPROFILE ?? \"\";\n\t\treturn resolve(home, p.slice(2));\n\t}\n\treturn resolve(p);\n}\n\nfunction describeType(value: unknown): string {\n\tif (Array.isArray(value)) {\n\t\treturn \"array\";\n\t}\n\tif (value === null) {\n\t\treturn \"null\";\n\t}\n\treturn typeof value;\n}\n\nconst mergeConfigDefaults = createDefu((object, key, value) => {\n\tif (Array.isArray(object[key]) && Array.isArray(value)) {\n\t\tobject[key] = value;\n\t\treturn true;\n\t}\n\treturn false;\n});\n\n/** @internal */\nexport function applyConfigDefaults(raw: Record<string, unknown>): LeitwerkConfig {\n\tconst merged = mergeConfigDefaults(structuredClone(raw), getDefaultConfig()) as LeitwerkConfig;\n\tif (Object.hasOwn(raw, \"worker_runtime_profiles\")) {\n\t\tmerged.worker_runtime_profiles =\n\t\t\traw.worker_runtime_profiles as LeitwerkConfig[\"worker_runtime_profiles\"];\n\t}\n\treturn merged;\n}\n\nexport function resolveConfigPath(explicitPath?: string): string | null {\n\tif (explicitPath) {\n\t\tconst expanded = expandHome(explicitPath);\n\t\treturn existsSync(expanded) ? expanded : null;\n\t}\n\tfor (const candidate of DEFAULT_SEARCH_PATHS) {\n\t\tconst expanded = expandHome(candidate);\n\t\tif (existsSync(expanded)) return expanded;\n\t}\n\treturn null;\n}\n\nexport function loadConfigFromFile(filePath: string): ConfigLoadResult | ConfigLoadError {\n\ttry {\n\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\tconst parsedYaml = parseYaml(raw);\n\t\tconst parsed = parsedYaml === null ? {} : parsedYaml;\n\t\tconst parsedRecord = v.safeParse(unknownRecordSchema, parsed);\n\t\tif (!parsedRecord.success) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `Config validation errors:\\nExpected object at <root>, got ${describeType(parsed)}`,\n\t\t\t};\n\t\t}\n\t\tconst config = applyConfigDefaults(parsedRecord.output);\n\t\tfor (const [index, provider] of (config.auth?.providers ?? []).entries()) {\n\t\t\tif (provider.kind !== \"oidc\" || typeof provider.client_secret !== \"string\") continue;\n\t\t\tprovider.client_secret = provider.client_secret.replace(\n\t\t\t\t/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g,\n\t\t\t\t(_placeholder, variable: string) => {\n\t\t\t\t\tconst value = process.env[variable];\n\t\t\t\t\tif (!value)\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`auth.providers[${index}].client_secret: environment variable ${variable} is missing or empty`,\n\t\t\t\t\t\t);\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst errors = validateResolvedConfig(config as unknown as Record<string, unknown>);\n\t\tif (errors.length > 0) {\n\t\t\treturn { ok: false, error: `Config validation errors:\\n${errors.join(\"\\n\")}` };\n\t\t}\n\t\treturn { ok: true, config, filePath };\n\t} catch (err) {\n\t\treturn { ok: false, error: `Failed to load config from ${filePath}: ${err}` };\n\t}\n}\n\n/** @public */\nexport function loadConfig(explicitPath?: string): ConfigLoadResult | ConfigLoadError {\n\tconst filePath = resolveConfigPath(explicitPath);\n\tif (!filePath) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror:\n\t\t\t\t\"Configuration file required: configure pi.default_model_profile and pi.model_profiles\",\n\t\t};\n\t}\n\treturn loadConfigFromFile(filePath);\n}\n\nconst stringArraySchema = v.array(v.string());\nconst skillIdsSchema = v.array(\n\tv.pipe(v.string(), v.regex(SAFE_SKILL_ID_PATTERN, \"Invalid skill ID\")),\n);\nconst modelTurnConfigSchema = v.looseObject({\n\tmodel_profile: v.optional(v.string()),\n\tmodel_requirements: v.optional(modelRequirementsSchema),\n});\n\nconst authNonEmptyString = v.pipe(v.string(), v.nonEmpty());\n\nconst authOidcProviderSchema = v.looseObject({\n\tid: authNonEmptyString,\n\tkind: v.literal(\"oidc\"),\n\tissuer: authNonEmptyString,\n\tclient_id: authNonEmptyString,\n\tclient_secret: authNonEmptyString,\n\tredirect_uri: v.optional(authNonEmptyString),\n\tscopes: v.optional(v.pipe(stringArraySchema, v.nonEmpty())),\n\tidentity_claim: v.optional(authNonEmptyString),\n\taccess: v.optional(\n\t\tv.strictObject({\n\t\t\tmode: v.picklist([\"all\", \"restricted\"]),\n\t\t\tmatch: v.optional(v.picklist([\"all\", \"any\"])),\n\t\t\tusers: v.optional(v.array(authNonEmptyString)),\n\t\t\tgroups: v.optional(v.array(authNonEmptyString)),\n\t\t\tgroups_claim: v.optional(authNonEmptyString),\n\t\t\temail_domains: v.optional(v.array(authNonEmptyString)),\n\t\t}),\n\t),\n});\n\nconst authGithubProviderSchema = v.looseObject({\n\tid: v.literal(\"github\"),\n\tkind: v.literal(\"oauth2\"),\n\tclient_id: authNonEmptyString,\n\tclient_secret: authNonEmptyString,\n\torganization: authNonEmptyString,\n\tredirect_uri: v.optional(authNonEmptyString),\n});\n\nconst authConfigSchema = v.looseObject({\n\tapi_tokens: v.optional(\n\t\tv.strictObject({\n\t\t\tenabled: v.optional(v.boolean()),\n\t\t\tdefault_ttl: v.optional(v.string()),\n\t\t\tmax_ttl: v.optional(v.string()),\n\t\t\tallow_no_expiry: v.optional(v.boolean()),\n\t\t}),\n\t),\n\tenabled: v.optional(v.boolean()),\n\tsession: v.optional(\n\t\tv.looseObject({\n\t\t\tcookie_name: v.optional(authNonEmptyString),\n\t\t\tttl: v.optional(authNonEmptyString),\n\t\t}),\n\t),\n\tproviders: v.optional(\n\t\tv.array(v.variant(\"kind\", [authOidcProviderSchema, authGithubProviderSchema])),\n\t),\n\tallowlist: v.optional(stringArraySchema),\n});\n\nconst safeSkillIdSchema = v.pipe(v.string(), v.regex(SAFE_SKILL_ID_PATTERN));\nconst kubernetesHostnameSchema = v.pipe(\n\tv.string(),\n\tv.nonEmpty(),\n\tv.maxLength(253),\n\tv.regex(\n\t\t/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/u,\n\t\t\"Expected a lowercase DNS hostname\",\n\t),\n);\nconst skillRepositorySchema = v.strictObject({\n\tid: safeSkillIdSchema,\n\tlabel: v.optional(v.pipe(v.string(), v.nonEmpty())),\n\turl: v.pipe(v.string(), v.nonEmpty()),\n\tref: v.pipe(v.string(), v.nonEmpty()),\n\tpath: v.optional(v.pipe(v.string(), v.nonEmpty())),\n});\n\nconst cpuMemoryEntries = { cpu: v.optional(v.string()), memory: v.optional(v.string()) };\n\nconst configSchema = v.looseObject({\n\tskill_repositories: v.optional(v.array(skillRepositorySchema)),\n\tcommit_messages: v.optional(\n\t\tv.strictObject({\n\t\t\ttemplates: v.record(\n\t\t\t\tv.string(),\n\t\t\t\tv.strictObject({\n\t\t\t\t\trules: v.pipe(v.string(), v.nonEmpty()),\n\t\t\t\t\tsignoff: v.optional(v.boolean()),\n\t\t\t\t}),\n\t\t\t),\n\t\t\tdefault_template: v.optional(v.nullable(v.pipe(v.string(), v.nonEmpty()))),\n\t\t\trepositories: v.record(v.string(), v.pipe(v.string(), v.nonEmpty())),\n\t\t}),\n\t),\n\tsession_transfer: v.optional(\n\t\tv.strictObject({\n\t\t\tmax_entries: v.pipe(\n\t\t\t\tv.number(),\n\t\t\t\tv.integer(),\n\t\t\t\tv.minValue(3),\n\t\t\t\tv.maxValue(Number.MAX_SAFE_INTEGER),\n\t\t\t),\n\t\t\tmax_logical_bytes: positiveSafeInteger,\n\t\t\tmax_compressed_bytes: positiveSafeInteger,\n\t\t}),\n\t),\n\tserver: v.looseObject({\n\t\thost: v.string(),\n\t\tport: v.number(),\n\t\tbase_url: v.string(),\n\t\twebsocket: v.looseObject({\n\t\t\theartbeat_interval: v.string(),\n\t\t\tclient_timeout: v.string(),\n\t\t\ttoast_ttl: v.string(),\n\t\t}),\n\t}),\n\tstorage: v.looseObject({\n\t\tsqlite_path: v.string(),\n\t\tprocess_workspaces_dir: v.string(),\n\t\ttree_files_dir: v.string(),\n\t}),\n\tcomponents: v.record(\n\t\tv.string(),\n\t\tv.looseObject({\n\t\t\trepo: v.string(),\n\t\t\tdefault_branch: v.string(),\n\t\t\tworker_runtime_profile: v.optional(v.string()),\n\t\t}),\n\t),\n\tdevelopment_tools: v.looseObject({\n\t\tinstall_timeout: v.string(),\n\t\tlocal: v.looseObject({ mise_command: v.string() }),\n\t}),\n\tworkers: v.looseObject({\n\t\trunner: v.optional(v.picklist([\"docker\", \"kubernetes\", \"local\"])),\n\t\tdefault_runtime_profile: v.optional(v.string()),\n\t\tmax_parallel_processes: v.number(),\n\t\tstartup_timeout: v.string(),\n\t\tshutdown_grace_period: v.string(),\n\t\theartbeat_interval: v.string(),\n\t\tturn_max_duration: v.string(),\n\t\tturn_inactivity_timeout: v.string(),\n\t\tturn_abort_grace_period: v.string(),\n\t\tstale_heartbeat_timeout: v.string(),\n\t\tresume_on_boot: v.boolean(),\n\t\tidle_worker_ttl: v.string(),\n\t\tsession_snapshot_max_size_bytes: v.optional(v.number()),\n\t\tlog_worker_events_to_stdout: v.boolean(),\n\t\tcleanup: v.looseObject({\n\t\t\ttransient_ttl: v.string(),\n\t\t\tcompleted_process_retention: v.string(),\n\t\t\terror_process_retention: v.string(),\n\t\t}),\n\t}),\n\tlocal_worker: v.optional(\n\t\tv.looseObject({\n\t\t\tcommand: v.string(),\n\t\t\targs: stringArraySchema,\n\t\t\tallow_host_docker: v.optional(v.boolean()),\n\t\t}),\n\t),\n\tpi: v.looseObject({\n\t\tagent_dir: v.string(),\n\t\tdefault_model_profile: v.pipe(\n\t\t\tv.string(),\n\t\t\tv.check((value) => value.trim() !== \"\", \"Must be a non-empty model profile ID\"),\n\t\t),\n\t\tmodel_profiles: v.array(\n\t\t\tv.looseObject({\n\t\t\t\tid: v.string(),\n\t\t\t\tprovider: v.string(),\n\t\t\t\tmodel_id: v.string(),\n\t\t\t\tthinking_level: v.optional(v.string()),\n\t\t\t\tlabels: v.optional(modelPolicyIdentifiersSchema),\n\t\t\t\tdefault: v.optional(v.boolean()),\n\t\t\t\tprovider_options: v.optional(v.record(v.string(), v.string())),\n\t\t\t}),\n\t\t),\n\t\tsystem_prompt_template: v.optional(v.string()),\n\t\tprocess_title_generation: v.looseObject({\n\t\t\tmodel_profile: v.nullable(v.string()),\n\t\t\tretry: v.looseObject({\n\t\t\t\tmax_attempts: v.pipe(v.number(), v.integer(), v.minValue(1)),\n\t\t\t\tbase_delay: v.string(),\n\t\t\t\tmax_delay: v.string(),\n\t\t\t}),\n\t\t}),\n\t\tretry: v.looseObject({\n\t\t\tenabled: v.boolean(),\n\t\t\tmax_retries: v.number(),\n\t\t\tbase_delay: v.string(),\n\t\t\tprovider: v.looseObject({\n\t\t\t\ttimeout: v.nullable(v.string()),\n\t\t\t\tmax_retries: v.nullable(v.number()),\n\t\t\t\tmax_retry_delay: v.string(),\n\t\t\t}),\n\t\t}),\n\t}),\n\tprocess_configs: v.optional(\n\t\tv.record(\n\t\t\tv.string(),\n\t\t\tv.looseObject({\n\t\t\t\tdefault_skills: v.optional(skillIdsSchema),\n\t\t\t\tdefault_model_profile: v.optional(v.string()),\n\t\t\t\tmodel_requirements: v.optional(modelRequirementsSchema),\n\t\t\t\tallowed_model_profiles: v.optional(v.pipe(stringArraySchema, v.nonEmpty())),\n\t\t\t\tworker_runtime_profile: v.optional(v.string()),\n\t\t\t\tstorage_size: v.optional(storageSizeSchema),\n\t\t\t\tpi: v.optional(\n\t\t\t\t\tv.looseObject({\n\t\t\t\t\t\tsystem_prompt_template: v.optional(v.string()),\n\t\t\t\t\t\tappend_system_prompt_template: v.optional(v.string()),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tturn_configs: v.optional(v.record(v.string(), modelTurnConfigSchema)),\n\t\t\t\twatchers: v.optional(v.record(v.string(), v.unknown())),\n\t\t\t}),\n\t\t),\n\t),\n\tnotifications: v.looseObject({\n\t\tall: v.looseObject({ enabled: v.boolean(), type: v.string(), url: v.string() }),\n\t\tdebug: v.looseObject({ enabled: v.boolean(), type: v.string(), url: v.string() }),\n\t\tsquad: v.looseObject({\n\t\t\tenabled: v.boolean(),\n\t\t\ttype: v.string(),\n\t\t\trouting_field: v.string(),\n\t\t\troutes: v.record(v.string(), v.looseObject({ url: v.string() })),\n\t\t}),\n\t}),\n\tsandbox: v.looseObject({ enabled: v.boolean(), profile: v.string() }),\n\textension_loading: v.looseObject({\n\t\tsources: stringArraySchema,\n\t}),\n\tauth: v.optional(authConfigSchema),\n\tdefault_skills: v.optional(skillIdsSchema),\n\tdocker_registries: v.optional(\n\t\tv.strictObject({\n\t\t\tprofiles: v.record(v.string(), v.strictObject(dockerRegistryCredentialSchema.entries)),\n\t\t\tprocess_bindings: v.record(v.string(), v.array(v.pipe(v.string(), v.nonEmpty()))),\n\t\t}),\n\t),\n\tdocker: v.optional(\n\t\tv.looseObject({\n\t\t\tsocket: v.string(),\n\t\t\tnetwork: v.string(),\n\t\t\tserver_url: v.string(),\n\t\t\tserver_ca_file: v.optional(v.string()),\n\t\t\tprocess_volume: v.looseObject({\n\t\t\t\tmode: v.picklist([\"bind\", \"named_volume\"]),\n\t\t\t\thost_root: v.string(),\n\t\t\t\tmount_path: v.string(),\n\t\t\t}),\n\t\t\tprivate_daemon: v.optional(\n\t\t\t\tv.strictObject({ isolation: v.picklist([\"privileged\", \"sysbox-runc\"]) }),\n\t\t\t),\n\t\t}),\n\t),\n\tkubernetes: v.optional(\n\t\tv.looseObject({\n\t\t\tserver_namespace: v.string(),\n\t\t\tprocess_namespace_prefix: v.string(),\n\t\t\tserver_url: v.string(),\n\t\t\tserver_ca_file: v.optional(v.string()),\n\t\t\tapi_server_url: v.optional(v.string()),\n\t\t\tdefault_worker_runtime_profile: v.optional(v.string()),\n\t\t\tworker_service_account: v.optional(v.string()),\n\t\t\timage_preload: v.optional(v.strictObject({ enabled: v.boolean() })),\n\t\t\tprocess_volume: v.looseObject({\n\t\t\t\treclaim_on_close: v.optional(v.boolean()),\n\t\t\t\tstorage_class_name: v.optional(v.string()),\n\t\t\t\tpre_provision: v.optional(\n\t\t\t\t\tv.strictObject({ count: v.pipe(v.number(), v.integer(), v.minValue(0)) }),\n\t\t\t\t),\n\t\t\t\tsize: storageSizeSchema,\n\t\t\t\taccess_modes: stringArraySchema,\n\t\t\t\tmount_path: v.string(),\n\t\t\t}),\n\t\t\tdocker: v.optional(\n\t\t\t\tv.strictObject({\n\t\t\t\t\tworker_runtime_profile: v.optional(v.pipe(v.string(), v.trim(), v.nonEmpty())),\n\t\t\t\t\tnode_selector: v.optional(v.record(v.string(), v.string())),\n\t\t\t\t\truntime_class_name: v.optional(v.string()),\n\t\t\t\t\thost_users: v.optional(v.boolean()),\n\t\t\t\t\tisolation: v.optional(v.picklist([\"gvisor\", \"virtual-machine\"])),\n\t\t\t\t\tgvisor: v.optional(v.boolean()),\n\t\t\t\t\tprocess_storage_class_name: v.optional(v.string()),\n\t\t\t\t\tnetwork: v.optional(dockerNetworkSchema),\n\t\t\t\t}),\n\t\t\t),\n\t\t\tpod: v.optional(\n\t\t\t\tv.looseObject({\n\t\t\t\t\tnode_selector: v.optional(v.record(v.string(), v.string())),\n\t\t\t\t\ttolerations: v.optional(v.array(v.unknown())),\n\t\t\t\t\tannotations: v.optional(v.record(v.string(), v.string())),\n\t\t\t\t\thost_aliases: v.optional(\n\t\t\t\t\t\tv.array(\n\t\t\t\t\t\t\tv.strictObject({\n\t\t\t\t\t\t\t\tip: kubernetesHostAliasIpSchema,\n\t\t\t\t\t\t\t\thostnames: v.pipe(v.array(kubernetesHostnameSchema), v.nonEmpty()),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t\t),\n\t\t\timage_pull_secrets: v.optional(stringArraySchema),\n\t\t\timage_pull_secret_copies: v.optional(\n\t\t\t\tv.array(\n\t\t\t\t\tv.strictObject({\n\t\t\t\t\t\tsource_name: v.pipe(v.string(), v.nonEmpty()),\n\t\t\t\t\t\ttarget_name: v.pipe(v.string(), v.nonEmpty()),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t\t}),\n\t),\n\tworker_runtime_profiles: v.optional(\n\t\tv.record(\n\t\t\tv.string(),\n\t\t\tv.looseObject({\n\t\t\t\timage: v.string(),\n\t\t\t\timage_pull_policy: v.optional(v.string()),\n\t\t\t\tresources: v.optional(\n\t\t\t\t\tv.looseObject({\n\t\t\t\t\t\t...cpuMemoryEntries,\n\t\t\t\t\t\trequests: v.optional(v.strictObject(cpuMemoryEntries)),\n\t\t\t\t\t\tlimits: v.optional(v.looseObject(cpuMemoryEntries)),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t}),\n\t\t),\n\t),\n\tinternal_tls: v.optional(\n\t\tv.looseObject({\n\t\t\tenabled: v.boolean(),\n\t\t\tcert_file: v.optional(v.string()),\n\t\t\tkey_file: v.optional(v.string()),\n\t\t\tclient_ca_file: v.optional(v.string()),\n\t\t}),\n\t),\n\textensions: unknownRecordSchema,\n});\n\nfunction formatValibotPath(issue: v.BaseIssue<unknown>): string {\n\tif (!issue.path || issue.path.length === 0) {\n\t\treturn \"<root>\";\n\t}\n\tlet formatted = \"\";\n\tfor (const item of issue.path) {\n\t\tconst key = item.key;\n\t\tif (typeof key === \"number\") {\n\t\t\tformatted += `[${key}]`;\n\t\t\tcontinue;\n\t\t}\n\t\tif (formatted.length > 0) {\n\t\t\tformatted += \".\";\n\t\t}\n\t\tformatted += String(key);\n\t}\n\treturn formatted;\n}\n\nfunction formatConfigSchemaIssue(issue: v.BaseIssue<unknown>): ConfigIssue {\n\tconst path = formatValibotPath(issue);\n\tif (issue.type === \"non_empty\") {\n\t\treturn { path, message: `${path} must not be empty when specified` };\n\t}\n\treturn { path, message: `${path}: ${issue.message}` };\n}\n\nfunction collectConfigSchemaErrors(config: unknown): string[] {\n\tconst parsed = v.safeParse(configSchema, config, { abortEarly: false });\n\tif (parsed.success) {\n\t\treturn [];\n\t}\n\treturn parsed.issues.map((issue) => formatConfigSchemaIssue(issue).message);\n}\n\nfunction collectModelProfileReferenceErrors(config: LeitwerkConfig): string[] {\n\tconst errors: string[] = [];\n\tconst configuredModelProfileIds = new Set(\n\t\tconfig.pi.model_profiles\n\t\t\t.map((profile) => profile.id)\n\t\t\t.filter((profileId) => typeof profileId === \"string\" && profileId.trim() !== \"\"),\n\t);\n\tconst titleModelProfile = config.pi.process_title_generation.model_profile;\n\tif (!configuredModelProfileIds.has(config.pi.default_model_profile)) {\n\t\terrors.push(\n\t\t\t`Unknown model profile '${config.pi.default_model_profile}' at pi.default_model_profile`,\n\t\t);\n\t}\n\tif (typeof titleModelProfile === \"string\") {\n\t\tif (titleModelProfile.trim() === \"\") {\n\t\t\terrors.push(\n\t\t\t\t\"pi.process_title_generation.model_profile must be a non-empty string when specified\",\n\t\t\t);\n\t\t} else if (!configuredModelProfileIds.has(titleModelProfile)) {\n\t\t\terrors.push(\n\t\t\t\t`Unknown model profile '${titleModelProfile}' at pi.process_title_generation.model_profile`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const [processId, processConfig] of Object.entries(config.process_configs ?? {})) {\n\t\tconst processConfigPath = `process_configs.${processId}`;\n\t\tif (processConfig.allowed_model_profiles !== undefined) {\n\t\t\tfor (const [index, profileId] of processConfig.allowed_model_profiles.entries()) {\n\t\t\t\tconst allowedProfilePath = `${processConfigPath}.allowed_model_profiles[${index}]`;\n\t\t\t\tif (typeof profileId !== \"string\" || profileId.trim() === \"\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!configuredModelProfileIds.has(profileId)) {\n\t\t\t\t\terrors.push(`Unknown model profile '${profileId}' at ${allowedProfilePath}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\nfunction isValidPositiveDuration(value: string): boolean {\n\treturn parseDurationMs(value, -1, { allowHours: true }) > 0;\n}\n\nfunction collectServerBaseUrlErrors(config: LeitwerkConfig): string[] {\n\treturn isValidHttpUrl(config.server.base_url)\n\t\t? []\n\t\t: [\"server.base_url must be an absolute http(s) URL\"];\n}\n\nfunction collectWorkerRuntimeProfileErrors(config: LeitwerkConfig): string[] {\n\tconst errors: string[] = [];\n\tconst profileIds = new Set(Object.keys(config.worker_runtime_profiles ?? {}));\n\tconst checkReference = (value: string | undefined, path: string) => {\n\t\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\treturn;\n\t\t}\n\t\tif (!profileIds.has(value)) {\n\t\t\terrors.push(`Unknown worker runtime profile '${value}' at ${path}`);\n\t\t}\n\t};\n\tfor (const [id, profile] of Object.entries(config.worker_runtime_profiles ?? {})) {\n\t\tif (typeof profile.image !== \"string\" || profile.image.trim() === \"\") {\n\t\t\terrors.push(`worker_runtime_profiles.${id}.image must be a non-empty string`);\n\t\t}\n\t}\n\t// Local is intentionally best-effort and does not consume image/profile\n\t// selection. Keep Docker/Kubernetes as the contract-defining profile users.\n\tif (config.workers.runner === \"local\") {\n\t\treturn errors;\n\t}\n\tcheckReference(config.workers.default_runtime_profile, \"workers.default_runtime_profile\");\n\tif (config.workers.runner === \"kubernetes\") {\n\t\tcheckReference(\n\t\t\tconfig.kubernetes?.default_worker_runtime_profile,\n\t\t\t\"kubernetes.default_worker_runtime_profile\",\n\t\t);\n\t\tcheckReference(\n\t\t\tconfig.kubernetes?.docker?.worker_runtime_profile,\n\t\t\t\"kubernetes.docker.worker_runtime_profile\",\n\t\t);\n\t}\n\tfor (const [key, component] of Object.entries(config.components)) {\n\t\tcheckReference(component.worker_runtime_profile, `components.${key}.worker_runtime_profile`);\n\t}\n\tfor (const [processId, processConfig] of Object.entries(config.process_configs ?? {})) {\n\t\tcheckReference(\n\t\t\tprocessConfig.worker_runtime_profile,\n\t\t\t`process_configs.${processId}.worker_runtime_profile`,\n\t\t);\n\t}\n\treturn errors;\n}\n\nfunction collectWorkersConfigErrors(config: LeitwerkConfig): string[] {\n\tconst errors: string[] = [];\n\tif (!isValidPositiveDuration(config.development_tools.install_timeout)) {\n\t\terrors.push(\"development_tools.install_timeout must be a positive duration\");\n\t}\n\tif (config.development_tools.local.mise_command.trim() === \"\") {\n\t\terrors.push(\"development_tools.local.mise_command must be a non-empty string\");\n\t}\n\tconst maxSnapshotBytes = config.workers.session_snapshot_max_size_bytes;\n\tif (\n\t\tmaxSnapshotBytes !== undefined &&\n\t\t(!Number.isSafeInteger(maxSnapshotBytes) || maxSnapshotBytes <= 0)\n\t) {\n\t\terrors.push(\"workers.session_snapshot_max_size_bytes must be a positive safe integer\");\n\t}\n\treturn errors;\n}\n\nfunction collectLocalRunnerConfigErrors(config: LeitwerkConfig): string[] {\n\tif (config.workers.runner !== \"local\") return [];\n\tconst errors: string[] = [];\n\tconst local = config.local_worker;\n\tif (!local) return [\"local_worker config block is required when workers.runner is 'local'\"];\n\trequireNonEmpty(\"local_worker\", { command: local.command }, errors);\n\tif (!Array.isArray(local.args)) errors.push(\"local_worker.args must be an array\");\n\treturn errors;\n}\n\nfunction collectDockerRunnerConfigErrors(config: LeitwerkConfig): string[] {\n\tif (config.workers.runner !== \"docker\") {\n\t\treturn [];\n\t}\n\tconst errors: string[] = [];\n\tconst docker = config.docker;\n\tif (!docker) {\n\t\treturn [\"docker config block is required when workers.runner is 'docker'\"];\n\t}\n\tif (Object.keys(config.worker_runtime_profiles ?? {}).length === 0) {\n\t\terrors.push(\n\t\t\t\"worker_runtime_profiles must include at least one profile when workers.runner is 'docker'\",\n\t\t);\n\t}\n\tif (!config.workers.default_runtime_profile?.trim()) {\n\t\terrors.push(\"workers.default_runtime_profile is required when workers.runner is 'docker'\");\n\t}\n\tif (!isValidHttpUrl(docker.server_url)) {\n\t\terrors.push(\"docker.server_url must be an absolute http(s) URL\");\n\t}\n\terrors.push(\n\t\t...collectProductionWorkerTransportSecurityErrors({\n\t\t\trunner: \"docker\",\n\t\t\tserverUrl: docker.server_url,\n\t\t\tserverCaFile: docker.server_ca_file,\n\t\t\tinternalTlsEnabled: config.internal_tls?.enabled === true,\n\t\t}),\n\t);\n\treturn errors;\n}\n\nfunction collectProductionWorkerTransportSecurityErrors(input: {\n\trunner: \"docker\" | \"kubernetes\";\n\tserverUrl: string;\n\tserverCaFile?: string;\n\tinternalTlsEnabled: boolean;\n}): string[] {\n\tconst errors: string[] = [];\n\tconst parsed = parseHttpUrl(input.serverUrl);\n\tif (!parsed) {\n\t\treturn errors;\n\t}\n\tconst prefix = input.runner;\n\tif (input.internalTlsEnabled) {\n\t\tif (parsed.protocol !== \"https:\") {\n\t\t\terrors.push(`${prefix}.server_url must use https when internal_tls.enabled is true`);\n\t\t}\n\t\tif (!input.serverCaFile?.trim()) {\n\t\t\terrors.push(\n\t\t\t\t`${prefix}.server_ca_file is required when internal_tls.enabled is true and workers.runner is '${input.runner}'`,\n\t\t\t);\n\t\t}\n\t\treturn errors;\n\t}\n\tif (parsed.protocol !== \"http:\") {\n\t\terrors.push(`${prefix}.server_url must use http when internal_tls.enabled is false`);\n\t}\n\treturn errors;\n}\n\nfunction isSafeKubernetesNamespacePrefix(value: string): boolean {\n\treturn /^(?!-)[a-z0-9-]+-$/.test(value) && value.length <= 40;\n}\n\nfunction isSafeKubernetesDnsLabel(value: string): boolean {\n\treturn /^(?!-)[a-z0-9-]{1,63}(?<!-)$/.test(value);\n}\n\nfunction isSafeKubernetesDnsSubdomain(value: string): boolean {\n\treturn (\n\t\tvalue.length <= 253 &&\n\t\t/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/.test(value)\n\t);\n}\n\nfunction requireNonEmpty(\n\tprefix: string,\n\tfields: Record<string, string | undefined>,\n\terrors: string[],\n): void {\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (typeof value !== \"string\" || value.trim() === \"\")\n\t\t\terrors.push(`${prefix}.${key} must be a non-empty string`);\n\t}\n}\n\nfunction collectKubernetesRunnerConfigErrors(config: LeitwerkConfig): string[] {\n\tif (config.workers.runner !== \"kubernetes\") return [];\n\tconst errors: string[] = [];\n\tconst k = config.kubernetes;\n\tif (!k) return [\"kubernetes config block is required when workers.runner is 'kubernetes'\"];\n\n\trequireNonEmpty(\n\t\t\"kubernetes\",\n\t\t{ server_namespace: k.server_namespace, server_url: k.server_url },\n\t\terrors,\n\t);\n\trequireNonEmpty(\n\t\t\"kubernetes.process_volume\",\n\t\t{ size: k.process_volume.size, mount_path: k.process_volume.mount_path },\n\t\terrors,\n\t);\n\n\tif (k.server_namespace.trim() && !isSafeKubernetesDnsLabel(k.server_namespace))\n\t\terrors.push(\"kubernetes.server_namespace must be a safe DNS label\");\n\tif (!k.process_namespace_prefix.trim())\n\t\terrors.push(\"kubernetes.process_namespace_prefix must be a non-empty string\");\n\telse if (!isSafeKubernetesNamespacePrefix(k.process_namespace_prefix))\n\t\terrors.push(\n\t\t\t\"kubernetes.process_namespace_prefix must contain only lowercase DNS-label characters and end with '-'\",\n\t\t);\n\tif (\n\t\tk.server_namespace.trim() &&\n\t\tk.process_namespace_prefix.trim() &&\n\t\tk.server_namespace.startsWith(k.process_namespace_prefix)\n\t)\n\t\terrors.push(\n\t\t\t\"kubernetes.server_namespace must be dedicated and must not match the process namespace prefix\",\n\t\t);\n\tif (!isValidHttpUrl(k.server_url))\n\t\terrors.push(\"kubernetes.server_url must be an absolute http(s) URL\");\n\terrors.push(\n\t\t...collectProductionWorkerTransportSecurityErrors({\n\t\t\trunner: \"kubernetes\",\n\t\t\tserverUrl: k.server_url,\n\t\t\tserverCaFile: k.server_ca_file,\n\t\t\tinternalTlsEnabled: config.internal_tls?.enabled === true,\n\t\t}),\n\t);\n\tif (k.api_server_url !== undefined && !isValidHttpUrl(k.api_server_url))\n\t\terrors.push(\"kubernetes.api_server_url must be an absolute http(s) URL\");\n\n\tif (Object.keys(config.worker_runtime_profiles ?? {}).length === 0)\n\t\terrors.push(\n\t\t\t\"worker_runtime_profiles must include at least one profile when workers.runner is 'kubernetes'\",\n\t\t);\n\tif (k.image_preload?.enabled) {\n\t\tfor (const [id, profile] of Object.entries(config.worker_runtime_profiles ?? {})) {\n\t\t\tif (!/^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[0-9a-f]{64}$/.test(profile.image))\n\t\t\t\terrors.push(\n\t\t\t\t\t`worker_runtime_profiles.${id}.image must be digest-qualified when kubernetes.image_preload.enabled is true`,\n\t\t\t\t);\n\t\t}\n\t}\n\tconst defaultProfile = k.default_worker_runtime_profile ?? config.workers.default_runtime_profile;\n\tif (!defaultProfile?.trim())\n\t\terrors.push(\n\t\t\t\"kubernetes.default_worker_runtime_profile or workers.default_runtime_profile is required when workers.runner is 'kubernetes'\",\n\t\t);\n\tif (\n\t\tk.process_volume.pre_provision &&\n\t\t!isSafeKubernetesDnsSubdomain(k.process_volume.storage_class_name ?? \"\")\n\t)\n\t\terrors.push(\"kubernetes.process_volume.pre_provision requires an explicit storage_class_name\");\n\tif (k.process_volume.access_modes.length === 0)\n\t\terrors.push(\"kubernetes.process_volume.access_modes must not be empty\");\n\n\tconst dockerNames = {\n\t\truntime_class_name: k.docker?.runtime_class_name,\n\t\tprocess_storage_class_name: k.docker?.process_storage_class_name,\n\t};\n\tfor (const [field, value] of Object.entries(dockerNames)) {\n\t\tif (value !== undefined && !isSafeKubernetesDnsSubdomain(value)) {\n\t\t\terrors.push(`kubernetes.docker.${field} must be a valid Kubernetes DNS subdomain name`);\n\t\t}\n\t}\n\n\treturn errors;\n}\n\nfunction collectInternalTlsConfigErrors(config: LeitwerkConfig): string[] {\n\tconst tls = config.internal_tls;\n\tif (!tls?.enabled) return [];\n\tconst errors: string[] = [];\n\trequireNonEmpty(\"internal_tls\", { cert_file: tls.cert_file, key_file: tls.key_file }, errors);\n\tif (tls.client_ca_file?.trim()) {\n\t\terrors.push(\n\t\t\t\"internal_tls.client_ca_file is not supported for worker IPC yet; workers do not receive client certificate/key material\",\n\t\t);\n\t}\n\treturn errors.map((e) =>\n\t\te.replace(\"must be a non-empty string\", \"is required when internal_tls.enabled is true\"),\n\t);\n}\n\nfunction collectAuthConfigErrors(config: LeitwerkConfig): string[] {\n\tconst errors: string[] = [];\n\tconst auth = config.auth;\n\ttry {\n\t\tresolveApiTokenPolicy(auth?.api_tokens);\n\t} catch (error) {\n\t\terrors.push(error instanceof Error ? error.message : \"Invalid auth.api_tokens configuration\");\n\t}\n\tfor (const [index, provider] of (auth?.providers ?? []).entries()) {\n\t\tif (provider.kind === \"oidc\" && provider.access) {\n\t\t\terrors.push(\n\t\t\t\t...policyErrors(provider.access, auth?.allowlist !== undefined).map(\n\t\t\t\t\t(message) => `auth.providers[${index}].access: ${message}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\tif (!auth || auth.enabled !== true) {\n\t\treturn errors;\n\t}\n\tconst providers = auth.providers ?? [];\n\tif (providers.length === 0) {\n\t\terrors.push(\n\t\t\t\"auth.providers must include one authentication provider when auth.enabled is true\",\n\t\t);\n\t}\n\tif (providers.length > 1) {\n\t\terrors.push(\"auth.providers currently supports exactly one provider\");\n\t}\n\tif (providers.length > 0 && !isHttpsOrLoopbackHttpUrl(config.server.base_url)) {\n\t\terrors.push(\"server.base_url must use https when auth is enabled, except for localhost\");\n\t}\n\tfor (const [index, provider] of providers.entries()) {\n\t\tif (provider.kind === \"oidc\" && !isHttpsOrLoopbackHttpUrl(provider.issuer)) {\n\t\t\terrors.push(\n\t\t\t\t`auth.providers[${index}].issuer must be an absolute https URL, except for localhost`,\n\t\t\t);\n\t\t}\n\t\tif (provider.redirect_uri !== undefined && !isHttpsOrLoopbackHttpUrl(provider.redirect_uri)) {\n\t\t\terrors.push(\n\t\t\t\t`auth.providers[${index}].redirect_uri must be an absolute https URL, except for localhost`,\n\t\t\t);\n\t\t}\n\t}\n\tif (auth.session?.ttl !== undefined && !isValidPositiveDuration(auth.session.ttl)) {\n\t\terrors.push(\"auth.session.ttl must be a positive duration\");\n\t}\n\treturn errors;\n}\n\nfunction hasOwnKey(value: unknown, key: string): boolean {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.hasOwn(value, key)\n\t);\n}\n\nfunction collectLegacyConfigKeyErrors(config: Record<string, unknown>): string[] {\n\tconst errors = Object.hasOwn(config, \"skills\")\n\t\t? [\"skills was removed; configure Git sources through skill_repositories\"]\n\t\t: [];\n\tconst legacyKeys = [\n\t\t{\n\t\t\tsection: \"pi\",\n\t\t\tkey: \"process_dir\",\n\t\t\tmessage: \"pi.process_dir was renamed to pi.agent_dir; move the configured value\",\n\t\t},\n\t\t{\n\t\t\tsection: \"local_worker\",\n\t\t\tkey: \"process_volume_root\",\n\t\t\tmessage:\n\t\t\t\t\"local_worker.process_volume_root was removed; remove the key because local workers use storage.process_workspaces_dir and storage.tree_files_dir directly\",\n\t\t},\n\t] as const;\n\terrors.push(\n\t\t...legacyKeys\n\t\t\t.filter(({ section, key }) => hasOwnKey(config[section], key))\n\t\t\t.map(({ message }) => message),\n\t);\n\tif (hasOwnKey(config.docker, \"dind\")) {\n\t\terrors.push(\"docker.dind was removed; configure docker.private_daemon.isolation\");\n\t}\n\tconst profiles = config.worker_runtime_profiles;\n\tif (profiles && typeof profiles === \"object\" && !Array.isArray(profiles)) {\n\t\tfor (const [id, profile] of Object.entries(profiles)) {\n\t\t\tif (hasOwnKey(profile, \"dind\")) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`worker_runtime_profiles.${id}.dind was removed; declare runtime.docker in process code`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn errors;\n}\n\nfunction collectCommitMessageConfigErrors(config: LeitwerkConfig): string[] {\n\tconst section = config.commit_messages;\n\tif (!section) return [];\n\tconst errors: string[] = [];\n\tconst templateIds = new Set(Object.keys(section.templates));\n\tif (section.default_template && !templateIds.has(section.default_template)) {\n\t\terrors.push(\n\t\t\t`Unknown commit-message template '${section.default_template}' at commit_messages.default_template`,\n\t\t);\n\t}\n\tconst normalized = new Map<string, string>();\n\tfor (const [locator, templateId] of Object.entries(section.repositories)) {\n\t\tif (!templateIds.has(templateId)) {\n\t\t\terrors.push(\n\t\t\t\t`Unknown commit-message template '${templateId}' at commit_messages.repositories.${locator}`,\n\t\t\t);\n\t\t}\n\t\tconst key = normalizeRepositoryLocator(locator);\n\t\tif (!key) {\n\t\t\terrors.push(\"commit_messages repository locators must be non-empty\");\n\t\t\tcontinue;\n\t\t}\n\t\tconst prior = normalized.get(key);\n\t\tif (prior && prior !== templateId) {\n\t\t\terrors.push(`Conflicting commit-message mappings normalize to repository locator '${key}'`);\n\t\t} else {\n\t\t\tnormalized.set(key, templateId);\n\t\t}\n\t}\n\treturn errors;\n}\n\nfunction validateResolvedConfig(config: Record<string, unknown>): string[] {\n\tconst legacyKeyErrors = collectLegacyConfigKeyErrors(config);\n\tif (legacyKeyErrors.length > 0) {\n\t\treturn legacyKeyErrors;\n\t}\n\tconst shapeErrors = collectConfigSchemaErrors(config);\n\tif (shapeErrors.length > 0) {\n\t\treturn shapeErrors;\n\t}\n\tconst resolvedConfig = config as unknown as LeitwerkConfig;\n\tconst skillErrors: string[] = [];\n\tfor (const processId of Object.keys(resolvedConfig.docker_registries?.process_bindings ?? {})) {\n\t\ttry {\n\t\t\tresolveDockerRegistryCredentials(resolvedConfig, processId, true);\n\t\t} catch {\n\t\t\tskillErrors.push(\n\t\t\t\t\"docker_registries.process_bindings contains an unknown profile or duplicate registry\",\n\t\t\t);\n\t\t}\n\t}\n\tconst repositoryIds = new Set<string>();\n\tfor (const repository of resolvedConfig.skill_repositories ?? []) {\n\t\tif (repositoryIds.has(repository.id)) {\n\t\t\tskillErrors.push(`Duplicate skill repository id '${repository.id}' at skill_repositories`);\n\t\t}\n\t\trepositoryIds.add(repository.id);\n\t}\n\treturn [\n\t\t...skillErrors,\n\t\t...collectServerBaseUrlErrors(resolvedConfig),\n\t\t...collectCommitMessageConfigErrors(resolvedConfig),\n\t\t...collectModelProfileReferenceErrors(resolvedConfig),\n\t\t...collectWorkerRuntimeProfileErrors(resolvedConfig),\n\t\t...collectWorkersConfigErrors(resolvedConfig),\n\t\t...collectLocalRunnerConfigErrors(resolvedConfig),\n\t\t...collectDockerRunnerConfigErrors(resolvedConfig),\n\t\t...collectKubernetesRunnerConfigErrors(resolvedConfig),\n\t\t...resolveKubernetesDockerIsolation(resolvedConfig.kubernetes?.docker).errors,\n\t\t...collectInternalTlsConfigErrors(resolvedConfig),\n\t\t...collectAuthConfigErrors(resolvedConfig),\n\t];\n}\n\nexport function validateConfig(raw: Record<string, unknown>): string[] {\n\tconst config = applyConfigDefaults(raw);\n\treturn validateResolvedConfig(config as unknown as Record<string, unknown>);\n}\n\nfunction shouldRedactForLogging(path: readonly string[], key: string): boolean {\n\treturn (\n\t\tSENSITIVE_CONFIG_KEY_PATTERN.test(key) ||\n\t\t(key === \"url\" &&\n\t\t\t(path[0] === \"notifications\" || path.some((segment) => /webhook/i.test(segment))))\n\t);\n}\n\n/** @internal */\nexport function sanitizeConfigForLogging(value: unknown, path: readonly string[] = []): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry, index) => sanitizeConfigForLogging(entry, [...path, String(index)]));\n\t}\n\tconst parsedRecord = v.safeParse(unknownRecordSchema, value);\n\tif (!parsedRecord.success) {\n\t\treturn value;\n\t}\n\n\tconst sanitized: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(parsedRecord.output)) {\n\t\tif (shouldRedactForLogging(path, key)) {\n\t\t\tsanitized[key] = entry === \"\" ? \"\" : REDACTED_LOG_VALUE;\n\t\t\tcontinue;\n\t\t}\n\t\tsanitized[key] = sanitizeConfigForLogging(entry, [...path, key]);\n\t}\n\treturn sanitized;\n}\n\n/** Configuration template; set model_profiles and default_model_profile before startup. @public */\nexport function getDefaultConfig(): LeitwerkConfig {\n\treturn {\n\t\tskill_repositories: [],\n\t\tcommit_messages: {\n\t\t\ttemplates: {},\n\t\t\tdefault_template: null,\n\t\t\trepositories: {},\n\t\t},\n\t\tsession_transfer: {\n\t\t\tmax_entries: DEFAULT_SESSION_TRANSFER_LIMITS.maxEntries,\n\t\t\tmax_logical_bytes: DEFAULT_SESSION_TRANSFER_LIMITS.maxLogicalBytes,\n\t\t\tmax_compressed_bytes: DEFAULT_SESSION_TRANSFER_LIMITS.maxCompressedBytes,\n\t\t},\n\t\tserver: {\n\t\t\thost: \"127.0.0.1\",\n\t\t\tport: 8080,\n\t\t\tbase_url: \"http://127.0.0.1:8080\",\n\t\t\twebsocket: { heartbeat_interval: \"10s\", client_timeout: \"30s\", toast_ttl: \"6s\" },\n\t\t},\n\t\tstorage: {\n\t\t\tsqlite_path: \":memory:\",\n\t\t\tprocess_workspaces_dir: \"/tmp/leitwerk/workspaces\",\n\t\t\ttree_files_dir: \"/tmp/leitwerk/trees\",\n\t\t},\n\t\tcomponents: {},\n\t\tdevelopment_tools: {\n\t\t\tinstall_timeout: \"30m\",\n\t\t\tlocal: { mise_command: \"mise\" },\n\t\t},\n\t\tworkers: {\n\t\t\trunner: \"docker\",\n\t\t\tdefault_runtime_profile: \"generic\",\n\t\t\tmax_parallel_processes: 8,\n\t\t\tstartup_timeout: \"30s\",\n\t\t\tshutdown_grace_period: \"15s\",\n\t\t\theartbeat_interval: \"5s\",\n\t\t\tturn_max_duration: \"30m\",\n\t\t\tturn_inactivity_timeout: \"5m\",\n\t\t\tturn_abort_grace_period: \"5s\",\n\t\t\tstale_heartbeat_timeout: \"30s\",\n\t\t\tresume_on_boot: true,\n\t\t\tidle_worker_ttl: \"0s\",\n\t\t\tsession_snapshot_max_size_bytes: 128 * 1024 * 1024,\n\t\t\tlog_worker_events_to_stdout: false,\n\t\t\tcleanup: {\n\t\t\t\ttransient_ttl: \"1h\",\n\t\t\t\tcompleted_process_retention: \"168h\",\n\t\t\t\terror_process_retention: \"720h\",\n\t\t\t},\n\t\t},\n\t\tpi: {\n\t\t\tagent_dir: \"~/.pi/leitwerk\",\n\t\t\tmodel_profiles: [],\n\t\t\tdefault_model_profile: \"\",\n\t\t\tprocess_title_generation: {\n\t\t\t\tmodel_profile: null,\n\t\t\t\tretry: {\n\t\t\t\t\tmax_attempts: 6,\n\t\t\t\t\tbase_delay: \"5s\",\n\t\t\t\t\tmax_delay: \"5m\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tretry: {\n\t\t\t\tenabled: true,\n\t\t\t\tmax_retries: 3,\n\t\t\t\tbase_delay: \"2s\",\n\t\t\t\tprovider: {\n\t\t\t\t\ttimeout: null,\n\t\t\t\t\tmax_retries: null,\n\t\t\t\t\tmax_retry_delay: \"60s\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tprocess_configs: {},\n\t\tdefault_skills: [],\n\t\tnotifications: {\n\t\t\tall: { enabled: false, type: \"teams_webhook\", url: \"\" },\n\t\t\tdebug: { enabled: false, type: \"teams_webhook\", url: \"\" },\n\t\t\tsquad: { enabled: false, type: \"teams_webhook\", routing_field: \"\", routes: {} },\n\t\t},\n\t\tsandbox: { enabled: false, profile: \"\" },\n\t\textension_loading: {\n\t\t\tsources: [],\n\t\t},\n\t\tlocal_worker: {\n\t\t\tcommand: \"node\",\n\t\t\targs: [\"@leitwerk-dev/worker/worker-entry\"],\n\t\t},\n\t\tdocker: {\n\t\t\tsocket: \"unix:///var/run/docker.sock\",\n\t\t\tnetwork: \"leitwerk\",\n\t\t\tserver_url: \"http://leitwerk-server:8080\",\n\t\t\tprocess_volume: {\n\t\t\t\tmode: \"bind\",\n\t\t\t\thost_root: \"/var/lib/leitwerk/processes\",\n\t\t\t\tmount_path: \"/state\",\n\t\t\t},\n\t\t},\n\t\tkubernetes: {\n\t\t\tserver_namespace: \"leitwerk-system\",\n\t\t\tprocess_namespace_prefix: \"leitwerk-process-\",\n\t\t\tserver_url: \"http://leitwerk-server.leitwerk-system.svc.cluster.local:8080\",\n\t\t\tdefault_worker_runtime_profile: \"generic\",\n\t\t\tworker_service_account: \"leitwerk-worker\",\n\t\t\tprocess_volume: {\n\t\t\t\treclaim_on_close: false,\n\t\t\t\tsize: \"20Gi\",\n\t\t\t\taccess_modes: [\"ReadWriteOnce\"],\n\t\t\t\tmount_path: \"/state\",\n\t\t\t},\n\t\t\tpod: { node_selector: {}, tolerations: [], annotations: {}, host_aliases: [] },\n\t\t\timage_pull_secrets: [],\n\t\t\timage_pull_secret_copies: [],\n\t\t},\n\t\tworker_runtime_profiles: {\n\t\t\tgeneric: { image: \"ghcr.io/example/leitwerk-worker-generic:0.1.0\" },\n\t\t},\n\t\tinternal_tls: { enabled: false },\n\t\textensions: {},\n\t\tauth: { enabled: false },\n\t} as unknown as LeitwerkConfig;\n}\n","import type { ApiTokenPolicy } from \"@leitwerk-dev/protocol/http-contracts\";\n\nexport type { ApiTokenPolicy } from \"@leitwerk-dev/protocol/http-contracts\";\n\nimport { parseDurationMs } from \"@leitwerk-dev/watcher-utils\";\nimport type { ApiTokensConfig } from \"../config/config-types.js\";\n\nexport function resolveApiTokenPolicy(config?: ApiTokensConfig): ApiTokenPolicy {\n\tconst duration = (value: string, key: string): number => {\n\t\tconst ms = parseDurationMs(value, -1, { allowHours: true });\n\t\tif (!Number.isSafeInteger(ms) || ms <= 0)\n\t\t\tthrow new Error(`auth.api_tokens.${key} must be a positive duration`);\n\t\treturn ms;\n\t};\n\tconst defaultTtlMs = duration(config?.default_ttl ?? \"7d\", \"default_ttl\");\n\tconst maxTtlMs = duration(config?.max_ttl ?? \"90d\", \"max_ttl\");\n\tif (defaultTtlMs > maxTtlMs)\n\t\tthrow new Error(\"auth.api_tokens.default_ttl must not exceed max_ttl\");\n\treturn {\n\t\tenabled: config?.enabled ?? true,\n\t\tdefaultTtlMs,\n\t\tmaxTtlMs,\n\t\tallowNoExpiry: config?.allow_no_expiry ?? true,\n\t};\n}\nexport class ApiTokenValidationError extends Error {}\n\nexport function tokenExpiry(\n\tpolicy: ApiTokenPolicy,\n\texpiresAt: unknown,\n\tnow: number,\n): string | null {\n\tif (expiresAt === null) {\n\t\tif (!policy.allowNoExpiry) throw new ApiTokenValidationError(\"No expiration is not allowed\");\n\t\treturn null;\n\t}\n\tif (expiresAt === undefined) return new Date(now + policy.defaultTtlMs).toISOString();\n\t// Require an absolute ISO date-time. Date.parse alone accepts surprising inputs such as \"1\".\n\tif (\n\t\ttypeof expiresAt !== \"string\" ||\n\t\t!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?(?:Z|[+-]\\d{2}:\\d{2})$/.test(expiresAt)\n\t)\n\t\tthrow new ApiTokenValidationError(\"expiresAt must be an ISO date-time\");\n\tconst datePart = expiresAt.slice(0, 10);\n\tif (\n\t\t!Number.isFinite(Date.parse(`${datePart}T00:00:00Z`)) ||\n\t\tnew Date(`${datePart}T00:00:00Z`).toISOString().slice(0, 10) !== datePart\n\t)\n\t\tthrow new ApiTokenValidationError(\"Invalid expiration date\");\n\tconst ms = Date.parse(expiresAt);\n\tif (!Number.isFinite(ms) || ms <= now || ms > now + policy.maxTtlMs)\n\t\tthrow new ApiTokenValidationError(\n\t\t\t\"Expiration must be in the future and within the maximum TTL\",\n\t\t);\n\treturn new Date(ms).toISOString();\n}\n","import type { Actor } from \"@leitwerk-dev/domain\";\nimport type { UserInformationResponseBody } from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { OidcAccessPolicy } from \"../config/config-types.js\";\nimport type { ResolvedAuthProvider, ResolvedOidcProvider } from \"./auth-config.js\";\nimport type { OidcTokensAndClaims } from \"./oidc-client.js\";\n\n/** Session/token evidence, never attached to an Actor. @internal */\nexport interface OidcEvidence extends UserInformationResponseBody {\n\t/** @internal */\n\tidentityClaim: string;\n}\n\n/** Exclude credential-shaped claims even when returned by a custom provider. */\nfunction safeClaims(claims: Record<string, unknown>): Record<string, unknown> {\n\treturn JSON.parse(\n\t\tJSON.stringify(claims, (key, value) =>\n\t\t\t/^(access_token|refresh_token|id_token|client_secret|authorization)$/i.test(key)\n\t\t\t\t? undefined\n\t\t\t\t: value,\n\t\t),\n\t);\n}\n\n/** @internal */\nexport function actorFromClaims(\n\tprovider: ResolvedAuthProvider,\n\tclaims: Record<string, unknown>,\n): Actor {\n\tconst rawIdentity = claims[provider.identity_claim];\n\tconst identity = typeof rawIdentity === \"string\" ? rawIdentity.trim() : \"\";\n\tif (!identity) {\n\t\tthrow new Error(`Authentication identity claim ${provider.identity_claim} was not present`);\n\t}\n\tconst displayName =\n\t\t[claims.name, claims.preferred_username, claims.email].find(\n\t\t\t(value): value is string => typeof value === \"string\" && value.trim() !== \"\",\n\t\t) ?? identity;\n\treturn {\n\t\tid: `${provider.id}:${identity}`,\n\t\tkind: \"user\",\n\t\tprovider: provider.id,\n\t\tdisplayName,\n\t};\n}\n\n/** @internal */\nexport function interpretOidcLogin(\n\tprovider: ResolvedOidcProvider,\n\texchange: OidcTokensAndClaims,\n): { actor: Actor; oidcEvidence: OidcEvidence } {\n\tconst idTokenClaims = safeClaims(exchange.idTokenClaims);\n\tconst userInfoClaims = exchange.userInfoClaims ? safeClaims(exchange.userInfoClaims) : null;\n\tif (\n\t\ttypeof idTokenClaims.sub !== \"string\" ||\n\t\t!idTokenClaims.sub.trim() ||\n\t\t(userInfoClaims && userInfoClaims.sub !== idTokenClaims.sub)\n\t)\n\t\tthrow new Error(\"Invalid OIDC subject evidence\");\n\tconst claims = { ...idTokenClaims, ...userInfoClaims };\n\tconst actor = actorFromClaims(provider, claims);\n\tconst groups = claims[provider.access?.groups_claim ?? \"groups\"];\n\treturn {\n\t\tactor,\n\t\toidcEvidence: {\n\t\t\tproviderId: provider.id,\n\t\t\tissuer: provider.issuer,\n\t\t\tidentityClaim: provider.identity_claim,\n\t\t\tsubject: idTokenClaims.sub,\n\t\t\tloginAt: new Date().toISOString(),\n\t\t\tidTokenClaims,\n\t\t\tuserInfoClaims,\n\t\t\tfacts: {\n\t\t\t\tidentity: actor.id.slice(provider.id.length + 1),\n\t\t\t\temail: typeof claims.email === \"string\" ? claims.email : null,\n\t\t\t\temailVerified: claims.email_verified === true,\n\t\t\t\tgroups:\n\t\t\t\t\tArray.isArray(groups) && groups.every((group) => typeof group === \"string\") ? groups : [],\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction validDomain(domain: string): boolean {\n\treturn (\n\t\tdomain.length <= 253 &&\n\t\tdomain.split(\".\").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))\n\t);\n}\n\n/** @internal */\nexport function policyErrors(policy: OidcAccessPolicy, legacy: boolean): string[] {\n\tconst errors: string[] = [];\n\tif (legacy) errors.push(\"cannot combine access with deprecated auth.allowlist\");\n\tconst lists = [policy.users, policy.groups, policy.email_domains];\n\tif (\n\t\tpolicy.mode === \"all\" &&\n\t\t(lists.some((list) => list !== undefined) ||\n\t\t\tpolicy.match !== undefined ||\n\t\t\tpolicy.groups_claim !== undefined)\n\t)\n\t\terrors.push(\"access mode all cannot include restrictions, match, or groups_claim\");\n\tif (policy.mode === \"restricted\" && !lists.some((list) => list && list.length > 0))\n\t\terrors.push(\"restricted access requires at least one non-empty criterion\");\n\tif (\n\t\tlists.some(\n\t\t\t(list) => list !== undefined && (list.length === 0 || list.some((item) => !item.trim())),\n\t\t)\n\t)\n\t\terrors.push(\"access criteria must be non-empty lists of non-empty strings\");\n\tif (policy.email_domains?.some((domain) => !validDomain(domain)))\n\t\terrors.push(\"access email_domains must contain exact domain names\");\n\treturn errors;\n}\n\n/** @internal */\nexport function evidenceAllows(\n\tactor: Actor,\n\tprovider: ResolvedOidcProvider,\n\tevidence: OidcEvidence | null | undefined,\n\tallowlist: Set<string>,\n): boolean {\n\tif (\n\t\t!evidence ||\n\t\tevidence.providerId !== provider.id ||\n\t\tevidence.issuer !== provider.issuer ||\n\t\tevidence.identityClaim !== provider.identity_claim ||\n\t\ttypeof evidence.subject !== \"string\" ||\n\t\t!evidence.subject.trim() ||\n\t\tevidence.idTokenClaims.sub !== evidence.subject ||\n\t\t(evidence.userInfoClaims !== null && evidence.userInfoClaims.sub !== evidence.subject)\n\t)\n\t\treturn false;\n\tconst claims = { ...evidence.idTokenClaims, ...evidence.userInfoClaims };\n\tconst identity =\n\t\ttypeof claims[provider.identity_claim] === \"string\"\n\t\t\t? (claims[provider.identity_claim] as string).trim()\n\t\t\t: \"\";\n\tif (!identity || actor.id !== `${provider.id}:${identity}`) return false;\n\tconst policy = provider.access;\n\tif (!policy) return allowlist.has(identity);\n\tif (policy.mode === \"all\") return true;\n\tconst matches: boolean[] = [];\n\tif (policy.users) matches.push(policy.users.includes(identity));\n\tif (policy.groups) {\n\t\tconst groups = claims[policy.groups_claim ?? \"groups\"];\n\t\tmatches.push(\n\t\t\tArray.isArray(groups) &&\n\t\t\t\tgroups.every((group) => typeof group === \"string\") &&\n\t\t\t\tpolicy.groups.some((group) => groups.includes(group)),\n\t\t);\n\t}\n\tif (policy.email_domains) {\n\t\tconst email = claims.email;\n\t\tconst domain =\n\t\t\ttypeof email === \"string\" && /^[^\\s@]+@[^\\s@]+$/.test(email)\n\t\t\t\t? email.split(\"@\")[1]?.toLowerCase()\n\t\t\t\t: undefined;\n\t\tmatches.push(\n\t\t\tclaims.email_verified === true &&\n\t\t\t\tdomain !== undefined &&\n\t\t\t\tvalidDomain(domain) &&\n\t\t\t\tpolicy.email_domains.some((allowed) => allowed.toLowerCase() === domain),\n\t\t);\n\t}\n\treturn (\n\t\tmatches.length > 0 && (policy.match === \"any\" ? matches.some(Boolean) : matches.every(Boolean))\n\t);\n}\n","import {\n\tBUILT_IN_COMMIT_MESSAGE_RULES,\n\ttype CommitMessageProjectMetadata,\n} from \"@leitwerk-dev/process-sdk\";\nimport type { CommitMessageConfig } from \"./config/config-types.js\";\n\nexport function normalizeRepositoryLocator(locator: string): string {\n\treturn locator.trim().replace(/\\/+$/, \"\");\n}\n\nexport function resolveCommitMessageMetadata(\n\trepoLocator: string,\n\tconfig?: CommitMessageConfig,\n): CommitMessageProjectMetadata {\n\tconst normalizedLocator = normalizeRepositoryLocator(repoLocator);\n\tconst override = Object.entries(config?.repositories ?? {}).find(\n\t\t([locator]) => normalizeRepositoryLocator(locator) === normalizedLocator,\n\t)?.[1];\n\tconst templateId = override ?? config?.default_template ?? null;\n\tconst template = templateId ? config?.templates[templateId] : undefined;\n\treturn {\n\t\ttemplateId,\n\t\trules: template?.rules ?? BUILT_IN_COMMIT_MESSAGE_RULES,\n\t\t...(template?.signoff ? { signoff: true } : {}),\n\t};\n}\n","import type { WorkerDockerRegistryCredential } from \"@leitwerk-dev/worker-protocol\";\nimport type { LeitwerkConfig } from \"./config/config-types.js\";\n\n/** Bindings are operator-owned; process parameters never select credentials. */\nexport function resolveDockerRegistryCredentials(\n\tconfig: LeitwerkConfig,\n\tprocessId: string,\n\tdockerEnabled: boolean,\n): WorkerDockerRegistryCredential[] {\n\tif (!dockerEnabled) return [];\n\tconst section = config.docker_registries;\n\tconst registries = new Set<string>();\n\treturn (section?.process_bindings[processId] ?? []).map((id) => {\n\t\tconst profile = section?.profiles[id];\n\t\tif (!profile) throw new Error(\"Docker registry binding references an unknown profile\");\n\t\tconst registry = profile.registry.toLowerCase();\n\t\tif (registries.has(registry)) throw new Error(\"Duplicate Docker registry credentials\");\n\t\tregistries.add(registry);\n\t\treturn { registry, username: profile.username, password: profile.password };\n\t});\n}\n","import type { ProcessInstance, ProcessProject } from \"@leitwerk-dev/domain\";\nimport type { ExtensionProcessDefinition } from \"@leitwerk-dev/process-sdk\";\nimport { WorkerStartDiagnosticError } from \"@leitwerk-dev/worker-runners/types\";\nimport type { LeitwerkConfig } from \"./config/config-types.js\";\n\n/** Positive Kubernetes resource quantity; whitespace and negative sizes are invalid. */\nexport function isValidStorageSize(value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\tconst match = /^(\\+?(?:\\d+(?:\\.\\d*)?|\\.\\d+))([numkMGTPE]|[KMGTPE]i|[eE][+-]?\\d+)?$/.exec(value);\n\tif (!match || match[0] !== value) return false;\n\tconst numeric = Number(\n\t\t/^[eE][+-]?\\d+$/.test(match[2] ?? \"\") ? `${match[1]}${match[2]}` : match[1],\n\t);\n\treturn Number.isFinite(numeric) && numeric > 0;\n}\n\n/** Capacity is consumed only by Kubernetes, never as a local/Docker disk quota. */\nexport function resolveProcessStorageSize(input: {\n\tconfig: LeitwerkConfig;\n\tprocess: Pick<ProcessInstance, \"processId\" | \"paramsJson\">;\n\tdefinition: ExtensionProcessDefinition | undefined;\n\tprojects: readonly ProcessProject[];\n}): string | undefined {\n\tconst { config, process, definition, projects } = input;\n\tif (config.workers.runner !== \"kubernetes\") return undefined;\n\tlet size = config.process_configs?.[process.processId]?.storage_size;\n\tlet source = `process_configs.${process.processId}.storage_size`;\n\tif (size === undefined && definition?.resolveStorageSize) {\n\t\tconst params = definition.paramsCodec.parse(\n\t\t\tprocess.paramsJson ? JSON.parse(process.paramsJson) : undefined,\n\t\t);\n\t\tsize = definition.resolveStorageSize({ params, projects });\n\t\tsource = `Process '${process.processId}' resolveStorageSize()`;\n\t}\n\tif (size === undefined) {\n\t\tsize = config.kubernetes?.process_volume.size;\n\t\tsource = \"kubernetes.process_volume.size\";\n\t}\n\tif (!isValidStorageSize(size)) {\n\t\tthrow new WorkerStartDiagnosticError(\n\t\t\t`${source} must be a positive storage quantity (for example, 128Mi or 1Gi).`,\n\t\t);\n\t}\n\treturn size;\n}\n","/** Keeps `skills/<id>/SKILL.md` within the canonical bundle's 100-byte path limit. */\nexport const SAFE_SKILL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,83}$/;\n","import type { KubernetesDockerConfig } from \"./config-types.js\";\n\n/** Normalize trusted sandbox selection before passing it to a worker runner. @internal */\nexport function resolveKubernetesDockerIsolation(docker: KubernetesDockerConfig | undefined): {\n\tisolation: KubernetesDockerConfig[\"isolation\"];\n\terrors: string[];\n} {\n\tconst isolation = docker?.isolation ?? (docker?.gvisor ? \"gvisor\" : undefined);\n\tconst errors: string[] = [];\n\tif (\n\t\tdocker?.isolation !== undefined &&\n\t\tdocker.gvisor !== undefined &&\n\t\tdocker.gvisor !== (docker.isolation === \"gvisor\")\n\t) {\n\t\terrors.push(\"kubernetes.docker.gvisor conflicts with kubernetes.docker.isolation\");\n\t}\n\tif (isolation !== undefined && docker?.host_users !== undefined) {\n\t\terrors.push(\"kubernetes.docker.host_users must be omitted for sandbox isolation\");\n\t}\n\treturn { isolation, errors };\n}\n","export function parseHttpUrl(value: string): URL | null {\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn url.protocol === \"https:\" || url.protocol === \"http:\" ? url : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function isValidHttpUrl(value: string): boolean {\n\treturn parseHttpUrl(value) !== null;\n}\n\nexport function isLoopbackHostname(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n\nexport function isLoopbackHttpUrl(value: string): boolean {\n\tconst url = parseHttpUrl(value);\n\treturn url?.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n}\n\nexport function isHttpsOrLoopbackHttpUrl(value: string): boolean {\n\tconst url = parseHttpUrl(value);\n\treturn (\n\t\turl !== null &&\n\t\t(url.protocol === \"https:\" || (url.protocol === \"http:\" && isLoopbackHostname(url.hostname)))\n\t);\n}\n","import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { drizzle } from \"drizzle-orm/node-sqlite\";\nimport type { SQLiteTable } from \"drizzle-orm/sqlite-core\";\nimport * as schema from \"./schema.js\";\nimport { generateCreateIndexDDL, generateCreateTableDDL, getTableName } from \"./schema-ddl.js\";\n\n/** @public */\nexport type LeitwerkDb = ReturnType<typeof drizzle>;\n\n/** @internal */\nexport interface DatabaseOptions {\n\t/** @internal */\n\tsqlitePath: string;\n\t/** @internal */\n\tenableWAL?: boolean;\n}\n\n/** @internal */\nexport interface InitializeSchemaOptions {\n\t/** @internal */\n\tsqlitePath?: string;\n}\n\n/** @internal */\nexport class DatabaseSchemaMismatchError extends Error {\n\t/** @internal */\n\tconstructor(\n\t\t/** @internal */\n\t\treadonly sqlitePath: string,\n\t\t/** @internal */\n\t\treadonly tableName: string,\n\t) {\n\t\tsuper(\n\t\t\t`SQLite schema mismatch for table \"${tableName}\" at ${sqlitePath}. ` +\n\t\t\t\t`Known migrations were applied automatically when possible. Stop the server, ` +\n\t\t\t\t`back up the configured SQLite database, add or apply the required explicit ` +\n\t\t\t\t`migration for this unknown drift, and restart. Leitwerk never resets ` +\n\t\t\t\t`configured storage automatically.`,\n\t\t);\n\t\tthis.name = \"DatabaseSchemaMismatchError\";\n\t}\n}\n\nconst ALL_TABLES = [\n\tschema.wikiTopics,\n\tschema.wikiPages,\n\tschema.wikiRevisions,\n\tschema.topicPublications,\n\tschema.inspectionContents,\n\tschema.executionInspections,\n\n\tschema.settingsSubjects,\n\tschema.settingsAliases,\n\tschema.settingsOverrides,\n\tschema.settingsSubjectRedirects,\n\tschema.startupObservations,\n\tschema.processInstances,\n\tschema.launchRuns,\n\tschema.launchRunReplays,\n\tschema.skills,\n\tschema.skillRevisions,\n\tschema.skillRevisionDependencies,\n\tschema.skillCatalogEntries,\n\tschema.processSkills,\n\tschema.skillInvocations,\n\tschema.processProjects,\n\tschema.processInputs,\n\tschema.processEvents,\n\tschema.turnSummaries,\n\tschema.sessionSummaries,\n\tschema.processHandoffDedupKeys,\n\tschema.futureExecutions,\n\tschema.launcherRecentValues,\n\tschema.ticketDestinationRecents,\n\tschema.processTitleJobs,\n\tschema.pendingExternalSourceFires,\n\tschema.processLeafOutcomeSnapshots,\n\tschema.turnRecords,\n\tschema.turnStartRecords,\n\tschema.mappedLlmRuns,\n\tschema.mappedLlmItems,\n\tschema.apiTokens,\n\tschema.authSessions,\n\tschema.authLoginFlows,\n\tschema.turnAnnotations,\n\tschema.workerLeases,\n\tschema.processQuestionRequests,\n\tschema.processRelations,\n\tschema.processToolApprovalRequests,\n\tschema.providerCredentials,\n\tschema.sessionTransferGrants,\n\tschema.sessionTransferAttempts,\n\tschema.externalWriteLog,\n] as const;\n\nfunction createTableSql(table: SQLiteTable): string {\n\treturn generateCreateTableDDL(\n\t\ttable,\n\t\tschema.BASELINE_TABLE_CONSTRAINTS[getTableName(table)] ?? [],\n\t);\n}\n\nfunction createTableWithIndexes(sqlite: DatabaseSync, table: SQLiteTable): void {\n\tsqlite.exec(createTableSql(table));\n\tfor (const statement of generateCreateIndexDDL(table)) sqlite.exec(statement);\n}\n\nfunction existingTableSql(sqlite: DatabaseSync, tableName: string): string | null {\n\tconst row = sqlite\n\t\t.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n\t\t.get(tableName) as { sql?: string | null } | undefined;\n\treturn typeof row?.sql === \"string\" ? row.sql : null;\n}\n\nfunction tableHasColumn(sqlite: DatabaseSync, tableName: string, columnName: string): boolean {\n\treturn (sqlite.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string }>).some(\n\t\t(column) => column.name === columnName,\n\t);\n}\n\nfunction existingSchemaObjects(sqlite: DatabaseSync, type: \"table\" | \"index\"): Map<string, string> {\n\tconst rows = sqlite\n\t\t.prepare(\n\t\t\t\"SELECT name, sql FROM sqlite_master WHERE type = ? AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n\t\t)\n\t\t.all(type) as Array<{ name: string; sql: string | null }>;\n\treturn new Map(rows.flatMap((row) => (row.sql ? [[row.name, row.sql] as const] : [])));\n}\n\nfunction hasExistingSchema(sqlite: DatabaseSync): boolean {\n\tconst row = sqlite\n\t\t.prepare(\n\t\t\t\"SELECT count(*) AS count FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\",\n\t\t)\n\t\t.get() as { count: number };\n\treturn row.count > 0;\n}\n\nfunction splitCreateTableDefinitions(body: string): string[] {\n\tconst definitions: string[] = [];\n\tlet start = 0;\n\tlet depth = 0;\n\tlet quote: \"'\" | '\"' | \"`\" | \"[\" | null = null;\n\tfor (let index = 0; index < body.length; index++) {\n\t\tconst character = body[index];\n\t\tif (quote !== null) {\n\t\t\tif (quote === \"[\" ? character === \"]\" : character === quote) {\n\t\t\t\tif (body[index + 1] === character && quote !== \"[\") {\n\t\t\t\t\tindex++;\n\t\t\t\t} else {\n\t\t\t\t\tquote = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"' || character === \"`\" || character === \"[\") {\n\t\t\tquote = character;\n\t\t} else if (character === \"(\") {\n\t\t\tdepth++;\n\t\t} else if (character === \")\") {\n\t\t\tdepth--;\n\t\t} else if (character === \",\" && depth === 0) {\n\t\t\tdefinitions.push(body.slice(start, index));\n\t\t\tstart = index + 1;\n\t\t}\n\t}\n\tdefinitions.push(body.slice(start));\n\treturn definitions;\n}\n\nfunction normalizeCreateTableSql(sql: string): string {\n\tconst compact = sql\n\t\t.toLowerCase()\n\t\t.replace(/create\\s+table\\s+if\\s+not\\s+exists/g, \"create table\")\n\t\t.replace(/\\s+/g, \"\")\n\t\t.trim();\n\tconst openingParenthesis = compact.indexOf(\"(\");\n\tconst closingParenthesis = compact.lastIndexOf(\")\");\n\tif (openingParenthesis < 0 || closingParenthesis <= openingParenthesis) return compact;\n\tconst body = compact.slice(openingParenthesis + 1, closingParenthesis);\n\tconst definitions = splitCreateTableDefinitions(body).sort();\n\treturn `${compact.slice(0, openingParenthesis + 1)}${definitions.join(\",\")}${compact.slice(closingParenthesis)}`;\n}\n\nfunction normalizeSchemaSql(sql: string): string {\n\treturn normalizeCreateTableSql(sql).replace(/create(unique)?indexifnotexists/g, \"create$1index\");\n}\n\nfunction assertCompatibleTableSchema(\n\tsqlite: DatabaseSync,\n\ttable: SQLiteTable,\n\tsqlitePath: string,\n): void {\n\tconst tableName = getTableName(table);\n\tconst actualSql = existingTableSql(sqlite, tableName);\n\tconst expectedSql = createTableSql(table);\n\tif (!actualSql || normalizeCreateTableSql(actualSql) !== normalizeCreateTableSql(expectedSql)) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, tableName);\n\t}\n}\n\nfunction assertBaselineSchema(\n\tsqlite: DatabaseSync,\n\tsqlitePath: string,\n\tmigratingTables: ReadonlySet<string> = new Set(),\n\tmigratingLegacyIndexes: ReadonlySet<string> = new Set(),\n): void {\n\tconst actualTables = existingSchemaObjects(sqlite, \"table\");\n\tconst expectedTableNames = new Set([...ALL_TABLES.map(getTableName), ...migratingTables]);\n\tconst unknownTable = [...actualTables.keys()].find((name) => !expectedTableNames.has(name));\n\tif (unknownTable) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, unknownTable);\n\t}\n\tfor (const table of ALL_TABLES) {\n\t\tif (!migratingTables.has(getTableName(table))) {\n\t\t\tassertCompatibleTableSchema(sqlite, table, sqlitePath);\n\t\t}\n\t}\n\n\tconst actualIndexes = existingSchemaObjects(sqlite, \"index\");\n\tconst expectedIndexes = new Map<string, string>();\n\tconst migratingIndexNames = new Set<string>(migratingLegacyIndexes);\n\tfor (const table of ALL_TABLES) {\n\t\tif (migratingTables.has(getTableName(table))) {\n\t\t\tfor (const statement of generateCreateIndexDDL(table)) {\n\t\t\t\tconst name = /index if not exists ([^ ]+)/i.exec(statement)?.[1];\n\t\t\t\tif (name) migratingIndexNames.add(name);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const statement of generateCreateIndexDDL(table)) {\n\t\t\tconst name = /index if not exists ([^ ]+)/i.exec(statement)?.[1];\n\t\t\tif (!name) throw new Error(`Could not read generated index name: ${statement}`);\n\t\t\texpectedIndexes.set(name, statement);\n\t\t}\n\t}\n\tconst changedIndex = [...new Set([...actualIndexes.keys(), ...expectedIndexes.keys()])].find(\n\t\t(name) =>\n\t\t\t!migratingIndexNames.has(name) &&\n\t\t\tnormalizeSchemaSql(actualIndexes.get(name) ?? \"\") !==\n\t\t\t\tnormalizeSchemaSql(expectedIndexes.get(name) ?? \"\"),\n\t);\n\tif (changedIndex) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, `index:${changedIndex}`);\n\t}\n}\n\nconst PROCESS_QUESTION_REQUESTS_WITH_DRAFT_STATE_SQL = `CREATE TABLE process_question_requests (\n\tid text PRIMARY KEY NOT NULL,\n\tinstance_id text NOT NULL REFERENCES process_instances(id) ON DELETE CASCADE,\n\tturn_record_id text NOT NULL,\n\tworker_lease_id text NOT NULL,\n\ttool_call_id text NOT NULL,\n\tquestions_json text NOT NULL,\n\tdraft_json text NOT NULL,\n\tdraft_revision integer NOT NULL DEFAULT 0,\n\tstatus text NOT NULL DEFAULT 'open',\n\tanswers_json text,\n\tasked_at text NOT NULL,\n\tanswered_at text,\n\tanswered_by_json text,\n\tcancelled_at text,\n\tCONSTRAINT question_requests_revision CHECK (\"process_question_requests\".\"draft_revision\" >= 0),\n\tCONSTRAINT question_requests_status CHECK (\"process_question_requests\".\"status\" in ('open', 'answered', 'cancelled')),\n\tCONSTRAINT question_requests_questions_json CHECK (json_valid(\"process_question_requests\".\"questions_json\")),\n\tCONSTRAINT question_requests_draft_json CHECK (json_valid(\"process_question_requests\".\"draft_json\")),\n\tCONSTRAINT question_requests_answers_json CHECK (\"process_question_requests\".\"answers_json\" is null or json_valid(\"process_question_requests\".\"answers_json\")),\n\tCONSTRAINT fk_question_requests_turn FOREIGN KEY (instance_id, turn_record_id) REFERENCES turn_records(instance_id, id),\n\tCONSTRAINT fk_question_requests_lease FOREIGN KEY (instance_id, worker_lease_id) REFERENCES worker_leases(instance_id, id)\n)`;\n\nconst PROVIDER_CREDENTIALS_WITH_SCHEMA_VERSION_SQL = `CREATE TABLE provider_credentials (\n\tprovider_id text PRIMARY KEY NOT NULL,\n\tcredential_schema_version integer NOT NULL,\n\trevision integer NOT NULL,\n\tencrypted_payload text NOT NULL,\n\tcreated_at text NOT NULL,\n\tupdated_at text NOT NULL,\n\tCONSTRAINT provider_credentials_positive_revision CHECK (\"provider_credentials\".\"revision\" > 0),\n\tCONSTRAINT provider_credentials_positive_schema_version CHECK (\"provider_credentials\".\"credential_schema_version\" > 0)\n)`;\n\nfunction assertMigrationSource(\n\tsqlite: DatabaseSync,\n\tsqlitePath: string,\n\ttableName: string,\n\texpectedSql: string,\n\texpectedIndexes: readonly string[],\n): void {\n\tif (\n\t\tnormalizeCreateTableSql(existingTableSql(sqlite, tableName) ?? \"\") !==\n\t\tnormalizeCreateTableSql(expectedSql)\n\t) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, tableName);\n\t}\n\tconst actualIndexes = sqlite\n\t\t.prepare(\n\t\t\t\"SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL\",\n\t\t)\n\t\t.all(tableName) as Array<{ sql: string }>;\n\tif (\n\t\tactualIndexes.length !== expectedIndexes.length ||\n\t\tactualIndexes.some(\n\t\t\t(actual) =>\n\t\t\t\t!expectedIndexes.some(\n\t\t\t\t\t(expected) => normalizeSchemaSql(actual.sql) === normalizeSchemaSql(expected),\n\t\t\t\t),\n\t\t)\n\t) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, `indexes:${tableName}`);\n\t}\n\tif (\n\t\tsqlite\n\t\t\t.prepare(\"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ?\")\n\t\t\t.get(tableName)\n\t) {\n\t\tthrow new DatabaseSchemaMismatchError(sqlitePath, `triggers:${tableName}`);\n\t}\n}\n\nconst SESSION_TRANSFER_ATTEMPTS_WITH_PROGRESS_SQL = `CREATE TABLE session_transfer_attempts (\n\tid text PRIMARY KEY NOT NULL,\n\tgrant_id text NOT NULL REFERENCES session_transfer_grants(id) ON DELETE CASCADE,\n\tinstance_id text NOT NULL REFERENCES process_instances(id) ON DELETE CASCADE,\n\tstate text NOT NULL,\n\tphase text NOT NULL,\n\tcreated_at text NOT NULL,\n\tlease_until text NOT NULL,\n\thard_deadline text NOT NULL,\n\tentries_total integer,\n\tentries_processed integer NOT NULL DEFAULT 0,\n\tlogical_bytes_total integer,\n\tlogical_bytes_processed integer NOT NULL DEFAULT 0,\n\tcompressed_bytes integer,\n\tstream_sha256 text,\n\tfailure_code text,\n\tcompleted_at text,\n\tCONSTRAINT session_transfer_attempts_state CHECK (\"session_transfer_attempts\".\"state\" in ('queued', 'exporting', 'awaiting_ack', 'cancelled', 'failed', 'consumed'))\n)`;\n\ninterface KnownMigration {\n\tid: string;\n\ttableNames: readonly string[];\n\tlegacyIndexNames?: readonly string[];\n\tmatches(sqlite: DatabaseSync): boolean;\n\tvalidateSource?(sqlite: DatabaseSync, sqlitePath: string): void;\n\tapply(sqlite: DatabaseSync): void;\n}\n\nfunction addTablesMigration(\n\tid: string,\n\ttables: readonly SQLiteTable[],\n\tmatches: KnownMigration[\"matches\"],\n): KnownMigration {\n\treturn {\n\t\tid,\n\t\ttableNames: tables.map(getTableName),\n\t\tmatches,\n\t\tapply(sqlite) {\n\t\t\tfor (const table of tables) createTableWithIndexes(sqlite, table);\n\t\t},\n\t};\n}\nconst HISTORY_INDEXES = [\n\t\"idx_turn_records_page\",\n\t\"idx_turn_annotations_created\",\n\t\"idx_worker_leases_started\",\n\t\"idx_worker_leases_exited\",\n] as const;\n\nconst KNOWN_MIGRATIONS: readonly KnownMigration[] = [\n\t{\n\t\tid: \"20261008_remove_repository_instruction_overrides\",\n\t\ttableNames: [],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"settings_overrides\") !== null &&\n\t\t\tBoolean(\n\t\t\t\tsqlite\n\t\t\t\t\t.prepare(\"SELECT 1 FROM settings_overrides WHERE key = ? LIMIT 1\")\n\t\t\t\t\t.get(\"coding.repository_instructions\"),\n\t\t\t),\n\t\tapply(sqlite) {\n\t\t\tsqlite\n\t\t\t\t.prepare(\"DELETE FROM settings_overrides WHERE key = ?\")\n\t\t\t\t.run(\"coding.repository_instructions\");\n\t\t},\n\t},\n\taddTablesMigration(\n\t\t\"20260930_add_topic_wiki\",\n\t\t[schema.wikiTopics, schema.wikiPages, schema.wikiRevisions, schema.topicPublications],\n\t\t(sqlite) => hasExistingSchema(sqlite) && existingTableSql(sqlite, \"wiki_topics\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260925_add_execution_inspections\",\n\t\t[schema.inspectionContents, schema.executionInspections],\n\t\t(sqlite) =>\n\t\t\thasExistingSchema(sqlite) && existingTableSql(sqlite, \"execution_inspections\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260926_add_scoped_settings\",\n\t\t[schema.settingsSubjects, schema.settingsAliases, schema.settingsOverrides],\n\t\t(sqlite) =>\n\t\t\texistingTableSql(sqlite, \"process_instances\") !== null &&\n\t\t\texistingTableSql(sqlite, \"settings_subjects\") === null &&\n\t\t\texistingTableSql(sqlite, \"settings_aliases\") === null &&\n\t\t\texistingTableSql(sqlite, \"settings_overrides\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260926_add_settings_subject_redirects\",\n\t\t[schema.settingsSubjectRedirects],\n\t\t(sqlite) =>\n\t\t\thasExistingSchema(sqlite) && existingTableSql(sqlite, \"settings_subject_redirects\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260911_add_startup_observations\",\n\t\t[schema.startupObservations],\n\t\t(sqlite) =>\n\t\t\thasExistingSchema(sqlite) && existingTableSql(sqlite, \"startup_observations\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260823_add_ticket_destination_recents\",\n\t\t[schema.ticketDestinationRecents],\n\t\t(sqlite) =>\n\t\t\thasExistingSchema(sqlite) && existingTableSql(sqlite, \"ticket_destination_recents\") === null,\n\t),\n\t{\n\t\tid: \"20260909_add_reasoning_summaries\",\n\t\ttableNames: [\"process_events\", \"turn_summaries\", \"session_summaries\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"process_events\") !== null &&\n\t\t\t!tableHasColumn(sqlite, \"process_events\", \"event_sequence\"),\n\t\tvalidateSource(sqlite, sqlitePath) {\n\t\t\tassertMigrationSource(\n\t\t\t\tsqlite,\n\t\t\t\tsqlitePath,\n\t\t\t\t\"process_events\",\n\t\t\t\t`CREATE TABLE process_events (\n id text PRIMARY KEY NOT NULL, instance_id text NOT NULL REFERENCES process_instances(id) ON DELETE CASCADE,\n event_type text NOT NULL, data text NOT NULL DEFAULT '{}', created_at text NOT NULL\n )`,\n\t\t\t\t[\n\t\t\t\t\t\"CREATE INDEX idx_process_events_instance ON process_events(instance_id)\",\n\t\t\t\t\t\"CREATE INDEX idx_process_events_instance_created ON process_events(instance_id, created_at)\",\n\t\t\t\t\t\"CREATE INDEX idx_process_events_type ON process_events(event_type)\",\n\t\t\t\t],\n\t\t\t);\n\t\t},\n\t\tapply(sqlite) {\n\t\t\t// rowid preserves ingestion order for legacy events, including equal timestamps.\n\t\t\tsqlite.exec(`CREATE TEMP TABLE staged_reasoning_events AS SELECT rowid AS event_sequence, * FROM process_events;\n DROP TABLE process_events;`);\n\t\t\tcreateTableWithIndexes(sqlite, schema.processEvents);\n\t\t\tsqlite.exec(`INSERT INTO process_events (id, instance_id, event_type, data, created_at, event_sequence, turn_record_id)\n SELECT id, instance_id, event_type, data, created_at, event_sequence, json_extract(data, '$.turnRecordId') FROM staged_reasoning_events;\n DROP TABLE staged_reasoning_events;`);\n\t\t\tcreateTableWithIndexes(sqlite, schema.turnSummaries);\n\t\t\tcreateTableWithIndexes(sqlite, schema.sessionSummaries);\n\t\t},\n\t},\n\taddTablesMigration(\n\t\t\"20260908_add_api_tokens\",\n\t\t[schema.apiTokens],\n\t\t(sqlite) =>\n\t\t\texistingTableSql(sqlite, \"auth_sessions\") !== null &&\n\t\t\texistingTableSql(sqlite, \"api_tokens\") === null,\n\t),\n\t{\n\t\tid: \"20260909_add_oidc_evidence\",\n\t\ttableNames: [\"auth_sessions\", \"api_tokens\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"auth_sessions\") !== null &&\n\t\t\t(!tableHasColumn(sqlite, \"auth_sessions\", \"oidc_evidence_json\") ||\n\t\t\t\t!tableHasColumn(sqlite, \"api_tokens\", \"oidc_evidence_json\")),\n\t\tapply(sqlite) {\n\t\t\tfor (const table of [\"auth_sessions\", \"api_tokens\"]) {\n\t\t\t\tif (!tableHasColumn(sqlite, table, \"oidc_evidence_json\"))\n\t\t\t\t\tsqlite.exec(`ALTER TABLE ${table} ADD COLUMN oidc_evidence_json text`);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20260901_add_session_transfers\",\n\t\ttableNames: [\"session_transfer_grants\", \"session_transfer_attempts\"],\n\t\tmatches: (sqlite) =>\n\t\t\thasExistingSchema(sqlite) &&\n\t\t\t(existingTableSql(sqlite, \"session_transfer_grants\") === null ||\n\t\t\t\texistingTableSql(sqlite, \"session_transfer_attempts\") === null),\n\t\tapply(sqlite) {\n\t\t\tif (existingTableSql(sqlite, \"session_transfer_grants\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.sessionTransferGrants);\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"session_transfer_attempts\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.sessionTransferAttempts);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20260902_session_transfer_phase_state_and_progress\",\n\t\ttableNames: [\"session_transfer_attempts\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"session_transfer_attempts\") !== null &&\n\t\t\t(tableHasColumn(sqlite, \"session_transfer_attempts\", \"state\") ||\n\t\t\t\ttableHasColumn(sqlite, \"session_transfer_attempts\", \"entries_processed\") ||\n\t\t\t\ttableHasColumn(sqlite, \"session_transfer_attempts\", \"logical_bytes_processed\")),\n\t\tvalidateSource(sqlite, sqlitePath) {\n\t\t\tconst legacyIndexes = generateCreateIndexDDL(schema.sessionTransferAttempts).map(\n\t\t\t\t(statement) =>\n\t\t\t\t\tstatement.includes(\"uq_session_transfer_active_instance\")\n\t\t\t\t\t\t? `CREATE UNIQUE INDEX uq_session_transfer_active_instance ON session_transfer_attempts(instance_id) WHERE \"session_transfer_attempts\".\"state\" in ('queued', 'exporting', 'awaiting_ack')`\n\t\t\t\t\t\t: statement,\n\t\t\t);\n\t\t\tassertMigrationSource(\n\t\t\t\tsqlite,\n\t\t\t\tsqlitePath,\n\t\t\t\t\"session_transfer_attempts\",\n\t\t\t\tSESSION_TRANSFER_ATTEMPTS_WITH_PROGRESS_SQL,\n\t\t\t\tlegacyIndexes,\n\t\t\t);\n\t\t},\n\t\tapply(sqlite) {\n\t\t\tfor (const index of [\n\t\t\t\t\"uq_session_transfer_active_instance\",\n\t\t\t\t\"idx_session_transfer_attempts_grant\",\n\t\t\t\t\"idx_session_transfer_attempts_instance\",\n\t\t\t\t\"idx_session_transfer_attempts_deadlines\",\n\t\t\t]) {\n\t\t\t\tsqlite.exec(`DROP INDEX IF EXISTS ${index}`);\n\t\t\t}\n\t\t\tsqlite.exec(\n\t\t\t\t\"ALTER TABLE session_transfer_attempts RENAME TO session_transfer_attempts_legacy\",\n\t\t\t);\n\t\t\tcreateTableWithIndexes(sqlite, schema.sessionTransferAttempts);\n\t\t\tsqlite.exec(`\n\t\t\t\tINSERT INTO session_transfer_attempts (\n\t\t\t\t\tid, grant_id, instance_id, phase, created_at, lease_until, hard_deadline,\n\t\t\t\t\tentries_total, logical_bytes_total, compressed_bytes, stream_sha256,\n\t\t\t\t\tfailure_code, completed_at\n\t\t\t\t)\n\t\t\t\tSELECT id, grant_id, instance_id, phase, created_at, lease_until, hard_deadline,\n\t\t\t\t\tentries_total, logical_bytes_total, compressed_bytes, stream_sha256,\n\t\t\t\t\tfailure_code, completed_at\n\t\t\t\tFROM session_transfer_attempts_legacy\n\t\t\t`);\n\t\t\tsqlite.exec(\"DROP TABLE session_transfer_attempts_legacy\");\n\t\t},\n\t},\n\t{\n\t\tid: \"20260827_add_worker_startup_observations\",\n\t\ttableNames: [\"worker_leases\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"worker_leases\") !== null &&\n\t\t\t(!tableHasColumn(sqlite, \"worker_leases\", \"turn_start_record_id\") ||\n\t\t\t\t!tableHasColumn(sqlite, \"worker_leases\", \"connected_at\") ||\n\t\t\t\t!tableHasColumn(sqlite, \"worker_leases\", \"workspace_preparation_started_at\") ||\n\t\t\t\t!tableHasColumn(sqlite, \"worker_leases\", \"ready_at\")),\n\t\tapply(sqlite) {\n\t\t\tif (!tableHasColumn(sqlite, \"worker_leases\", \"turn_start_record_id\")) {\n\t\t\t\tsqlite.exec(\n\t\t\t\t\t\"ALTER TABLE worker_leases ADD COLUMN turn_start_record_id text REFERENCES turn_start_records(id)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!tableHasColumn(sqlite, \"worker_leases\", \"connected_at\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE worker_leases ADD COLUMN connected_at text\");\n\t\t\t}\n\t\t\tif (!tableHasColumn(sqlite, \"worker_leases\", \"workspace_preparation_started_at\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE worker_leases ADD COLUMN workspace_preparation_started_at text\");\n\t\t\t}\n\t\t\tif (!tableHasColumn(sqlite, \"worker_leases\", \"ready_at\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE worker_leases ADD COLUMN ready_at text\");\n\t\t\t}\n\t\t\tsqlite.exec(\n\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_worker_leases_turn_start ON worker_leases(turn_start_record_id)\",\n\t\t\t);\n\t\t},\n\t},\n\t{\n\t\tid: \"20260826_add_launch_runs\",\n\t\ttableNames: [\"launch_runs\", \"launch_run_replays\", \"process_title_jobs\"],\n\t\tmatches: (sqlite) =>\n\t\t\thasExistingSchema(sqlite) &&\n\t\t\t(existingTableSql(sqlite, \"launch_runs\") === null ||\n\t\t\t\texistingTableSql(sqlite, \"launch_run_replays\") === null ||\n\t\t\t\t!tableHasColumn(sqlite, \"process_title_jobs\", \"launch_run_id\")),\n\t\tapply(sqlite) {\n\t\t\tif (existingTableSql(sqlite, \"launch_runs\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.launchRuns);\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"launch_run_replays\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.launchRunReplays);\n\t\t\t}\n\t\t\tif (!tableHasColumn(sqlite, \"process_title_jobs\", \"launch_run_id\")) {\n\t\t\t\tsqlite.exec(\n\t\t\t\t\t\"ALTER TABLE process_title_jobs ADD COLUMN launch_run_id text REFERENCES launch_runs(id) ON DELETE SET NULL\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tsqlite.exec(\n\t\t\t\t\"CREATE INDEX IF NOT EXISTS idx_process_title_jobs_launch_run ON process_title_jobs(launch_run_id)\",\n\t\t\t);\n\t\t},\n\t},\n\t{\n\t\tid: \"20260823_add_ticket_approval_destination\",\n\t\ttableNames: [\"process_tool_approval_requests\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"process_tool_approval_requests\") !== null &&\n\t\t\t!tableHasColumn(sqlite, \"process_tool_approval_requests\", \"destination_json\"),\n\t\tapply(sqlite) {\n\t\t\tsqlite.exec(\"ALTER TABLE process_tool_approval_requests ADD COLUMN destination_json text\");\n\t\t},\n\t},\n\t{\n\t\tid: \"20260727_remove_process_question_draft_state\",\n\t\ttableNames: [\"process_question_requests\"],\n\t\tlegacyIndexNames: [\"idx_question_requests_turn\"],\n\t\tmatches: (sqlite) =>\n\t\t\tnormalizeCreateTableSql(existingTableSql(sqlite, \"process_question_requests\") ?? \"\") ===\n\t\t\tnormalizeCreateTableSql(PROCESS_QUESTION_REQUESTS_WITH_DRAFT_STATE_SQL),\n\t\tapply(sqlite) {\n\t\t\tsqlite.exec(\n\t\t\t\t\"ALTER TABLE process_question_requests RENAME TO process_question_requests_before_20260727\",\n\t\t\t);\n\t\t\tsqlite.exec(createTableSql(schema.processQuestionRequests));\n\t\t\tsqlite.exec(`INSERT INTO process_question_requests\n\t\t\t\t(id, instance_id, turn_record_id, tool_call_id, questions_json, status,\n\t\t\t\t answers_json, asked_at, answered_at, answered_by_json, cancelled_at)\n\t\t\tSELECT id, instance_id, turn_record_id, tool_call_id, questions_json, status,\n\t\t\t\tanswers_json, asked_at, answered_at, answered_by_json, cancelled_at\n\t\t\tFROM process_question_requests_before_20260727`);\n\t\t\tsqlite.exec(\"DROP TABLE process_question_requests_before_20260727\");\n\t\t\tfor (const statement of generateCreateIndexDDL(schema.processQuestionRequests)) {\n\t\t\t\tsqlite.exec(statement);\n\t\t\t}\n\t\t},\n\t},\n\taddTablesMigration(\n\t\t\"20260726_add_sql_backed_skills\",\n\t\t[schema.skills, schema.skillRevisions, schema.processSkills],\n\t\t(sqlite) =>\n\t\t\texistingTableSql(sqlite, \"process_instances\") !== null &&\n\t\t\texistingTableSql(sqlite, \"skills\") === null,\n\t),\n\t{\n\t\tid: \"20260728_add_skill_catalog_and_invocations\",\n\t\ttableNames: [\"skills\", \"skill_catalog_entries\", \"skill_invocations\"],\n\t\tmatches: (sqlite) =>\n\t\t\texistingTableSql(sqlite, \"skills\") === null ||\n\t\t\t!tableHasColumn(sqlite, \"skills\", \"registration_kind\") ||\n\t\t\texistingTableSql(sqlite, \"skill_catalog_entries\") === null ||\n\t\t\t!tableHasColumn(sqlite, \"skill_catalog_entries\", \"available\") ||\n\t\t\ttableHasColumn(sqlite, \"skill_catalog_entries\", \"skill_markdown\") ||\n\t\t\texistingTableSql(sqlite, \"skill_invocations\") === null,\n\t\tapply(sqlite) {\n\t\t\tif (!tableHasColumn(sqlite, \"skills\", \"registration_kind\")) {\n\t\t\t\tsqlite.exec(\n\t\t\t\t\t\"ALTER TABLE skills ADD COLUMN registration_kind text NOT NULL DEFAULT 'configuration'\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"skill_catalog_entries\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.skillCatalogEntries);\n\t\t\t} else {\n\t\t\t\tif (!tableHasColumn(sqlite, \"skill_catalog_entries\", \"available\")) {\n\t\t\t\t\tsqlite.exec(\n\t\t\t\t\t\t\"ALTER TABLE skill_catalog_entries ADD COLUMN available integer NOT NULL DEFAULT true\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (tableHasColumn(sqlite, \"skill_catalog_entries\", \"skill_markdown\")) {\n\t\t\t\t\tsqlite.exec(\"ALTER TABLE skill_catalog_entries DROP COLUMN skill_markdown\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"skill_invocations\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.skillInvocations);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20261006_add_extension_skill_provenance\",\n\t\ttableNames: [\"skills\", \"skill_revisions\"],\n\t\tmatches: (sqlite) =>\n\t\t\t!tableHasColumn(sqlite, \"skills\", \"owner_extension_id\") ||\n\t\t\t!tableHasColumn(sqlite, \"skill_revisions\", \"provenance_json\"),\n\t\tapply(sqlite) {\n\t\t\tif (!tableHasColumn(sqlite, \"skills\", \"owner_extension_id\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE skills ADD COLUMN owner_extension_id text\");\n\t\t\t}\n\t\t\tif (!tableHasColumn(sqlite, \"skill_revisions\", \"provenance_json\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE skill_revisions ADD COLUMN provenance_json text\");\n\t\t\t}\n\t\t},\n\t},\n\taddTablesMigration(\n\t\t\"20260729_add_skill_revision_dependencies\",\n\t\t[schema.skillRevisionDependencies],\n\t\t(sqlite) => existingTableSql(sqlite, \"skill_revision_dependencies\") === null,\n\t),\n\taddTablesMigration(\n\t\t\"20260726_add_process_question_requests\",\n\t\t[schema.processQuestionRequests],\n\t\t(sqlite) => existingTableSql(sqlite, \"process_question_requests\") === null,\n\t),\n\t{\n\t\tid: \"20260725_add_model_policy_provenance_and_future_blocks\",\n\t\ttableNames: [\"process_instances\", \"future_executions\", \"turn_records\"],\n\t\tmatches: (sqlite) =>\n\t\t\t!tableHasColumn(sqlite, \"process_instances\", \"selected_turn_model_kind\") &&\n\t\t\t!tableHasColumn(sqlite, \"future_executions\", \"model_profile_id\") &&\n\t\t\t!tableHasColumn(sqlite, \"turn_records\", \"model_selection_kind\"),\n\t\tapply(sqlite) {\n\t\t\tsqlite.exec(`\n\t\t\t\tALTER TABLE process_instances ADD COLUMN selected_turn_model_kind text;\n\t\t\t\tALTER TABLE future_executions ADD COLUMN model_profile_id text;\n\t\t\t\tALTER TABLE future_executions ADD COLUMN model_selection_kind text;\n\t\t\t\tALTER TABLE future_executions ADD COLUMN model_selection_source text;\n\t\t\t\tALTER TABLE future_executions ADD COLUMN blocked_reason_json text;\n\t\t\t\tALTER TABLE turn_records ADD COLUMN model_selection_kind text;\n\t\t\t\tALTER TABLE turn_records ADD COLUMN model_selection_source text;\n\t\t\t\tUPDATE process_instances SET\n\t\t\t\t\tselected_turn_model_kind = CASE\n\t\t\t\t\t\tWHEN selected_turn_model_profile_id IS NULL THEN NULL\n\t\t\t\t\t\tWHEN selected_turn_model_source IN ('action_override','instance_turn_config','instance_default') THEN 'explicit'\n\t\t\t\t\t\tELSE 'inherited' END,\n\t\t\t\t\tselected_turn_model_source = CASE\n\t\t\t\t\t\tWHEN selected_turn_model_profile_id IS NOT NULL AND (selected_turn_model_source IS NULL OR selected_turn_model_source NOT IN ('action_override','instance_turn_config','process_config_turn','instance_default','process_config_default','catalog_default')) THEN 'legacy_persisted'\n\t\t\t\t\t\tELSE selected_turn_model_source END;\n\t\t\t\tUPDATE turn_records SET model_selection_kind = 'inherited', model_selection_source = 'legacy_persisted'\n\t\t\t\t\tWHERE model_profile_id IS NOT NULL;\n\t\t\t`);\n\t\t},\n\t},\n\t{\n\t\tid: \"20260730_add_process_launch_intent\",\n\t\ttableNames: [\"process_instances\", \"process_launch_intents\"],\n\t\tmatches: (sqlite) =>\n\t\t\t!tableHasColumn(sqlite, \"process_instances\", \"launch_intent_json\") ||\n\t\t\texistingTableSql(sqlite, \"process_launch_intents\") !== null,\n\t\tapply(sqlite) {\n\t\t\tif (!tableHasColumn(sqlite, \"process_instances\", \"launch_intent_json\")) {\n\t\t\t\tsqlite.exec(\"ALTER TABLE process_instances ADD COLUMN launch_intent_json text\");\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"process_launch_intents\") !== null) {\n\t\t\t\tsqlite.exec(`\n\t\t\t\t\tUPDATE process_instances\n\t\t\t\t\tSET launch_intent_json = (\n\t\t\t\t\t\tSELECT json_object(\n\t\t\t\t\t\t\t'launcherId', launcher_id,\n\t\t\t\t\t\t\t'launcherInput', json(launcher_input_json),\n\t\t\t\t\t\t\t'selectedSkillIds', json(selected_skill_ids_json)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tFROM process_launch_intents\n\t\t\t\t\t\tWHERE instance_id = process_instances.id\n\t\t\t\t\t)\n\t\t\t\t\tWHERE launch_intent_json IS NULL\n\t\t\t\t\t\tAND id IN (SELECT instance_id FROM process_launch_intents);\n\t\t\t\t\tDROP TABLE process_launch_intents;\n\t\t\t\t`);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20260725_add_process_relations_and_tool_approvals\",\n\t\ttableNames: [\"process_relations\", \"process_tool_approval_requests\"],\n\t\tmatches: (sqlite) =>\n\t\t\thasExistingSchema(sqlite) &&\n\t\t\t(existingTableSql(sqlite, \"process_relations\") === null ||\n\t\t\t\texistingTableSql(sqlite, \"process_tool_approval_requests\") === null),\n\t\tapply(sqlite) {\n\t\t\tif (existingTableSql(sqlite, \"process_relations\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.processRelations);\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"process_tool_approval_requests\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.processToolApprovalRequests);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20260724_remove_provider_credential_schema_version\",\n\t\ttableNames: [\"provider_credentials\"],\n\t\tmatches: (sqlite) =>\n\t\t\tnormalizeCreateTableSql(existingTableSql(sqlite, \"provider_credentials\") ?? \"\") ===\n\t\t\tnormalizeCreateTableSql(PROVIDER_CREDENTIALS_WITH_SCHEMA_VERSION_SQL),\n\t\tapply(sqlite) {\n\t\t\tsqlite.exec(\n\t\t\t\t\"ALTER TABLE provider_credentials RENAME TO provider_credentials_before_20260724\",\n\t\t\t);\n\t\t\tsqlite.exec(createTableSql(schema.providerCredentials));\n\t\t\tsqlite.exec(`INSERT INTO provider_credentials\n\t\t\t\t(provider_id, revision, encrypted_payload, created_at, updated_at)\n\t\t\tSELECT provider_id, revision, encrypted_payload, created_at, updated_at\n\t\t\tFROM provider_credentials_before_20260724`);\n\t\t\tsqlite.exec(\"DROP TABLE provider_credentials_before_20260724\");\n\t\t},\n\t},\n\t{\n\t\t// Runs before 20260821 so its legacy turn_records validation sees these columns.\n\t\tid: \"20260922_add_mapped_llm_runs\",\n\t\ttableNames: [\"mapped_llm_runs\", \"mapped_llm_items\", \"turn_records\", \"turn_start_records\"],\n\t\tmatches: (sqlite) =>\n\t\t\thasExistingSchema(sqlite) &&\n\t\t\t(existingTableSql(sqlite, \"mapped_llm_runs\") === null ||\n\t\t\t\texistingTableSql(sqlite, \"mapped_llm_items\") === null ||\n\t\t\t\t!tableHasColumn(sqlite, \"turn_records\", \"mapped_run_id\") ||\n\t\t\t\t!tableHasColumn(sqlite, \"turn_start_records\", \"mapped_run_id\")),\n\t\tapply(sqlite) {\n\t\t\tfor (const table of [\"turn_records\", \"turn_start_records\"]) {\n\t\t\t\tif (!tableHasColumn(sqlite, table, \"mapped_run_id\")) {\n\t\t\t\t\tsqlite.exec(`ALTER TABLE ${table} ADD COLUMN mapped_run_id text;\n\t\t\t\t\t\tALTER TABLE ${table} ADD COLUMN mapped_item_key text;\n\t\t\t\t\t\tALTER TABLE ${table} ADD COLUMN mapped_item_index integer;`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"mapped_llm_runs\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.mappedLlmRuns);\n\t\t\t}\n\t\t\tif (existingTableSql(sqlite, \"mapped_llm_items\") === null) {\n\t\t\t\tcreateTableWithIndexes(sqlite, schema.mappedLlmItems);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20260821_remove_server_automatic_execution\",\n\t\ttableNames: [\"process_instances\", \"turn_records\"],\n\t\tmatches: (sqlite) =>\n\t\t\ttableHasColumn(sqlite, \"process_instances\", \"current_server_turn_record_id\") ||\n\t\t\t(existingTableSql(sqlite, \"turn_records\") ?? \"\").includes(\"server_automatic\"),\n\t\tvalidateSource(sqlite, sqlitePath) {\n\t\t\t// Earlier migrations restore model provenance and launch-intent columns first.\n\t\t\t// Validate the complete source before rebuilding either table loses its DDL.\n\t\t\tconst legacyProcessSql = createTableSql(schema.processInstances)\n\t\t\t\t.replace(\"(\\n\", \"(\\ncurrent_server_turn_record_id text,\\n\")\n\t\t\t\t.replace(\n\t\t\t\t\t/\\n\\)$/,\n\t\t\t\t\t`,\n\t\t\t\tCONSTRAINT process_instances_one_current_execution CHECK (not (\"process_instances\".\"current_worker_start_id\" is not null and \"process_instances\".\"current_server_turn_record_id\" is not null)),\n\t\t\t\tCONSTRAINT fk_process_instances_server_turn FOREIGN KEY (id, current_server_turn_record_id) REFERENCES turn_records(instance_id, id)\n\t\t\t\t)`,\n\t\t\t\t);\n\t\t\tconst legacyTurnSql = createTableSql(schema.turnRecords).replace(\n\t\t\t\t\"in ('llm', 'human', 'external', 'automatic')\",\n\t\t\t\t\"in ('llm', 'human', 'external', 'automatic', 'server_automatic')\",\n\t\t\t);\n\t\t\tfor (const [table, expectedSql] of [\n\t\t\t\t[schema.processInstances, legacyProcessSql],\n\t\t\t\t[schema.turnRecords, legacyTurnSql],\n\t\t\t] as const) {\n\t\t\t\tassertMigrationSource(\n\t\t\t\t\tsqlite,\n\t\t\t\t\tsqlitePath,\n\t\t\t\t\tgetTableName(table),\n\t\t\t\t\texpectedSql,\n\t\t\t\t\tgenerateCreateIndexDDL(table),\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tapply(sqlite) {\n\t\t\tconst endedAt = new Date().toISOString();\n\t\t\tsqlite\n\t\t\t\t.prepare(`UPDATE turn_records\n\t\t\t\t\tSET status = 'failed',\n\t\t\t\t\t\terror_summary = coalesce(error_summary, 'Server-automatic execution was removed'),\n\t\t\t\t\t\tended_at = coalesce(ended_at, ?)\n\t\t\t\t\tWHERE turn_type = 'server_automatic' AND status = 'running'`)\n\t\t\t\t.run(endedAt);\n\t\t\tsqlite\n\t\t\t\t.prepare(`UPDATE process_instances\n\t\t\t\t\tSET lifecycle_status = 'aborted',\n\t\t\t\t\t\tclosed_at = coalesce(closed_at, ?),\n\t\t\t\t\t\tupdated_at = ?\n\t\t\t\t\tWHERE current_server_turn_record_id IS NOT NULL`)\n\t\t\t\t.run(endedAt, endedAt);\n\t\t\tsqlite\n\t\t\t\t.prepare(`INSERT INTO worker_leases\n\t\t\t\t\t(id, instance_id, worker_id, state, started_at, exited_at)\n\t\t\t\tSELECT 'wkr_migrated_20260821_' || id, instance_id,\n\t\t\t\t\t'server-automatic-migration:' || id, 'exited', started_at, coalesce(ended_at, ?)\n\t\t\t\tFROM turn_records WHERE turn_type = 'server_automatic'`)\n\t\t\t\t.run(endedAt);\n\t\t\tsqlite\n\t\t\t\t.prepare(`INSERT INTO turn_start_records\n\t\t\t\t\t(id, instance_id, turn_id, turn_type, proposed_turn_record_id, start_kind,\n\t\t\t\t\t state_json, created_at, updated_at)\n\t\t\t\tSELECT 'tsr_migrated_20260821_' || id, instance_id, turn_id, 'automatic', id,\n\t\t\t\t\t'selected_turn',\n\t\t\t\t\tjson_object(\n\t\t\t\t\t\t'kind', 'accepted',\n\t\t\t\t\t\t'start', json_object('kind', 'automatic'),\n\t\t\t\t\t\t'turnRecordId', id,\n\t\t\t\t\t\t'acceptedWorkerLeaseId', 'wkr_migrated_20260821_' || id,\n\t\t\t\t\t\t'acceptedAt', coalesce(ended_at, ?)\n\t\t\t\t\t),\n\t\t\t\t\tstarted_at, coalesce(ended_at, ?)\n\t\t\t\tFROM turn_records WHERE turn_type = 'server_automatic'`)\n\t\t\t\t.run(endedAt, endedAt);\n\t\t\tconst stagedProcesses = \"staged_process_instances_20260821\";\n\t\t\tconst stagedTurns = \"staged_turn_records_20260821\";\n\t\t\tsqlite.exec(`\n\t\t\t\tCREATE TEMP TABLE ${stagedProcesses} AS\n\t\t\t\tSELECT id, process_id, selected_turn_id, lifecycle_status, current_worker_start_id,\n\t\t\t\t\tplan_revision, title, external_id, external_url, metadata, default_model_profile_id,\n\t\t\t\t\tturn_configs_json, selected_turn_model_profile_id, params_json, state_json,\n\t\t\t\t\tcreated_at, updated_at, closed_at, initial_default_model_profile_id,\n\t\t\t\t\tselected_turn_model_source, selected_turn_model_kind, launch_intent_json\n\t\t\t\tFROM process_instances;\n\n\t\t\t\tCREATE TEMP TABLE ${stagedTurns} AS\n\t\t\t\tSELECT id, instance_id, turn_id,\n\t\t\t\t\tCASE turn_type WHEN 'server_automatic' THEN 'automatic' ELSE turn_type END AS turn_type,\n\t\t\t\t\tstatus, attempt_number, parent_turn_record_id,\n\t\t\t\t\tCASE turn_type\n\t\t\t\t\t\tWHEN 'server_automatic' THEN 'tsr_migrated_20260821_' || id\n\t\t\t\t\t\tELSE turn_start_record_id\n\t\t\t\t\tEND AS turn_start_record_id,\n\t\t\t\t\tCASE turn_type\n\t\t\t\t\t\tWHEN 'server_automatic' THEN 'wkr_migrated_20260821_' || id\n\t\t\t\t\t\tELSE accepted_worker_lease_id\n\t\t\t\t\tEND AS accepted_worker_lease_id,\n\t\t\t\t\tpath_type, fork_pi_entry_id, result_pi_entry_id,\n\t\t\t\t\tmodel_profile_id, turn_result_markdown, error_summary, error_class, started_at,\n\t\t\t\t\tended_at, model_selection_kind, model_selection_source\n\t\t\t\tFROM turn_records;\n\n\t\t\t\tDROP TABLE turn_records;\n\t\t\t\tDROP TABLE process_instances;\n\t\t\t`);\n\t\t\tsqlite.exec(createTableSql(schema.processInstances));\n\t\t\tsqlite.exec(createTableSql(schema.turnRecords));\n\t\t\tsqlite.exec(`\n\t\t\t\tINSERT INTO process_instances (\n\t\t\t\t\tid, process_id, selected_turn_id, lifecycle_status, current_worker_start_id,\n\t\t\t\t\tplan_revision, title, external_id, external_url, metadata, default_model_profile_id,\n\t\t\t\t\tturn_configs_json, selected_turn_model_profile_id, params_json, state_json,\n\t\t\t\t\tcreated_at, updated_at, closed_at, initial_default_model_profile_id,\n\t\t\t\t\tselected_turn_model_source, selected_turn_model_kind, launch_intent_json\n\t\t\t\t)\n\t\t\t\tSELECT * FROM ${stagedProcesses};\n\n\t\t\t\tINSERT INTO turn_records (\n\t\t\t\t\tid, instance_id, turn_id, turn_type, status, attempt_number, parent_turn_record_id,\n\t\t\t\t\tturn_start_record_id, accepted_worker_lease_id, path_type, fork_pi_entry_id,\n\t\t\t\t\tresult_pi_entry_id, model_profile_id, turn_result_markdown, error_summary,\n\t\t\t\t\terror_class, started_at, ended_at, model_selection_kind, model_selection_source\n\t\t\t\t)\n\t\t\t\tSELECT * FROM ${stagedTurns};\n\t\t\t\tDROP TABLE ${stagedProcesses};\n\t\t\t\tDROP TABLE ${stagedTurns};\n\t\t\t`);\n\t\t\tfor (const table of [schema.processInstances, schema.turnRecords]) {\n\t\t\t\tfor (const statement of generateCreateIndexDDL(table)) sqlite.exec(statement);\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tid: \"20261005_add_process_history_indexes\",\n\t\ttableNames: [],\n\t\tlegacyIndexNames: [...HISTORY_INDEXES, \"idx_leaf_outcomes_anchored\"],\n\t\tmatches(sqlite) {\n\t\t\tconst indexes = existingSchemaObjects(sqlite, \"index\");\n\t\t\treturn (\n\t\t\t\thasExistingSchema(sqlite) &&\n\t\t\t\t(indexes.has(\"idx_leaf_outcomes_anchored\") ||\n\t\t\t\t\tHISTORY_INDEXES.some((name) => !indexes.has(name)))\n\t\t\t);\n\t\t},\n\t\tapply(sqlite) {\n\t\t\tsqlite.exec(`CREATE INDEX IF NOT EXISTS idx_turn_records_page ON turn_records(instance_id, started_at, id);\nCREATE INDEX IF NOT EXISTS idx_turn_annotations_created ON turn_annotations(instance_id, created_at);\nCREATE INDEX IF NOT EXISTS idx_worker_leases_started ON worker_leases(instance_id, started_at);\nCREATE INDEX IF NOT EXISTS idx_worker_leases_exited ON worker_leases(instance_id, exited_at);\nDROP INDEX IF EXISTS idx_leaf_outcomes_anchored;`);\n\t\t},\n\t},\n];\n\nfunction backupSqliteFiles(sqlite: DatabaseSync, sqlitePath: string): string {\n\tconst stamp = new Date().toISOString().replaceAll(/[:.]/g, \"-\");\n\tconst backupDir = join(dirname(sqlitePath), \"backups\");\n\tmkdirSync(backupDir, { recursive: true });\n\tconst backupBasePath = join(backupDir, `${basename(sqlitePath)}.${stamp}.bak`);\n\n\t// Fold committed WAL pages into the main file before taking the startup copy.\n\tsqlite.prepare(\"PRAGMA wal_checkpoint(TRUNCATE)\").all();\n\tfor (const suffix of [\"\", \"-wal\", \"-shm\"]) {\n\t\tconst source = `${sqlitePath}${suffix}`;\n\t\tif (existsSync(source)) copyFileSync(source, `${backupBasePath}${suffix}`);\n\t}\n\treturn backupBasePath;\n}\n\nexport interface AppliedMigrationSummary {\n\tbackupPath: string;\n\tmigrationIds: string[];\n}\n\nexport function applyKnownMigrations(\n\tsqlite: DatabaseSync,\n\tsqlitePath: string,\n): AppliedMigrationSummary | null {\n\tconst migrations = KNOWN_MIGRATIONS.filter((migration) => migration.matches(sqlite));\n\tif (migrations.length === 0) return null;\n\n\tconst migratingTables = new Set(migrations.flatMap((migration) => migration.tableNames));\n\tconst migratingLegacyIndexes = new Set(\n\t\tmigrations.flatMap((migration) => migration.legacyIndexNames ?? []),\n\t);\n\tassertBaselineSchema(sqlite, sqlitePath, migratingTables, migratingLegacyIndexes);\n\tconst backupPath = backupSqliteFiles(sqlite, sqlitePath);\n\tsqlite.exec(\"PRAGMA foreign_keys = OFF\");\n\ttry {\n\t\tsqlite.exec(\"BEGIN\");\n\t\ttry {\n\t\t\tfor (const migration of migrations) {\n\t\t\t\tmigration.validateSource?.(sqlite, sqlitePath);\n\t\t\t\tmigration.apply(sqlite);\n\t\t\t}\n\t\t\tassertBaselineSchema(sqlite, sqlitePath);\n\t\t\tconst violations = sqlite.prepare(\"PRAGMA foreign_key_check\").all();\n\t\t\tif (violations.length > 0) {\n\t\t\t\tthrow new Error(`SQLite migration produced ${violations.length} foreign-key violation(s)`);\n\t\t\t}\n\t\t\tsqlite.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\tsqlite.exec(\"ROLLBACK\");\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\tsqlite.exec(\"PRAGMA foreign_keys = ON\");\n\t}\n\treturn { backupPath, migrationIds: migrations.map((migration) => migration.id) };\n}\n\n/** @internal */\nexport function initializeSchema(sqlite: DatabaseSync, opts: InitializeSchemaOptions = {}) {\n\tconst sqlitePath = opts.sqlitePath ?? \":memory:\";\n\tfor (const table of ALL_TABLES) {\n\t\tcreateTableWithIndexes(sqlite, table);\n\t\tassertCompatibleTableSchema(sqlite, table, sqlitePath);\n\t}\n}\n\n/** @internal */\nexport function createDatabase(opts: DatabaseOptions) {\n\tconst fileBacked = opts.sqlitePath !== \":memory:\";\n\tconst existingFileBackedDatabase = fileBacked && existsSync(opts.sqlitePath);\n\tif (fileBacked) {\n\t\tmkdirSync(dirname(opts.sqlitePath), { recursive: true });\n\t}\n\n\tconst sqlite = new DatabaseSync(opts.sqlitePath, { timeout: 5_000 });\n\ttry {\n\t\tif (opts.enableWAL !== false) {\n\t\t\tsqlite.prepare(\"PRAGMA journal_mode = WAL\").get();\n\t\t}\n\t\tsqlite.exec(\"PRAGMA foreign_keys = ON\");\n\n\t\tif (existingFileBackedDatabase && hasExistingSchema(sqlite)) {\n\t\t\tconst applied = applyKnownMigrations(sqlite, opts.sqlitePath);\n\t\t\tif (applied) {\n\t\t\t\tconsole.info(\n\t\t\t\t\t`[database] Applied SQLite migration(s): ${applied.migrationIds.join(\", \")}. Backup: ${applied.backupPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBaselineSchema(sqlite, opts.sqlitePath);\n\t\t} else {\n\t\t\tinitializeSchema(sqlite, { sqlitePath: opts.sqlitePath });\n\t\t}\n\t\treturn drizzle({ client: sqlite });\n\t} catch (error) {\n\t\tsqlite.close();\n\t\tthrow error;\n\t}\n}\n\n/** @internal */\nexport function createInMemoryDatabase() {\n\treturn createDatabase({ sqlitePath: \":memory:\", enableWAL: false });\n}\n\n/** @internal */\nexport function closeDatabase(db: LeitwerkDb): void {\n\tconst sqlite = (db as unknown as { $client?: DatabaseSync }).$client;\n\tsqlite?.close();\n}\n","import { wikiTopics } from \"@leitwerk-dev/wiki/server\";\n\nexport { wikiPages, wikiRevisions, wikiTopics } from \"@leitwerk-dev/wiki/server\";\n\nimport {\n\ttype MappedItem,\n\ttype MappedRunStatus,\n\tSERIALIZED_SYSTEM_ACTOR,\n} from \"@leitwerk-dev/domain\";\nimport type { SkillRevisionProvenance } from \"@leitwerk-dev/protocol\";\nimport type { SessionTransferPhase } from \"@leitwerk-dev/session-transfer\";\nimport { sql } from \"drizzle-orm\";\nimport {\n\tblob,\n\tcheck,\n\tindex,\n\tinteger,\n\tsqliteTable,\n\ttext,\n\tuniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nexport const topicPublications = sqliteTable(\n\t\"topic_publications\",\n\t{\n\t\tkey: text(\"key\").primaryKey(),\n\t\ttopicId: text(\"topic_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => wikiTopics.id),\n\t\texternalId: text(\"external_id\"),\n\t\tdata: text(\"data\").notNull(),\n\t},\n\t(table) => [uniqueIndex(\"idx_topic_publications_external\").on(table.externalId)],\n);\n\nexport const startupObservations = sqliteTable(\n\t\"startup_observations\",\n\t{\n\t\tworkerLeaseId: text(\"worker_lease_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => workerLeases.id, { onDelete: \"cascade\" }),\n\t\tmilestone: text(\"milestone\").notNull(),\n\t\tobservationJson: text(\"observation_json\").notNull(),\n\t},\n\t(t) => [uniqueIndex(\"idx_startup_observations_lease_milestone\").on(t.workerLeaseId, t.milestone)],\n);\n\nexport const inspectionContents = sqliteTable(\"inspection_contents\", {\n\tdigest: text(\"digest\").primaryKey(),\n\tcontentJson: text(\"content_json\").notNull(),\n});\n\nexport const executionInspections = sqliteTable(\n\t\"execution_inspections\",\n\t{\n\t\tsequence: integer(\"sequence\").primaryKey({ autoIncrement: true }),\n\t\tid: text(\"id\").notNull(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnRecordId: text(\"turn_record_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => turnRecords.id, { onDelete: \"cascade\" }),\n\t\tstartRecordId: text(\"start_record_id\").notNull(),\n\t\tworkerLeaseId: text(\"worker_lease_id\").notNull(),\n\t\tcapturedAt: text(\"captured_at\").notNull(),\n\t\tfactJson: text(\"fact_json\").notNull(),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"idx_execution_inspections_id\").on(t.id),\n\t\tindex(\"idx_execution_inspections_turn\").on(t.instanceId, t.turnRecordId),\n\t],\n);\n\nexport const processInstances = sqliteTable(\n\t\"process_instances\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tprocessId: text(\"process_id\").notNull(),\n\t\tselectedTurnId: text(\"selected_turn_id\"),\n\t\tlifecycleStatus: text(\"lifecycle_status\").notNull().default(\"discovered\"),\n\t\tcurrentWorkerStartId: text(\"current_worker_start_id\"),\n\t\tplanRevision: integer(\"plan_revision\").notNull().default(0),\n\t\ttitle: text(\"title\"),\n\t\texternalId: text(\"external_id\"),\n\t\texternalUrl: text(\"external_url\"),\n\t\tmetadata: text(\"metadata\"),\n\t\tdefaultModelProfileId: text(\"default_model_profile_id\"),\n\t\tturnConfigsJson: text(\"turn_configs_json\"),\n\t\tselectedTurnModelProfileId: text(\"selected_turn_model_profile_id\"),\n\t\tparamsJson: text(\"params_json\"),\n\t\tstateJson: text(\"state_json\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\tclosedAt: text(\"closed_at\"),\n\t\t// ALTER TABLE appends migrated columns; keep these in migration order so\n\t\t// durable databases and newly initialized databases have the same schema.\n\t\tinitialDefaultModelProfileId: text(\"initial_default_model_profile_id\"),\n\t\tselectedTurnModelSource: text(\"selected_turn_model_source\"),\n\t\tselectedTurnModelKind: text(\"selected_turn_model_kind\"),\n\t\tlaunchIntentJson: text(\"launch_intent_json\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_process_instances_selected_turn\").on(t.selectedTurnId),\n\t\tindex(\"idx_process_instances_external_id\").on(t.externalId),\n\t\tindex(\"idx_process_instances_process\").on(t.processId),\n\t],\n);\n\nexport const launchRuns = sqliteTable(\n\t\"launch_runs\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tidempotencyKey: text(\"idempotency_key\").unique(),\n\t\tlauncherId: text(\"launcher_id\"),\n\t\torigin: text(\"origin\").notNull(),\n\t\tinstanceId: text(\"instance_id\").references(() => processInstances.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tstatus: text(\"status\").notNull(),\n\t\tstepsJson: text(\"steps_json\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\tcompletedAt: text(\"completed_at\"),\n\t\trevision: integer(\"revision\").notNull().default(0),\n\t},\n\t(t) => [\n\t\tindex(\"idx_launch_runs_instance\").on(t.instanceId),\n\t\tindex(\"idx_launch_runs_status\").on(t.status),\n\t],\n);\n\nexport const launchRunReplays = sqliteTable(\"launch_run_replays\", {\n\tlaunchRunId: text(\"launch_run_id\")\n\t\t.primaryKey()\n\t\t.references(() => launchRuns.id, { onDelete: \"cascade\" }),\n\tpayloadJson: text(\"payload_json\").notNull(),\n});\n\nexport const skills = sqliteTable(\"skills\", {\n\tid: text(\"id\").primaryKey(),\n\tlabel: text(\"label\").notNull(),\n\tdescription: text(\"description\"),\n\tactiveRevisionId: text(\"active_revision_id\"),\n\tcreatedAt: text(\"created_at\").notNull(),\n\tupdatedAt: text(\"updated_at\").notNull(),\n\townerExtensionId: text(\"owner_extension_id\"),\n\tregistrationKind: text(\"registration_kind\", { enum: [\"configuration\", \"catalog\", \"extension\"] })\n\t\t.notNull()\n\t\t.default(\"configuration\"),\n});\n\nexport const skillRevisions = sqliteTable(\n\t\"skill_revisions\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tskillId: text(\"skill_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skills.id),\n\t\tbundleDigest: text(\"bundle_digest\").notNull(),\n\t\tbundleBytes: blob(\"bundle_bytes\", { mode: \"buffer\" }).notNull(),\n\t\tprovenance: text(\"provenance_json\", { mode: \"json\" }).$type<SkillRevisionProvenance>(),\n\t\tsourceRevision: text(\"source_revision\"),\n\t\timportedAt: text(\"imported_at\").notNull(),\n\t},\n\t(t) => [uniqueIndex(\"uq_skill_revisions_skill_digest\").on(t.skillId, t.bundleDigest)],\n);\n\nexport const skillRevisionDependencies = sqliteTable(\n\t\"skill_revision_dependencies\",\n\t{\n\t\tskillRevisionId: text(\"skill_revision_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skillRevisions.id, { onDelete: \"cascade\" }),\n\t\tdependencySkillId: text(\"dependency_skill_id\").notNull(),\n\t\tposition: integer(\"position\").notNull(),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_skill_revision_dependency\").on(t.skillRevisionId, t.dependencySkillId),\n\t\tuniqueIndex(\"uq_skill_revision_dependency_position\").on(t.skillRevisionId, t.position),\n\t],\n);\n\nexport const skillCatalogEntries = sqliteTable(\n\t\"skill_catalog_entries\",\n\t{\n\t\trepositoryId: text(\"repository_id\").notNull(),\n\t\tskillId: text(\"skill_id\").notNull(),\n\t\tlabel: text(\"label\").notNull(),\n\t\tdescription: text(\"description\"),\n\t\tsourcePath: text(\"source_path\").notNull(),\n\t\tsourceRevision: text(\"source_revision\").notNull(),\n\t\tbundleDigest: text(\"bundle_digest\").notNull(),\n\t\tbundleBytes: blob(\"bundle_bytes\", { mode: \"buffer\" }).notNull(),\n\t\tdiscoveredAt: text(\"discovered_at\").notNull(),\n\t\tavailable: integer(\"available\", { mode: \"boolean\" }).notNull().default(true),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_skill_catalog_entry\").on(t.repositoryId, t.skillId),\n\t\tindex(\"idx_skill_catalog_skill\").on(t.skillId),\n\t],\n);\n\nexport const processSkills = sqliteTable(\n\t\"process_skills\",\n\t{\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tskillId: text(\"skill_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skills.id),\n\t\tskillRevisionId: text(\"skill_revision_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skillRevisions.id),\n\t\tposition: integer(\"position\").notNull(),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_process_skills_instance_skill\").on(t.instanceId, t.skillId),\n\t\tuniqueIndex(\"uq_process_skills_instance_position\").on(t.instanceId, t.position),\n\t],\n);\n\nexport const skillInvocations = sqliteTable(\n\t\"skill_invocations\",\n\t{\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnRecordId: text(\"turn_record_id\").notNull(),\n\t\tskillId: text(\"skill_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skills.id),\n\t\tskillRevisionId: text(\"skill_revision_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => skillRevisions.id),\n\t\tinvokedAt: text(\"invoked_at\").notNull(),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_skill_invocation_turn_skill\").on(t.turnRecordId, t.skillId),\n\t\tindex(\"idx_skill_invocations_skill_time\").on(t.skillId, t.invokedAt),\n\t],\n);\n\nexport const processProjects = sqliteTable(\n\t\"process_projects\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tkey: text(\"key\").notNull(),\n\t\trepoLocator: text(\"repo_locator\").notNull(),\n\t\trepoLocatorKind: text(\"repo_locator_kind\").notNull(),\n\t\tbaseBranch: text(\"base_branch\").notNull(),\n\t\tworkBranch: text(\"work_branch\"),\n\t\texternalId: text(\"external_id\"),\n\t\texternalUrl: text(\"external_url\"),\n\t\tmetadata: text(\"metadata\"),\n\t\tpipelineStatus: text(\"pipeline_status\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_process_projects_instance\").on(t.instanceId),\n\t\tuniqueIndex(\"uq_process_projects_instance_key\").on(t.instanceId, t.key),\n\t],\n);\n\nexport const processInputs = sqliteTable(\n\t\"process_inputs\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tsequence: integer(\"sequence\").notNull(),\n\t\tsource: text(\"source\").notNull(),\n\t\tkind: text(\"kind\").notNull(),\n\t\ttargetSemanticRef: text(\"target_semantic_ref\"),\n\t\ttargetProductName: text(\"target_product_name\"),\n\t\tbodyMarkdown: text(\"body_markdown\").notNull(),\n\t\treceivedAt: text(\"received_at\").notNull(),\n\t\tconsumedAt: text(\"consumed_at\"),\n\t\t// Appended last to match `ALTER TABLE ... ADD COLUMN` ordering so a migrated\n\t\t// database stays schema-compatible with a freshly created one. The default is\n\t\t// the canonical serialized SYSTEM_ACTOR so the schema column default and the\n\t\t// runtime fallback share a single source of truth; the migration SQL must keep\n\t\t// the same literal, which the startup schema-compatibility guard enforces.\n\t\tactor: text(\"actor\").notNull().default(SERIALIZED_SYSTEM_ACTOR),\n\t},\n\t(t) => [\n\t\tindex(\"idx_process_inputs_instance\").on(t.instanceId),\n\t\tuniqueIndex(\"uq_process_inputs_instance_seq\").on(t.instanceId, t.sequence),\n\t\tindex(\"idx_process_inputs_unconsumed\").on(t.instanceId, t.consumedAt),\n\t],\n);\n\nexport const processEvents = sqliteTable(\n\t\"process_events\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\teventSequence: integer(\"event_sequence\").notNull(),\n\t\tturnRecordId: text(\"turn_record_id\"),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\teventType: text(\"event_type\").notNull(),\n\t\tdata: text(\"data\").notNull().default(\"{}\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_process_events_instance\").on(t.instanceId),\n\t\tindex(\"idx_process_events_instance_created\").on(t.instanceId, t.createdAt),\n\t\tindex(\"idx_process_events_instance_sequence\").on(t.instanceId, t.eventSequence),\n\t\tindex(\"idx_process_events_type\").on(t.eventType),\n\t\tuniqueIndex(\"uq_process_events_sequence\").on(t.eventSequence),\n\t\tindex(\"idx_process_events_turn_sequence\").on(t.instanceId, t.turnRecordId, t.eventSequence),\n\t\tindex(\"idx_process_events_turn_type_sequence\").on(\n\t\t\tt.instanceId,\n\t\t\tt.turnRecordId,\n\t\t\tt.eventType,\n\t\t\tt.eventSequence,\n\t\t),\n\t\tindex(\"idx_process_events_instance_type_sequence\").on(\n\t\t\tt.instanceId,\n\t\t\tt.eventType,\n\t\t\tt.eventSequence,\n\t\t),\n\t],\n);\n\nexport const futureExecutions = sqliteTable(\n\t\"future_executions\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tkind: text(\"kind\").notNull(),\n\t\tscheduleKind: text(\"schedule_kind\").notNull(),\n\t\tprocessId: text(\"process_id\").notNull(),\n\t\tinstanceId: text(\"instance_id\").references(() => processInstances.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tlauncherId: text(\"launcher_id\"),\n\t\tactionId: text(\"action_id\"),\n\t\tpayloadJson: text(\"payload_json\").notNull(),\n\t\tcronExpression: text(\"cron_expression\"),\n\t\tnextRunAt: text(\"next_run_at\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\t// Durable model-policy state. Appended in migration order.\n\t\tmodelProfileId: text(\"model_profile_id\"),\n\t\tmodelSelectionKind: text(\"model_selection_kind\"),\n\t\tmodelSelectionSource: text(\"model_selection_source\"),\n\t\tblockedReasonJson: text(\"blocked_reason_json\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_future_executions_next_run\").on(t.nextRunAt),\n\t\tindex(\"idx_future_executions_instance\").on(t.instanceId),\n\t\tindex(\"idx_future_executions_kind\").on(t.kind),\n\t\tuniqueIndex(\"uq_future_executions_action_instance\")\n\t\t\t.on(t.instanceId)\n\t\t\t.where(sql`${t.kind} = 'action'`),\n\t],\n);\n\nexport const launcherRecentValues = sqliteTable(\n\t\"launcher_recent_values\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tlauncherId: text(\"launcher_id\").notNull(),\n\t\tfieldId: text(\"field_id\").notNull(),\n\t\tvalue: text(\"value\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_launcher_recent_values_launcher_field\").on(t.launcherId, t.fieldId),\n\t\tindex(\"idx_launcher_recent_values_updated\").on(t.launcherId, t.fieldId, t.updatedAt),\n\t\tuniqueIndex(\"uq_launcher_recent_values_value\").on(t.launcherId, t.fieldId, t.value),\n\t],\n);\n\nexport const ticketDestinationRecents = sqliteTable(\n\t\"ticket_destination_recents\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tactorKey: text(\"actor_key\").notNull(),\n\t\ttoolName: text(\"tool_name\").notNull(),\n\t\tdestinationId: text(\"destination_id\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_ticket_destination_recents_actor_tool\").on(t.actorKey, t.toolName, t.updatedAt),\n\t\tuniqueIndex(\"uq_ticket_destination_recent\").on(t.actorKey, t.toolName, t.destinationId),\n\t],\n);\n\nexport const processTitleJobs = sqliteTable(\n\t\"process_title_jobs\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\ttargetKind: text(\"target_kind\", { enum: [\"process\", \"future_execution\"] }).notNull(),\n\t\tprocessDefinitionId: text(\"process_definition_id\").notNull(),\n\t\tprocessInstanceId: text(\"process_instance_id\").references(() => processInstances.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tfutureExecutionId: text(\"future_execution_id\").references(() => futureExecutions.id, {\n\t\t\tonDelete: \"cascade\",\n\t\t}),\n\t\tlaunchRunId: text(\"launch_run_id\").references(() => launchRuns.id, {\n\t\t\tonDelete: \"set null\",\n\t\t}),\n\t\tmodelProfileId: text(\"model_profile_id\").notNull(),\n\t\tprompt: text(\"prompt\").notNull(),\n\t\texpectedPayloadJson: text(\"expected_payload_json\"),\n\t\tstatus: text(\"status\", {\n\t\t\tenum: [\"pending\", \"running\", \"completed\", \"superseded\", \"failed\"],\n\t\t}).notNull(),\n\t\tattemptCount: integer(\"attempt_count\").notNull().default(0),\n\t\tmaxAttempts: integer(\"max_attempts\").notNull(),\n\t\tnextRunAt: text(\"next_run_at\").notNull(),\n\t\tlastError: text(\"last_error\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_process_title_jobs_due\").on(t.status, t.nextRunAt),\n\t\tindex(\"idx_process_title_jobs_process_instance\").on(t.processInstanceId),\n\t\tindex(\"idx_process_title_jobs_future_execution\").on(t.futureExecutionId),\n\t\tindex(\"idx_process_title_jobs_launch_run\").on(t.launchRunId),\n\t],\n);\n\nexport const processHandoffDedupKeys = sqliteTable(\n\t\"process_handoff_dedup_keys\",\n\t{\n\t\tkey: text(\"key\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tmetadata: text(\"metadata\").notNull().default(\"{}\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_handoff_dedup_keys_instance\").on(t.instanceId),\n\t\tuniqueIndex(\"uq_handoff_dedup_keys_instance\").on(t.instanceId),\n\t],\n);\n\nexport const processLeafOutcomeSnapshots = sqliteTable(\n\t\"process_leaf_outcome_snapshots\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tleafEntryId: text(\"leaf_entry_id\").notNull(),\n\t\tturnRecordId: text(\"turn_record_id\"),\n\t\trendererId: text(\"renderer_id\"),\n\t\tschemaVersion: integer(\"schema_version\"),\n\t\tpropsJson: text(\"props_json\"),\n\t\tfallbackMarkdown: text(\"fallback_markdown\"),\n\t\tstatus: text(\"status\").notNull(),\n\t\twarningCode: text(\"warning_code\"),\n\t\twarningMessage: text(\"warning_message\"),\n\t\tanchoredAt: text(\"anchored_at\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_leaf_outcome_snapshots_instance\").on(t.instanceId),\n\t\tindex(\"idx_leaf_outcome_snapshots_instance_anchor\").on(t.instanceId, t.anchoredAt),\n\t\tuniqueIndex(\"uq_leaf_outcome_snapshots_instance_leaf\").on(t.instanceId, t.leafEntryId),\n\t],\n);\n\nexport const turnRecords = sqliteTable(\n\t\"turn_records\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnId: text(\"turn_id\").notNull(),\n\t\tturnType: text(\"turn_type\").notNull().default(\"llm\"),\n\t\tstatus: text(\"status\").notNull(),\n\t\tattemptNumber: integer(\"attempt_number\").notNull().default(1),\n\t\tparentTurnRecordId: text(\"parent_turn_record_id\"),\n\t\tturnStartRecordId: text(\"turn_start_record_id\"),\n\t\tacceptedWorkerLeaseId: text(\"accepted_worker_lease_id\"),\n\t\tpathType: text(\"path_type\").notNull().default(\"primary\"),\n\t\tforkPiEntryId: text(\"fork_pi_entry_id\"),\n\t\tresultPiEntryId: text(\"result_pi_entry_id\"),\n\t\tmodelProfileId: text(\"model_profile_id\"),\n\t\tturnResultMarkdown: text(\"turn_result_markdown\"),\n\t\terrorSummary: text(\"error_summary\"),\n\t\terrorClass: text(\"error_class\"),\n\t\tstartedAt: text(\"started_at\").notNull(),\n\t\tendedAt: text(\"ended_at\"),\n\t\tmodelSelectionKind: text(\"model_selection_kind\"),\n\t\tmodelSelectionSource: text(\"model_selection_source\"),\n\t\tmappedRunId: text(\"mapped_run_id\"),\n\t\tmappedItemKey: text(\"mapped_item_key\"),\n\t\tmappedItemIndex: integer(\"mapped_item_index\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_turn_records_page\").on(t.instanceId, t.startedAt, t.id),\n\t\tuniqueIndex(\"uq_turn_records_instance_id\").on(t.instanceId, t.id),\n\t\tuniqueIndex(\"uq_turn_records_turn_start_record\").on(t.turnStartRecordId),\n\t\tindex(\"idx_turn_records_instance\").on(t.instanceId),\n\t\tindex(\"idx_turn_records_status\").on(t.status),\n\t\tindex(\"idx_turn_records_instance_started\").on(t.instanceId, t.startedAt),\n\t\tcheck(\n\t\t\t\"turn_records_worker_start_link\",\n\t\t\tsql`((${t.turnType} in ('llm', 'automatic')) and ${t.turnStartRecordId} is not null and ${t.acceptedWorkerLeaseId} is not null) or ((${t.turnType} not in ('llm', 'automatic')) and ${t.turnStartRecordId} is null and ${t.acceptedWorkerLeaseId} is null)`,\n\t\t),\n\t\tcheck(\"turn_records_type\", sql`${t.turnType} in ('llm', 'human', 'external', 'automatic')`),\n\t],\n);\n\nexport const turnStartRecords = sqliteTable(\n\t\"turn_start_records\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnId: text(\"turn_id\").notNull(),\n\t\tturnType: text(\"turn_type\").notNull(),\n\t\tproposedTurnRecordId: text(\"proposed_turn_record_id\").notNull(),\n\t\tstartKind: text(\"start_kind\").notNull(),\n\t\trecoveryTurnRecordId: text(\"recovery_turn_record_id\"),\n\t\tcontinuationJson: text(\"continuation_json\"),\n\t\tstateJson: text(\"state_json\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\tmappedRunId: text(\"mapped_run_id\"),\n\t\tmappedItemKey: text(\"mapped_item_key\"),\n\t\tmappedItemIndex: integer(\"mapped_item_index\"),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_turn_start_records_proposed_turn_record\").on(t.proposedTurnRecordId),\n\t\tuniqueIndex(\"uq_turn_start_records_instance_id\").on(t.instanceId, t.id),\n\t\tuniqueIndex(\"uq_turn_start_records_acceptance_target\").on(\n\t\t\tt.id,\n\t\t\tt.instanceId,\n\t\t\tt.proposedTurnRecordId,\n\t\t\tt.turnId,\n\t\t),\n\t\tindex(\"idx_turn_start_records_instance_created\").on(t.instanceId, t.createdAt),\n\t\tindex(\"idx_turn_start_records_recovery\").on(t.recoveryTurnRecordId),\n\t\tcheck(\"turn_start_records_type\", sql`${t.turnType} in ('llm', 'automatic')`),\n\t\tcheck(\n\t\t\t\"turn_start_records_kind\",\n\t\t\tsql`${t.startKind} in ('selected_turn', 'retry', 'continue', 'startup_retry')`,\n\t\t),\n\t\tcheck(\n\t\t\t\"turn_start_records_state\",\n\t\t\tsql`json_valid(${t.stateJson}) and json_extract(${t.stateJson}, '$.kind') in ('preparation_failed', 'starting', 'bootstrap_failed', 'accepted', 'superseded')`,\n\t\t),\n\t\tcheck(\n\t\t\t\"turn_start_records_continuation\",\n\t\t\tsql`${t.continuationJson} is null or json_valid(${t.continuationJson})`,\n\t\t),\n\t],\n);\n\nexport const authSessions = sqliteTable(\n\t\"auth_sessions\",\n\t{\n\t\tidHash: text(\"id_hash\").primaryKey(),\n\t\tactorId: text(\"actor_id\").notNull(),\n\t\tactorProvider: text(\"actor_provider\"),\n\t\tdisplayName: text(\"display_name\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\texpiresAt: text(\"expires_at\").notNull(),\n\t\toidcEvidenceJson: text(\"oidc_evidence_json\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_auth_sessions_expires\").on(t.expiresAt),\n\t\tindex(\"idx_auth_sessions_actor\").on(t.actorId),\n\t],\n);\n\nexport const authLoginFlows = sqliteTable(\n\t\"auth_login_flows\",\n\t{\n\t\tidHash: text(\"id_hash\").primaryKey(),\n\t\tproviderId: text(\"provider_id\").notNull(),\n\t\tstate: text(\"state\").notNull(),\n\t\tpkceVerifier: text(\"pkce_verifier\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\texpiresAt: text(\"expires_at\").notNull(),\n\t},\n\t(t) => [index(\"idx_auth_login_flows_expires\").on(t.expiresAt)],\n);\n\nexport const turnAnnotations = sqliteTable(\n\t\"turn_annotations\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tannotationType: text(\"annotation_type\").notNull(),\n\t\t/**\n\t\t * Null means append-only: the annotation is valid, but it is not addressable\n\t\t * through key-based upsert/update mechanics.\n\t\t */\n\t\tannotationKey: text(\"annotation_key\"),\n\t\treferencesJson: text(\"references_json\").notNull().default(\"[]\"),\n\t\tpayloadJson: text(\"payload_json\").notNull().default(\"{}\"),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_turn_annotations_created\").on(t.instanceId, t.createdAt),\n\t\tindex(\"idx_turn_annotations_instance\").on(t.instanceId),\n\t\tindex(\"idx_turn_annotations_type\").on(t.annotationType),\n\t\tuniqueIndex(\"uq_turn_annotations_instance_key\").on(t.instanceId, t.annotationKey),\n\t],\n);\n\nexport const workerLeases = sqliteTable(\n\t\"worker_leases\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tworkerId: text(\"worker_id\").notNull(),\n\t\tstate: text(\"state\").notNull(),\n\t\tlastHeartbeatAt: text(\"last_heartbeat_at\"),\n\t\tstartedAt: text(\"started_at\").notNull(),\n\t\texitedAt: text(\"exited_at\"),\n\t\t// Keep migrated columns in `ALTER TABLE ... ADD COLUMN` order for existing DBs.\n\t\tserverEpoch: text(\"server_epoch\"),\n\t\tsnapshotTokenHash: text(\"snapshot_token_hash\"),\n\t\tconnectTokenHash: text(\"connect_token_hash\"),\n\t\tmodelPolicyFingerprint: text(\"model_policy_fingerprint\"),\n\t\tbootstrapReceiptJson: text(\"bootstrap_receipt_json\"),\n\t\tturnStartRecordId: text(\"turn_start_record_id\").references(() => turnStartRecords.id),\n\t\tconnectedAt: text(\"connected_at\"),\n\t\tworkspacePreparationStartedAt: text(\"workspace_preparation_started_at\"),\n\t\treadyAt: text(\"ready_at\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_worker_leases_exited\").on(t.instanceId, t.exitedAt),\n\t\tindex(\"idx_worker_leases_started\").on(t.instanceId, t.startedAt),\n\t\tuniqueIndex(\"uq_worker_leases_instance_id\").on(t.instanceId, t.id),\n\t\tindex(\"idx_worker_leases_instance\").on(t.instanceId),\n\t\tindex(\"idx_worker_leases_turn_start\").on(t.turnStartRecordId),\n\t\tuniqueIndex(\"uq_worker_leases_worker\").on(t.workerId),\n\t\tindex(\"idx_worker_leases_state\").on(t.state),\n\t],\n);\n\nexport const processRelations = sqliteTable(\n\t\"process_relations\",\n\t{\n\t\tparentInstanceId: text(\"parent_instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tchildInstanceId: text(\"child_instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tkind: text(\"kind\").notNull().default(\"derived\"),\n\t\tpurpose: text(\"purpose\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tcreatedByJson: text(\"created_by_json\").notNull(),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_process_relations_child\").on(t.childInstanceId),\n\t\tindex(\"idx_process_relations_parent\").on(t.parentInstanceId),\n\t\tcheck(\"process_relations_kind\", sql`${t.kind} = 'derived'`),\n\t\tcheck(\"process_relations_actor_json\", sql`json_valid(${t.createdByJson})`),\n\t\tcheck(\"process_relations_not_self\", sql`${t.parentInstanceId} <> ${t.childInstanceId}`),\n\t],\n);\n\nexport const processToolApprovalRequests = sqliteTable(\n\t\"process_tool_approval_requests\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnRecordId: text(\"turn_record_id\").notNull(),\n\t\ttoolCallId: text(\"tool_call_id\").notNull(),\n\t\ttoolName: text(\"tool_name\").notNull(),\n\t\targumentsJson: text(\"arguments_json\").notNull(),\n\t\tdestinationJson: text(\"destination_json\"),\n\t\tstatus: text(\"status\").notNull().default(\"open\"),\n\t\trequestedAt: text(\"requested_at\").notNull(),\n\t\tresolvedAt: text(\"resolved_at\"),\n\t\tresolvedByJson: text(\"resolved_by_json\"),\n\t\tfeedback: text(\"feedback\"),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_tool_approval_turn_call\").on(t.instanceId, t.turnRecordId, t.toolCallId),\n\t\tindex(\"idx_tool_approval_instance_status\").on(t.instanceId, t.status),\n\t\tcheck(\"tool_approval_arguments_json\", sql`json_valid(${t.argumentsJson})`),\n\t\tcheck(\n\t\t\t\"tool_approval_actor_json\",\n\t\t\tsql`${t.resolvedByJson} is null or json_valid(${t.resolvedByJson})`,\n\t\t),\n\t\tcheck(\n\t\t\t\"tool_approval_status\",\n\t\t\tsql`${t.status} in ('open', 'accepted', 'feedback', 'declined', 'cancelled')`,\n\t\t),\n\t],\n);\n\nexport const processQuestionRequests = sqliteTable(\n\t\"process_question_requests\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnRecordId: text(\"turn_record_id\").notNull(),\n\t\ttoolCallId: text(\"tool_call_id\").notNull(),\n\t\tquestionsJson: text(\"questions_json\").notNull(),\n\t\tstatus: text(\"status\").notNull().default(\"open\"),\n\t\tanswersJson: text(\"answers_json\"),\n\t\taskedAt: text(\"asked_at\").notNull(),\n\t\tansweredAt: text(\"answered_at\"),\n\t\tansweredByJson: text(\"answered_by_json\"),\n\t\tcancelledAt: text(\"cancelled_at\"),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_question_requests_turn_tool\").on(t.instanceId, t.turnRecordId, t.toolCallId),\n\t\tindex(\"idx_question_requests_instance_status\").on(t.instanceId, t.status),\n\t\tcheck(\"question_requests_status\", sql`${t.status} in ('open', 'answered', 'cancelled')`),\n\t\tcheck(\"question_requests_questions_json\", sql`json_valid(${t.questionsJson})`),\n\t\tcheck(\n\t\t\t\"question_requests_answers_json\",\n\t\t\tsql`${t.answersJson} is null or json_valid(${t.answersJson})`,\n\t\t),\n\t],\n);\n\nexport const providerCredentials = sqliteTable(\n\t\"provider_credentials\",\n\t{\n\t\tproviderId: text(\"provider_id\").primaryKey(),\n\t\trevision: integer(\"revision\").notNull(),\n\t\tencryptedPayload: text(\"encrypted_payload\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [check(\"provider_credentials_positive_revision\", sql`${t.revision} > 0`)],\n);\n\nexport const pendingExternalSourceFires = sqliteTable(\n\t\"pending_external_source_fires\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tarmingId: text(\"arming_id\").notNull(),\n\t\tturnId: text(\"turn_id\").notNull(),\n\t\texternalActionId: text(\"external_action_id\").notNull(),\n\t\tsourceKind: text(\"source_kind\").notNull().default(\"\"),\n\t\tinputJson: text(\"input_json\").notNull().default(\"{}\"),\n\t\teventJson: text(\"event_json\").notNull().default(\"{}\"),\n\t\tmergeKey: text(\"merge_key\"),\n\t\tqueuedCount: integer(\"queued_count\").notNull().default(1),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_pending_external_fires_instance\").on(t.instanceId),\n\t\tindex(\"idx_pending_external_fires_arming\").on(t.instanceId, t.armingId),\n\t\tindex(\"idx_pending_external_fires_created\").on(t.createdAt),\n\t\tuniqueIndex(\"uq_pending_external_fires_merge_key\")\n\t\t\t.on(t.instanceId, t.armingId, t.mergeKey)\n\t\t\t.where(sql`${t.mergeKey} is not null`),\n\t],\n);\n\nexport const sessionTransferGrants = sqliteTable(\n\t\"session_transfer_grants\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\ttokenHash: text(\"token_hash\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\texpiresAt: text(\"expires_at\").notNull(),\n\t\tconsumedAt: text(\"consumed_at\"),\n\t\ttombstoneUntil: text(\"tombstone_until\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_session_transfer_grants_instance\").on(t.instanceId),\n\t\tindex(\"idx_session_transfer_grants_expiry\").on(t.expiresAt),\n\t\tindex(\"idx_session_transfer_grants_tombstone\").on(t.tombstoneUntil),\n\t],\n);\n\nexport const sessionTransferAttempts = sqliteTable(\n\t\"session_transfer_attempts\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tgrantId: text(\"grant_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => sessionTransferGrants.id, { onDelete: \"cascade\" }),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tphase: text(\"phase\").$type<SessionTransferPhase>().notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tleaseUntil: text(\"lease_until\").notNull(),\n\t\thardDeadline: text(\"hard_deadline\").notNull(),\n\t\tentriesTotal: integer(\"entries_total\"),\n\t\tlogicalBytesTotal: integer(\"logical_bytes_total\"),\n\t\tcompressedBytes: integer(\"compressed_bytes\"),\n\t\tstreamSha256: text(\"stream_sha256\"),\n\t\tfailureCode: text(\"failure_code\"),\n\t\tcompletedAt: text(\"completed_at\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_session_transfer_attempts_grant\").on(t.grantId),\n\t\tindex(\"idx_session_transfer_attempts_instance\").on(t.instanceId),\n\t\tindex(\"idx_session_transfer_attempts_deadlines\").on(t.leaseUntil, t.hardDeadline),\n\t\tuniqueIndex(\"uq_session_transfer_active_instance\")\n\t\t\t.on(t.instanceId)\n\t\t\t.where(\n\t\t\t\tsql`${t.phase} in ('queued', 'waiting_for_execution_chain', 'stopping_worker', 'starting_exporter', 'scanning', 'ready_to_stream', 'streaming', 'awaiting_ack')`,\n\t\t\t),\n\t\tcheck(\n\t\t\t\"session_transfer_attempts_phase\",\n\t\t\tsql`${t.phase} in ('queued', 'waiting_for_execution_chain', 'stopping_worker', 'starting_exporter', 'scanning', 'ready_to_stream', 'streaming', 'awaiting_ack', 'consumed', 'cancelled', 'failed')`,\n\t\t),\n\t],\n);\n\nexport const externalWriteLog = sqliteTable(\n\t\"external_write_log\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\twriteType: text(\"write_type\").notNull(),\n\t\tdedupKey: text(\"dedup_key\").notNull(),\n\t\tcompletedAt: text(\"completed_at\").notNull(),\n\t\tmetadata: text(\"metadata\").notNull().default(\"{}\"),\n\t},\n\t(t) => [\n\t\tindex(\"idx_ewl_instance\").on(t.instanceId),\n\t\tuniqueIndex(\"uq_ewl_dedup_key\").on(t.dedupKey),\n\t\tindex(\"idx_ewl_write_type\").on(t.writeType),\n\t],\n);\n\nexport const mappedLlmRuns = sqliteTable(\n\t\"mapped_llm_runs\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tturnId: text(\"turn_id\").notNull(),\n\t\tstatus: text(\"status\").$type<MappedRunStatus>().notNull(),\n\t\titemCount: integer(\"item_count\").notNull(),\n\t\tnextIndex: integer(\"next_index\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t},\n\t(t) => [\n\t\tindex(\"idx_mapped_llm_runs_instance\").on(t.instanceId),\n\t\tuniqueIndex(\"uq_mapped_llm_runs_active_instance\")\n\t\t\t.on(t.instanceId)\n\t\t\t.where(sql`${t.status} = 'active'`),\n\t\tcheck(\"mapped_llm_runs_status\", sql`${t.status} in ('active', 'completed', 'aborted')`),\n\t\tcheck(\n\t\t\t\"mapped_llm_runs_progress\",\n\t\t\tsql`${t.itemCount} >= 0 and ${t.nextIndex} >= 0 and ${t.nextIndex} <= ${t.itemCount}`,\n\t\t),\n\t],\n);\n\nexport const mappedLlmItems = sqliteTable(\n\t\"mapped_llm_items\",\n\t{\n\t\trunId: text(\"run_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => mappedLlmRuns.id, { onDelete: \"cascade\" }),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\titemIndex: integer(\"item_index\").notNull(),\n\t\titemKey: text(\"item_key\").notNull(),\n\t\tlabel: text(\"label\").notNull(),\n\t\titemJson: text(\"item_json\").notNull(),\n\t\tstatus: text(\"status\").$type<MappedItem[\"status\"]>().notNull().default(\"pending\"),\n\t\toutcome: text(\"outcome\"),\n\t\tresultJson: text(\"result_json\"),\n\t\tturnRecordId: text(\"turn_record_id\"),\n\t\tcompletedAt: text(\"completed_at\"),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"uq_mapped_llm_items_run_index\").on(t.runId, t.itemIndex),\n\t\tuniqueIndex(\"uq_mapped_llm_items_run_key\").on(t.runId, t.itemKey),\n\t\tindex(\"idx_mapped_llm_items_instance\").on(t.instanceId),\n\t\tcheck(\"mapped_llm_items_status\", sql`${t.status} in ('pending', 'completed')`),\n\t\tcheck(\"mapped_llm_items_item_json\", sql`json_valid(${t.itemJson})`),\n\t\tcheck(\n\t\t\t\"mapped_llm_items_result\",\n\t\t\tsql`(${t.status} = 'pending' and ${t.resultJson} is null) or (${t.status} = 'completed' and ${t.resultJson} is not null and json_valid(${t.resultJson}))`,\n\t\t),\n\t],\n);\n\n/**\n * Composite foreign keys for the cyclic execution graph. Drizzle cannot infer\n * these mutually recursive table types without degrading declarations to any,\n * so the fresh baseline DDL adds them explicitly.\n */\nexport const BASELINE_TABLE_CONSTRAINTS: Readonly<Record<string, readonly string[]>> = {\n\tskills: [\n\t\t\"CONSTRAINT fk_skills_active_revision FOREIGN KEY (active_revision_id) REFERENCES skill_revisions(id)\",\n\t],\n\tprocess_instances: [\n\t\t\"CONSTRAINT fk_process_instances_worker_start FOREIGN KEY (id, current_worker_start_id) REFERENCES turn_start_records(instance_id, id)\",\n\t],\n\tturn_records: [\n\t\t\"CONSTRAINT fk_turn_records_accepted_start FOREIGN KEY (turn_start_record_id, instance_id, id, turn_id) REFERENCES turn_start_records(id, instance_id, proposed_turn_record_id, turn_id)\",\n\t\t\"CONSTRAINT fk_turn_records_accepted_lease FOREIGN KEY (instance_id, accepted_worker_lease_id) REFERENCES worker_leases(instance_id, id)\",\n\t\t\"CONSTRAINT fk_turn_records_parent FOREIGN KEY (instance_id, parent_turn_record_id) REFERENCES turn_records(instance_id, id)\",\n\t],\n\tturn_start_records: [\n\t\t\"CONSTRAINT fk_turn_start_records_recovery FOREIGN KEY (instance_id, recovery_turn_record_id) REFERENCES turn_records(instance_id, id)\",\n\t],\n\tprocess_question_requests: [\n\t\t\"CONSTRAINT fk_question_requests_turn FOREIGN KEY (instance_id, turn_record_id) REFERENCES turn_records(instance_id, id)\",\n\t],\n\tprocess_tool_approval_requests: [\n\t\t\"CONSTRAINT fk_tool_approval_turn FOREIGN KEY (instance_id, turn_record_id) REFERENCES turn_records(instance_id, id)\",\n\t],\n};\n\nexport const apiTokens = sqliteTable(\n\t\"api_tokens\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tprefix: text(\"prefix\").notNull(),\n\t\tsecretHash: text(\"secret_hash\").notNull(),\n\t\townerKind: text(\"owner_kind\", { enum: [\"user\", \"anonymous\"] }).notNull(),\n\t\townerId: text(\"owner_id\").notNull(),\n\t\tactorJson: text(\"actor_json\").notNull(),\n\t\tproviderBindingJson: text(\"provider_binding_json\"),\n\t\tname: text(\"name\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\texpiresAt: text(\"expires_at\"),\n\t\trevokedAt: text(\"revoked_at\"),\n\t\tlastUsedAt: text(\"last_used_at\"),\n\t\toidcEvidenceJson: text(\"oidc_evidence_json\"),\n\t},\n\t(t) => [\n\t\tuniqueIndex(\"idx_api_tokens_secret_hash\").on(t.secretHash),\n\t\tindex(\"idx_api_tokens_owner\").on(t.ownerKind, t.ownerId),\n\t],\n);\n\nexport const turnSummaries = sqliteTable(\n\t\"turn_summaries\",\n\t{\n\t\tturnRecordId: text(\"turn_record_id\").primaryKey(),\n\t\tinstanceId: text(\"instance_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\t\tsummaryJson: text(\"summary_json\").notNull(),\n\t},\n\t(t) => [index(\"idx_turn_summaries_instance\").on(t.instanceId)],\n);\n\nexport const sessionSummaries = sqliteTable(\"session_summaries\", {\n\tinstanceId: text(\"instance_id\")\n\t\t.primaryKey()\n\t\t.references(() => processInstances.id, { onDelete: \"cascade\" }),\n\tsummaryJson: text(\"summary_json\").notNull(),\n});\nexport const settingsSubjects = sqliteTable(\n\t\"settings_subjects\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tscopeType: text(\"scope_type\").notNull(),\n\t\tidentity: text(\"identity\").notNull(),\n\t\tlabel: text(\"label\").notNull(),\n\t\tcontextJson: text(\"context_json\").notNull(),\n\t\tschemaVersion: integer(\"schema_version\").notNull(),\n\t\trevision: integer(\"revision\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\tactorJson: text(\"actor_json\").notNull(),\n\t},\n\t(t) => [uniqueIndex(\"uq_settings_subject_identity\").on(t.scopeType, t.identity)],\n);\n\nexport const settingsAliases = sqliteTable(\"settings_aliases\", {\n\talias: text(\"alias\").primaryKey(),\n\tsubjectId: text(\"subject_id\")\n\t\t.notNull()\n\t\t.references(() => settingsSubjects.id),\n});\n\nexport const settingsSubjectRedirects = sqliteTable(\"settings_subject_redirects\", {\n\tsubjectId: text(\"subject_id\")\n\t\t.primaryKey()\n\t\t.references(() => settingsSubjects.id),\n\tcanonicalSubjectId: text(\"canonical_subject_id\")\n\t\t.notNull()\n\t\t.references(() => settingsSubjects.id),\n});\n\nexport const settingsOverrides = sqliteTable(\n\t\"settings_overrides\",\n\t{\n\t\tsubjectId: text(\"subject_id\")\n\t\t\t.notNull()\n\t\t\t.references(() => settingsSubjects.id),\n\t\tkey: text(\"key\").notNull(),\n\t\tvalueJson: text(\"value_json\").notNull(),\n\t\tmode: text(\"mode\").notNull(),\n\t\treset: integer(\"reset\", { mode: \"boolean\" }).notNull(),\n\t\tschemaVersion: integer(\"schema_version\").notNull(),\n\t\trevision: integer(\"revision\").notNull(),\n\t\tcreatedAt: text(\"created_at\").notNull(),\n\t\tupdatedAt: text(\"updated_at\").notNull(),\n\t\tactorJson: text(\"actor_json\").notNull(),\n\t},\n\t(t) => [uniqueIndex(\"uq_settings_override\").on(t.subjectId, t.key)],\n);\n","import type { SQLiteColumn, SQLiteTable } from \"drizzle-orm/sqlite-core\";\nimport { getTableConfig, SQLiteDialect } from \"drizzle-orm/sqlite-core\";\n\nconst sqliteDialect = new SQLiteDialect();\n\nfunction renderSql(value: Parameters<SQLiteDialect[\"sqlToQuery\"]>[0]): string {\n\tconst query = sqliteDialect.sqlToQuery(value);\n\tif (query.params.length > 0) throw new Error(\"DDL constraints must not contain bound parameters\");\n\treturn query.sql;\n}\n\nfunction sqlStringLiteral(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction buildForeignKeyMap(\n\ttable: SQLiteTable,\n): Map<string, { table: string; column: string; onDelete?: string; onUpdate?: string }> {\n\tconst cfg = getTableConfig(table);\n\tconst fkMap = new Map<\n\t\tstring,\n\t\t{ table: string; column: string; onDelete?: string; onUpdate?: string }\n\t>();\n\tfor (const fk of cfg.foreignKeys) {\n\t\tconst ref = fk.reference();\n\t\tif (ref.columns.length !== 1) continue;\n\t\tconst refTable = getTableConfig(ref.foreignTable).name;\n\t\tfkMap.set(ref.columns[0].name, {\n\t\t\ttable: refTable,\n\t\t\tcolumn: ref.foreignColumns[0].name,\n\t\t\t...(fk.onDelete ? { onDelete: String(fk.onDelete).toUpperCase() } : {}),\n\t\t\t...(fk.onUpdate ? { onUpdate: String(fk.onUpdate).toUpperCase() } : {}),\n\t\t});\n\t}\n\treturn fkMap;\n}\n\nfunction columnDef(\n\tcol: SQLiteColumn,\n\tfkMap: Map<string, { table: string; column: string; onDelete?: string; onUpdate?: string }>,\n): string {\n\tconst parts: string[] = [col.name, col.getSQLType()];\n\n\tif ((col as unknown as { primary: boolean }).primary) {\n\t\tparts.push(\"PRIMARY KEY\");\n\t}\n\tif (col.notNull) {\n\t\tparts.push(\"NOT NULL\");\n\t}\n\tif (col.hasDefault && col.default !== undefined) {\n\t\tconst val = col.default;\n\t\tparts.push(`DEFAULT ${typeof val === \"string\" ? sqlStringLiteral(val) : String(val)}`);\n\t}\n\n\tconst fk = fkMap.get(col.name);\n\tif (fk) {\n\t\tparts.push(`REFERENCES ${fk.table}(${fk.column})`);\n\t\tif (fk.onDelete) {\n\t\t\tparts.push(`ON DELETE ${fk.onDelete}`);\n\t\t}\n\t\tif (fk.onUpdate) {\n\t\t\tparts.push(`ON UPDATE ${fk.onUpdate}`);\n\t\t}\n\t}\n\n\treturn parts.join(\" \");\n}\n\nexport function getTableName(table: SQLiteTable): string {\n\treturn getTableConfig(table).name;\n}\n\nexport function generateCreateTableDDL(\n\ttable: SQLiteTable,\n\textraConstraints: readonly string[] = [],\n): string {\n\tconst cfg = getTableConfig(table);\n\tconst fkMap = buildForeignKeyMap(table);\n\tconst definitions = cfg.columns.map((column) => `\\t${columnDef(column, fkMap)}`);\n\tfor (const fk of cfg.foreignKeys) {\n\t\tconst ref = fk.reference();\n\t\tif (ref.columns.length === 1) continue;\n\t\tconst foreignTable = getTableConfig(ref.foreignTable).name;\n\t\tconst columns = ref.columns.map((column) => column.name).join(\", \");\n\t\tconst foreignColumns = ref.foreignColumns.map((column) => column.name).join(\", \");\n\t\tconst actions = [\n\t\t\tfk.onDelete ? ` ON DELETE ${String(fk.onDelete).toUpperCase()}` : \"\",\n\t\t\tfk.onUpdate ? ` ON UPDATE ${String(fk.onUpdate).toUpperCase()}` : \"\",\n\t\t].join(\"\");\n\t\tdefinitions.push(\n\t\t\t`\\tFOREIGN KEY (${columns}) REFERENCES ${foreignTable}(${foreignColumns})${actions}`,\n\t\t);\n\t}\n\tfor (const constraint of cfg.checks) {\n\t\tdefinitions.push(`\\tCONSTRAINT ${constraint.name} CHECK (${renderSql(constraint.value)})`);\n\t}\n\tfor (const constraint of extraConstraints) {\n\t\tdefinitions.push(`\\t${constraint}`);\n\t}\n\treturn `CREATE TABLE IF NOT EXISTS ${cfg.name} (\\n${definitions.join(\",\\n\")}\\n)`;\n}\n\nexport function generateCreateIndexDDL(table: SQLiteTable): string[] {\n\tconst cfg = getTableConfig(table);\n\treturn cfg.indexes.map((idx) => {\n\t\tconst unique = idx.config.unique ? \"UNIQUE \" : \"\";\n\t\tconst colNames = idx.config.columns\n\t\t\t.map((column) => (\"name\" in column ? (column as SQLiteColumn).name : \"\"))\n\t\t\t.filter(Boolean)\n\t\t\t.join(\", \");\n\t\tconst where = idx.config.where ? ` WHERE ${renderSql(idx.config.where)}` : \"\";\n\t\treturn `CREATE ${unique}INDEX IF NOT EXISTS ${idx.config.name} ON ${cfg.name}(${colNames})${where}`;\n\t});\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\n/** Application boundary for encrypted credential payloads. Callers supply deployment key material. @internal */\nexport interface CredentialCipher {\n\t/** @internal */\n\tencrypt(plaintext: string): string;\n\t/** @internal */\n\tdecrypt(ciphertext: string): string;\n}\n\n/** @internal */\nexport const PROVIDER_CREDENTIAL_KEY_ENV = \"LEITWERK_CREDENTIAL_ENCRYPTION_KEY\";\n\n/** A missing deployment key may inspect an empty table but can never read or write credentials. @internal */\nexport function createUnavailableCredentialCipher(): CredentialCipher {\n\tconst unavailable = (): never => {\n\t\tthrow new Error(\n\t\t\t`Provider credential encryption key is unavailable; set ${PROVIDER_CREDENTIAL_KEY_ENV}`,\n\t\t);\n\t};\n\treturn { encrypt: unavailable, decrypt: unavailable };\n}\n\n/** Parses an exact 32-byte Base64 deployment secret. @internal */\nexport function createCredentialCipherFromBase64(value: string): CredentialCipher {\n\tconst normalized = value.trim();\n\tif (normalized === \"\") {\n\t\tthrow new Error(`${PROVIDER_CREDENTIAL_KEY_ENV} must not be empty`);\n\t}\n\tconst key = Buffer.from(normalized, \"base64\");\n\tif (\n\t\tkey.length !== 32 ||\n\t\tkey.toString(\"base64\").replace(/=+$/, \"\") !== normalized.replace(/=+$/, \"\")\n\t) {\n\t\tthrow new Error(`${PROVIDER_CREDENTIAL_KEY_ENV} must be Base64 for exactly 32 bytes`);\n\t}\n\treturn createAes256GcmCredentialCipher(key);\n}\n\n/** @internal */\nexport function createCredentialCipherFromEnvironment(\n\tenvironment: NodeJS.ProcessEnv = process.env,\n): CredentialCipher | null {\n\tconst value = environment[PROVIDER_CREDENTIAL_KEY_ENV];\n\treturn value === undefined ? null : createCredentialCipherFromBase64(value);\n}\n\n/** @internal */\nexport function createAes256GcmCredentialCipher(key: Buffer): CredentialCipher {\n\tif (key.length !== 32) throw new Error(\"Credential encryption key must be 32 bytes\");\n\treturn {\n\t\tencrypt(plaintext) {\n\t\t\tconst iv = randomBytes(12);\n\t\t\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\t\t\tconst body = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\t\t\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString(\"base64\");\n\t\t},\n\t\tdecrypt(ciphertext) {\n\t\t\tconst bytes = Buffer.from(ciphertext, \"base64\");\n\t\t\tif (bytes.length < 29) throw new Error(\"Invalid encrypted credential payload\");\n\t\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, bytes.subarray(0, 12));\n\t\t\tdecipher.setAuthTag(bytes.subarray(12, 28));\n\t\t\treturn Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString(\n\t\t\t\t\"utf8\",\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createTopicWikiRepo } from \"@leitwerk-dev/wiki/server\";\nimport { createApiTokenRepo } from \"./api-token-repo.js\";\nimport { createExecutionInspectionRepo } from \"./execution-inspection-repo.js\";\nimport { createPublicationRepo } from \"./publication-repo.js\";\nimport { createScopedSettingsRepo } from \"./scoped-settings-repo.js\";\nimport { createStartupObservationRepo } from \"./startup-observation-repo.js\";\nimport { createTurnSummaryRepo } from \"./turn-summary-repo.js\";\n\nexport * from \"./api-token-repo.js\";\n\nimport { createAuthLoginFlowRepo, createAuthSessionRepo } from \"./auth-repo.js\";\nimport { type CredentialCipher, createUnavailableCredentialCipher } from \"./credential-cipher.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { createExternalWriteLogRepo } from \"./external-write-log-repo.js\";\n\nexport * from \"./auth-repo.js\";\nexport * from \"./credential-cipher.js\";\nexport * from \"./external-write-log-repo.js\";\nexport * from \"./future-execution-repo.js\";\nexport * from \"./launch-run-repo.js\";\nexport * from \"./launcher-recent-value-repo.js\";\nexport * from \"./mapped-llm-run-repo.js\";\nexport * from \"./pending-external-source-fire-repo.js\";\nexport * from \"./process-event-repo.js\";\nexport * from \"./process-handoff-dedup-key-repo.js\";\nexport * from \"./process-input-repo.js\";\nexport * from \"./process-instance-repo.js\";\nexport * from \"./process-leaf-outcome-snapshot-repo.js\";\nexport * from \"./process-project-repo.js\";\nexport * from \"./process-question-request-repo.js\";\nexport * from \"./process-relation-repo.js\";\nexport * from \"./process-skill-repo.js\";\nexport * from \"./process-title-job-repo.js\";\nexport * from \"./process-tool-approval-request-repo.js\";\nexport * from \"./process-turn-annotation-repo.js\";\nexport * from \"./process-turn-record-repo.js\";\nexport * from \"./provider-credential-repo.js\";\nexport * from \"./session-transfer-repo.js\";\nexport * from \"./skill-repo.js\";\nexport * from \"./ticket-destination-recent-repo.js\";\nexport * from \"./turn-start-record-repo.js\";\nexport * from \"./worker-lease-repo.js\";\n\nimport { createFutureExecutionRepo } from \"./future-execution-repo.js\";\nimport { createLaunchRunRepo } from \"./launch-run-repo.js\";\nimport { createLauncherRecentValueRepo } from \"./launcher-recent-value-repo.js\";\nimport { createMappedLlmRunRepo } from \"./mapped-llm-run-repo.js\";\nimport { createPendingExternalSourceFireRepo } from \"./pending-external-source-fire-repo.js\";\nimport { createProcessEventRepo } from \"./process-event-repo.js\";\nimport { createProcessHandoffDedupKeyRepo } from \"./process-handoff-dedup-key-repo.js\";\nimport { createProcessInputRepo } from \"./process-input-repo.js\";\nimport { createProcessInstanceRepo } from \"./process-instance-repo.js\";\nimport { createProcessLeafOutcomeSnapshotRepo } from \"./process-leaf-outcome-snapshot-repo.js\";\nimport { createProcessProjectRepo } from \"./process-project-repo.js\";\nimport { createProcessQuestionRequestRepo } from \"./process-question-request-repo.js\";\nimport { createProcessRelationRepo } from \"./process-relation-repo.js\";\nimport { createProcessSkillRepo } from \"./process-skill-repo.js\";\nimport { createProcessTitleJobRepo } from \"./process-title-job-repo.js\";\nimport { createProcessToolApprovalRequestRepo } from \"./process-tool-approval-request-repo.js\";\nimport { createProcessTurnAnnotationRepo } from \"./process-turn-annotation-repo.js\";\nimport { createProcessTurnRecordRepo } from \"./process-turn-record-repo.js\";\nimport { createProviderCredentialRepo } from \"./provider-credential-repo.js\";\nimport { createSessionTransferRepo } from \"./session-transfer-repo.js\";\nimport { createSkillRepo } from \"./skill-repo.js\";\nimport { createTicketDestinationRecentRepo } from \"./ticket-destination-recent-repo.js\";\nimport { createTurnStartRecordRepo } from \"./turn-start-record-repo.js\";\nimport { createWorkerLeaseRepo } from \"./worker-lease-repo.js\";\n\n// ── Repository bundle ──\n\n/** @public */\nexport interface RepositoryBundle {\n\t/** @internal */\n\ttopicWiki: ReturnType<typeof createTopicWikiRepo>;\n\t/** @internal */\n\tpublications: ReturnType<typeof createPublicationRepo>;\n\t/** @internal */\n\texecutionInspections: ReturnType<typeof createExecutionInspectionRepo>;\n\t/** @internal */\n\tscopedSettings: ReturnType<typeof createScopedSettingsRepo>;\n\t/** @internal */\n\tstartupObservations: ReturnType<typeof createStartupObservationRepo>;\n\t/** @internal */\n\tturnSummaries: ReturnType<typeof createTurnSummaryRepo>;\n\t/** @public */\n\tprocesses: ReturnType<typeof createProcessInstanceRepo>;\n\t/** @public */\n\tprojects: ReturnType<typeof createProcessProjectRepo>;\n\t/** @internal */\n\tquestionRequests: ReturnType<typeof createProcessQuestionRequestRepo>;\n\t/** @internal */\n\tprocessRelations: ReturnType<typeof createProcessRelationRepo>;\n\t/** @internal */\n\ttoolApprovalRequests: ReturnType<typeof createProcessToolApprovalRequestRepo>;\n\t/** @internal */\n\tinputs: ReturnType<typeof createProcessInputRepo>;\n\t/** @internal */\n\tevents: ReturnType<typeof createProcessEventRepo>;\n\t/** @internal */\n\thandoffDedupKeys: ReturnType<typeof createProcessHandoffDedupKeyRepo>;\n\t/** @internal */\n\tfutureExecutions: ReturnType<typeof createFutureExecutionRepo>;\n\t/** @internal */\n\tlauncherRecentValues: ReturnType<typeof createLauncherRecentValueRepo>;\n\t/** @internal */\n\tticketDestinationRecents: ReturnType<typeof createTicketDestinationRecentRepo>;\n\t/** @internal */\n\tlaunchRuns: ReturnType<typeof createLaunchRunRepo>;\n\t/** @internal */\n\ttitleJobs: ReturnType<typeof createProcessTitleJobRepo>;\n\t/** @internal */\n\tpendingExternalSourceFires: ReturnType<typeof createPendingExternalSourceFireRepo>;\n\t/** @internal */\n\tleafOutcomeSnapshots: ReturnType<typeof createProcessLeafOutcomeSnapshotRepo>;\n\t/** @public */\n\tturnRecords: ReturnType<typeof createProcessTurnRecordRepo>;\n\t/** @internal */\n\tturnStarts: ReturnType<typeof createTurnStartRecordRepo>;\n\t/** @internal */\n\tturnAnnotations: ReturnType<typeof createProcessTurnAnnotationRepo>;\n\t/** @internal */\n\tmappedRuns: ReturnType<typeof createMappedLlmRunRepo>;\n\t/** @internal */\n\tleases: ReturnType<typeof createWorkerLeaseRepo>;\n\t/** @internal */\n\tproviderCredentials: ReturnType<typeof createProviderCredentialRepo>;\n\t/** @public */\n\texternalWrites: ReturnType<typeof createExternalWriteLogRepo>;\n\t/** @internal */\n\tsessionTransfers: ReturnType<typeof createSessionTransferRepo>;\n\t/** @internal */\n\tskills: ReturnType<typeof createSkillRepo>;\n\t/** @internal */\n\tprocessSkills: ReturnType<typeof createProcessSkillRepo>;\n\t/** @internal */\n\tapiTokens: ReturnType<typeof createApiTokenRepo>;\n\t/** @internal */\n\tauthSessions: ReturnType<typeof createAuthSessionRepo>;\n\t/** @internal */\n\tauthLoginFlows: ReturnType<typeof createAuthLoginFlowRepo>;\n\t/** @internal */\n\ttransaction<T>(fn: (repos: RepositoryBundle) => T): T;\n}\n\n/** @internal */\nexport function createAllRepos(\n\tdb: LeitwerkDb,\n\toptions: {\n\t\t/** @internal */\n\t\tcredentialCipher?: CredentialCipher;\n\t} = {},\n): RepositoryBundle {\n\tconst credentialCipher = options.credentialCipher ?? createUnavailableCredentialCipher();\n\tconst bundle: RepositoryBundle = {\n\t\ttopicWiki: createTopicWikiRepo(db),\n\t\tpublications: createPublicationRepo(db),\n\t\texecutionInspections: createExecutionInspectionRepo(db),\n\n\t\tscopedSettings: createScopedSettingsRepo(db),\n\t\tstartupObservations: createStartupObservationRepo(db),\n\t\tturnSummaries: createTurnSummaryRepo(db),\n\t\tprocesses: createProcessInstanceRepo(db),\n\t\tprojects: createProcessProjectRepo(db),\n\t\tquestionRequests: createProcessQuestionRequestRepo(db),\n\t\tprocessRelations: createProcessRelationRepo(db),\n\t\ttoolApprovalRequests: createProcessToolApprovalRequestRepo(db),\n\t\tinputs: createProcessInputRepo(db),\n\t\tevents: createProcessEventRepo(db),\n\t\thandoffDedupKeys: createProcessHandoffDedupKeyRepo(db),\n\t\tfutureExecutions: createFutureExecutionRepo(db),\n\t\tlauncherRecentValues: createLauncherRecentValueRepo(db),\n\t\tticketDestinationRecents: createTicketDestinationRecentRepo(db),\n\t\tlaunchRuns: createLaunchRunRepo(db),\n\t\ttitleJobs: createProcessTitleJobRepo(db),\n\t\tpendingExternalSourceFires: createPendingExternalSourceFireRepo(db),\n\t\tleafOutcomeSnapshots: createProcessLeafOutcomeSnapshotRepo(db),\n\t\tturnRecords: createProcessTurnRecordRepo(db),\n\t\tturnStarts: createTurnStartRecordRepo(db),\n\t\tturnAnnotations: createProcessTurnAnnotationRepo(db),\n\t\tmappedRuns: createMappedLlmRunRepo(db),\n\t\tleases: createWorkerLeaseRepo(db),\n\t\tproviderCredentials: createProviderCredentialRepo(db, credentialCipher),\n\t\texternalWrites: createExternalWriteLogRepo(db),\n\t\tsessionTransfers: createSessionTransferRepo(db),\n\t\tskills: createSkillRepo(db),\n\t\tprocessSkills: createProcessSkillRepo(db),\n\t\tapiTokens: createApiTokenRepo(db),\n\t\tauthSessions: createAuthSessionRepo(db),\n\t\tauthLoginFlows: createAuthLoginFlowRepo(db),\n\t\ttransaction<T>(fn: (repos: RepositoryBundle) => T): T {\n\t\t\tconst transaction = db.transaction.bind(db) as unknown as (callback: (tx: unknown) => T) => T;\n\t\t\treturn transaction((tx) => fn(createAllRepos(tx as LeitwerkDb, { credentialCipher })));\n\t\t},\n\t};\n\treturn bundle;\n}\n","import type { Actor } from \"@leitwerk-dev/domain\";\nimport type { ApiTokenMetadata } from \"@leitwerk-dev/protocol/http-contracts\";\nimport { and, desc, eq, isNull } from \"drizzle-orm\";\nimport type { OidcEvidence } from \"../auth/oidc-evidence.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { apiTokens } from \"./schema.js\";\n\n/** @internal */\nexport type TokenProviderBinding =\n\t| {\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\tkind: \"oidc\";\n\t\t\t/** @internal */\n\t\t\tissuer: string;\n\t\t\t/** @internal */\n\t\t\tidentityClaim: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\tkind: \"oauth2\";\n\t\t\t/** @internal */\n\t\t\torganization: string;\n\t };\n/** @internal */\nexport interface ApiTokenOwner {\n\t/** @internal */\n\tkind: \"user\" | \"anonymous\";\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tactor: Actor;\n\t/** @internal */\n\tproviderBinding: TokenProviderBinding | null;\n\t/** @internal */\n\toidcEvidence?: OidcEvidence | null;\n}\n/** @internal */\nexport interface ApiTokenRecord extends ApiTokenMetadata {\n\t/** @internal */\n\tsecretHash: string;\n\t/** @internal */\n\towner: ApiTokenOwner;\n}\nfunction record(row: typeof apiTokens.$inferSelect): ApiTokenRecord {\n\tconst { ownerKind, ownerId, actorJson, providerBindingJson, oidcEvidenceJson, ...fields } = row;\n\treturn {\n\t\t...fields,\n\t\towner: {\n\t\t\toidcEvidence: oidcEvidenceJson ? JSON.parse(oidcEvidenceJson) : null,\n\t\t\tkind: ownerKind,\n\t\t\tid: ownerId,\n\t\t\tactor: JSON.parse(actorJson),\n\t\t\tproviderBinding: providerBindingJson ? JSON.parse(providerBindingJson) : null,\n\t\t},\n\t};\n}\nfunction owned(owner: ApiTokenOwner) {\n\treturn and(eq(apiTokens.ownerKind, owner.kind), eq(apiTokens.ownerId, owner.id));\n}\n/** @internal */\nexport function createApiTokenRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate({ owner, ...fields }: ApiTokenRecord): void {\n\t\t\tdb.insert(apiTokens)\n\t\t\t\t.values({\n\t\t\t\t\t...fields,\n\t\t\t\t\townerKind: owner.kind,\n\t\t\t\t\townerId: owner.id,\n\t\t\t\t\tactorJson: JSON.stringify(owner.actor),\n\t\t\t\t\toidcEvidenceJson: owner.oidcEvidence ? JSON.stringify(owner.oidcEvidence) : null,\n\t\t\t\t\tproviderBindingJson: owner.providerBinding ? JSON.stringify(owner.providerBinding) : null,\n\t\t\t\t})\n\t\t\t\t.run();\n\t\t},\n\t\t/** @internal */\n\t\tlist(owner: ApiTokenOwner): ApiTokenRecord[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(apiTokens)\n\t\t\t\t.where(owned(owner))\n\t\t\t\t.orderBy(desc(apiTokens.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(record);\n\t\t},\n\t\t/** @internal */\n\t\tfindByHash(hash: string): ApiTokenRecord | null {\n\t\t\tconst row = db.select().from(apiTokens).where(eq(apiTokens.secretHash, hash)).get();\n\t\t\treturn row ? record(row) : null;\n\t\t},\n\t\t/** @internal */\n\t\trevoke(owner: ApiTokenOwner, id: string, at: string): boolean {\n\t\t\tconst filter = and(owned(owner), eq(apiTokens.id, id));\n\t\t\tif (!db.select({ id: apiTokens.id }).from(apiTokens).where(filter).get()) return false;\n\t\t\tdb.update(apiTokens)\n\t\t\t\t.set({ revokedAt: at })\n\t\t\t\t.where(and(filter, isNull(apiTokens.revokedAt)))\n\t\t\t\t.run();\n\t\t\treturn true;\n\t\t},\n\t\t/** @internal */\n\t\trevokeAll(owner: ApiTokenOwner, at: string): number {\n\t\t\tconst result = db\n\t\t\t\t.update(apiTokens)\n\t\t\t\t.set({ revokedAt: at })\n\t\t\t\t.where(and(owned(owner), isNull(apiTokens.revokedAt)))\n\t\t\t\t.run();\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\t/** @internal */\n\t\trevokeAnonymous(at: string): number {\n\t\t\tconst result = db\n\t\t\t\t.update(apiTokens)\n\t\t\t\t.set({ revokedAt: at })\n\t\t\t\t.where(and(eq(apiTokens.ownerKind, \"anonymous\"), isNull(apiTokens.revokedAt)))\n\t\t\t\t.run();\n\t\t\treturn Number(result.changes);\n\t\t},\n\t\t/** @internal */\n\t\ttouch(id: string, at: string): void {\n\t\t\tdb.update(apiTokens).set({ lastUsedAt: at }).where(eq(apiTokens.id, id)).run();\n\t\t},\n\t};\n}\n","import { createHash } from \"node:crypto\";\nimport type {\n\tExecutionInspectionCapture,\n\tExecutionInspectionRecord,\n\tInspectionContextObservation,\n} from \"@leitwerk-dev/domain\";\nimport type { InspectionConfigurationRevision } from \"@leitwerk-dev/protocol\";\nimport { and, asc, eq, inArray, sql } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { executionInspections, inspectionContents } from \"./schema.js\";\n\n/** Immutable content and incremental observation references. No session ancestry is copied. @internal */\nexport function createExecutionInspectionRepo(db: LeitwerkDb) {\n\tfunction pack(value: unknown): unknown {\n\t\tif (Array.isArray(value)) return value.map(pack);\n\t\tif (!value || typeof value !== \"object\") return value;\n\t\tconst record = value as Record<string, unknown>;\n\t\tif ((record.state === \"recorded\" || record.state === \"redacted\") && \"value\" in record) {\n\t\t\tconst contentJson = JSON.stringify(record.value);\n\t\t\tconst digest = createHash(\"sha256\").update(contentJson).digest(\"hex\");\n\t\t\tdb.insert(inspectionContents).values({ digest, contentJson }).onConflictDoNothing().run();\n\t\t\treturn { state: record.state, contentDigest: digest };\n\t\t}\n\t\treturn Object.fromEntries(Object.entries(record).map(([key, item]) => [key, pack(item)]));\n\t}\n\tfunction unpack(value: unknown): unknown {\n\t\tif (Array.isArray(value)) return value.map(unpack);\n\t\tif (!value || typeof value !== \"object\") return value;\n\t\tconst record = value as Record<string, unknown>;\n\t\tif (typeof record.contentDigest === \"string\") {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(inspectionContents)\n\t\t\t\t.where(eq(inspectionContents.digest, record.contentDigest))\n\t\t\t\t.get();\n\t\t\treturn row\n\t\t\t\t? { state: record.state, value: JSON.parse(row.contentJson) }\n\t\t\t\t: { state: \"unavailable\", reason: \"Recorded content is unavailable\" };\n\t\t}\n\t\treturn Object.fromEntries(Object.entries(record).map(([key, item]) => [key, unpack(item)]));\n\t}\n\treturn {\n\t\t/** Model identities without loading retained prompts or message contents. @internal */\n\t\tmodelInputs(\n\t\t\tinstanceId: string,\n\t\t\tturnRecordId: string,\n\t\t): Pick<InspectionConfigurationRevision, \"id\" | \"timestamp\" | \"boundaryEntryId\" | \"model\">[] {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\tid: executionInspections.id,\n\t\t\t\t\ttimestamp: executionInspections.capturedAt,\n\t\t\t\t\tboundaryEntryId: sql<\n\t\t\t\t\t\tstring | null\n\t\t\t\t\t>`json_extract(${executionInspections.factJson}, '$.boundaryEntryId')`,\n\t\t\t\t\tmodel: sql<string>`json_extract(${executionInspections.factJson}, '$.model')`,\n\t\t\t\t})\n\t\t\t\t.from(executionInspections)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(executionInspections.instanceId, instanceId),\n\t\t\t\t\t\teq(executionInspections.turnRecordId, turnRecordId),\n\t\t\t\t\t\tsql`json_extract(${executionInspections.factJson}, '$.kind') = 'model_input'`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(executionInspections.sequence))\n\t\t\t\t.all()\n\t\t\t\t.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tmodel: JSON.parse(row.model) as InspectionConfigurationRevision[\"model\"],\n\t\t\t\t}));\n\t\t},\n\t\t/** @internal */\n\t\tappend(input: Omit<ExecutionInspectionRecord, \"sequence\">): \"stored\" | \"replay\" {\n\t\t\treturn db.transaction(() => {\n\t\t\t\tconst factJson = JSON.stringify(pack(input.fact));\n\t\t\t\tconst existing = db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(executionInspections)\n\t\t\t\t\t.where(eq(executionInspections.id, input.id))\n\t\t\t\t\t.get();\n\t\t\t\tif (existing) {\n\t\t\t\t\tif (\n\t\t\t\t\t\texisting.instanceId !== input.instanceId ||\n\t\t\t\t\t\texisting.turnRecordId !== input.turnRecordId ||\n\t\t\t\t\t\texisting.factJson !== factJson\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Inspection observation identity was reused with different evidence\");\n\t\t\t\t\treturn \"replay\";\n\t\t\t\t}\n\t\t\t\tdb.insert(executionInspections)\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\t\tturnRecordId: input.turnRecordId,\n\t\t\t\t\t\tstartRecordId: input.startRecordId,\n\t\t\t\t\t\tworkerLeaseId: input.workerLeaseId,\n\t\t\t\t\t\tcapturedAt: input.timestamp,\n\t\t\t\t\t\tfactJson,\n\t\t\t\t\t})\n\t\t\t\t\t.run();\n\t\t\t\treturn \"stored\";\n\t\t\t});\n\t\t},\n\t\t/** Expanded evidence is read only on demand. @internal */\n\t\tlist(instanceId: string, turnRecordId: string): ExecutionInspectionRecord[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(executionInspections)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(executionInspections.instanceId, instanceId),\n\t\t\t\t\t\teq(executionInspections.turnRecordId, turnRecordId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(executionInspections.sequence))\n\t\t\t\t.all()\n\t\t\t\t.map((row) => ({\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tsequence: row.sequence,\n\t\t\t\t\tinstanceId: row.instanceId,\n\t\t\t\t\tturnRecordId: row.turnRecordId,\n\t\t\t\t\tstartRecordId: row.startRecordId,\n\t\t\t\t\tworkerLeaseId: row.workerLeaseId,\n\t\t\t\t\ttimestamp: row.capturedAt,\n\t\t\t\t\tfact: unpack(JSON.parse(row.factJson)) as ExecutionInspectionCapture[\"fact\"],\n\t\t\t\t}));\n\t\t},\n\t\t/** Small origin/product references for compact lineage without loading prompts. @internal */\n\t\tlistContextFacts(instanceId: string, turnRecordIds?: string[]): InspectionContextObservation[] {\n\t\t\tif (turnRecordIds?.length === 0) return [];\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(executionInspections)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(executionInspections.instanceId, instanceId),\n\t\t\t\t\t\tturnRecordIds ? inArray(executionInspections.turnRecordId, turnRecordIds) : undefined,\n\t\t\t\t\t\tsql`json_extract(${executionInspections.factJson}, '$.kind') IN ('supplied_context', 'product_consumed', 'entry_link')`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(executionInspections.sequence))\n\t\t\t\t.all()\n\t\t\t\t.map((row) => {\n\t\t\t\t\tconst fact = JSON.parse(row.factJson) as Extract<\n\t\t\t\t\t\tExecutionInspectionCapture[\"fact\"],\n\t\t\t\t\t\t{ kind: \"supplied_context\" | \"product_consumed\" | \"entry_link\" }\n\t\t\t\t\t>;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tturnRecordId: row.turnRecordId,\n\t\t\t\t\t\tfact:\n\t\t\t\t\t\t\tfact.kind === \"supplied_context\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t...fact,\n\t\t\t\t\t\t\t\t\t\tproducts: fact.products.map(({ content: _content, ...source }) => source),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: fact,\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t},\n\t};\n}\n","import type { PublicationReceipt, PublicationStore } from \"@leitwerk-dev/external-writes\";\nimport { eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { topicPublications } from \"./schema.js\";\n\n/** @internal */\nexport function createPublicationRepo(db: LeitwerkDb): PublicationStore {\n\tconst store: PublicationStore = {\n\t\tpublication(key) {\n\t\t\tconst row = db.select().from(topicPublications).where(eq(topicPublications.key, key)).get();\n\t\t\treturn row ? JSON.parse(row.data) : null;\n\t\t},\n\t\tpublicationByExternalId(externalId) {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(topicPublications)\n\t\t\t\t.where(eq(topicPublications.externalId, externalId))\n\t\t\t\t.get();\n\t\t\treturn row ? JSON.parse(row.data) : null;\n\t\t},\n\t\treservePublication(input) {\n\t\t\treturn (\n\t\t\t\tNumber(\n\t\t\t\t\tdb\n\t\t\t\t\t\t.insert(topicPublications)\n\t\t\t\t\t\t.values({\n\t\t\t\t\t\t\tkey: input.key,\n\t\t\t\t\t\t\ttopicId: input.topicId,\n\t\t\t\t\t\t\texternalId: null,\n\t\t\t\t\t\t\tdata: JSON.stringify(input),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.onConflictDoNothing()\n\t\t\t\t\t\t.run().changes,\n\t\t\t\t) === 1\n\t\t\t);\n\t\t},\n\t\tfinishPublication(key, externalId, url) {\n\t\t\tconst current = store.publication(key);\n\t\t\tif (!current || (current.externalId && current.externalId !== externalId))\n\t\t\t\tthrow new Error(\"Publication receipt conflict\");\n\t\t\tconst receipt: PublicationReceipt = { ...current, externalId, url };\n\t\t\tdb.update(topicPublications)\n\t\t\t\t.set({ externalId, data: JSON.stringify(receipt) })\n\t\t\t\t.where(eq(topicPublications.key, key))\n\t\t\t\t.run();\n\t\t},\n\t\treleaseRejectedPublication(key) {\n\t\t\tconst current = store.publication(key);\n\t\t\tif (current?.externalId) throw new Error(\"Cannot release a published ticket\");\n\t\t\tdb.delete(topicPublications).where(eq(topicPublications.key, key)).run();\n\t\t},\n\t\tmarkPublicationTriggered(key) {\n\t\t\tconst current = store.publication(key);\n\t\t\tif (!current?.externalId)\n\t\t\t\tthrow new Error(\"Ticket receipt is required before triggering changes\");\n\t\t\tdb.update(topicPublications)\n\t\t\t\t.set({ data: JSON.stringify({ ...current, triggered: true }) })\n\t\t\t\t.where(eq(topicPublications.key, key))\n\t\t\t\t.run();\n\t\t},\n\t};\n\treturn store;\n}\n","import type { SettingsOverride, SettingsSubject } from \"@leitwerk-dev/domain\";\nimport { SYSTEM_ACTOR } from \"@leitwerk-dev/domain\";\nimport { and, eq, notInArray } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport type SettingsWrite = Omit<SettingsOverride, \"revision\" | \"createdAt\" | \"updatedAt\"> & {\n\t/** @internal */\n\texpectedRevision: number;\n};\n/** @internal */\ntype SubjectWrite = Pick<SettingsSubject, \"scopeType\" | \"identity\" | \"label\" | \"context\"> & {\n\t/** @internal */\n\tid?: string;\n};\n\nfunction subject(row: typeof s.settingsSubjects.$inferSelect): SettingsSubject {\n\tconst { contextJson, actorJson, ...rest } = row;\n\treturn { ...rest, context: JSON.parse(contextJson), actor: JSON.parse(actorJson) };\n}\n\nfunction override(row: typeof s.settingsOverrides.$inferSelect): SettingsOverride {\n\tconst { valueJson, actorJson, mode, ...rest } = row;\n\treturn {\n\t\t...rest,\n\t\tmode: mode as SettingsOverride[\"mode\"],\n\t\tvalue: JSON.parse(valueJson),\n\t\tactor: JSON.parse(actorJson),\n\t};\n}\n\nfunction overrideRow({ value, actor, ...rest }: SettingsOverride) {\n\treturn { ...rest, valueJson: JSON.stringify(value), actorJson: JSON.stringify(actor) };\n}\n\n/** @internal */\nexport function createScopedSettingsRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tlistSubjects(): SettingsSubject[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.settingsSubjects)\n\t\t\t\t.where(\n\t\t\t\t\tnotInArray(\n\t\t\t\t\t\ts.settingsSubjects.id,\n\t\t\t\t\t\tdb\n\t\t\t\t\t\t\t.select({ id: s.settingsSubjectRedirects.subjectId })\n\t\t\t\t\t\t\t.from(s.settingsSubjectRedirects),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.all()\n\t\t\t\t.map(subject);\n\t\t},\n\t\t/** @internal */\n\t\tgetSubject(id: string): SettingsSubject | null {\n\t\t\tconst visited = new Set<string>();\n\t\t\twhile (!visited.has(id)) {\n\t\t\t\tvisited.add(id);\n\t\t\t\tconst redirect = db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(s.settingsSubjectRedirects)\n\t\t\t\t\t.where(eq(s.settingsSubjectRedirects.subjectId, id))\n\t\t\t\t\t.get();\n\t\t\t\tif (!redirect) {\n\t\t\t\t\tconst row = db\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(s.settingsSubjects)\n\t\t\t\t\t\t.where(eq(s.settingsSubjects.id, id))\n\t\t\t\t\t\t.get();\n\t\t\t\t\treturn row ? subject(row) : null;\n\t\t\t\t}\n\t\t\t\tid = redirect.canonicalSubjectId;\n\t\t\t}\n\t\t\tthrow new Error(\"Cyclic settings subject redirects\");\n\t\t},\n\t\t/** @internal */\n\t\tfindIdentity(scopeType: string, identity: string): SettingsSubject | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.settingsSubjects)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.settingsSubjects.scopeType, scopeType),\n\t\t\t\t\t\teq(s.settingsSubjects.identity, identity),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\treturn row ? this.getSubject(row.id) : null;\n\t\t},\n\t\t/** @internal */\n\t\tfindAlias(alias: string): SettingsSubject | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.settingsAliases)\n\t\t\t\t.where(eq(s.settingsAliases.alias, alias))\n\t\t\t\t.get();\n\t\t\treturn row ? this.getSubject(row.subjectId) : null;\n\t\t},\n\t\t/** @internal */\n\t\tputSubject(input: SubjectWrite): SettingsSubject {\n\t\t\tconst ts = now();\n\t\t\tconst previous = input.id ? this.getSubject(input.id) : null;\n\t\t\tconst values = {\n\t\t\t\tid: input.id ?? generateId(\"scope\"),\n\t\t\t\tscopeType: input.scopeType,\n\t\t\t\tidentity: input.identity,\n\t\t\t\tlabel: input.label,\n\t\t\t\tcontextJson: JSON.stringify(input.context),\n\t\t\t\tschemaVersion: 1,\n\t\t\t\trevision: (previous?.revision ?? 0) + 1,\n\t\t\t\tcreatedAt: previous?.createdAt ?? ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t\tactorJson: JSON.stringify(SYSTEM_ACTOR),\n\t\t\t};\n\t\t\tdb.insert(s.settingsSubjects)\n\t\t\t\t.values(values)\n\t\t\t\t.onConflictDoUpdate({ target: s.settingsSubjects.id, set: values })\n\t\t\t\t.run();\n\t\t\treturn subject(values);\n\t\t},\n\t\t/** @internal */\n\t\tputAlias(alias: string, subjectId: string): void {\n\t\t\tdb.insert(s.settingsAliases).values({ alias, subjectId }).onConflictDoNothing().run();\n\t\t\tif (this.findAlias(alias)?.id !== subjectId)\n\t\t\t\tthrow new Error(`Repository alias '${alias}' already belongs to another settings subject`);\n\t\t},\n\t\t/** @internal */\n\t\tlistOverrides(subjectId?: string): SettingsOverride[] {\n\t\t\tconst canonicalId = subjectId ? (this.getSubject(subjectId)?.id ?? subjectId) : undefined;\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.settingsOverrides)\n\t\t\t\t.where(\n\t\t\t\t\tcanonicalId\n\t\t\t\t\t\t? eq(s.settingsOverrides.subjectId, canonicalId)\n\t\t\t\t\t\t: notInArray(\n\t\t\t\t\t\t\t\ts.settingsOverrides.subjectId,\n\t\t\t\t\t\t\t\tdb\n\t\t\t\t\t\t\t\t\t.select({ id: s.settingsSubjectRedirects.subjectId })\n\t\t\t\t\t\t\t\t\t.from(s.settingsSubjectRedirects),\n\t\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.all()\n\t\t\t\t.map(override);\n\t\t},\n\t\t/** @internal */\n\t\tgetOverride(subjectId: string, key: string): SettingsOverride | null {\n\t\t\tsubjectId = this.getSubject(subjectId)?.id ?? subjectId;\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.settingsOverrides)\n\t\t\t\t.where(and(eq(s.settingsOverrides.subjectId, subjectId), eq(s.settingsOverrides.key, key)))\n\t\t\t\t.get();\n\t\t\treturn row ? override(row) : null;\n\t\t},\n\t\t/** Atomic compare-and-swap, including resets and first writes. @internal */\n\t\twrite(input: SettingsWrite): SettingsOverride | null {\n\t\t\tconst ts = now();\n\t\t\tconst { expectedRevision, ...change } = input;\n\t\t\tconst values = overrideRow({\n\t\t\t\t...change,\n\t\t\t\tsubjectId: this.getSubject(input.subjectId)?.id ?? input.subjectId,\n\t\t\t\trevision: expectedRevision + 1,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t});\n\t\t\tconst { createdAt: _createdAt, ...update } = values;\n\t\t\tif (input.expectedRevision > 0) {\n\t\t\t\tconst row = db\n\t\t\t\t\t.update(s.settingsOverrides)\n\t\t\t\t\t.set(update)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(s.settingsOverrides.subjectId, values.subjectId),\n\t\t\t\t\t\t\teq(s.settingsOverrides.key, input.key),\n\t\t\t\t\t\t\teq(s.settingsOverrides.revision, input.expectedRevision),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.returning()\n\t\t\t\t\t.get();\n\t\t\t\treturn row ? override(row) : null;\n\t\t\t}\n\t\t\tconst row = db\n\t\t\t\t.insert(s.settingsOverrides)\n\t\t\t\t.values(values)\n\t\t\t\t.onConflictDoNothing()\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn row ? override(row) : null;\n\t\t},\n\t\t/** Call inside a transaction after verifying that active overrides agree. @internal */\n\t\tmergeLocatorSubject(sourceId: string, targetId: string): void {\n\t\t\tconst source = this.getSubject(sourceId);\n\t\t\tconst target = this.getSubject(targetId);\n\t\t\tif (\n\t\t\t\t!source ||\n\t\t\t\t!target ||\n\t\t\t\tsource.id === target.id ||\n\t\t\t\tsource.scopeType !== \"repository\" ||\n\t\t\t\ttarget.scopeType !== \"repository\" ||\n\t\t\t\t!source.identity.startsWith(\"locator:\")\n\t\t\t)\n\t\t\t\tthrow new Error(\"Only distinct locator subjects can merge into a repository\");\n\t\t\tfor (const incoming of this.listOverrides(source.id)) {\n\t\t\t\tconst current = this.getOverride(target.id, incoming.key);\n\t\t\t\tconst retained = current && !current.reset ? current : incoming;\n\t\t\t\tconst values = overrideRow({\n\t\t\t\t\t...retained,\n\t\t\t\t\tsubjectId: target.id,\n\t\t\t\t\trevision: Math.max(incoming.revision, current?.revision ?? 0) + 1,\n\t\t\t\t\tupdatedAt: now(),\n\t\t\t\t});\n\t\t\t\tdb.insert(s.settingsOverrides)\n\t\t\t\t\t.values(values)\n\t\t\t\t\t.onConflictDoUpdate({\n\t\t\t\t\t\ttarget: [s.settingsOverrides.subjectId, s.settingsOverrides.key],\n\t\t\t\t\t\tset: values,\n\t\t\t\t\t})\n\t\t\t\t\t.run();\n\t\t\t}\n\t\t\tdb.update(s.settingsAliases)\n\t\t\t\t.set({ subjectId: target.id })\n\t\t\t\t.where(eq(s.settingsAliases.subjectId, source.id))\n\t\t\t\t.run();\n\t\t\t// Keep original subjects and overrides for historical references and attribution.\n\t\t\tdb.insert(s.settingsSubjectRedirects)\n\t\t\t\t.values({ subjectId: source.id, canonicalSubjectId: target.id })\n\t\t\t\t.run();\n\t\t},\n\t};\n}\n","import { asUnknownRecord, type MappedTurnItemRef } from \"@leitwerk-dev/domain\";\n\nexport function mappedItemRef(row: {\n\tmappedRunId: string | null;\n\tmappedItemKey: string | null;\n\tmappedItemIndex: number | null;\n}): MappedTurnItemRef | null {\n\treturn row.mappedRunId !== null && row.mappedItemKey !== null && row.mappedItemIndex !== null\n\t\t? { runId: row.mappedRunId, itemKey: row.mappedItemKey, itemIndex: row.mappedItemIndex }\n\t\t: null;\n}\n\nexport function parsePersistedJson<T>(value: string, label: string): T {\n\ttry {\n\t\treturn JSON.parse(value) as T;\n\t} catch (error) {\n\t\tthrow new Error(`Malformed persisted ${label}`, { cause: error });\n\t}\n}\n\nexport function parseMetadata(raw: string | null | undefined): Record<string, unknown> | null {\n\tif (!raw) return null;\n\ttry {\n\t\treturn JSON.parse(raw) as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function parseJsonRecord(raw: string | null | undefined): Record<string, unknown> | null {\n\treturn asUnknownRecord(parseMetadata(raw));\n}\n\nexport function generateId(prefix: string): string {\n\tconst ts = Date.now().toString(36);\n\tconst rand = Math.random().toString(36).slice(2, 10);\n\treturn `${prefix}_${ts}${rand}`;\n}\n\nexport function now(): string {\n\treturn new Date().toISOString();\n}\n\nexport function sqliteLikePatterns(value: string | undefined): string[] {\n\treturn (value?.trim().toLocaleLowerCase().split(/\\s+/).filter(Boolean) ?? []).map(\n\t\t(term) => `%${term.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\")}%`,\n\t);\n}\n","import type { StartupObservation } from \"@leitwerk-dev/domain\";\nimport { eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport * as s from \"./schema.js\";\n/** @internal */\nexport function createStartupObservationRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\trecord(observation: StartupObservation): boolean {\n\t\t\tif (\n\t\t\t\t!Number.isFinite(Date.parse(observation.observedAt)) ||\n\t\t\t\t(observation.sourceAt !== null && !Number.isFinite(Date.parse(observation.sourceAt)))\n\t\t\t)\n\t\t\t\treturn false;\n\t\t\tconst lease = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.workerLeases)\n\t\t\t\t.where(eq(s.workerLeases.id, observation.workerLeaseId))\n\t\t\t\t.get();\n\t\t\tif (!lease) return false;\n\t\t\treturn (\n\t\t\t\tdb\n\t\t\t\t\t.insert(s.startupObservations)\n\t\t\t\t\t.values({\n\t\t\t\t\t\tworkerLeaseId: observation.workerLeaseId,\n\t\t\t\t\t\tmilestone: observation.milestone,\n\t\t\t\t\t\tobservationJson: JSON.stringify(observation),\n\t\t\t\t\t})\n\t\t\t\t\t.onConflictDoNothing()\n\t\t\t\t\t.run().changes > 0\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\tlistByLease(workerLeaseId: string): StartupObservation[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.startupObservations)\n\t\t\t\t.where(eq(s.startupObservations.workerLeaseId, workerLeaseId))\n\t\t\t\t.all()\n\t\t\t\t.map((row) => JSON.parse(row.observationJson) as StartupObservation);\n\t\t},\n\t};\n}\n","import type {\n\tCompactTurnSummary,\n\tPrimaryPathUiSnapshot,\n\tTurnTracePreview,\n} from \"@leitwerk-dev/protocol\";\nimport { and, eq, inArray, sql } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { sessionSummaries, turnRecords, turnStartRecords, turnSummaries } from \"./schema.js\";\n\n/** @internal */\nexport interface SessionSummary {\n\t/** @internal */\n\tsignature: string | null;\n\t/** @internal */\n\tleafId: string | null;\n\t/** @internal */\n\tprimaryPath: Pick<\n\t\tPrimaryPathUiSnapshot,\n\t\t\"currentLeaf\" | \"semanticEntryRefs\" | \"entryCount\" | \"turnAnnotations\"\n\t>;\n\t/** @internal */\n\tprompt: {\n\t\t/** @internal */\n\t\ttext: string | null;\n\t\t/** @internal */\n\t\tcreatedAt: string | null;\n\t};\n\t/** @internal */\n\ttracePreviewsByTurnRecordId: Record<string, TurnTracePreview>;\n\t/** @internal */\n\tcontinuationByTurnRecordId: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** @internal */\n\t\t\thasProgress: boolean;\n\t\t\t/** @internal */\n\t\t\tuserPrompt: string | null;\n\t\t}\n\t>;\n}\n\n/** @internal */\nexport function createTurnSummaryRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** Dashboard projections never load assistant text, event payloads or session files. @internal */\n\t\tlistDashboardCosts() {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tproviderId: sql<\n\t\t\t\t\t\tstring | null\n\t\t\t\t\t>`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.providerId') end`,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tmodelId: sql<\n\t\t\t\t\t\tstring | null\n\t\t\t\t\t>`case when json_extract(${turnStartRecords.stateJson}, '$.kind') = 'accepted' then json_extract(${turnStartRecords.stateJson}, '$.start.model.modelId') end`,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tcostUsd: sql<\n\t\t\t\t\t\tnumber | null\n\t\t\t\t\t>`json_extract(${turnSummaries.summaryJson}, '$.usage.cost.total')`,\n\t\t\t\t})\n\t\t\t\t.from(turnRecords)\n\t\t\t\t.leftJoin(turnSummaries, eq(turnSummaries.turnRecordId, turnRecords.id))\n\t\t\t\t.leftJoin(turnStartRecords, eq(turnStartRecords.id, turnRecords.turnStartRecordId))\n\t\t\t\t.where(eq(turnRecords.turnType, \"llm\"))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tget(turnRecordId: string): CompactTurnSummary | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(turnSummaries)\n\t\t\t\t.where(eq(turnSummaries.turnRecordId, turnRecordId))\n\t\t\t\t.get();\n\t\t\treturn row ? (JSON.parse(row.summaryJson) as CompactTurnSummary) : null;\n\t\t},\n\t\t/** @internal */\n\t\tput(instanceId: string, turnRecordId: string, summary: CompactTurnSummary) {\n\t\t\tconst summaryJson = JSON.stringify(summary);\n\t\t\tdb.insert(turnSummaries)\n\t\t\t\t.values({ instanceId, turnRecordId, summaryJson })\n\t\t\t\t.onConflictDoUpdate({ target: turnSummaries.turnRecordId, set: { summaryJson } })\n\t\t\t\t.run();\n\t\t},\n\t\t/** @internal */\n\t\tlistByInstance(\n\t\t\tinstanceId: string,\n\t\t\tturnRecordIds?: string[],\n\t\t): Record<string, CompactTurnSummary> {\n\t\t\tif (turnRecordIds?.length === 0) return {};\n\t\t\treturn Object.fromEntries(\n\t\t\t\tdb\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(turnSummaries)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(turnSummaries.instanceId, instanceId),\n\t\t\t\t\t\t\tturnRecordIds ? inArray(turnSummaries.turnRecordId, turnRecordIds) : undefined,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.all()\n\t\t\t\t\t.map((row) => [row.turnRecordId, JSON.parse(row.summaryJson) as CompactTurnSummary]),\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\tgetSession(instanceId: string): SessionSummary | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(sessionSummaries)\n\t\t\t\t.where(eq(sessionSummaries.instanceId, instanceId))\n\t\t\t\t.get();\n\t\t\treturn row ? (JSON.parse(row.summaryJson) as SessionSummary) : null;\n\t\t},\n\t\t/** @internal */\n\t\tputSession(instanceId: string, summary: SessionSummary) {\n\t\t\tconst summaryJson = JSON.stringify(summary);\n\t\t\tdb.insert(sessionSummaries)\n\t\t\t\t.values({ instanceId, summaryJson })\n\t\t\t\t.onConflictDoUpdate({ target: sessionSummaries.instanceId, set: { summaryJson } })\n\t\t\t\t.run();\n\t\t},\n\t\t/** @internal */\n\t\tdeleteSession(instanceId: string) {\n\t\t\tdb.delete(sessionSummaries).where(eq(sessionSummaries.instanceId, instanceId)).run();\n\t\t},\n\t};\n}\n","import type { Actor } from \"@leitwerk-dev/domain\";\nimport { and, eq, gt, lt } from \"drizzle-orm\";\nimport type { OidcEvidence } from \"../auth/oidc-evidence.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface AuthSessionRecord {\n\t/** @internal */\n\tidHash: string;\n\t/** @internal */\n\tactor: Actor;\n\t/** @internal */\n\toidcEvidence: OidcEvidence | null;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\texpiresAt: string;\n}\n\n/** @internal */\nexport interface AuthLoginFlowRecord {\n\t/** @internal */\n\tidHash: string;\n\t/** @internal */\n\tproviderId: string;\n\t/** @internal */\n\tstate: string;\n\t/** @internal */\n\tpkceVerifier: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\texpiresAt: string;\n}\n\nfunction sessionRowToRecord(row: typeof s.authSessions.$inferSelect): AuthSessionRecord {\n\treturn {\n\t\tidHash: row.idHash,\n\t\toidcEvidence: row.oidcEvidenceJson ? JSON.parse(row.oidcEvidenceJson) : null,\n\t\tactor: {\n\t\t\tid: row.actorId,\n\t\t\tkind: \"user\",\n\t\t\tprovider: row.actorProvider as Actor[\"provider\"],\n\t\t\t...(row.displayName && { displayName: row.displayName }),\n\t\t},\n\t\tcreatedAt: row.createdAt,\n\t\texpiresAt: row.expiresAt,\n\t};\n}\n\n/** @internal */\nexport function createAuthSessionRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: {\n\t\t\t/** @internal */\n\t\t\tidHash: string;\n\t\t\t/** @internal */\n\t\t\tactor: Actor;\n\t\t\t/** @internal */\n\t\t\toidcEvidence?: OidcEvidence | null;\n\t\t\t/** @internal */\n\t\t\texpiresAt: string;\n\t\t}): AuthSessionRecord {\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tidHash: input.idHash,\n\t\t\t\tactorId: input.actor.id,\n\t\t\t\toidcEvidenceJson: input.oidcEvidence ? JSON.stringify(input.oidcEvidence) : null,\n\t\t\t\tactorProvider: input.actor.provider,\n\t\t\t\tdisplayName: input.actor.displayName ?? null,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\texpiresAt: input.expiresAt,\n\t\t\t};\n\t\t\tdb.insert(s.authSessions).values(values).run();\n\t\t\treturn sessionRowToRecord(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetValid(idHash: string, atIso: string = now()): AuthSessionRecord | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.authSessions)\n\t\t\t\t.where(and(eq(s.authSessions.idHash, idHash), gt(s.authSessions.expiresAt, atIso)))\n\t\t\t\t.get();\n\t\t\treturn row ? sessionRowToRecord(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(idHash: string): boolean {\n\t\t\tconst result = db.delete(s.authSessions).where(eq(s.authSessions.idHash, idHash)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\n\t\t/** @internal */\n\t\tdeleteExpired(atIso: string = now()): number {\n\t\t\tconst result = db.delete(s.authSessions).where(lt(s.authSessions.expiresAt, atIso)).run();\n\t\t\treturn Number(result.changes);\n\t\t},\n\t};\n}\n\n/** @internal */\nexport function createAuthLoginFlowRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: {\n\t\t\t/** @internal */\n\t\t\tidHash: string;\n\t\t\t/** @internal */\n\t\t\tproviderId: string;\n\t\t\t/** @internal */\n\t\t\tstate: string;\n\t\t\t/** @internal */\n\t\t\tpkceVerifier: string;\n\t\t\t/** @internal */\n\t\t\texpiresAt: string;\n\t\t}): AuthLoginFlowRecord {\n\t\t\tconst values = {\n\t\t\t\tidHash: input.idHash,\n\t\t\t\tproviderId: input.providerId,\n\t\t\t\tstate: input.state,\n\t\t\t\tpkceVerifier: input.pkceVerifier,\n\t\t\t\tcreatedAt: now(),\n\t\t\t\texpiresAt: input.expiresAt,\n\t\t\t};\n\t\t\tdb.insert(s.authLoginFlows).values(values).run();\n\t\t\treturn values;\n\t\t},\n\n\t\t/** @internal */\n\t\tgetValid(idHash: string, atIso: string = now()): AuthLoginFlowRecord | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.authLoginFlows)\n\t\t\t\t.where(and(eq(s.authLoginFlows.idHash, idHash), gt(s.authLoginFlows.expiresAt, atIso)))\n\t\t\t\t.get();\n\t\t\treturn row ?? null;\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(idHash: string): boolean {\n\t\t\tconst result = db.delete(s.authLoginFlows).where(eq(s.authLoginFlows.idHash, idHash)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\n\t\t/** @internal */\n\t\tdeleteExpired(atIso: string = now()): number {\n\t\t\tconst result = db.delete(s.authLoginFlows).where(lt(s.authLoginFlows.expiresAt, atIso)).run();\n\t\t\treturn Number(result.changes);\n\t\t},\n\t};\n}\n","import type { ExternalWriteLog, ExternalWriteType } from \"@leitwerk-dev/domain\";\nimport type { ExternalWriteLogRecordInput } from \"@leitwerk-dev/external-writes/internal\";\nimport { desc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateExternalWriteLogInput extends ExternalWriteLogRecordInput {}\n\nfunction rowToExternalWriteLog(row: typeof s.externalWriteLog.$inferSelect): ExternalWriteLog {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\twriteType: row.writeType as ExternalWriteType,\n\t\tdedupKey: row.dedupKey,\n\t\tcompletedAt: row.completedAt,\n\t\tmetadata: JSON.parse(row.metadata) as Record<string, unknown>,\n\t};\n}\n\n/** @public */\nexport function createExternalWriteLogRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\trecord(input: CreateExternalWriteLogInput): ExternalWriteLog {\n\t\t\tconst id = generateId(\"ewl\");\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\twriteType: input.writeType,\n\t\t\t\tdedupKey: input.dedupKey,\n\t\t\t\tcompletedAt: ts,\n\t\t\t\tmetadata: JSON.stringify(input.metadata ?? {}),\n\t\t\t};\n\t\t\tdb.insert(s.externalWriteLog).values(values).run();\n\t\t\treturn rowToExternalWriteLog(values);\n\t\t},\n\n\t\t/** @internal */\n\t\thasDedupKey(dedupKey: string): boolean {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.externalWriteLog)\n\t\t\t\t.where(eq(s.externalWriteLog.dedupKey, dedupKey))\n\t\t\t\t.get();\n\t\t\treturn row !== undefined;\n\t\t},\n\n\t\t/** @public */\n\t\tlistByInstance(instanceId: string): ExternalWriteLog[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.externalWriteLog)\n\t\t\t\t.where(eq(s.externalWriteLog.instanceId, instanceId))\n\t\t\t\t.orderBy(desc(s.externalWriteLog.completedAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToExternalWriteLog);\n\t\t},\n\t};\n}\n","import type {\n\tDurableModelSelection,\n\tFutureExecution,\n\tFutureExecutionBlockReason,\n\tFutureExecutionKind,\n\tFutureExecutionScheduleKind,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, count, desc, eq, inArray, lte, or, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now, sqliteLikePatterns } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\ninterface FutureExecutionWritableFields {\n\t/** @internal */\n\tscheduleKind: FutureExecutionScheduleKind;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tinstanceId?: string | null;\n\t/** @internal */\n\tlauncherId?: string | null;\n\t/** @internal */\n\tactionId?: string | null;\n\t/** @internal */\n\tpayloadJson: string;\n\t/** @internal */\n\tcronExpression?: string | null;\n\t/** @internal */\n\tnextRunAt: string;\n\t/** @internal */\n\tmodelSelection?: DurableModelSelection | null;\n\t/** @internal */\n\tblockedReason?: FutureExecutionBlockReason | null;\n}\n\n/** @internal */\nexport interface CreateFutureExecutionInput extends FutureExecutionWritableFields {\n\t/** @internal */\n\tid?: string;\n\t/** @internal */\n\tkind: FutureExecutionKind;\n}\n\n/** @internal */\nexport interface FutureExecutionOverviewQuery {\n\t/** @internal */\n\tquery?: string;\n\t/** @internal */\n\tprocessType?: string;\n\t/** @internal */\n\tstatus?: \"all\" | \"running\" | \"scheduled\" | \"needs_attention\" | \"completed\" | \"aborted\";\n\t/** @internal */\n\tmatchingLauncherIdsByTerm?: readonly (readonly string[])[];\n}\n\n/** @internal */\nexport interface FutureExecutionOverviewPageQuery extends FutureExecutionOverviewQuery {\n\t/** @internal */\n\tlimit: number;\n\t/** @internal */\n\toffset: number;\n}\n\n/** @internal */\nexport interface FutureExecutionOverviewWindowQuery extends FutureExecutionOverviewQuery {\n\t/** @internal */\n\tlimit: number;\n\t/** @internal */\n\tsortKey: \"status\" | \"title\" | \"timeline\";\n\t/** @internal */\n\tsortDirection: \"asc\" | \"desc\";\n\t/** @internal */\n\tlauncherFallbackTitles: Readonly<Record<string, string>>;\n}\n\n/** @internal */\nexport type UpdateFutureExecutionInput = Partial<FutureExecutionWritableFields>;\n\nfunction overviewPredicates(input: FutureExecutionOverviewQuery): SQL[] {\n\t// Scheduled actions already have a durable process row; only scheduled launches\n\t// are separate browse records.\n\tconst predicates: SQL[] = [eq(s.futureExecutions.kind, \"launch\")];\n\tif (input.status === \"needs_attention\") {\n\t\tpredicates.push(sql`${s.futureExecutions.blockedReasonJson} is not null`);\n\t} else if (input.status === \"scheduled\") {\n\t\tpredicates.push(sql`${s.futureExecutions.blockedReasonJson} is null`);\n\t} else if (input.status && input.status !== \"all\") {\n\t\tpredicates.push(sql`0 = 1`);\n\t}\n\tconst processType = input.processType?.trim();\n\tif (processType) {\n\t\tpredicates.push(eq(s.futureExecutions.processId, processType));\n\t}\n\tfor (const [index, pattern] of sqliteLikePatterns(input.query).entries()) {\n\t\tconst matchingLauncherIds = input.matchingLauncherIdsByTerm?.[index] ?? [];\n\t\tconst launcherMatch =\n\t\t\tmatchingLauncherIds.length > 0\n\t\t\t\t? inArray(s.futureExecutions.launcherId, [...matchingLauncherIds])\n\t\t\t\t: sql`0 = 1`;\n\t\tpredicates.push(\n\t\t\tor(\n\t\t\t\tsql`lower(${s.futureExecutions.payloadJson}) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tsql`lower(${s.futureExecutions.processId}) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tsql`lower(coalesce(${s.futureExecutions.id}, '')) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tlauncherMatch,\n\t\t\t) as SQL,\n\t\t);\n\t}\n\treturn predicates;\n}\n\nfunction overviewWhere(input: FutureExecutionOverviewQuery): SQL | undefined {\n\tconst predicates = overviewPredicates(input);\n\treturn predicates.length ? and(...predicates) : undefined;\n}\n\nfunction parseBlockReason(value: string | null): FutureExecutionBlockReason | null {\n\tif (!value) return null;\n\tconst parsed = JSON.parse(value) as FutureExecutionBlockReason;\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed === null ||\n\t\ttypeof parsed.code !== \"string\" ||\n\t\ttypeof parsed.summary !== \"string\" ||\n\t\ttypeof parsed.detectedAt !== \"string\" ||\n\t\t(parsed.availabilityRevision !== undefined && typeof parsed.availabilityRevision !== \"number\")\n\t) {\n\t\tthrow new Error(\"Invalid persisted future execution block reason\");\n\t}\n\treturn parsed;\n}\n\nfunction selectionFromRow(\n\trow: typeof s.futureExecutions.$inferSelect,\n): DurableModelSelection | null {\n\tconst values = [row.modelProfileId, row.modelSelectionKind, row.modelSelectionSource];\n\tif (values.every((value) => value === null)) return null;\n\tif (\n\t\ttypeof row.modelProfileId !== \"string\" ||\n\t\t(row.modelSelectionKind !== \"explicit\" && row.modelSelectionKind !== \"inherited\") ||\n\t\ttypeof row.modelSelectionSource !== \"string\"\n\t) {\n\t\tthrow new Error(`Incomplete model selection provenance for future execution '${row.id}'`);\n\t}\n\treturn {\n\t\tmodelProfileId: row.modelProfileId,\n\t\tprovenance: {\n\t\t\tkind: row.modelSelectionKind,\n\t\t\tsource: row.modelSelectionSource as DurableModelSelection[\"provenance\"][\"source\"],\n\t\t},\n\t};\n}\n\nfunction modelSelectionColumns(selection: DurableModelSelection | null | undefined) {\n\treturn {\n\t\tmodelProfileId: selection?.modelProfileId ?? null,\n\t\tmodelSelectionKind: selection?.provenance.kind ?? null,\n\t\tmodelSelectionSource: selection?.provenance.source ?? null,\n\t};\n}\n\nfunction rowToFutureExecution(row: typeof s.futureExecutions.$inferSelect): FutureExecution {\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind as FutureExecutionKind,\n\t\tscheduleKind: row.scheduleKind as FutureExecutionScheduleKind,\n\t\tprocessId: row.processId,\n\t\tinstanceId: row.instanceId ?? null,\n\t\tlauncherId: row.launcherId ?? null,\n\t\tactionId: row.actionId ?? null,\n\t\tpayloadJson: row.payloadJson,\n\t\tcronExpression: row.cronExpression ?? null,\n\t\tnextRunAt: row.nextRunAt,\n\t\tmodelSelection: selectionFromRow(row),\n\t\tblockedReason: parseBlockReason(row.blockedReasonJson),\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n}\n\n/** @internal */\nexport function createFutureExecutionRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateFutureExecutionInput): FutureExecution {\n\t\t\tconst id = input.id ?? generateId(\"fut\");\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tkind: input.kind,\n\t\t\t\tscheduleKind: input.scheduleKind,\n\t\t\t\tprocessId: input.processId,\n\t\t\t\tinstanceId: input.instanceId ?? null,\n\t\t\t\tlauncherId: input.launcherId ?? null,\n\t\t\t\tactionId: input.actionId ?? null,\n\t\t\t\tpayloadJson: input.payloadJson,\n\t\t\t\tcronExpression: input.cronExpression ?? null,\n\t\t\t\tnextRunAt: input.nextRunAt,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t\t...modelSelectionColumns(input.modelSelection),\n\t\t\t\tblockedReasonJson: input.blockedReason ? JSON.stringify(input.blockedReason) : null,\n\t\t\t};\n\t\t\tdb.insert(s.futureExecutions).values(values).run();\n\t\t\treturn rowToFutureExecution(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): FutureExecution | null {\n\t\t\tconst row = db.select().from(s.futureExecutions).where(eq(s.futureExecutions.id, id)).get();\n\t\t\treturn row ? rowToFutureExecution(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tlistAll(): FutureExecution[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t},\n\n\t\t/** @internal */\n\t\tcountOverview(input: FutureExecutionOverviewQuery): number {\n\t\t\treturn (\n\t\t\t\tdb.select({ value: count() }).from(s.futureExecutions).where(overviewWhere(input)).get()\n\t\t\t\t\t?.value ?? 0\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistOverviewProcessTypes(\n\t\t\tinput: Pick<FutureExecutionOverviewQuery, \"query\" | \"status\" | \"matchingLauncherIdsByTerm\">,\n\t\t) {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tprocessId: s.futureExecutions.processId,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tvalue: count(),\n\t\t\t\t})\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(overviewWhere(input))\n\t\t\t\t.groupBy(s.futureExecutions.processId)\n\t\t\t\t.orderBy(asc(s.futureExecutions.processId))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistOverviewWindow(input: FutureExecutionOverviewWindowQuery): FutureExecution[] {\n\t\t\tconst fallbackCases = Object.entries(input.launcherFallbackTitles).map(\n\t\t\t\t([launcherId, title]) => sql`when ${launcherId} then ${title}`,\n\t\t\t);\n\t\t\tconst unknownLauncherFallback = sql<string>`case\n\t\t\t\twhen json_valid(${s.futureExecutions.payloadJson}) then ${s.futureExecutions.processId}\n\t\t\t\telse coalesce(${s.futureExecutions.launcherId}, ${s.futureExecutions.processId}) end`;\n\t\t\tconst launcherFallback =\n\t\t\t\tfallbackCases.length > 0\n\t\t\t\t\t? sql<string>`case ${s.futureExecutions.launcherId} ${sql.join(fallbackCases, sql.raw(\" \"))} else ${unknownLauncherFallback} end`\n\t\t\t\t\t: unknownLauncherFallback;\n\t\t\tconst title = sql<string>`coalesce(\n\t\t\t\tcase when json_valid(${s.futureExecutions.payloadJson})\n\t\t\t\t\tthen nullif(trim(json_extract(${s.futureExecutions.payloadJson}, '$.launchPlan.processInput.title')), '') end,\n\t\t\t\tcase when json_valid(${s.futureExecutions.payloadJson})\n\t\t\t\t\tthen nullif(trim(json_extract(${s.futureExecutions.payloadJson}, '$.launchPlan.processInput.externalId')), '') end,\n\t\t\t\t${launcherFallback}\n\t\t\t)`;\n\t\t\tconst primary = input.sortKey === \"timeline\" ? s.futureExecutions.nextRunAt : title;\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(overviewWhere(input))\n\t\t\t\t.orderBy(\n\t\t\t\t\tinput.sortKey !== \"status\" && input.sortDirection === \"desc\"\n\t\t\t\t\t\t? desc(primary)\n\t\t\t\t\t\t: asc(primary),\n\t\t\t\t\tasc(title),\n\t\t\t\t\tasc(s.futureExecutions.id),\n\t\t\t\t)\n\t\t\t\t.limit(input.limit)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistOverviewPage(input: FutureExecutionOverviewPageQuery): {\n\t\t\t/** @internal */\n\t\t\titems: FutureExecution[];\n\t\t\t/** @internal */\n\t\t\ttotal: number;\n\t\t} {\n\t\t\tconst items = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(overviewWhere(input))\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.limit(input.limit)\n\t\t\t\t.offset(input.offset)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t\tconst total = this.countOverview(input);\n\t\t\treturn { items, total };\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string): FutureExecution[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(eq(s.futureExecutions.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistRunnableDue(asOf: string): FutureExecution[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\tlte(s.futureExecutions.nextRunAt, asOf),\n\t\t\t\t\t\tsql`${s.futureExecutions.blockedReasonJson} is null`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistBlockedCronDue(asOf: string): FutureExecution[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\tlte(s.futureExecutions.nextRunAt, asOf),\n\t\t\t\t\t\teq(s.futureExecutions.scheduleKind, \"cron\"),\n\t\t\t\t\t\tsql`${s.futureExecutions.blockedReasonJson} is not null`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToFutureExecution);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetScheduledActionByInstance(instanceId: string): FutureExecution | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.futureExecutions)\n\t\t\t\t.where(\n\t\t\t\t\tand(eq(s.futureExecutions.instanceId, instanceId), eq(s.futureExecutions.kind, \"action\")),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.futureExecutions.nextRunAt), asc(s.futureExecutions.createdAt))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToFutureExecution(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdatePayloadJsonIfUnchanged(\n\t\t\tid: string,\n\t\t\texpectedPayloadJson: string,\n\t\t\tpayloadJson: string,\n\t\t): FutureExecution | null {\n\t\t\tconst result = db\n\t\t\t\t.update(s.futureExecutions)\n\t\t\t\t.set({ payloadJson, updatedAt: now() })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.futureExecutions.id, id),\n\t\t\t\t\t\teq(s.futureExecutions.payloadJson, expectedPayloadJson),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0 ? this.getById(id) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(id: string, input: UpdateFutureExecutionInput): FutureExecution | null {\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.futureExecutions> = {\n\t\t\t\tupdatedAt: now(),\n\t\t\t\tscheduleKind: input.scheduleKind,\n\t\t\t\tprocessId: input.processId,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tlauncherId: input.launcherId,\n\t\t\t\tactionId: input.actionId,\n\t\t\t\tpayloadJson: input.payloadJson,\n\t\t\t\tcronExpression: input.cronExpression,\n\t\t\t\tnextRunAt: input.nextRunAt,\n\t\t\t};\n\t\t\tif (input.modelSelection !== undefined)\n\t\t\t\tObject.assign(setValues, modelSelectionColumns(input.modelSelection));\n\t\t\tif (input.blockedReason !== undefined)\n\t\t\t\tsetValues.blockedReasonJson = input.blockedReason\n\t\t\t\t\t? JSON.stringify(input.blockedReason)\n\t\t\t\t\t: null;\n\n\t\t\tdb.update(s.futureExecutions).set(setValues).where(eq(s.futureExecutions.id, id)).run();\n\t\t\treturn this.getById(id);\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(id: string): boolean {\n\t\t\tconst result = db.delete(s.futureExecutions).where(eq(s.futureExecutions.id, id)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\t};\n}\n","import type {\n\tLaunchChecklistStep,\n\tLaunchOrigin,\n\tLaunchRun,\n\tLaunchRunStatus,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, eq, inArray, type SQL } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nconst ACTIVE_STATUSES: readonly LaunchRunStatus[] = [\"preparing\", \"process_created\", \"starting\"];\n\nfunction parseSteps(value: string): LaunchChecklistStep[] {\n\tconst parsed: unknown = JSON.parse(value);\n\tif (!Array.isArray(parsed)) throw new Error(\"Invalid launch checklist state\");\n\treturn parsed as LaunchChecklistStep[];\n}\n\nfunction toLaunchRun(row: typeof s.launchRuns.$inferSelect): LaunchRun {\n\treturn {\n\t\tid: row.id,\n\t\tlauncherId: row.launcherId ?? null,\n\t\torigin: row.origin as LaunchOrigin,\n\t\tinstanceId: row.instanceId ?? null,\n\t\tstatus: row.status as LaunchRunStatus,\n\t\tsteps: parseSteps(row.stepsJson),\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t\tcompletedAt: row.completedAt ?? null,\n\t\trevision: row.revision,\n\t};\n}\n\n/** @internal */\nexport interface CreateLaunchRunInput {\n\t/** @internal */\n\tlauncherId: string | null;\n\t/** @internal */\n\tidempotencyKey?: string | null;\n\t/** @internal */\n\torigin: LaunchOrigin;\n\t/** @internal */\n\tsteps: readonly LaunchChecklistStep[];\n}\n\n/** @internal */\nexport function createLaunchRunRepo(db: LeitwerkDb) {\n\tconst list = (where: SQL): LaunchRun[] =>\n\t\tdb\n\t\t\t.select()\n\t\t\t.from(s.launchRuns)\n\t\t\t.where(where)\n\t\t\t.orderBy(asc(s.launchRuns.createdAt), asc(s.launchRuns.id))\n\t\t\t.all()\n\t\t\t.map(toLaunchRun);\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateLaunchRunInput): LaunchRun {\n\t\t\tconst ts = now();\n\t\t\tconst row = {\n\t\t\t\tid: generateId(\"lnr\"),\n\t\t\t\tidempotencyKey: input.idempotencyKey ?? null,\n\t\t\t\tlauncherId: input.launcherId,\n\t\t\t\torigin: input.origin,\n\t\t\t\tinstanceId: null,\n\t\t\t\tstatus: \"preparing\",\n\t\t\t\tstepsJson: JSON.stringify(input.steps),\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t\tcompletedAt: null,\n\t\t\t\trevision: 0,\n\t\t\t} satisfies typeof s.launchRuns.$inferInsert;\n\t\t\tdb.insert(s.launchRuns).values(row).run();\n\t\t\treturn toLaunchRun(row);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): LaunchRun | null {\n\t\t\tconst row = db.select().from(s.launchRuns).where(eq(s.launchRuns.id, id)).get();\n\t\t\treturn row ? toLaunchRun(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tsaveReplay(runId: string, payload: unknown): void {\n\t\t\tdb.insert(s.launchRunReplays)\n\t\t\t\t.values({ launchRunId: runId, payloadJson: JSON.stringify(payload) })\n\t\t\t\t.onConflictDoUpdate({\n\t\t\t\t\ttarget: s.launchRunReplays.launchRunId,\n\t\t\t\t\tset: { payloadJson: JSON.stringify(payload) },\n\t\t\t\t})\n\t\t\t\t.run();\n\t\t},\n\n\t\t/** @internal */\n\t\tgetReplay<T>(runId: string): T | null {\n\t\t\tconst row = db\n\t\t\t\t.select({ payloadJson: s.launchRunReplays.payloadJson })\n\t\t\t\t.from(s.launchRunReplays)\n\t\t\t\t.where(eq(s.launchRunReplays.launchRunId, runId))\n\t\t\t\t.get();\n\t\t\treturn row ? (JSON.parse(row.payloadJson) as T) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tdeleteReplay(runId: string): void {\n\t\t\tdb.delete(s.launchRunReplays).where(eq(s.launchRunReplays.launchRunId, runId)).run();\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByIdempotencyKey(key: string): LaunchRun | null {\n\t\t\tconst row = db.select().from(s.launchRuns).where(eq(s.launchRuns.idempotencyKey, key)).get();\n\t\t\treturn row ? toLaunchRun(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tarchiveIdempotencyKey(id: string, key: string): void {\n\t\t\tdb.update(s.launchRuns)\n\t\t\t\t.set({ idempotencyKey: `${key}:attempt:${id}` })\n\t\t\t\t.where(and(eq(s.launchRuns.id, id), eq(s.launchRuns.idempotencyKey, key)))\n\t\t\t\t.run();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance: (instanceId: string) => list(eq(s.launchRuns.instanceId, instanceId)),\n\t\t/** @internal */\n\t\tlistIncomplete: () => list(inArray(s.launchRuns.status, [...ACTIVE_STATUSES])),\n\n\t\t/** @internal */\n\t\tcompareAndSet(next: LaunchRun, expectedRevision: number): LaunchRun | null {\n\t\t\tconst updatedAt = now();\n\t\t\tconst result = db\n\t\t\t\t.update(s.launchRuns)\n\t\t\t\t.set({\n\t\t\t\t\tlauncherId: next.launcherId,\n\t\t\t\t\torigin: next.origin,\n\t\t\t\t\tinstanceId: next.instanceId,\n\t\t\t\t\tstatus: next.status,\n\t\t\t\t\tstepsJson: JSON.stringify(next.steps),\n\t\t\t\t\tupdatedAt,\n\t\t\t\t\tcompletedAt: next.completedAt,\n\t\t\t\t\trevision: expectedRevision + 1,\n\t\t\t\t})\n\t\t\t\t.where(and(eq(s.launchRuns.id, next.id), eq(s.launchRuns.revision, expectedRevision)))\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0 ? this.getById(next.id) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(id: string, mutate: (current: LaunchRun) => LaunchRun): LaunchRun | null {\n\t\t\tfor (let attempt = 0; attempt < 8; attempt += 1) {\n\t\t\t\tconst current = this.getById(id);\n\t\t\t\tif (!current) return null;\n\t\t\t\tconst updated = this.compareAndSet(mutate(current), current.revision);\n\t\t\t\tif (updated) return updated;\n\t\t\t}\n\t\t\tthrow new Error(`Launch run '${id}' could not be updated concurrently`);\n\t\t},\n\t};\n}\n","import { and, desc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface LauncherRecentValue {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tfieldId: string;\n\t/** @internal */\n\tvalue: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tupdatedAt: string;\n}\n\n/** @internal */\nexport function createLauncherRecentValueRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tlistByLauncher(launcherId: string): LauncherRecentValue[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.launcherRecentValues)\n\t\t\t\t.where(eq(s.launcherRecentValues.launcherId, launcherId))\n\t\t\t\t.orderBy(desc(s.launcherRecentValues.updatedAt), desc(s.launcherRecentValues.createdAt))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\trecordValue(input: {\n\t\t\t/** @internal */\n\t\t\tlauncherId: string;\n\t\t\t/** @internal */\n\t\t\tfieldId: string;\n\t\t\t/** @internal */\n\t\t\tvalue: string;\n\t\t\t/** @internal */\n\t\t\tlimit?: number;\n\t\t}): LauncherRecentValue {\n\t\t\tconst ts = now();\n\t\t\tconst row = db\n\t\t\t\t.insert(s.launcherRecentValues)\n\t\t\t\t.values({\n\t\t\t\t\tid: generateId(\"lrv\"),\n\t\t\t\t\tlauncherId: input.launcherId,\n\t\t\t\t\tfieldId: input.fieldId,\n\t\t\t\t\tvalue: input.value,\n\t\t\t\t\tcreatedAt: ts,\n\t\t\t\t\tupdatedAt: ts,\n\t\t\t\t})\n\t\t\t\t.onConflictDoUpdate({\n\t\t\t\t\ttarget: [\n\t\t\t\t\t\ts.launcherRecentValues.launcherId,\n\t\t\t\t\t\ts.launcherRecentValues.fieldId,\n\t\t\t\t\t\ts.launcherRecentValues.value,\n\t\t\t\t\t],\n\t\t\t\t\tset: { updatedAt: ts },\n\t\t\t\t})\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\tthis.pruneField(input.launcherId, input.fieldId, input.limit ?? 5);\n\t\t\treturn row;\n\t\t},\n\n\t\t/** @internal */\n\t\tpruneField(launcherId: string, fieldId: string, limit = 5): void {\n\t\t\tconst stale = db\n\t\t\t\t.select({ id: s.launcherRecentValues.id })\n\t\t\t\t.from(s.launcherRecentValues)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.launcherRecentValues.launcherId, launcherId),\n\t\t\t\t\t\teq(s.launcherRecentValues.fieldId, fieldId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(desc(s.launcherRecentValues.updatedAt), desc(s.launcherRecentValues.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.slice(limit);\n\t\t\tfor (const entry of stale) {\n\t\t\t\tdb.delete(s.launcherRecentValues).where(eq(s.launcherRecentValues.id, entry.id)).run();\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { MappedItem, MappedRun, MappedRunStatus, TurnId } from \"@leitwerk-dev/domain\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateMappedRunInput {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tstatus: MappedRunStatus;\n\t/** @internal */\n\titems: ReadonlyArray<Pick<MappedItem, \"itemIndex\" | \"itemKey\" | \"label\" | \"itemJson\">>;\n}\n\n/** @internal */\nexport interface CompleteMappedItemInput {\n\t/** @internal */\n\trunId: string;\n\t/** @internal */\n\titemIndex: number;\n\t/** @internal */\n\toutcome: string;\n\t/** @internal */\n\tresultJson: string;\n\t/** @internal */\n\tturnRecordId: string;\n}\n\n/** @internal */\nexport function createMappedLlmRunRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateMappedRunInput): MappedRun {\n\t\t\tconst ts = now();\n\t\t\tconst run = {\n\t\t\t\tid: input.id,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tstatus: input.status,\n\t\t\t\titemCount: input.items.length,\n\t\t\t\tnextIndex: input.status === \"completed\" ? input.items.length : 0,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t};\n\t\t\tdb.insert(s.mappedLlmRuns).values(run).run();\n\t\t\tfor (const item of input.items) {\n\t\t\t\tdb.insert(s.mappedLlmItems)\n\t\t\t\t\t.values({\n\t\t\t\t\t\trunId: input.id,\n\t\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\t\titemIndex: item.itemIndex,\n\t\t\t\t\t\titemKey: item.itemKey,\n\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\titemJson: item.itemJson,\n\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t})\n\t\t\t\t\t.run();\n\t\t\t}\n\t\t\treturn run;\n\t\t},\n\t\t/** @internal */\n\t\tgetById(id: string): MappedRun | null {\n\t\t\treturn db.select().from(s.mappedLlmRuns).where(eq(s.mappedLlmRuns.id, id)).get() ?? null;\n\t\t},\n\t\t/** @internal */\n\t\tgetActiveByInstance(instanceId: string): MappedRun | null {\n\t\t\treturn (\n\t\t\t\tdb\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(s.mappedLlmRuns)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(eq(s.mappedLlmRuns.instanceId, instanceId), eq(s.mappedLlmRuns.status, \"active\")),\n\t\t\t\t\t)\n\t\t\t\t\t.get() ?? null\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string): MappedRun[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.mappedLlmRuns)\n\t\t\t\t.where(eq(s.mappedLlmRuns.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(s.mappedLlmRuns.createdAt))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tlistItems(runId: string): MappedItem[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.mappedLlmItems)\n\t\t\t\t.where(eq(s.mappedLlmItems.runId, runId))\n\t\t\t\t.orderBy(asc(s.mappedLlmItems.itemIndex))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tlistItemsByInstance(instanceId: string): MappedItem[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.mappedLlmItems)\n\t\t\t\t.where(eq(s.mappedLlmItems.instanceId, instanceId))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tgetItem(runId: string, itemIndex: number): MappedItem | null {\n\t\t\treturn (\n\t\t\t\tdb\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(s.mappedLlmItems)\n\t\t\t\t\t.where(and(eq(s.mappedLlmItems.runId, runId), eq(s.mappedLlmItems.itemIndex, itemIndex)))\n\t\t\t\t\t.get() ?? null\n\t\t\t);\n\t\t},\n\t\t/**\n\t\t * Records one item result and advances the run. Fails unless the item is the\n\t\t * run's current pending item, so a replayed outcome cannot complete it twice.\n\t\t * @internal\n\t\t */\n\t\tcompleteItem(input: CompleteMappedItemInput): MappedRun {\n\t\t\tconst run = this.getById(input.runId);\n\t\t\tif (!run || run.status !== \"active\" || run.nextIndex !== input.itemIndex) {\n\t\t\t\tthrow new Error(`Mapped item ${input.itemIndex} of run '${input.runId}' is not current`);\n\t\t\t}\n\t\t\tconst ts = now();\n\t\t\tconst updated = db\n\t\t\t\t.update(s.mappedLlmItems)\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\toutcome: input.outcome,\n\t\t\t\t\tresultJson: input.resultJson,\n\t\t\t\t\tturnRecordId: input.turnRecordId,\n\t\t\t\t\tcompletedAt: ts,\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.mappedLlmItems.runId, input.runId),\n\t\t\t\t\t\teq(s.mappedLlmItems.itemIndex, input.itemIndex),\n\t\t\t\t\t\teq(s.mappedLlmItems.status, \"pending\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\tif (updated.changes !== 1) {\n\t\t\t\tthrow new Error(`Mapped item ${input.itemIndex} of run '${input.runId}' is not pending`);\n\t\t\t}\n\t\t\tconst nextIndex = input.itemIndex + 1;\n\t\t\tdb.update(s.mappedLlmRuns)\n\t\t\t\t.set({\n\t\t\t\t\tnextIndex,\n\t\t\t\t\tstatus: nextIndex === run.itemCount ? \"completed\" : \"active\",\n\t\t\t\t\tupdatedAt: ts,\n\t\t\t\t})\n\t\t\t\t.where(eq(s.mappedLlmRuns.id, input.runId))\n\t\t\t\t.run();\n\t\t\treturn this.getById(input.runId) as MappedRun;\n\t\t},\n\t\t/** @internal */\n\t\tabortActiveByInstance(instanceId: string): number {\n\t\t\treturn Number(\n\t\t\t\tdb\n\t\t\t\t\t.update(s.mappedLlmRuns)\n\t\t\t\t\t.set({ status: \"aborted\", updatedAt: now() })\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(eq(s.mappedLlmRuns.instanceId, instanceId), eq(s.mappedLlmRuns.status, \"active\")),\n\t\t\t\t\t)\n\t\t\t\t\t.run().changes,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** @internal */\nexport type MappedLlmRunRepo = ReturnType<typeof createMappedLlmRunRepo>;\n","import { and, asc, eq } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface PendingExternalSourceFire {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tarmingId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\texternalActionId: string;\n\t/** @internal */\n\tsourceKind: string;\n\t/** @internal */\n\tinput: Record<string, unknown>;\n\t/** @internal */\n\tevent: Record<string, unknown>;\n\t/** @internal */\n\tmergeKey: string | null;\n\t/** @internal */\n\tqueuedCount: number;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tupdatedAt: string;\n}\n\n/** @internal */\nexport interface CreatePendingExternalSourceFireInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tarmingId: string;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\texternalActionId: string;\n\t/** @internal */\n\tsourceKind?: string;\n\t/** @internal */\n\tinput?: Record<string, unknown>;\n\t/** @internal */\n\tevent?: Record<string, unknown>;\n\t/** @internal */\n\tmergeKey?: string | null;\n\t/** @internal */\n\tqueuedCount?: number;\n}\n\n/** @internal */\nexport interface UpdatePendingExternalSourceFireInput {\n\t/** @internal */\n\tinput?: Record<string, unknown>;\n\t/** @internal */\n\tevent?: Record<string, unknown>;\n\t/** @internal */\n\tqueuedCount?: number;\n}\n\nfunction parseRecord(json: string): Record<string, unknown> {\n\tconst value = JSON.parse(json) as unknown;\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: {};\n}\n\nfunction rowToPendingExternalSourceFire(\n\trow: typeof s.pendingExternalSourceFires.$inferSelect,\n): PendingExternalSourceFire {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tarmingId: row.armingId,\n\t\tturnId: row.turnId,\n\t\texternalActionId: row.externalActionId,\n\t\tsourceKind: row.sourceKind,\n\t\tinput: parseRecord(row.inputJson),\n\t\tevent: parseRecord(row.eventJson),\n\t\tmergeKey: row.mergeKey,\n\t\tqueuedCount: row.queuedCount,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n}\n\n/** @internal */\nexport function createPendingExternalSourceFireRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreatePendingExternalSourceFireInput): PendingExternalSourceFire {\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tid: generateId(\"pxf\"),\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tarmingId: input.armingId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\texternalActionId: input.externalActionId,\n\t\t\t\tsourceKind: input.sourceKind ?? \"\",\n\t\t\t\tinputJson: JSON.stringify(input.input ?? {}),\n\t\t\t\teventJson: JSON.stringify(input.event ?? {}),\n\t\t\t\tmergeKey: input.mergeKey ?? null,\n\t\t\t\tqueuedCount: input.queuedCount ?? 1,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t};\n\t\t\tdb.insert(s.pendingExternalSourceFires).values(values).run();\n\t\t\treturn rowToPendingExternalSourceFire(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string): PendingExternalSourceFire[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.pendingExternalSourceFires)\n\t\t\t\t.where(eq(s.pendingExternalSourceFires.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(s.pendingExternalSourceFires.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToPendingExternalSourceFire);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByMergeKey(\n\t\t\tinstanceId: string,\n\t\t\tarmingId: string,\n\t\t\tmergeKey: string,\n\t\t): PendingExternalSourceFire | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.pendingExternalSourceFires)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.pendingExternalSourceFires.instanceId, instanceId),\n\t\t\t\t\t\teq(s.pendingExternalSourceFires.armingId, armingId),\n\t\t\t\t\t\teq(s.pendingExternalSourceFires.mergeKey, mergeKey),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\treturn row ? rowToPendingExternalSourceFire(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(\n\t\t\tid: string,\n\t\t\tinput: UpdatePendingExternalSourceFireInput,\n\t\t): PendingExternalSourceFire | null {\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.pendingExternalSourceFires> = {\n\t\t\t\tupdatedAt: now(),\n\t\t\t\tqueuedCount: input.queuedCount,\n\t\t\t};\n\t\t\tif (input.input !== undefined) setValues.inputJson = JSON.stringify(input.input);\n\t\t\tif (input.event !== undefined) setValues.eventJson = JSON.stringify(input.event);\n\n\t\t\tdb.update(s.pendingExternalSourceFires)\n\t\t\t\t.set(setValues)\n\t\t\t\t.where(eq(s.pendingExternalSourceFires.id, id))\n\t\t\t\t.run();\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.pendingExternalSourceFires)\n\t\t\t\t.where(eq(s.pendingExternalSourceFires.id, id))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToPendingExternalSourceFire(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(id: string): boolean {\n\t\t\tconst result = db\n\t\t\t\t.delete(s.pendingExternalSourceFires)\n\t\t\t\t.where(eq(s.pendingExternalSourceFires.id, id))\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\t};\n}\n","import type { ProcessEvent } from \"@leitwerk-dev/domain\";\nimport { applyEventToCompactTurnSummary, emptyCompactTurnSummary } from \"@leitwerk-dev/protocol\";\nimport type { SQL } from \"drizzle-orm\";\nimport { and, asc, desc, eq, getTableColumns, gte, inArray, like, sql } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\nimport { createTurnSummaryRepo } from \"./turn-summary-repo.js\";\n\n/** @internal */\nexport interface CreateProcessEventInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata?: Record<string, unknown>;\n}\n\nfunction rowToProcessEvent(row: typeof s.processEvents.$inferSelect): ProcessEvent {\n\treturn {\n\t\tid: row.id,\n\t\teventSequence: row.eventSequence,\n\t\tinstanceId: row.instanceId,\n\t\teventType: row.eventType,\n\t\tdata: JSON.parse(row.data) as Record<string, unknown>,\n\t\tcreatedAt: row.createdAt,\n\t};\n}\n\n/** @internal */\nexport function createProcessEventRepo(db: LeitwerkDb) {\n\tconst summaries = createTurnSummaryRepo(db);\n\tconst listNewest = (where: SQL | undefined, limit: number): ProcessEvent[] =>\n\t\tdb\n\t\t\t.select()\n\t\t\t.from(s.processEvents)\n\t\t\t.where(where)\n\t\t\t.orderBy(desc(s.processEvents.eventSequence))\n\t\t\t.limit(limit)\n\t\t\t.all()\n\t\t\t.map(rowToProcessEvent);\n\treturn {\n\t\t/** Timeline facts without embedded process state or provider responses. @internal */\n\t\tlistUiSnapshotEvents(instanceId: string, turnRecordIds: readonly string[]): ProcessEvent[] {\n\t\t\tconst newestIds = (where: SQL | undefined, limit: number) =>\n\t\t\t\tdb\n\t\t\t\t\t.select({ id: s.processEvents.id, sequence: s.processEvents.eventSequence })\n\t\t\t\t\t.from(s.processEvents)\n\t\t\t\t\t.where(where)\n\t\t\t\t\t.orderBy(desc(s.processEvents.eventSequence))\n\t\t\t\t\t.limit(limit)\n\t\t\t\t\t.all();\n\t\t\t// Select identities before loading payloads. Most candidates are discarded\n\t\t\t// by the combined limit, and one provider response can be megabytes.\n\t\t\tconst candidates = [\n\t\t\t\t\"worker_capacity_queued\",\n\t\t\t\t\"lifecycle_parked\",\n\t\t\t\t\"worker_failed\",\n\t\t\t\t\"external_trigger_listener_armed\",\n\t\t\t\t\"external_source_armed\",\n\t\t\t\t\"external_trigger_failed\",\n\t\t\t\t\"external_source_failed\",\n\t\t\t\t\"external_trigger_consumed\",\n\t\t\t\t\"external_source_consumed\",\n\t\t\t].flatMap((eventType) =>\n\t\t\t\tnewestIds(\n\t\t\t\t\tand(eq(s.processEvents.instanceId, instanceId), eq(s.processEvents.eventType, eventType)),\n\t\t\t\t\t40,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcandidates.sort((left, right) => right.sequence - left.sequence);\n\t\t\tconst selected = candidates.slice(0, 40);\n\t\t\tfor (const turnRecordId of turnRecordIds) {\n\t\t\t\tfor (const eventType of [\"turn.progress\", \"turn_outcome_recorded\"]) {\n\t\t\t\t\tselected.push(\n\t\t\t\t\t\t...newestIds(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\t\t\t\teq(s.processEvents.turnRecordId, turnRecordId),\n\t\t\t\t\t\t\t\teq(s.processEvents.eventType, eventType),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst ids = [...new Set(selected.map((event) => event.id))];\n\t\t\tif (ids.length === 0) return [];\n\t\t\tconst data = s.processEvents.data;\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t...getTableColumns(s.processEvents),\n\t\t\t\t\tdata: sql<string>`json_object(\n\t\t\t\t\t\t'turnRecordId', json_extract(${data}, '$.turnRecordId'),\n\t\t\t\t\t\t'turnId', json_extract(${data}, '$.turnId'),\n\t\t\t\t\t\t'outcome', json_extract(${data}, '$.outcome'),\n\t\t\t\t\t\t'params', json_object(\n\t\t\t\t\t\t\t'summary', json_extract(${data}, '$.params.summary'),\n\t\t\t\t\t\t\t'planMarkdown', json_extract(${data}, '$.params.planMarkdown'),\n\t\t\t\t\t\t\t'reviewMarkdown', json_extract(${data}, '$.params.reviewMarkdown'),\n\t\t\t\t\t\t\t'feedback', json_extract(${data}, '$.params.feedback')),\n\t\t\t\t\t\t'report', json_extract(${data}, '$.report'),\n\t\t\t\t\t\t'revision', json_extract(${data}, '$.revision'),\n\t\t\t\t\t\t'startRecordId', json_extract(${data}, '$.startRecordId'),\n\t\t\t\t\t\t'reason', json_extract(${data}, '$.reason'),\n\t\t\t\t\t\t'message', json_extract(${data}, '$.message'),\n\t\t\t\t\t\t'errorCode', json_extract(${data}, '$.errorCode'),\n\t\t\t\t\t\t'errorClass', json_extract(${data}, '$.errorClass'),\n\t\t\t\t\t\t'armingId', json_extract(${data}, '$.armingId'),\n\t\t\t\t\t\t'trigger', json_extract(${data}, '$.trigger'),\n\t\t\t\t\t\t'path', json_extract(${data}, '$.path'),\n\t\t\t\t\t\t'pollInterval', json_extract(${data}, '$.pollInterval'),\n\t\t\t\t\t\t'provider', json_object(\n\t\t\t\t\t\t\t'path', json_extract(${data}, '$.provider.path'),\n\t\t\t\t\t\t\t'pollInterval', json_extract(${data}, '$.provider.pollInterval'))\n\t\t\t\t\t)`,\n\t\t\t\t})\n\t\t\t\t.from(s.processEvents)\n\t\t\t\t.where(inArray(s.processEvents.id, ids))\n\t\t\t\t.orderBy(asc(s.processEvents.createdAt), asc(s.processEvents.id))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessEvent);\n\t\t},\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessEventInput): ProcessEvent {\n\t\t\tconst id = generateId(\"evt\");\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\teventSequence:\n\t\t\t\t\t(db\n\t\t\t\t\t\t.select({ sequence: sql<number>`coalesce(max(${s.processEvents.eventSequence}), 0)` })\n\t\t\t\t\t\t.from(s.processEvents)\n\t\t\t\t\t\t.get()?.sequence ?? 0) + 1,\n\t\t\t\tturnRecordId: typeof input.data?.turnRecordId === \"string\" ? input.data.turnRecordId : null,\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\teventType: input.eventType,\n\t\t\t\tdata: JSON.stringify(input.data ?? {}),\n\t\t\t\tcreatedAt: ts,\n\t\t\t};\n\t\t\tdb.transaction(() => {\n\t\t\t\tdb.insert(s.processEvents).values(values).run();\n\t\t\t\tif (values.turnRecordId) {\n\t\t\t\t\tsummaries.put(\n\t\t\t\t\t\tinput.instanceId,\n\t\t\t\t\t\tvalues.turnRecordId,\n\t\t\t\t\t\tapplyEventToCompactTurnSummary(\n\t\t\t\t\t\t\tsummaries.get(values.turnRecordId) ?? emptyCompactTurnSummary(),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\teventType: input.eventType,\n\t\t\t\t\t\t\t\tdata: input.data ?? {},\n\t\t\t\t\t\t\t\tcreatedAt: ts,\n\t\t\t\t\t\t\t\teventSequence: values.eventSequence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn rowToProcessEvent(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tlatestSequence(instanceId: string): number {\n\t\t\treturn (\n\t\t\t\tdb\n\t\t\t\t\t.select({ sequence: s.processEvents.eventSequence })\n\t\t\t\t\t.from(s.processEvents)\n\t\t\t\t\t.where(eq(s.processEvents.instanceId, instanceId))\n\t\t\t\t\t.orderBy(desc(s.processEvents.eventSequence))\n\t\t\t\t\t.limit(1)\n\t\t\t\t\t.get()?.sequence ?? 0\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\tlistByTurnRecord(instanceId: string, turnRecordId: string): ProcessEvent[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processEvents)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\t\teq(s.processEvents.turnRecordId, turnRecordId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.processEvents.eventSequence))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessEvent);\n\t\t},\n\t\t/** @internal */\n\t\tlatestByTurnRecordEventType(\n\t\t\tinstanceId: string,\n\t\t\tturnRecordId: string,\n\t\t\teventType: string,\n\t\t): ProcessEvent | null {\n\t\t\treturn (\n\t\t\t\tlistNewest(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\t\teq(s.processEvents.turnRecordId, turnRecordId),\n\t\t\t\t\t\teq(s.processEvents.eventType, eventType),\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t)[0] ?? null\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\tsummary(turnRecordId: string) {\n\t\t\treturn summaries.get(turnRecordId);\n\t\t},\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string, limit = 100): ProcessEvent[] {\n\t\t\treturn listNewest(eq(s.processEvents.instanceId, instanceId), limit);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstanceEventTypes(\n\t\t\tinstanceId: string,\n\t\t\teventTypes: readonly string[],\n\t\t\tlimit = 100,\n\t\t): ProcessEvent[] {\n\t\t\tconst filteredEventTypes = [\n\t\t\t\t...new Set(eventTypes.filter((eventType) => eventType.trim() !== \"\")),\n\t\t\t];\n\t\t\tif (filteredEventTypes.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// With IN + ORDER BY, SQLite may scan the instance's entire event stream.\n\t\t\t// Equality on each type uses the type/sequence index and bounds every read.\n\t\t\tconst events = filteredEventTypes.flatMap((eventType) =>\n\t\t\t\tlistNewest(\n\t\t\t\t\tand(eq(s.processEvents.instanceId, instanceId), eq(s.processEvents.eventType, eventType)),\n\t\t\t\t\tlimit,\n\t\t\t\t),\n\t\t\t);\n\t\t\tevents.sort((a, b) => (b.eventSequence ?? 0) - (a.eventSequence ?? 0));\n\t\t\treturn limit < 0 ? events : events.slice(0, limit);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstanceSince(\n\t\t\tinstanceId: string,\n\t\t\tsinceCreatedAt: string,\n\t\t\toptions: {\n\t\t\t\t/** @internal */\n\t\t\t\tlimit?: number;\n\t\t\t\t/** @internal */\n\t\t\t\teventTypePrefix?: string;\n\t\t\t} = {},\n\t\t): ProcessEvent[] {\n\t\t\tconst prefix =\n\t\t\t\ttypeof options.eventTypePrefix === \"string\" ? options.eventTypePrefix.trim() : \"\";\n\t\t\treturn listNewest(\n\t\t\t\tand(\n\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\tgte(s.processEvents.createdAt, sinceCreatedAt),\n\t\t\t\t\tprefix ? like(s.processEvents.eventType, `${prefix}%`) : undefined,\n\t\t\t\t),\n\t\t\t\toptions.limit ?? 100,\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstanceTurnRecordEventTypes(\n\t\t\tinstanceId: string,\n\t\t\tturnRecordId: string,\n\t\t\teventTypes: readonly string[],\n\t\t): ProcessEvent[] {\n\t\t\tconst filteredEventTypes = eventTypes.filter((eventType) => eventType.trim() !== \"\");\n\t\t\tif (filteredEventTypes.length === 0 || turnRecordId.trim() === \"\") {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processEvents)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\t\tinArray(s.processEvents.eventType, filteredEventTypes),\n\t\t\t\t\t\teq(s.processEvents.turnRecordId, turnRecordId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.processEvents.eventSequence))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessEvent);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstanceSinceEventTypes(\n\t\t\tinstanceId: string,\n\t\t\tsinceCreatedAt: string,\n\t\t\teventTypes: readonly string[],\n\t\t\tlimit = 100,\n\t\t): ProcessEvent[] {\n\t\t\tconst filteredEventTypes = eventTypes.filter((eventType) => eventType.trim() !== \"\");\n\t\t\tif (filteredEventTypes.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn listNewest(\n\t\t\t\tand(\n\t\t\t\t\teq(s.processEvents.instanceId, instanceId),\n\t\t\t\t\tgte(s.processEvents.createdAt, sinceCreatedAt),\n\t\t\t\t\tinArray(s.processEvents.eventType, filteredEventTypes),\n\t\t\t\t),\n\t\t\t\tlimit,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { HandoffDedupKeyRecordLike } from \"@leitwerk-dev/process-sdk\";\nimport { eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface ProcessHandoffDedupKeyRecord extends HandoffDedupKeyRecordLike {}\n\n/** @internal */\nexport interface CreateProcessHandoffDedupKeyInput {\n\t/** @internal */\n\tkey: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tmetadata?: Record<string, unknown> | null;\n}\n\nfunction rowToRecord(\n\trow: typeof s.processHandoffDedupKeys.$inferSelect,\n): ProcessHandoffDedupKeyRecord {\n\treturn {\n\t\tkey: row.key,\n\t\tinstanceId: row.instanceId,\n\t\tcreatedAt: row.createdAt,\n\t\tmetadata: JSON.parse(row.metadata) as Record<string, unknown>,\n\t};\n}\n\n/** @internal */\nexport function createProcessHandoffDedupKeyRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessHandoffDedupKeyInput): ProcessHandoffDedupKeyRecord {\n\t\t\tconst values = {\n\t\t\t\tkey: input.key,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tcreatedAt: now(),\n\t\t\t\tmetadata: JSON.stringify(input.metadata ?? {}),\n\t\t\t};\n\t\t\tdb.insert(s.processHandoffDedupKeys).values(values).run();\n\t\t\treturn rowToRecord(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByKey(key: string): ProcessHandoffDedupKeyRecord | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processHandoffDedupKeys)\n\t\t\t\t.where(eq(s.processHandoffDedupKeys.key, key))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToRecord(row) : null;\n\t\t},\n\t};\n}\n","import type {\n\tActor,\n\tInputKind,\n\tInputSource,\n\tProcessInput,\n\tProcessInputTarget,\n} from \"@leitwerk-dev/domain\";\nimport { parseActorOrSystem, SYSTEM_ACTOR, serializeActor } from \"@leitwerk-dev/domain\";\nimport { and, asc, eq, isNull, max } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateProcessInputInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tsequence: number;\n\t/** @internal */\n\tsource: InputSource;\n\t/** @internal */\n\tkind: InputKind;\n\t/** @internal */\n\ttarget?: ProcessInputTarget | null;\n\t/** @internal */\n\tbodyMarkdown: string;\n\t/** @internal */\n\tactor?: Actor;\n}\n\nfunction toProcessInputTarget(\n\tsemanticRef: string | null,\n\tproductName: string | null,\n): ProcessInputTarget | null {\n\tif (productName) {\n\t\treturn { productName };\n\t}\n\treturn semanticRef\n\t\t? { semanticRef: semanticRef as NonNullable<ProcessInputTarget[\"semanticRef\"]> }\n\t\t: null;\n}\n\nfunction rowToProcessInput(row: typeof s.processInputs.$inferSelect): ProcessInput {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tsequence: row.sequence,\n\t\tsource: row.source as InputSource,\n\t\tkind: row.kind as InputKind,\n\t\ttarget: toProcessInputTarget(row.targetSemanticRef, row.targetProductName),\n\t\tbodyMarkdown: row.bodyMarkdown,\n\t\tactor: parseActorOrSystem(row.actor),\n\t\treceivedAt: row.receivedAt,\n\t\tconsumedAt: row.consumedAt,\n\t};\n}\n\n/** @internal */\nexport function createProcessInputRepo(db: LeitwerkDb) {\n\tconst list = (instanceId: string, unconsumed = false): ProcessInput[] =>\n\t\tdb\n\t\t\t.select()\n\t\t\t.from(s.processInputs)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\teq(s.processInputs.instanceId, instanceId),\n\t\t\t\t\tunconsumed ? isNull(s.processInputs.consumedAt) : undefined,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(asc(s.processInputs.sequence))\n\t\t\t.all()\n\t\t\t.map(rowToProcessInput);\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessInputInput): ProcessInput {\n\t\t\tconst id = generateId(\"inp\");\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tsequence: input.sequence,\n\t\t\t\tsource: input.source,\n\t\t\t\tkind: input.kind,\n\t\t\t\ttargetSemanticRef: input.target?.semanticRef ?? null,\n\t\t\t\ttargetProductName: input.target?.productName ?? null,\n\t\t\t\tbodyMarkdown: input.bodyMarkdown,\n\t\t\t\tactor: serializeActor(input.actor ?? SYSTEM_ACTOR),\n\t\t\t\treceivedAt: ts,\n\t\t\t\tconsumedAt: null as string | null,\n\t\t\t};\n\t\t\tdb.insert(s.processInputs).values(values).run();\n\t\t\treturn rowToProcessInput(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance: (instanceId: string) => list(instanceId),\n\t\t/** @internal */\n\t\tlistUnconsumed: (instanceId: string) => list(instanceId, true),\n\n\t\t/** @internal */\n\t\tmarkConsumed(id: string): boolean {\n\t\t\tconst result = db\n\t\t\t\t.update(s.processInputs)\n\t\t\t\t.set({ consumedAt: now() })\n\t\t\t\t.where(eq(s.processInputs.id, id))\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(id: string): boolean {\n\t\t\tconst result = db.delete(s.processInputs).where(eq(s.processInputs.id, id)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\n\t\t/** @internal */\n\t\tgetMaxSequence(instanceId: string): number {\n\t\t\tconst row = db\n\t\t\t\t.select({ sequence: max(s.processInputs.sequence) })\n\t\t\t\t.from(s.processInputs)\n\t\t\t\t.where(eq(s.processInputs.instanceId, instanceId))\n\t\t\t\t.get();\n\t\t\treturn row?.sequence ?? 0;\n\t\t},\n\t};\n}\n","import {\n\ttype CurrentExecutionRef,\n\tisProcessSelectedTurnModelSource,\n\ttype ModelSelectionKind,\n\ttype ProcessCustomizableFields,\n\ttype ProcessInstance,\n\ttype ProcessLifecycleStatus,\n\ttype ProcessSelectedTurnModelSource,\n\ttype TurnId,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, count, desc, eq, inArray, notInArray, or, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport { normalizeProcessTitleInput } from \"../launch-title.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now, parseMetadata, sqliteLikePatterns } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface ProcessLaunchIntent {\n\t/** @internal */\n\tlauncherId: string;\n\t/** @internal */\n\tlauncherInput: Record<string, unknown>;\n}\n\n/** @public */\nexport interface CreateProcessInstanceInput extends ProcessCustomizableFields {\n\t/** @public */\n\tprocessId: string;\n\t/** @public */\n\tselectedTurnId?: TurnId | null;\n\t/** @public */\n\tlifecycleStatus?: ProcessLifecycleStatus;\n\t/** @internal */\n\tcurrentExecution?: CurrentExecutionRef;\n\t/** @internal */\n\tselectedTurnModelKind?: ModelSelectionKind | null;\n\t/** @internal */\n\tselectedTurnModelSource?: ProcessSelectedTurnModelSource | null;\n\t/** @public */\n\tparamsJson?: string | null;\n\t/** @public */\n\tstateJson?: string | null;\n\t/** @internal */\n\tlaunchIntent?: ProcessLaunchIntent;\n}\n\n/** @internal */\nexport type ProcessOverviewStatusFilter =\n\t| \"all\"\n\t| \"running\"\n\t| \"needs_attention\"\n\t| \"completed\"\n\t| \"aborted\"\n\t| \"scheduled\";\n\n/** @internal */\nexport interface ProcessOverviewQuery {\n\t/** @internal */\n\tquery?: string;\n\t/** @internal */\n\tprocessType?: string;\n\t/** @internal */\n\tstatus?: ProcessOverviewStatusFilter;\n}\n\n/** @internal */\nexport interface ProcessOverviewWindowQuery extends ProcessOverviewQuery {\n\t/** @internal */\n\tlimit: number;\n\t/** @internal */\n\tsortKey: \"status\" | \"title\" | \"timeline\";\n\t/** @internal */\n\tsortDirection: \"asc\" | \"desc\";\n}\n\n/** @public */\nexport interface UpdateProcessInstanceInput extends ProcessCustomizableFields {\n\t/** @internal */\n\tselectedTurnId?: TurnId | null;\n\t/** @internal */\n\tlifecycleStatus?: ProcessLifecycleStatus;\n\t/** @internal */\n\tcurrentExecution?: CurrentExecutionRef;\n\t/** @internal */\n\tplanRevision?: number;\n\t/** @internal */\n\tselectedTurnModelKind?: ModelSelectionKind | null;\n\t/** @internal */\n\tselectedTurnModelSource?: ProcessSelectedTurnModelSource | null;\n\t/** @public */\n\tparamsJson?: string | null;\n\t/** @internal */\n\tstateJson?: string | null;\n}\n\nfunction isTerminalLifecycleStatus(status: ProcessLifecycleStatus | null | undefined): boolean {\n\treturn status === \"completed\" || status === \"aborted\";\n}\n\nfunction overviewPredicates(input: ProcessOverviewQuery): SQL[] {\n\tconst predicates: SQL[] = [];\n\tconst processType = input.processType?.trim();\n\tif (processType) {\n\t\tpredicates.push(eq(s.processInstances.processId, processType));\n\t}\n\tswitch (input.status ?? \"all\") {\n\t\tcase \"running\":\n\t\t\tpredicates.push(inArray(s.processInstances.lifecycleStatus, [\"discovered\", \"active\"]));\n\t\t\tbreak;\n\t\tcase \"needs_attention\":\n\t\t\tpredicates.push(inArray(s.processInstances.lifecycleStatus, [\"waiting\", \"error\"]));\n\t\t\tbreak;\n\t\tcase \"completed\":\n\t\t\tpredicates.push(eq(s.processInstances.lifecycleStatus, \"completed\"));\n\t\t\tbreak;\n\t\tcase \"aborted\":\n\t\t\tpredicates.push(eq(s.processInstances.lifecycleStatus, \"aborted\"));\n\t\t\tbreak;\n\t\tcase \"scheduled\":\n\t\t\t// Scheduled rows are future executions, not process instances.\n\t\t\tpredicates.push(sql`0 = 1`);\n\t\t\tbreak;\n\t\tcase \"all\":\n\t\t\tbreak;\n\t}\n\tfor (const pattern of sqliteLikePatterns(input.query)) {\n\t\tpredicates.push(\n\t\t\tor(\n\t\t\t\tsql`lower(coalesce(${s.processInstances.title}, '')) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tsql`lower(coalesce(${s.processInstances.externalId}, '')) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tsql`lower(${s.processInstances.id}) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t\tsql`lower(coalesce(${s.processInstances.paramsJson}, '')) LIKE ${pattern} ESCAPE '\\\\'`,\n\t\t\t) as SQL,\n\t\t);\n\t}\n\treturn predicates;\n}\n\nfunction overviewWhere(input: ProcessOverviewQuery): SQL | undefined {\n\tconst predicates = overviewPredicates(input);\n\treturn predicates.length ? and(...predicates) : undefined;\n}\n\nfunction parseLaunchIntent(raw: string | null): ProcessLaunchIntent | null {\n\tif (!raw) return null;\n\ttry {\n\t\tconst value = JSON.parse(raw) as Partial<ProcessLaunchIntent>;\n\t\treturn typeof value.launcherId === \"string\" &&\n\t\t\ttypeof value.launcherInput === \"object\" &&\n\t\t\tvalue.launcherInput !== null &&\n\t\t\t!Array.isArray(value.launcherInput)\n\t\t\t? (value as ProcessLaunchIntent)\n\t\t\t: null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction rowToProcessInstance(row: typeof s.processInstances.$inferSelect): ProcessInstance {\n\treturn {\n\t\tid: row.id,\n\t\tprocessId: row.processId,\n\t\tselectedTurnId: row.selectedTurnId ?? null,\n\t\tlifecycleStatus: (row.lifecycleStatus as ProcessLifecycleStatus) ?? \"discovered\",\n\t\tcurrentExecution: row.currentWorkerStartId\n\t\t\t? { kind: \"worker_start\", id: row.currentWorkerStartId }\n\t\t\t: null,\n\t\tplanRevision: row.planRevision,\n\t\ttitle: row.title ?? null,\n\t\texternalId: row.externalId ?? null,\n\t\texternalUrl: row.externalUrl ?? null,\n\t\tmetadata: parseMetadata(row.metadata),\n\t\tdefaultModelProfileId: row.defaultModelProfileId ?? null,\n\t\tinitialDefaultModelProfileId: row.initialDefaultModelProfileId ?? null,\n\t\tturnConfigsJson: row.turnConfigsJson ?? null,\n\t\tselectedTurnModelProfileId: row.selectedTurnModelProfileId ?? null,\n\t\tselectedTurnModelKind:\n\t\t\trow.selectedTurnModelKind === \"explicit\" || row.selectedTurnModelKind === \"inherited\"\n\t\t\t\t? row.selectedTurnModelKind\n\t\t\t\t: null,\n\t\tselectedTurnModelSource: isProcessSelectedTurnModelSource(row.selectedTurnModelSource)\n\t\t\t? row.selectedTurnModelSource\n\t\t\t: null,\n\t\tparamsJson: row.paramsJson ?? null,\n\t\tstateJson: row.stateJson ?? null,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t\tclosedAt: row.closedAt ?? null,\n\t};\n}\n\n/** @public */\nexport function createProcessInstanceRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tgetLaunchIntent(instanceId: string): ProcessLaunchIntent | null {\n\t\t\tconst row = db\n\t\t\t\t.select({ launchIntentJson: s.processInstances.launchIntentJson })\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(eq(s.processInstances.id, instanceId))\n\t\t\t\t.get();\n\t\t\treturn parseLaunchIntent(row?.launchIntentJson ?? null);\n\t\t},\n\t\t/** @public */\n\t\tcreate(input: CreateProcessInstanceInput): ProcessInstance {\n\t\t\tconst id = generateId(\"agt\");\n\t\t\tconst ts = now();\n\t\t\tconst lifecycleStatus = input.lifecycleStatus ?? \"discovered\";\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tprocessId: input.processId,\n\t\t\t\tselectedTurnId: input.selectedTurnId ?? null,\n\t\t\t\tlifecycleStatus,\n\t\t\t\tcurrentWorkerStartId:\n\t\t\t\t\tinput.currentExecution?.kind === \"worker_start\" ? input.currentExecution.id : null,\n\t\t\t\tplanRevision: 0,\n\t\t\t\ttitle: normalizeProcessTitleInput(input.title),\n\t\t\t\texternalId: input.externalId ?? null,\n\t\t\t\texternalUrl: input.externalUrl ?? null,\n\t\t\t\tmetadata: input.metadata ? JSON.stringify(input.metadata) : null,\n\t\t\t\tdefaultModelProfileId: input.defaultModelProfileId ?? null,\n\t\t\t\tinitialDefaultModelProfileId: input.initialDefaultModelProfileId ?? null,\n\t\t\t\tturnConfigsJson: input.turnConfigsJson ?? null,\n\t\t\t\tselectedTurnModelProfileId: input.selectedTurnModelProfileId ?? null,\n\t\t\t\tselectedTurnModelKind: input.selectedTurnModelKind ?? null,\n\t\t\t\tselectedTurnModelSource: input.selectedTurnModelSource ?? null,\n\t\t\t\tparamsJson: input.paramsJson ?? null,\n\t\t\t\tstateJson: input.stateJson ?? null,\n\t\t\t\tlaunchIntentJson: input.launchIntent ? JSON.stringify(input.launchIntent) : null,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t\tclosedAt: isTerminalLifecycleStatus(lifecycleStatus) ? ts : null,\n\t\t\t};\n\t\t\tdb.insert(s.processInstances).values(values).run();\n\t\t\treturn rowToProcessInstance({ ...values, planRevision: 0 });\n\t\t},\n\n\t\t/** @public */\n\t\tgetById(id: string): ProcessInstance | null {\n\t\t\tconst row = db.select().from(s.processInstances).where(eq(s.processInstances.id, id)).get();\n\t\t\treturn row ? rowToProcessInstance(row) : null;\n\t\t},\n\n\t\t/** @public */\n\t\tlistAll(): ProcessInstance[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.orderBy(desc(s.processInstances.updatedAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessInstance);\n\t\t},\n\n\t\t/** Model references for current work without loading prompts or process state. @internal */\n\t\tlistModelConfigurations() {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tid: s.processInstances.id,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tprocessId: s.processInstances.processId,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\ttitle: s.processInstances.title,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tdefaultModelProfileId: s.processInstances.defaultModelProfileId,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tturnConfigsJson: s.processInstances.turnConfigsJson,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tselectedTurnId: s.processInstances.selectedTurnId,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tselectedTurnModelProfileId: s.processInstances.selectedTurnModelProfileId,\n\t\t\t\t})\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(notInArray(s.processInstances.lifecycleStatus, [\"completed\", \"aborted\"]))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistCurrent(limit: number): ProcessInstance[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(notInArray(s.processInstances.lifecycleStatus, [\"completed\", \"aborted\"]))\n\t\t\t\t.orderBy(desc(s.processInstances.updatedAt), asc(s.processInstances.id))\n\t\t\t\t.limit(limit)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessInstance);\n\t\t},\n\n\t\t/** @internal */\n\t\tcountCurrent(): number {\n\t\t\treturn (\n\t\t\t\tdb\n\t\t\t\t\t.select({ value: count() })\n\t\t\t\t\t.from(s.processInstances)\n\t\t\t\t\t.where(notInArray(s.processInstances.lifecycleStatus, [\"completed\", \"aborted\"]))\n\t\t\t\t\t.get()?.value ?? 0\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tcountOverview(input: ProcessOverviewQuery): number {\n\t\t\treturn (\n\t\t\t\tdb.select({ value: count() }).from(s.processInstances).where(overviewWhere(input)).get()\n\t\t\t\t\t?.value ?? 0\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tcountOverviewByLifecycle(input: Pick<ProcessOverviewQuery, \"query\" | \"processType\">) {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tlifecycleStatus: s.processInstances.lifecycleStatus,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tvalue: count(),\n\t\t\t\t})\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(overviewWhere({ ...input, status: \"all\" }))\n\t\t\t\t.groupBy(s.processInstances.lifecycleStatus)\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistOverviewProcessTypes(input: Pick<ProcessOverviewQuery, \"query\" | \"status\">) {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tprocessId: s.processInstances.processId,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tvalue: count(),\n\t\t\t\t})\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(overviewWhere(input))\n\t\t\t\t.groupBy(s.processInstances.processId)\n\t\t\t\t.orderBy(asc(s.processInstances.processId))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistOverviewWindow(input: ProcessOverviewWindowQuery): ProcessInstance[] {\n\t\t\tconst title = sql<string>`coalesce(${s.processInstances.title}, ${s.processInstances.externalId}, ${s.processInstances.id})`;\n\t\t\tconst status = sql<number>`case\n\t\t\t\twhen ${s.processInstances.lifecycleStatus} in ('waiting', 'error') then 0\n\t\t\t\twhen ${s.processInstances.lifecycleStatus} in ('discovered', 'active') then 1\n\t\t\t\twhen ${s.processInstances.lifecycleStatus} = 'completed' then 3\n\t\t\t\telse 4 end`;\n\t\t\tconst timeline = sql<string>`case\n\t\t\t\twhen ${s.processInstances.lifecycleStatus} in ('completed', 'aborted')\n\t\t\t\t\tthen coalesce(${s.processInstances.closedAt}, ${s.processInstances.updatedAt})\n\t\t\t\telse ${s.processInstances.updatedAt} end`;\n\t\t\tconst primary =\n\t\t\t\tinput.sortKey === \"status\" ? status : input.sortKey === \"title\" ? title : timeline;\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processInstances)\n\t\t\t\t.where(overviewWhere(input))\n\t\t\t\t.orderBy(\n\t\t\t\t\tinput.sortDirection === \"desc\" ? desc(primary) : asc(primary),\n\t\t\t\t\tasc(title),\n\t\t\t\t\tasc(s.processInstances.id),\n\t\t\t\t)\n\t\t\t\t.limit(input.limit)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessInstance);\n\t\t},\n\n\t\t/** @internal */\n\t\tsetGeneratedTitleIfBlank(id: string, title: string): ProcessInstance | null {\n\t\t\tconst normalizedTitle = normalizeProcessTitleInput(title);\n\t\t\tif (!normalizedTitle) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst result = db\n\t\t\t\t.update(s.processInstances)\n\t\t\t\t.set({ title: normalizedTitle, updatedAt: now() })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processInstances.id, id),\n\t\t\t\t\t\tsql`trim(coalesce(${s.processInstances.title}, '')) = ''`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0 ? this.getById(id) : null;\n\t\t},\n\n\t\t/** @public */\n\t\tupdate(\n\t\t\tid: string,\n\t\t\tinput: UpdateProcessInstanceInput,\n\t\t\toptions: {\n\t\t\t\t/** Scheduling-only writes retain process activity time; never part of a process patch. @internal */\n\t\t\t\tpreserveUpdatedAt?: boolean;\n\t\t\t} = {},\n\t\t): ProcessInstance | null {\n\t\t\tconst ts = now();\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.processInstances> = {\n\t\t\t\t...(options.preserveUpdatedAt ? {} : { updatedAt: ts }),\n\t\t\t\tdefaultModelProfileId: input.defaultModelProfileId,\n\t\t\t\tinitialDefaultModelProfileId: input.initialDefaultModelProfileId,\n\t\t\t\tselectedTurnId: input.selectedTurnId,\n\t\t\t\tlifecycleStatus: input.lifecycleStatus,\n\t\t\t\tplanRevision: input.planRevision,\n\t\t\t\texternalId: input.externalId,\n\t\t\t\texternalUrl: input.externalUrl,\n\t\t\t\tturnConfigsJson: input.turnConfigsJson,\n\t\t\t\tselectedTurnModelProfileId: input.selectedTurnModelProfileId,\n\t\t\t\tselectedTurnModelKind: input.selectedTurnModelKind,\n\t\t\t\tselectedTurnModelSource: input.selectedTurnModelSource,\n\t\t\t\tparamsJson: input.paramsJson,\n\t\t\t\tstateJson: input.stateJson,\n\t\t\t};\n\t\t\tif (input.currentExecution !== undefined) {\n\t\t\t\tsetValues.currentWorkerStartId =\n\t\t\t\t\tinput.currentExecution?.kind === \"worker_start\" ? input.currentExecution.id : null;\n\t\t\t}\n\t\t\tif (input.title !== undefined) setValues.title = normalizeProcessTitleInput(input.title);\n\t\t\tif (input.metadata !== undefined)\n\t\t\t\tsetValues.metadata = input.metadata ? JSON.stringify(input.metadata) : null;\n\t\t\tif (isTerminalLifecycleStatus(input.lifecycleStatus)) {\n\t\t\t\tsetValues.closedAt = sql`coalesce(${s.processInstances.closedAt}, ${ts})`;\n\t\t\t}\n\n\t\t\tdb.update(s.processInstances).set(setValues).where(eq(s.processInstances.id, id)).run();\n\t\t\treturn this.getById(id);\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(id: string): boolean {\n\t\t\tconst result = db.delete(s.processInstances).where(eq(s.processInstances.id, id)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\t};\n}\n","import type { ProcessLaunchPlan } from \"@leitwerk-dev/process-sdk\";\n\nexport const MAX_PROCESS_TITLE_LENGTH = 80;\n\nexport interface SubmittedProcessTitleInput {\n\ttitle: string | null;\n\ttitleProvided: boolean;\n}\n\nexport function truncateTextAtWordBoundary(value: string, maxLength: number): string {\n\tif (value.length <= maxLength) {\n\t\treturn value;\n\t}\n\tconst sliced = value.slice(0, Math.max(1, maxLength - 1)).trimEnd();\n\tconst lastWhitespace = sliced.lastIndexOf(\" \");\n\tconst base =\n\t\tlastWhitespace >= Math.floor(maxLength * 0.6) ? sliced.slice(0, lastWhitespace) : sliced;\n\treturn `${base.trimEnd()}…`;\n}\n\nexport function normalizeProcessTitleInput(value: string | null | undefined): string | null {\n\tif (typeof value !== \"string\") {\n\t\treturn null;\n\t}\n\tconst trimmed = value.trim();\n\tif (trimmed === \"\") {\n\t\treturn null;\n\t}\n\treturn truncateTextAtWordBoundary(trimmed.replace(/\\s+/g, \" \"), MAX_PROCESS_TITLE_LENGTH);\n}\n\nexport function normalizeSubmittedProcessTitle(value: unknown): string | null {\n\treturn typeof value === \"string\" ? normalizeProcessTitleInput(value) : null;\n}\n\nexport function applySubmittedProcessTitleToLaunchPlan(\n\tlaunchPlan: ProcessLaunchPlan,\n\tinput: SubmittedProcessTitleInput,\n): ProcessLaunchPlan {\n\tif (!input.titleProvided) {\n\t\treturn launchPlan;\n\t}\n\treturn {\n\t\t...launchPlan,\n\t\tprocessInput: {\n\t\t\t...launchPlan.processInput,\n\t\t\ttitle: input.title,\n\t\t},\n\t};\n}\n","import type {\n\tProcessLeafOutcomeSnapshot,\n\tProcessLeafOutcomeSnapshotStatus,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, desc, eq, sql } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { type HistoryWindow, historyWindow } from \"./history-window.js\";\nimport { generateId, now, parseJsonRecord } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateProcessLeafOutcomeSnapshotInput {\n\t/** @internal */\n\tid?: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tleafEntryId: string;\n\t/** @internal */\n\tturnRecordId?: string | null;\n\t/** @internal */\n\trendererId?: string | null;\n\t/** @internal */\n\tschemaVersion?: number | null;\n\t/** @internal */\n\tprops?: Record<string, unknown> | null;\n\t/** @internal */\n\tfallbackMarkdown?: string | null;\n\t/** @internal */\n\tstatus: ProcessLeafOutcomeSnapshotStatus;\n\t/** @internal */\n\twarningCode?: string | null;\n\t/** @internal */\n\twarningMessage?: string | null;\n\t/** @internal */\n\tanchoredAt: string;\n\t/** @internal */\n\tcreatedAt?: string;\n}\n\nfunction rowToProcessLeafOutcomeSnapshot(\n\trow: typeof s.processLeafOutcomeSnapshots.$inferSelect,\n): ProcessLeafOutcomeSnapshot {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tleafEntryId: row.leafEntryId,\n\t\tturnRecordId: row.turnRecordId ?? null,\n\t\trendererId: row.rendererId ?? null,\n\t\tschemaVersion: row.schemaVersion ?? null,\n\t\tprops: parseJsonRecord(row.propsJson),\n\t\tfallbackMarkdown: row.fallbackMarkdown ?? null,\n\t\tstatus: row.status as ProcessLeafOutcomeSnapshotStatus,\n\t\twarningCode: row.warningCode ?? null,\n\t\twarningMessage: row.warningMessage ?? null,\n\t\tanchoredAt: row.anchoredAt,\n\t\tcreatedAt: row.createdAt,\n\t};\n}\n\n/** @internal */\nexport function createProcessLeafOutcomeSnapshotRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessLeafOutcomeSnapshotInput): ProcessLeafOutcomeSnapshot {\n\t\t\tconst values = {\n\t\t\t\tid: input.id ?? generateId(\"los\"),\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tleafEntryId: input.leafEntryId,\n\t\t\t\tturnRecordId: input.turnRecordId ?? null,\n\t\t\t\trendererId: input.rendererId ?? null,\n\t\t\t\tschemaVersion: input.schemaVersion ?? null,\n\t\t\t\tpropsJson: input.props ? JSON.stringify(input.props) : null,\n\t\t\t\tfallbackMarkdown: input.fallbackMarkdown ?? null,\n\t\t\t\tstatus: input.status,\n\t\t\t\twarningCode: input.warningCode ?? null,\n\t\t\t\twarningMessage: input.warningMessage ?? null,\n\t\t\t\tanchoredAt: input.anchoredAt,\n\t\t\t\tcreatedAt: input.createdAt ?? now(),\n\t\t\t};\n\t\t\tdb.insert(s.processLeafOutcomeSnapshots).values(values).run();\n\t\t\treturn rowToProcessLeafOutcomeSnapshot(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string, window?: HistoryWindow): ProcessLeafOutcomeSnapshot[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processLeafOutcomeSnapshots)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processLeafOutcomeSnapshots.instanceId, instanceId),\n\t\t\t\t\t\thistoryWindow(s.processLeafOutcomeSnapshots.anchoredAt, window),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(\n\t\t\t\t\tasc(s.processLeafOutcomeSnapshots.anchoredAt),\n\t\t\t\t\tasc(s.processLeafOutcomeSnapshots.createdAt),\n\t\t\t\t)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessLeafOutcomeSnapshot);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByInstanceAndLeafEntryId(\n\t\t\tinstanceId: string,\n\t\t\tleafEntryId: string,\n\t\t): ProcessLeafOutcomeSnapshot | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processLeafOutcomeSnapshots)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processLeafOutcomeSnapshots.instanceId, instanceId),\n\t\t\t\t\t\teq(s.processLeafOutcomeSnapshots.leafEntryId, leafEntryId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(desc(s.processLeafOutcomeSnapshots.createdAt), desc(sql`rowid`))\n\t\t\t\t.limit(1)\n\t\t\t\t.get();\n\t\t\treturn row ? rowToProcessLeafOutcomeSnapshot(row) : null;\n\t\t},\n\t};\n}\n","import { and, gte, lte } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\n\n/** @internal */\nexport interface HistoryWindow {\n\t/** @internal */\n\tsince?: string;\n\t/** @internal */\n\tuntil?: string;\n}\n\n/** @internal */\nexport function historyWindow(column: SQLiteColumn, window?: HistoryWindow) {\n\treturn and(\n\t\twindow?.since ? gte(column, window.since) : undefined,\n\t\twindow?.until ? lte(column, window.until) : undefined,\n\t);\n}\n","import {\n\tassertRepoLocator,\n\tdetectRepoLocatorKind,\n\ttype ProcessProject,\n} from \"@leitwerk-dev/domain\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now, parseMetadata } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateProcessProjectInput extends UpdateProcessProjectInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tkey: string;\n\t/** @internal */\n\trepoLocator: string;\n\t/** @internal */\n\tbaseBranch: string;\n}\n\n/** @public */\nexport interface UpdateProcessProjectInput {\n\t/** @internal */\n\trepoLocator?: string;\n\t/** @internal */\n\tworkBranch?: string | null;\n\t/** @internal */\n\texternalId?: string | null;\n\t/** @internal */\n\texternalUrl?: string | null;\n\t/** @public */\n\tmetadata?: Record<string, unknown> | null;\n\t/** @internal */\n\tpipelineStatus?: string | null;\n\t/** @internal */\n\tbaseBranch?: string;\n}\n\nfunction rowToProcessProject(row: typeof s.processProjects.$inferSelect): ProcessProject {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tkey: row.key,\n\t\trepoLocator: row.repoLocator,\n\t\trepoLocatorKind: row.repoLocatorKind as ProcessProject[\"repoLocatorKind\"],\n\t\tbaseBranch: row.baseBranch,\n\t\tworkBranch: row.workBranch,\n\t\texternalId: row.externalId ?? null,\n\t\texternalUrl: row.externalUrl ?? null,\n\t\tmetadata: parseMetadata(row.metadata),\n\t\tpipelineStatus: row.pipelineStatus,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n}\n\n/** @public */\nexport function createProcessProjectRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tlistAll(): ProcessProject[] {\n\t\t\treturn db.select().from(s.processProjects).all().map(rowToProcessProject);\n\t\t},\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessProjectInput): ProcessProject {\n\t\t\tconst id = generateId(\"prj\");\n\t\t\tconst ts = now();\n\t\t\tconst repoLocator = assertRepoLocator(input.repoLocator);\n\t\t\tconst repoLocatorKind = detectRepoLocatorKind(repoLocator) ?? \"remote_url\";\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tkey: input.key,\n\t\t\t\trepoLocator,\n\t\t\t\trepoLocatorKind,\n\t\t\t\tbaseBranch: input.baseBranch,\n\t\t\t\tworkBranch: input.workBranch ?? null,\n\t\t\t\texternalId: input.externalId ?? null,\n\t\t\t\texternalUrl: input.externalUrl ?? null,\n\t\t\t\tmetadata: input.metadata ? JSON.stringify(input.metadata) : null,\n\t\t\t\tpipelineStatus: input.pipelineStatus ?? null,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t};\n\t\t\tdb.insert(s.processProjects).values(values).run();\n\t\t\treturn rowToProcessProject(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): ProcessProject | null {\n\t\t\tconst row = db.select().from(s.processProjects).where(eq(s.processProjects.id, id)).get();\n\t\t\treturn row ? rowToProcessProject(row) : null;\n\t\t},\n\n\t\t/** @public */\n\t\tlistByInstance(instanceId: string): ProcessProject[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processProjects)\n\t\t\t\t.where(eq(s.processProjects.instanceId, instanceId))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessProject);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstances(instanceIds: readonly string[]): ProcessProject[] {\n\t\t\tif (instanceIds.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processProjects)\n\t\t\t\t.where(inArray(s.processProjects.instanceId, [...instanceIds]))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessProject);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByInstanceAndKey(instanceId: string, key: string): ProcessProject | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processProjects)\n\t\t\t\t.where(and(eq(s.processProjects.instanceId, instanceId), eq(s.processProjects.key, key)))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToProcessProject(row) : null;\n\t\t},\n\n\t\t/** @public */\n\t\tupdate(id: string, input: UpdateProcessProjectInput): ProcessProject | null {\n\t\t\tconst previous = this.getById(id);\n\t\t\tif (!previous) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst ts = now();\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.processProjects> = {\n\t\t\t\tupdatedAt: ts,\n\t\t\t\tworkBranch: input.workBranch,\n\t\t\t\texternalId: input.externalId,\n\t\t\t\texternalUrl: input.externalUrl,\n\t\t\t\tpipelineStatus: input.pipelineStatus,\n\t\t\t\tbaseBranch: input.baseBranch,\n\t\t\t};\n\t\t\tif (input.repoLocator !== undefined) {\n\t\t\t\tconst repoLocator = assertRepoLocator(input.repoLocator);\n\t\t\t\tsetValues.repoLocator = repoLocator;\n\t\t\t\tsetValues.repoLocatorKind = detectRepoLocatorKind(repoLocator) ?? \"remote_url\";\n\t\t\t}\n\t\t\tif (input.metadata !== undefined)\n\t\t\t\tsetValues.metadata = input.metadata ? JSON.stringify(input.metadata) : null;\n\n\t\t\tdb.update(s.processProjects).set(setValues).where(eq(s.processProjects.id, id)).run();\n\t\t\tconst row = db.select().from(s.processProjects).where(eq(s.processProjects.id, id)).get();\n\t\t\treturn row ? rowToProcessProject(row) : null;\n\t\t},\n\t};\n}\n","import type { Actor, NormalizedQuestion, ProcessQuestionRequest } from \"@leitwerk-dev/domain\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now, parsePersistedJson } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nfunction map(row: typeof s.processQuestionRequests.$inferSelect): ProcessQuestionRequest {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tturnRecordId: row.turnRecordId,\n\t\ttoolCallId: row.toolCallId,\n\t\tquestions: parsePersistedJson<NormalizedQuestion[]>(row.questionsJson, \"question request\"),\n\t\tstatus: row.status as ProcessQuestionRequest[\"status\"],\n\t\tanswers: row.answersJson\n\t\t\t? parsePersistedJson<string[]>(row.answersJson, \"question answers\")\n\t\t\t: null,\n\t\taskedAt: row.askedAt,\n\t\tansweredAt: row.answeredAt ?? null,\n\t\tansweredBy: row.answeredByJson\n\t\t\t? parsePersistedJson<Actor>(row.answeredByJson, \"answer actor\")\n\t\t\t: null,\n\t\tcancelledAt: row.cancelledAt ?? null,\n\t};\n}\n\n/** @internal */\nexport interface CreateQuestionRequestInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tturnRecordId: string;\n\t/** @internal */\n\ttoolCallId: string;\n\t/** @internal */\n\tquestions: readonly NormalizedQuestion[];\n\t/** @internal */\n\taskedAt?: string;\n}\n\n/** @internal */\nexport function createProcessQuestionRequestRepo(db: LeitwerkDb) {\n\tconst getById = (id: string): ProcessQuestionRequest | null => {\n\t\tconst row = db\n\t\t\t.select()\n\t\t\t.from(s.processQuestionRequests)\n\t\t\t.where(eq(s.processQuestionRequests.id, id))\n\t\t\t.get();\n\t\treturn row ? map(row) : null;\n\t};\n\tconst list = (instanceId?: string, openOnly = false): ProcessQuestionRequest[] => {\n\t\tconst filters = [\n\t\t\t...(instanceId ? [eq(s.processQuestionRequests.instanceId, instanceId)] : []),\n\t\t\t...(openOnly ? [eq(s.processQuestionRequests.status, \"open\")] : []),\n\t\t];\n\t\treturn db\n\t\t\t.select()\n\t\t\t.from(s.processQuestionRequests)\n\t\t\t.where(filters.length ? and(...filters) : undefined)\n\t\t\t.orderBy(asc(s.processQuestionRequests.askedAt))\n\t\t\t.all()\n\t\t\t.map(map);\n\t};\n\treturn {\n\t\t/** @internal */\n\t\tgetById,\n\t\t/** @internal */\n\t\tlistByInstance: (instanceId: string) => list(instanceId),\n\t\t/** @internal */\n\t\tlistOpen: (instanceId?: string) => list(instanceId, true),\n\t\t/** @internal */\n\t\tcreateIdempotent(input: CreateQuestionRequestInput): {\n\t\t\t/** @internal */\n\t\t\tkind: \"created\" | \"replay\";\n\t\t\t/** @internal */\n\t\t\trequest: ProcessQuestionRequest;\n\t\t} {\n\t\t\tconst existingRow = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processQuestionRequests)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processQuestionRequests.instanceId, input.instanceId),\n\t\t\t\t\t\teq(s.processQuestionRequests.turnRecordId, input.turnRecordId),\n\t\t\t\t\t\teq(s.processQuestionRequests.toolCallId, input.toolCallId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\tif (existingRow) {\n\t\t\t\tconst existing = map(existingRow);\n\t\t\t\tif (JSON.stringify(existing.questions) !== JSON.stringify(input.questions)) {\n\t\t\t\t\tthrow new Error(\"Question request correlation was replayed with different questions\");\n\t\t\t\t}\n\t\t\t\treturn { kind: \"replay\", request: existing };\n\t\t\t}\n\t\t\tconst row = db\n\t\t\t\t.insert(s.processQuestionRequests)\n\t\t\t\t.values({\n\t\t\t\t\tid: generateId(\"qst\"),\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\tturnRecordId: input.turnRecordId,\n\t\t\t\t\ttoolCallId: input.toolCallId,\n\t\t\t\t\tquestionsJson: JSON.stringify(input.questions),\n\t\t\t\t\taskedAt: input.askedAt ?? now(),\n\t\t\t\t})\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn { kind: \"created\", request: map(row) };\n\t\t},\n\t\t/** @internal */\n\t\tanswer(input: {\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\tanswers: readonly string[];\n\t\t\t/** @internal */\n\t\t\tactor: Actor;\n\t\t\t/** @internal */\n\t\t\tansweredAt?: string;\n\t\t}): ProcessQuestionRequest | null {\n\t\t\tconst row = db\n\t\t\t\t.update(s.processQuestionRequests)\n\t\t\t\t.set({\n\t\t\t\t\tstatus: \"answered\",\n\t\t\t\t\tanswersJson: JSON.stringify(input.answers),\n\t\t\t\t\tansweredAt: input.answeredAt ?? now(),\n\t\t\t\t\tansweredByJson: JSON.stringify(input.actor),\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processQuestionRequests.id, input.id),\n\t\t\t\t\t\teq(s.processQuestionRequests.status, \"open\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn row ? map(row) : null;\n\t\t},\n\t\t/** @internal */\n\t\tcancelOpenByTurn(instanceId: string, turnRecordId: string): number {\n\t\t\treturn Number(\n\t\t\t\tdb\n\t\t\t\t\t.update(s.processQuestionRequests)\n\t\t\t\t\t.set({ status: \"cancelled\", cancelledAt: now() })\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(s.processQuestionRequests.instanceId, instanceId),\n\t\t\t\t\t\t\teq(s.processQuestionRequests.turnRecordId, turnRecordId),\n\t\t\t\t\t\t\teq(s.processQuestionRequests.status, \"open\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.run().changes,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { Actor, ProcessRelation } from \"@leitwerk-dev/domain\";\nimport { asc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { now, parsePersistedJson } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nfunction map(row: typeof s.processRelations.$inferSelect): ProcessRelation {\n\treturn {\n\t\tparentInstanceId: row.parentInstanceId,\n\t\tchildInstanceId: row.childInstanceId,\n\t\tkind: \"derived\",\n\t\tpurpose: row.purpose,\n\t\tcreatedAt: row.createdAt,\n\t\tcreatedBy: parsePersistedJson<Actor>(row.createdByJson, \"process relation actor\"),\n\t};\n}\n\n/** @internal */\nexport function createProcessRelationRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(\n\t\t\tinput: Omit<ProcessRelation, \"kind\" | \"createdAt\"> & {\n\t\t\t\t/** @internal */\n\t\t\t\tcreatedAt?: string;\n\t\t\t},\n\t\t): ProcessRelation {\n\t\t\tconst row = db\n\t\t\t\t.insert(s.processRelations)\n\t\t\t\t.values({\n\t\t\t\t\tparentInstanceId: input.parentInstanceId,\n\t\t\t\t\tchildInstanceId: input.childInstanceId,\n\t\t\t\t\tkind: \"derived\",\n\t\t\t\t\tpurpose: input.purpose,\n\t\t\t\t\tcreatedAt: input.createdAt ?? now(),\n\t\t\t\t\tcreatedByJson: JSON.stringify(input.createdBy),\n\t\t\t\t})\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn map(row);\n\t\t},\n\t\t/** @internal */\n\t\tgetByChild(childInstanceId: string): ProcessRelation | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processRelations)\n\t\t\t\t.where(eq(s.processRelations.childInstanceId, childInstanceId))\n\t\t\t\t.get();\n\t\t\treturn row ? map(row) : null;\n\t\t},\n\t\t/** @internal */\n\t\tlistByParent(parentInstanceId: string): ProcessRelation[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processRelations)\n\t\t\t\t.where(eq(s.processRelations.parentInstanceId, parentInstanceId))\n\t\t\t\t.orderBy(asc(s.processRelations.createdAt))\n\t\t\t\t.all()\n\t\t\t\t.map(map);\n\t\t},\n\t};\n}\n","import type { SkillSelection } from \"@leitwerk-dev/protocol\";\nimport { asc, eq } from \"drizzle-orm\";\nimport { type PiResourceLayer, SKILL_RESOURCE_OWNER } from \"../pi-resources/resource-collector.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { processSkills, skillRevisions } from \"./schema.js\";\n\n/** @internal */\nexport function createProcessSkillRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tattach(instanceId: string, selections: readonly SkillSelection[]): void {\n\t\t\tconst seen = new Set<string>();\n\t\t\tselections.forEach((selection, position) => {\n\t\t\t\tif (seen.has(selection.skillId))\n\t\t\t\t\tthrow new Error(`Duplicate skill selection '${selection.skillId}'`);\n\t\t\t\tseen.add(selection.skillId);\n\t\t\t\tconst revision = db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(skillRevisions)\n\t\t\t\t\t.where(eq(skillRevisions.id, selection.revisionId))\n\t\t\t\t\t.get();\n\t\t\t\tif (!revision || revision.skillId !== selection.skillId)\n\t\t\t\t\tthrow new Error(`Invalid revision for skill '${selection.skillId}'`);\n\t\t\t\tdb.insert(processSkills)\n\t\t\t\t\t.values({\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tskillId: selection.skillId,\n\t\t\t\t\t\tskillRevisionId: selection.revisionId,\n\t\t\t\t\t\tposition,\n\t\t\t\t\t})\n\t\t\t\t\t.run();\n\t\t\t});\n\t\t},\n\t\t/** @internal */\n\t\tlistSelections(instanceId: string): SkillSelection[] {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\tskillId: processSkills.skillId,\n\t\t\t\t\trevisionId: processSkills.skillRevisionId,\n\t\t\t\t})\n\t\t\t\t.from(processSkills)\n\t\t\t\t.where(eq(processSkills.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(processSkills.position))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tlistResourceLayers(instanceId: string): PiResourceLayer[] {\n\t\t\treturn db\n\t\t\t\t.select({\n\t\t\t\t\tdigest: skillRevisions.bundleDigest,\n\t\t\t\t\tbytes: skillRevisions.bundleBytes,\n\t\t\t\t\tprovenance: skillRevisions.provenance,\n\t\t\t\t})\n\t\t\t\t.from(processSkills)\n\t\t\t\t.innerJoin(skillRevisions, eq(processSkills.skillRevisionId, skillRevisions.id))\n\t\t\t\t.where(eq(processSkills.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(processSkills.position))\n\t\t\t\t.all()\n\t\t\t\t.map(({ digest, bytes, provenance }) => ({\n\t\t\t\t\tbundle: { digest, bytes },\n\t\t\t\t\towner: provenance\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: \"skill\" as const,\n\t\t\t\t\t\t\t\townerExtensionId: provenance.extensionId,\n\t\t\t\t\t\t\t\tpackageName: provenance.packageName,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: SKILL_RESOURCE_OWNER,\n\t\t\t\t}));\n\t\t},\n\t};\n}\n","import { constants } from \"node:fs\";\nimport { lstat, open, readdir, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n\ttype PiResourceBundle,\n\ttype PiResourceFile,\n\ttype PiResourceFileProvenance,\n\ttype PiResourceProvenanceKind,\n\tsha256Digest,\n\tvalidateResourceRelativePath,\n\tverifyCanonicalPiResourceBundle,\n} from \"@leitwerk-dev/worker-protocol\";\n\nexport const DEFAULT_PI_RESOURCE_LIMITS = {\n\tmaxFiles: 2_048,\n\tmaxFileBytes: 32 * 1024 * 1024,\n\tmaxTotalBytes: 64 * 1024 * 1024,\n} as const;\n\n/** @internal */\nexport interface PiResourceLimits {\n\t/** @internal */\n\treadonly maxFiles?: number;\n\t/** @internal */\n\treadonly maxFileBytes?: number;\n\t/** @internal */\n\treadonly maxTotalBytes?: number;\n}\n\n/** @internal */\nexport interface ResourceOwner {\n\t/** @internal */\n\treadonly kind: Exclude<PiResourceProvenanceKind, \"generated\">;\n\t/** @internal */\n\treadonly ownerExtensionId: string | null;\n\t/** @internal */\n\treadonly packageName: string | null;\n}\n\nexport const SKILL_RESOURCE_OWNER: ResourceOwner = {\n\tkind: \"skill\",\n\townerExtensionId: null,\n\tpackageName: null,\n};\n\n/** @internal */\nexport interface PiResourceLayer {\n\t/** @internal */\n\treadonly bundle: PiResourceBundle;\n\t/** @internal */\n\treadonly owner: ResourceOwner;\n}\n\nfunction resolveLimits(input?: PiResourceLimits): Required<PiResourceLimits> {\n\tconst limits = {\n\t\tmaxFiles: input?.maxFiles ?? DEFAULT_PI_RESOURCE_LIMITS.maxFiles,\n\t\tmaxFileBytes: input?.maxFileBytes ?? DEFAULT_PI_RESOURCE_LIMITS.maxFileBytes,\n\t\tmaxTotalBytes: input?.maxTotalBytes ?? DEFAULT_PI_RESOURCE_LIMITS.maxTotalBytes,\n\t};\n\tfor (const [name, value] of Object.entries(limits)) {\n\t\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\t\tthrow new Error(`${name} must be a positive safe integer`);\n\t\t}\n\t}\n\treturn limits;\n}\n\nexport function compareResourcePaths(left: string, right: string): number {\n\treturn Buffer.compare(Buffer.from(left, \"utf8\"), Buffer.from(right, \"utf8\"));\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n\tconst relative = path.relative(root, candidate);\n\treturn relative === \"\" || (!relative.startsWith(`..${path.sep}`) && relative !== \"..\");\n}\n\nexport function validatePhysicalSourcePath(sourcePath: string): void {\n\tif (!path.isAbsolute(sourcePath) || path.normalize(sourcePath) !== sourcePath) {\n\t\tthrow new Error(`Pi resource source path must be normalized and absolute: ${sourcePath}`);\n\t}\n}\n\nexport class ResourceCollector {\n\treadonly files = new Map<string, Uint8Array>();\n\treadonly provenance: PiResourceFileProvenance[] = [];\n\tprivate readonly sourceFileIdentities = new Map<string, string>();\n\tprivate readonly sourceFileRealPaths = new Map<string, string>();\n\tprivate readonly sourceRootRealPaths = new Map<string, string>();\n\tprivate readonly limits: Required<PiResourceLimits>;\n\tprivate totalBytes = 0;\n\n\tconstructor(limits?: PiResourceLimits) {\n\t\tthis.limits = resolveLimits(limits);\n\t}\n\n\tprivate checkCapacity(snapshotPath: string, size: number): void {\n\t\tif (size > this.limits.maxFileBytes) {\n\t\t\tthrow new Error(\n\t\t\t\t`Pi resource '${snapshotPath}' size ${size} exceeds per-file limit ${this.limits.maxFileBytes}`,\n\t\t\t);\n\t\t}\n\t\tif (this.files.size + 1 > this.limits.maxFiles) {\n\t\t\tthrow new Error(`Pi resource snapshot exceeds file-count limit ${this.limits.maxFiles}`);\n\t\t}\n\t\tif (this.totalBytes + size > this.limits.maxTotalBytes) {\n\t\t\tthrow new Error(`Pi resource snapshot exceeds byte limit ${this.limits.maxTotalBytes}`);\n\t\t}\n\t}\n\n\taddBytes(snapshotPathInput: string, contentInput: Uint8Array, owner?: ResourceOwner): void {\n\t\tconst snapshotPath = validateResourceRelativePath(snapshotPathInput);\n\t\tif (this.files.has(snapshotPath)) {\n\t\t\tthrow new Error(`Duplicate Pi resource snapshot path '${snapshotPath}'`);\n\t\t}\n\t\tconst content = Uint8Array.from(contentInput);\n\t\tthis.checkCapacity(snapshotPath, content.byteLength);\n\t\tthis.files.set(snapshotPath, content);\n\t\tthis.totalBytes += content.byteLength;\n\t\tthis.provenance.push({\n\t\t\tkind: owner?.kind ?? \"generated\",\n\t\t\townerExtensionId: owner?.ownerExtensionId ?? null,\n\t\t\tpackageName: owner?.packageName ?? null,\n\t\t\tsnapshotPath,\n\t\t\tsha256: sha256Digest(content),\n\t\t\tsize: content.byteLength,\n\t\t});\n\t}\n\n\taddBundle(bundle: PiResourceBundle, owner: ResourceOwner): void {\n\t\tfor (const file of verifyCanonicalPiResourceBundle(bundle.bytes, bundle.digest)) {\n\t\t\tthis.addBytes(file.path, file.content, owner);\n\t\t}\n\t}\n\n\tprivate async addSourceFile(\n\t\tsourcePath: string,\n\t\tsnapshotPath: string,\n\t\towner: ResourceOwner,\n\t\tphysicalRoot: string,\n\t): Promise<void> {\n\t\tconst before = await lstat(sourcePath);\n\t\tif (before.isSymbolicLink() || !before.isFile()) {\n\t\t\tthrow new Error(`Pi resource source must be a regular file: ${sourcePath}`);\n\t\t}\n\t\tconst physicalPath = await realpath(sourcePath);\n\t\tif (!isWithin(physicalRoot, physicalPath)) {\n\t\t\tthrow new Error(`Pi resource path escapes its declared directory: ${sourcePath}`);\n\t\t}\n\t\tconst identity = `${before.dev}:${before.ino}`;\n\t\tconst duplicate =\n\t\t\tthis.sourceFileIdentities.get(identity) ?? this.sourceFileRealPaths.get(physicalPath);\n\t\tif (duplicate) {\n\t\t\tthrow new Error(\n\t\t\t\t`Physical Pi resource file is included more than once: ${sourcePath} (first: ${duplicate})`,\n\t\t\t);\n\t\t}\n\t\tif (before.size > this.limits.maxFileBytes) {\n\t\t\tthrow new Error(\n\t\t\t\t`Pi resource source '${sourcePath}' size ${before.size} exceeds per-file limit ${this.limits.maxFileBytes}`,\n\t\t\t);\n\t\t}\n\t\tconst handle = await open(sourcePath, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\tlet content: Uint8Array;\n\t\ttry {\n\t\t\tconst opened = await handle.stat();\n\t\t\tif (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {\n\t\t\t\tthrow new Error(`Pi resource source changed while being read: ${sourcePath}`);\n\t\t\t}\n\t\t\tcontent = await handle.readFile();\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tthis.sourceFileIdentities.set(identity, sourcePath);\n\t\tthis.sourceFileRealPaths.set(physicalPath, sourcePath);\n\t\tthis.addBytes(snapshotPath, content, owner);\n\t}\n\n\tasync addDirectory(\n\t\tsourceRoot: string,\n\t\ttargetRoot: string,\n\t\towner: ResourceOwner,\n\t\toptions: { forbiddenNames?: ReadonlySet<string> } = {},\n\t): Promise<void> {\n\t\tvalidatePhysicalSourcePath(sourceRoot);\n\t\tconst rootStat = await lstat(sourceRoot);\n\t\tif (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {\n\t\t\tthrow new Error(`Pi resource root must be a real directory: ${sourceRoot}`);\n\t\t}\n\t\tconst physicalRoot = await realpath(sourceRoot);\n\t\tconst duplicateRoot = this.sourceRootRealPaths.get(physicalRoot);\n\t\tif (duplicateRoot) {\n\t\t\tthrow new Error(\n\t\t\t\t`Physical Pi resource directory is declared more than once: ${sourceRoot} (first: ${duplicateRoot})`,\n\t\t\t);\n\t\t}\n\t\tthis.sourceRootRealPaths.set(physicalRoot, sourceRoot);\n\n\t\tconst visit = async (directory: string, relativeDirectory: string): Promise<void> => {\n\t\t\tconst entries = await readdir(directory, { withFileTypes: true });\n\t\t\tentries.sort((left, right) => compareResourcePaths(left.name, right.name));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (options.forbiddenNames?.has(entry.name)) {\n\t\t\t\t\tthrow new Error(`Pi resource contains forbidden path component '${entry.name}'`);\n\t\t\t\t}\n\t\t\t\tconst source = path.join(directory, entry.name);\n\t\t\t\tconst relative = relativeDirectory\n\t\t\t\t\t? path.posix.join(relativeDirectory, entry.name)\n\t\t\t\t\t: entry.name;\n\t\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\t\tthrow new Error(`Symbolic links are forbidden in Pi resources: ${source}`);\n\t\t\t\t}\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tawait visit(source, relative);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!entry.isFile()) {\n\t\t\t\t\tthrow new Error(`Special filesystem entries are forbidden in Pi resources: ${source}`);\n\t\t\t\t}\n\t\t\t\tawait this.addSourceFile(\n\t\t\t\t\tsource,\n\t\t\t\t\tvalidateResourceRelativePath(path.posix.join(targetRoot, relative)),\n\t\t\t\t\towner,\n\t\t\t\t\tphysicalRoot,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t\tawait visit(sourceRoot, \"\");\n\t}\n\n\ttoResourceFiles(): PiResourceFile[] {\n\t\treturn [...this.files]\n\t\t\t.sort(([left], [right]) => compareResourcePaths(left, right))\n\t\t\t.map(([resourcePath, content]) => ({ path: resourcePath, content }));\n\t}\n}\n","import { and, asc, eq, inArray, lte, sql } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport type ProcessTitleJob = typeof s.processTitleJobs.$inferSelect;\n\n/** @internal */\nexport type EnqueueProcessTitleJobInput = {\n\t/** @internal */\n\tprocessDefinitionId: string;\n\t/** @internal */\n\tmodelProfileId: string;\n\t/** @internal */\n\tprompt: string;\n\t/** @internal */\n\tmaxAttempts: number;\n\t/** @internal */\n\tnextRunAt: string;\n} & (\n\t| {\n\t\t\t/** @internal */\n\t\t\tprocessInstanceId: string;\n\t\t\t/** @internal */\n\t\t\tlaunchRunId?: string | null;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tfutureExecutionId: string;\n\t\t\t/** @internal */\n\t\t\texpectedPayloadJson: string;\n\t }\n);\n\n/** @internal */\nexport function createProcessTitleJobRepo(db: LeitwerkDb) {\n\tfunction transition(\n\t\tid: string,\n\t\tfrom: ProcessTitleJob[\"status\"][],\n\t\tvalues: SQLiteUpdateSetSource<typeof s.processTitleJobs>,\n\t): ProcessTitleJob | null {\n\t\treturn (\n\t\t\tdb\n\t\t\t\t.update(s.processTitleJobs)\n\t\t\t\t.set({ ...values, updatedAt: now() })\n\t\t\t\t.where(and(eq(s.processTitleJobs.id, id), inArray(s.processTitleJobs.status, from)))\n\t\t\t\t.returning()\n\t\t\t\t.get() ?? null\n\t\t);\n\t}\n\n\treturn {\n\t\t/** @internal */\n\t\tenqueue(input: EnqueueProcessTitleJobInput): ProcessTitleJob {\n\t\t\tconst ts = now();\n\t\t\tconst target =\n\t\t\t\t\"processInstanceId\" in input\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttargetKind: \"process\" as const,\n\t\t\t\t\t\t\tprocessInstanceId: input.processInstanceId,\n\t\t\t\t\t\t\tlaunchRunId: input.launchRunId ?? null,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttargetKind: \"future_execution\" as const,\n\t\t\t\t\t\t\tfutureExecutionId: input.futureExecutionId,\n\t\t\t\t\t\t\texpectedPayloadJson: input.expectedPayloadJson,\n\t\t\t\t\t\t};\n\t\t\tdb.update(s.processTitleJobs)\n\t\t\t\t.set({ status: \"superseded\", updatedAt: ts })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\tinArray(s.processTitleJobs.status, [\"pending\", \"running\"]),\n\t\t\t\t\t\ttarget.targetKind === \"process\"\n\t\t\t\t\t\t\t? eq(s.processTitleJobs.processInstanceId, target.processInstanceId)\n\t\t\t\t\t\t\t: eq(s.processTitleJobs.futureExecutionId, target.futureExecutionId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn db\n\t\t\t\t.insert(s.processTitleJobs)\n\t\t\t\t.values({\n\t\t\t\t\t...target,\n\t\t\t\t\tid: generateId(\"ttj\"),\n\t\t\t\t\tprocessDefinitionId: input.processDefinitionId,\n\t\t\t\t\tmodelProfileId: input.modelProfileId,\n\t\t\t\t\tprompt: input.prompt,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tmaxAttempts: input.maxAttempts,\n\t\t\t\t\tnextRunAt: input.nextRunAt,\n\t\t\t\t\tcreatedAt: ts,\n\t\t\t\t\tupdatedAt: ts,\n\t\t\t\t})\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): ProcessTitleJob | null {\n\t\t\tconst row = db.select().from(s.processTitleJobs).where(eq(s.processTitleJobs.id, id)).get();\n\t\t\treturn row ?? null;\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByProcessInstance(processInstanceId: string): ProcessTitleJob[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processTitleJobs)\n\t\t\t\t.where(eq(s.processTitleJobs.processInstanceId, processInstanceId))\n\t\t\t\t.orderBy(asc(s.processTitleJobs.createdAt), asc(s.processTitleJobs.id))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistAll(): ProcessTitleJob[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processTitleJobs)\n\t\t\t\t.orderBy(asc(s.processTitleJobs.createdAt), asc(s.processTitleJobs.id))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tlistDuePending(asOf: string, limit: number): ProcessTitleJob[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processTitleJobs)\n\t\t\t\t.where(\n\t\t\t\t\tand(eq(s.processTitleJobs.status, \"pending\"), lte(s.processTitleJobs.nextRunAt, asOf)),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.processTitleJobs.nextRunAt), asc(s.processTitleJobs.createdAt))\n\t\t\t\t.limit(Math.max(0, limit))\n\t\t\t\t.all();\n\t\t},\n\n\t\t/** @internal */\n\t\tmarkRunning(id: string): ProcessTitleJob | null {\n\t\t\treturn transition(id, [\"pending\"], {\n\t\t\t\tstatus: \"running\",\n\t\t\t\tattemptCount: sql`${s.processTitleJobs.attemptCount} + 1`,\n\t\t\t\tlastError: null,\n\t\t\t});\n\t\t},\n\n\t\t/** @internal */\n\t\treschedule(id: string, nextRunAt: string, lastError: string): ProcessTitleJob | null {\n\t\t\treturn transition(id, [\"running\"], { status: \"pending\", nextRunAt, lastError });\n\t\t},\n\n\t\t/** @internal */\n\t\tmarkCompleted(id: string): ProcessTitleJob | null {\n\t\t\treturn transition(id, [\"running\"], { status: \"completed\", lastError: null });\n\t\t},\n\n\t\t/** @internal */\n\t\tmarkFailed(id: string, lastError: string): ProcessTitleJob | null {\n\t\t\treturn transition(id, [\"running\"], { status: \"failed\", lastError });\n\t\t},\n\n\t\t/** @internal */\n\t\tmarkSuperseded(id: string): ProcessTitleJob | null {\n\t\t\treturn transition(id, [\"pending\", \"running\"], { status: \"superseded\" });\n\t\t},\n\t};\n}\n","import type {\n\tActor,\n\tProcessToolApprovalDestination,\n\tProcessToolApprovalRequest,\n\tToolApprovalStatus,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now, parsePersistedJson } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nfunction map(row: typeof s.processToolApprovalRequests.$inferSelect): ProcessToolApprovalRequest {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tturnRecordId: row.turnRecordId,\n\t\ttoolCallId: row.toolCallId,\n\t\ttoolName: row.toolName,\n\t\targuments: parsePersistedJson<Record<string, unknown>>(\n\t\t\trow.argumentsJson,\n\t\t\t\"tool approval arguments\",\n\t\t),\n\t\tdestination: row.destinationJson\n\t\t\t? parsePersistedJson<ProcessToolApprovalDestination>(\n\t\t\t\t\trow.destinationJson,\n\t\t\t\t\t\"tool approval destination\",\n\t\t\t\t)\n\t\t\t: null,\n\t\tstatus: row.status as ToolApprovalStatus,\n\t\trequestedAt: row.requestedAt,\n\t\tresolvedAt: row.resolvedAt,\n\t\tresolvedBy: row.resolvedByJson\n\t\t\t? parsePersistedJson<Actor>(row.resolvedByJson, \"tool approval actor\")\n\t\t\t: null,\n\t\tfeedback: row.feedback,\n\t};\n}\n\n/** @internal */\nexport function createProcessToolApprovalRequestRepo(db: LeitwerkDb) {\n\tconst list = (instanceId?: string, openOnly = false): ProcessToolApprovalRequest[] => {\n\t\tconst filters = [\n\t\t\t...(instanceId ? [eq(s.processToolApprovalRequests.instanceId, instanceId)] : []),\n\t\t\t...(openOnly ? [eq(s.processToolApprovalRequests.status, \"open\")] : []),\n\t\t];\n\t\treturn db\n\t\t\t.select()\n\t\t\t.from(s.processToolApprovalRequests)\n\t\t\t.where(filters.length ? and(...filters) : undefined)\n\t\t\t.orderBy(asc(s.processToolApprovalRequests.requestedAt))\n\t\t\t.all()\n\t\t\t.map(map);\n\t};\n\treturn {\n\t\t/** @internal */\n\t\tlistByInstance: (instanceId: string) => list(instanceId),\n\t\t/** @internal */\n\t\tlistOpen: (instanceId?: string) => list(instanceId, true),\n\t\t/** @internal */\n\t\tcreateIdempotent(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tturnRecordId: string;\n\t\t\t/** @internal */\n\t\t\ttoolCallId: string;\n\t\t\t/** @internal */\n\t\t\ttoolName: string;\n\t\t\t/** @internal */\n\t\t\targuments: Record<string, unknown>;\n\t\t\t/** @internal */\n\t\t\tdestination?: ProcessToolApprovalDestination;\n\t\t\t/** @internal */\n\t\t\trequestedAt?: string;\n\t\t}): {\n\t\t\t/** @internal */\n\t\t\tkind: \"created\" | \"replay\";\n\t\t\t/** @internal */\n\t\t\trequest: ProcessToolApprovalRequest;\n\t\t} {\n\t\t\tconst existing = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.processToolApprovalRequests)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processToolApprovalRequests.instanceId, input.instanceId),\n\t\t\t\t\t\teq(s.processToolApprovalRequests.turnRecordId, input.turnRecordId),\n\t\t\t\t\t\teq(s.processToolApprovalRequests.toolCallId, input.toolCallId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\tif (existing) {\n\t\t\t\tconst request = map(existing);\n\t\t\t\tif (\n\t\t\t\t\trequest.toolName !== input.toolName ||\n\t\t\t\t\tJSON.stringify(request.arguments) !== JSON.stringify(input.arguments) ||\n\t\t\t\t\tJSON.stringify(request.destination) !== JSON.stringify(input.destination ?? null)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"Tool approval correlation was replayed with different arguments\");\n\t\t\t\t}\n\t\t\t\treturn { kind: \"replay\", request };\n\t\t\t}\n\t\t\tconst row = db\n\t\t\t\t.insert(s.processToolApprovalRequests)\n\t\t\t\t.values({\n\t\t\t\t\tid: generateId(\"tap\"),\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\tturnRecordId: input.turnRecordId,\n\t\t\t\t\ttoolCallId: input.toolCallId,\n\t\t\t\t\ttoolName: input.toolName,\n\t\t\t\t\targumentsJson: JSON.stringify(input.arguments),\n\t\t\t\t\tdestinationJson: input.destination ? JSON.stringify(input.destination) : null,\n\t\t\t\t\trequestedAt: input.requestedAt ?? now(),\n\t\t\t\t})\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn { kind: \"created\", request: map(row) };\n\t\t},\n\t\t/** @internal */\n\t\tresolve(input: {\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\tstatus: Exclude<ToolApprovalStatus, \"open\" | \"cancelled\">;\n\t\t\t/** @internal */\n\t\t\tactor: Actor;\n\t\t\t/** @internal */\n\t\t\tfeedback?: string;\n\t\t\t/** @internal */\n\t\t\tresolvedAt?: string;\n\t\t}): ProcessToolApprovalRequest | null {\n\t\t\tif (input.status === \"feedback\" && !input.feedback?.trim())\n\t\t\t\tthrow new Error(\"Feedback is required\");\n\t\t\tconst row = db\n\t\t\t\t.update(s.processToolApprovalRequests)\n\t\t\t\t.set({\n\t\t\t\t\tstatus: input.status,\n\t\t\t\t\tresolvedAt: input.resolvedAt ?? now(),\n\t\t\t\t\tresolvedByJson: JSON.stringify(input.actor),\n\t\t\t\t\tfeedback: input.feedback?.trim() ?? null,\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processToolApprovalRequests.id, input.id),\n\t\t\t\t\t\teq(s.processToolApprovalRequests.status, \"open\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.returning()\n\t\t\t\t.get();\n\t\t\treturn row ? map(row) : null;\n\t\t},\n\t\t/** @internal */\n\t\tcancelOpenByTurn(instanceId: string, turnRecordId: string): number {\n\t\t\tconst result = db\n\t\t\t\t.update(s.processToolApprovalRequests)\n\t\t\t\t.set({ status: \"cancelled\", resolvedAt: now() })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.processToolApprovalRequests.instanceId, instanceId),\n\t\t\t\t\t\teq(s.processToolApprovalRequests.turnRecordId, turnRecordId),\n\t\t\t\t\t\teq(s.processToolApprovalRequests.status, \"open\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn Number(result.changes);\n\t\t},\n\t};\n}\n","import type { ProcessTurnAnnotation, TurnAnnotationReference } from \"@leitwerk-dev/domain\";\nimport { parseTurnAnnotationReferences } from \"@leitwerk-dev/domain\";\nimport { and, asc, eq, getTableColumns, sql } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { type HistoryWindow, historyWindow } from \"./history-window.js\";\nimport { generateId, now, parseJsonRecord } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateProcessTurnAnnotationInput {\n\t/** @internal */\n\tid?: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tannotationType: string;\n\t/** Null means append-only and therefore not addressable via upsert key. @internal */\n\tannotationKey?: string | null;\n\t/** @internal */\n\treferences?: readonly TurnAnnotationReference[];\n\t/** @internal */\n\tpayload?: Record<string, unknown>;\n\t/** @internal */\n\tcreatedAt?: string;\n\t/** @internal */\n\tupdatedAt?: string;\n}\n\n/** @internal */\nexport interface UpdateProcessTurnAnnotationInput {\n\t/** @internal */\n\tannotationType?: string;\n\t/** Null means append-only and therefore not addressable via upsert key. @internal */\n\tannotationKey?: string | null;\n\t/** @internal */\n\treferences?: readonly TurnAnnotationReference[];\n\t/** @internal */\n\tpayload?: Record<string, unknown>;\n\t/** @internal */\n\tupdatedAt?: string;\n}\n\nfunction parseReferences(value: string): TurnAnnotationReference[] {\n\ttry {\n\t\treturn parseTurnAnnotationReferences(JSON.parse(value));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction rowToProcessTurnAnnotation(\n\trow: typeof s.turnAnnotations.$inferSelect,\n): ProcessTurnAnnotation {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tannotationType: row.annotationType,\n\t\tannotationKey: row.annotationKey ?? null,\n\t\treferences: parseReferences(row.referencesJson),\n\t\tpayload: parseJsonRecord(row.payloadJson) ?? {},\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n}\n\n/** @internal */\nexport function createProcessTurnAnnotationRepo(db: LeitwerkDb) {\n\tconst list = (instanceId: string, window: HistoryWindow | undefined, compact: boolean) =>\n\t\tdb\n\t\t\t.select({\n\t\t\t\t...getTableColumns(s.turnAnnotations),\n\t\t\t\tpayloadJson: compact\n\t\t\t\t\t? sql<string>`json_remove(${s.turnAnnotations.payloadJson}, '$.event')`\n\t\t\t\t\t: s.turnAnnotations.payloadJson,\n\t\t\t})\n\t\t\t.from(s.turnAnnotations)\n\t\t\t.where(\n\t\t\t\tand(\n\t\t\t\t\teq(s.turnAnnotations.instanceId, instanceId),\n\t\t\t\t\thistoryWindow(s.turnAnnotations.createdAt, window),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.orderBy(asc(s.turnAnnotations.createdAt))\n\t\t\t.all()\n\t\t\t.map(rowToProcessTurnAnnotation);\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessTurnAnnotationInput): ProcessTurnAnnotation {\n\t\t\tconst id = input.id ?? generateId(\"tan\");\n\t\t\tconst createdAt = input.createdAt ?? now();\n\t\t\tconst updatedAt = input.updatedAt ?? createdAt;\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tannotationType: input.annotationType,\n\t\t\t\tannotationKey: input.annotationKey ?? null,\n\t\t\t\treferencesJson: JSON.stringify(input.references ?? []),\n\t\t\t\tpayloadJson: JSON.stringify(input.payload ?? {}),\n\t\t\t\tcreatedAt,\n\t\t\t\tupdatedAt,\n\t\t\t};\n\t\t\tdb.insert(s.turnAnnotations).values(values).run();\n\t\t\treturn rowToProcessTurnAnnotation(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): ProcessTurnAnnotation | null {\n\t\t\tconst row = db.select().from(s.turnAnnotations).where(eq(s.turnAnnotations.id, id)).get();\n\t\t\treturn row ? rowToProcessTurnAnnotation(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tfindByKey(instanceId: string, annotationKey: string): ProcessTurnAnnotation | null {\n\t\t\tconst key = annotationKey.trim();\n\t\t\tif (key.length === 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.turnAnnotations)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.turnAnnotations.instanceId, instanceId),\n\t\t\t\t\t\teq(s.turnAnnotations.annotationKey, key),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\treturn row ? rowToProcessTurnAnnotation(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string, window?: HistoryWindow): ProcessTurnAnnotation[] {\n\t\t\treturn list(instanceId, window, false);\n\t\t},\n\n\t\t/** Keep presentation and observation fields without the raw source event. @internal */\n\t\tlistForTimeline(instanceId: string, window?: HistoryWindow): ProcessTurnAnnotation[] {\n\t\t\treturn list(instanceId, window, true);\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(id: string, input: UpdateProcessTurnAnnotationInput): ProcessTurnAnnotation | null {\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.turnAnnotations> = {\n\t\t\t\tupdatedAt: input.updatedAt ?? now(),\n\t\t\t\tannotationType: input.annotationType,\n\t\t\t\tannotationKey: input.annotationKey,\n\t\t\t};\n\t\t\tif (input.references !== undefined)\n\t\t\t\tsetValues.referencesJson = JSON.stringify(input.references);\n\t\t\tif (input.payload !== undefined) setValues.payloadJson = JSON.stringify(input.payload);\n\n\t\t\tdb.update(s.turnAnnotations).set(setValues).where(eq(s.turnAnnotations.id, id)).run();\n\t\t\treturn this.getById(id);\n\t\t},\n\n\t\t/** @internal */\n\t\tdelete(id: string): boolean {\n\t\t\tconst result = db.delete(s.turnAnnotations).where(eq(s.turnAnnotations.id, id)).run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\t};\n}\n","import type {\n\tMappedTurnItemRef,\n\tModelSelectionProvenance,\n\tProcessTurnRecord,\n\tProcessTurnRecordPathType,\n\tProcessTurnRecordStatus,\n\tProcessTurnType,\n\tTurnId,\n\tWorkerErrorClass,\n} from \"@leitwerk-dev/domain\";\nimport { and, asc, desc, eq, getTableColumns, isNull, ne, sql } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, mappedItemRef, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateProcessTurnRecordInput extends UpdateProcessTurnRecordInput {\n\t/** @internal */\n\tid?: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tturnId: TurnId;\n\t/** @internal */\n\tpathType?: ProcessTurnRecordPathType;\n\t/** @internal */\n\tstartedAt?: string;\n}\n\n/** @internal */\nexport interface UpdateProcessTurnRecordInput {\n\t/** @internal */\n\tturnType?: ProcessTurnType;\n\t/** @internal */\n\tstatus?: ProcessTurnRecordStatus;\n\t/** @internal */\n\tattemptNumber?: number;\n\t/** @internal */\n\tparentTurnRecordId?: string | null;\n\t/** @internal */\n\tturnStartRecordId?: string | null;\n\t/** @internal */\n\tacceptedWorkerLeaseId?: string | null;\n\t/** @internal */\n\tforkPiEntryId?: string | null;\n\t/** @internal */\n\tresultPiEntryId?: string | null;\n\t/** @internal */\n\tmodelProfileId?: string | null;\n\t/** @internal */\n\tmodelSelectionProvenance?: ModelSelectionProvenance | null;\n\t/** @internal */\n\titeration?: MappedTurnItemRef | null;\n\t/** @internal */\n\tturnResultMarkdown?: string | null;\n\t/** @internal */\n\terrorSummary?: string | null;\n\t/** @internal */\n\terrorClass?: WorkerErrorClass | null;\n\t/** @internal */\n\tendedAt?: string | null;\n}\n\nfunction rowToProcessTurnRecord(row: typeof s.turnRecords.$inferSelect): ProcessTurnRecord {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tturnId: row.turnId,\n\t\tturnType: row.turnType as ProcessTurnType,\n\t\tstatus: row.status as ProcessTurnRecordStatus,\n\t\tattemptNumber: row.attemptNumber,\n\t\tparentTurnRecordId: row.parentTurnRecordId ?? null,\n\t\tturnStartRecordId: row.turnStartRecordId ?? null,\n\t\tacceptedWorkerLeaseId: row.acceptedWorkerLeaseId ?? null,\n\t\tpathType: row.pathType as ProcessTurnRecordPathType,\n\t\tforkPiEntryId: row.forkPiEntryId ?? null,\n\t\tresultPiEntryId: row.resultPiEntryId ?? null,\n\t\tmodelProfileId: row.modelProfileId ?? null,\n\t\tmodelSelectionProvenance:\n\t\t\trow.modelSelectionKind && row.modelSelectionSource\n\t\t\t\t? {\n\t\t\t\t\t\tkind: row.modelSelectionKind as ModelSelectionProvenance[\"kind\"],\n\t\t\t\t\t\tsource: row.modelSelectionSource as ModelSelectionProvenance[\"source\"],\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\titeration: mappedItemRef(row),\n\t\tturnResultMarkdown: row.turnResultMarkdown ?? null,\n\t\terrorSummary: row.errorSummary ?? null,\n\t\terrorClass: (row.errorClass as WorkerErrorClass | null | undefined) ?? null,\n\t\tstartedAt: row.startedAt,\n\t\tendedAt: row.endedAt ?? null,\n\t};\n}\n\n/** @public */\nexport function createProcessTurnRecordRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateProcessTurnRecordInput): ProcessTurnRecord {\n\t\t\tconst id = input.id ?? generateId(\"trn\");\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tturnType: input.turnType ?? \"llm\",\n\t\t\t\tstatus: input.status ?? \"running\",\n\t\t\t\tattemptNumber: input.attemptNumber ?? 1,\n\t\t\t\tparentTurnRecordId: input.parentTurnRecordId ?? null,\n\t\t\t\tturnStartRecordId: input.turnStartRecordId ?? null,\n\t\t\t\tacceptedWorkerLeaseId: input.acceptedWorkerLeaseId ?? null,\n\t\t\t\tpathType: input.pathType ?? \"primary\",\n\t\t\t\tforkPiEntryId: input.forkPiEntryId ?? null,\n\t\t\t\tresultPiEntryId: input.resultPiEntryId ?? null,\n\t\t\t\tmodelProfileId: input.modelProfileId ?? null,\n\t\t\t\tmodelSelectionKind: input.modelSelectionProvenance?.kind ?? null,\n\t\t\t\tmodelSelectionSource: input.modelSelectionProvenance?.source ?? null,\n\t\t\t\tturnResultMarkdown: input.turnResultMarkdown ?? null,\n\t\t\t\terrorSummary: input.errorSummary ?? null,\n\t\t\t\terrorClass: input.errorClass ?? null,\n\t\t\t\tstartedAt: input.startedAt ?? now(),\n\t\t\t\tendedAt: input.endedAt ?? null,\n\t\t\t\tmappedRunId: input.iteration?.runId ?? null,\n\t\t\t\tmappedItemKey: input.iteration?.itemKey ?? null,\n\t\t\t\tmappedItemIndex: input.iteration?.itemIndex ?? null,\n\t\t\t};\n\t\t\tdb.insert(s.turnRecords).values(values).run();\n\t\t\treturn rowToProcessTurnRecord(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): ProcessTurnRecord | null {\n\t\t\tconst row = db.select().from(s.turnRecords).where(eq(s.turnRecords.id, id)).get();\n\t\t\treturn row ? rowToProcessTurnRecord(row) : null;\n\t\t},\n\n\t\t/** @public */\n\t\tlistByInstance(instanceId: string): ProcessTurnRecord[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.turnRecords)\n\t\t\t\t.where(eq(s.turnRecords.instanceId, instanceId))\n\t\t\t\t.orderBy(asc(s.turnRecords.startedAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessTurnRecord);\n\t\t},\n\n\t\t/** Only absent summaries need repair; don't read every retained turn at startup. @internal */\n\t\tlistMissingSummaries(instanceId: string): ProcessTurnRecord[] {\n\t\t\treturn db\n\t\t\t\t.select(getTableColumns(s.turnRecords))\n\t\t\t\t.from(s.turnRecords)\n\t\t\t\t.leftJoin(s.turnSummaries, eq(s.turnSummaries.turnRecordId, s.turnRecords.id))\n\t\t\t\t.where(and(eq(s.turnRecords.instanceId, instanceId), isNull(s.turnSummaries.turnRecordId)))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessTurnRecord);\n\t\t},\n\t\t/** A stable page, even when new turns arrive or timestamps tie. @internal */\n\t\tlistPage(\n\t\t\tinstanceId: string,\n\t\t\tbefore?: Pick<ProcessTurnRecord, \"startedAt\" | \"id\">,\n\t\t\tlimit = 40,\n\t\t): ProcessTurnRecord[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.turnRecords)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.turnRecords.instanceId, instanceId),\n\t\t\t\t\t\tbefore\n\t\t\t\t\t\t\t? sql`(${s.turnRecords.startedAt}, ${s.turnRecords.id}) < (${before.startedAt}, ${before.id})`\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(desc(s.turnRecords.startedAt), desc(s.turnRecords.id))\n\t\t\t\t.limit(limit)\n\t\t\t\t.all()\n\t\t\t\t.map(rowToProcessTurnRecord)\n\t\t\t\t.reverse();\n\t\t},\n\n\t\t/** @internal */\n\t\tgetLatestSucceededPrimaryByInstance(instanceId: string): ProcessTurnRecord | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.turnRecords)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.turnRecords.instanceId, instanceId),\n\t\t\t\t\t\teq(s.turnRecords.status, \"succeeded\"),\n\t\t\t\t\t\teq(s.turnRecords.pathType, \"primary\"),\n\t\t\t\t\t\tne(s.turnRecords.resultPiEntryId, \"\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(desc(s.turnRecords.startedAt))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToProcessTurnRecord(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(id: string, input: UpdateProcessTurnRecordInput): ProcessTurnRecord | null {\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.turnRecords> = {\n\t\t\t\tturnType: input.turnType,\n\t\t\t\tstatus: input.status,\n\t\t\t\tattemptNumber: input.attemptNumber,\n\t\t\t\tparentTurnRecordId: input.parentTurnRecordId,\n\t\t\t\tturnStartRecordId: input.turnStartRecordId,\n\t\t\t\tacceptedWorkerLeaseId: input.acceptedWorkerLeaseId,\n\t\t\t\tforkPiEntryId: input.forkPiEntryId,\n\t\t\t\tresultPiEntryId: input.resultPiEntryId,\n\t\t\t\tmodelProfileId: input.modelProfileId,\n\t\t\t\tturnResultMarkdown: input.turnResultMarkdown,\n\t\t\t\terrorSummary: input.errorSummary,\n\t\t\t\terrorClass: input.errorClass,\n\t\t\t\tendedAt: input.endedAt,\n\t\t\t};\n\t\t\tif (input.modelSelectionProvenance !== undefined) {\n\t\t\t\tsetValues.modelSelectionKind = input.modelSelectionProvenance?.kind ?? null;\n\t\t\t\tsetValues.modelSelectionSource = input.modelSelectionProvenance?.source ?? null;\n\t\t\t}\n\n\t\t\tdb.update(s.turnRecords).set(setValues).where(eq(s.turnRecords.id, id)).run();\n\t\t\treturn this.getById(id);\n\t\t},\n\t};\n}\n","import { and, count, eq } from \"drizzle-orm\";\nimport type { CredentialCipher } from \"./credential-cipher.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface ProviderCredentialRecord {\n\t/** @internal */\n\tproviderId: string;\n\t/** @internal */\n\trevision: number;\n\t/** @internal */\n\tpayload: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tupdatedAt: string;\n}\n\n/** @internal */\nexport function createProviderCredentialRepo(db: LeitwerkDb, cipher: CredentialCipher) {\n\tconst row = (value: typeof s.providerCredentials.$inferSelect): ProviderCredentialRecord => ({\n\t\tproviderId: value.providerId,\n\t\trevision: value.revision,\n\t\tpayload: cipher.decrypt(value.encryptedPayload),\n\t\tcreatedAt: value.createdAt,\n\t\tupdatedAt: value.updatedAt,\n\t});\n\treturn {\n\t\t/** @internal */\n\t\tcount(): number {\n\t\t\treturn db.select({ value: count() }).from(s.providerCredentials).get()?.value ?? 0;\n\t\t},\n\t\t/** @internal */\n\t\tget(providerId: string): ProviderCredentialRecord | null {\n\t\t\tconst value = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.providerCredentials)\n\t\t\t\t.where(eq(s.providerCredentials.providerId, providerId))\n\t\t\t\t.get();\n\t\t\treturn value ? row(value) : null;\n\t\t},\n\t\t/** @internal */\n\t\tcreate(input: {\n\t\t\t/** @internal */\n\t\t\tproviderId: string;\n\t\t\t/** @internal */\n\t\t\tpayload: string;\n\t\t}): ProviderCredentialRecord {\n\t\t\tconst ts = now();\n\t\t\tconst value = {\n\t\t\t\t...input,\n\t\t\t\trevision: 1,\n\t\t\t\tencryptedPayload: cipher.encrypt(input.payload),\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t};\n\t\t\tdb.insert(s.providerCredentials).values(value).run();\n\t\t\treturn {\n\t\t\t\tproviderId: input.providerId,\n\t\t\t\trevision: 1,\n\t\t\t\tpayload: input.payload,\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t};\n\t\t},\n\t\t/** @internal */\n\t\tcompareAndSet(input: {\n\t\t\t/** @internal */\n\t\t\tproviderId: string;\n\t\t\t/** @internal */\n\t\t\texpectedRevision: number;\n\t\t\t/** @internal */\n\t\t\tpayload: string;\n\t\t}): ProviderCredentialRecord | null {\n\t\t\tconst ts = now();\n\t\t\tconst revision = input.expectedRevision + 1;\n\t\t\tconst result = db\n\t\t\t\t.update(s.providerCredentials)\n\t\t\t\t.set({\n\t\t\t\t\trevision,\n\t\t\t\t\tencryptedPayload: cipher.encrypt(input.payload),\n\t\t\t\t\tupdatedAt: ts,\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.providerCredentials.providerId, input.providerId),\n\t\t\t\t\t\teq(s.providerCredentials.revision, input.expectedRevision),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\tif (result.changes !== 1) return null;\n\t\t\treturn this.get(input.providerId);\n\t\t},\n\t};\n}\n","import {\n\ttype SessionTransferAttemptWire,\n\ttype SessionTransferPhase,\n\tsessionTransferAttemptStateForPhase,\n} from \"@leitwerk-dev/session-transfer\";\nimport { and, eq, inArray, isNotNull, isNull, lt, notExists, or } from \"drizzle-orm\";\nimport { createOpaqueToken, hashOpaqueToken, verifyOpaqueToken } from \"../auth/auth-tokens.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nexport type { SessionTransferPhase } from \"@leitwerk-dev/session-transfer\";\n\n/** @internal */\nexport interface SessionTransferGrant {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\ttokenHash: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\texpiresAt: string;\n\t/** @internal */\n\tconsumedAt: string | null;\n\t/** @internal */\n\ttombstoneUntil: string | null;\n}\n\n/** @internal */\nexport interface SessionTransferAttempt extends SessionTransferAttemptWire {\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tcompletedAt: string | null;\n}\n\nconst ACTIVE_PHASES: SessionTransferPhase[] = [\n\t\"queued\",\n\t\"waiting_for_execution_chain\",\n\t\"stopping_worker\",\n\t\"starting_exporter\",\n\t\"scanning\",\n\t\"ready_to_stream\",\n\t\"streaming\",\n\t\"awaiting_ack\",\n];\n\nfunction isActivePhase(phase: SessionTransferPhase): boolean {\n\treturn ACTIVE_PHASES.includes(phase);\n}\n\n/** @internal */\nexport function createSessionTransferRepo(db: LeitwerkDb) {\n\tconst toAttempt = (\n\t\trow: typeof s.sessionTransferAttempts.$inferSelect | undefined,\n\t): SessionTransferAttempt | null =>\n\t\trow\n\t\t\t? {\n\t\t\t\t\t...row,\n\t\t\t\t\tstate: sessionTransferAttemptStateForPhase(row.phase),\n\t\t\t\t}\n\t\t\t: null;\n\n\treturn {\n\t\t/** @internal */\n\t\tcreateGrant(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tnow: Date;\n\t\t\t/** @internal */\n\t\t\tlifetimeMs: number;\n\t\t}): {\n\t\t\t/** @internal */\n\t\t\tgrant: SessionTransferGrant;\n\t\t\t/** @internal */\n\t\t\trawToken: string;\n\t\t} {\n\t\t\tconst rawToken = createOpaqueToken();\n\t\t\tconst values: typeof s.sessionTransferGrants.$inferInsert = {\n\t\t\t\tid: generateId(\"trg\"),\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\ttokenHash: hashOpaqueToken(rawToken, \"hex\"),\n\t\t\t\tcreatedAt: input.now.toISOString(),\n\t\t\t\texpiresAt: new Date(input.now.getTime() + input.lifetimeMs).toISOString(),\n\t\t\t\tconsumedAt: null,\n\t\t\t\ttombstoneUntil: null,\n\t\t\t};\n\t\t\tdb.insert(s.sessionTransferGrants).values(values).run();\n\t\t\treturn { grant: this.getGrant(values.id) as SessionTransferGrant, rawToken };\n\t\t},\n\n\t\t/** @internal */\n\t\tgetGrant(id: string): SessionTransferGrant | null {\n\t\t\treturn (\n\t\t\t\tdb.select().from(s.sessionTransferGrants).where(eq(s.sessionTransferGrants.id, id)).get() ??\n\t\t\t\tnull\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetAttempt(id: string): SessionTransferAttempt | null {\n\t\t\treturn toAttempt(\n\t\t\t\tdb\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(s.sessionTransferAttempts)\n\t\t\t\t\t.where(eq(s.sessionTransferAttempts.id, id))\n\t\t\t\t\t.get(),\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetActiveByInstance(instanceId: string): SessionTransferAttempt | null {\n\t\t\treturn toAttempt(\n\t\t\t\tdb\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(s.sessionTransferAttempts)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(s.sessionTransferAttempts.instanceId, instanceId),\n\t\t\t\t\t\t\tinArray(s.sessionTransferAttempts.phase, ACTIVE_PHASES),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.get(),\n\t\t\t);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistActive(): SessionTransferAttempt[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.sessionTransferAttempts)\n\t\t\t\t.where(inArray(s.sessionTransferAttempts.phase, ACTIVE_PHASES))\n\t\t\t\t.all()\n\t\t\t\t.map((row) => toAttempt(row) as SessionTransferAttempt);\n\t\t},\n\n\t\t/** @internal */\n\t\tstartAttempt(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tgrantId: string;\n\t\t\t/** @internal */\n\t\t\ttoken: string;\n\t\t\t/** @internal */\n\t\t\tnow: Date;\n\t\t\t/** @internal */\n\t\t\tleaseMs: number;\n\t\t\t/** @internal */\n\t\t\thardDeadlineMs: number;\n\t\t}):\n\t\t\t| {\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tkind: \"created\";\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tattempt: SessionTransferAttempt;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tkind: \"not_found\";\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tkind: \"busy\";\n\t\t\t } {\n\t\t\tconst grant = this.getGrant(input.grantId);\n\t\t\tif (\n\t\t\t\t!grant ||\n\t\t\t\tgrant.instanceId !== input.instanceId ||\n\t\t\t\tgrant.consumedAt !== null ||\n\t\t\t\tDate.parse(grant.expiresAt) <= input.now.getTime() ||\n\t\t\t\t!verifyOpaqueToken(input.token, grant.tokenHash, \"hex\")\n\t\t\t) {\n\t\t\t\treturn { kind: \"not_found\" };\n\t\t\t}\n\t\t\tif (this.getActiveByInstance(input.instanceId)) return { kind: \"busy\" };\n\t\t\tconst values: typeof s.sessionTransferAttempts.$inferInsert = {\n\t\t\t\tid: generateId(\"tra\"),\n\t\t\t\tgrantId: grant.id,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tphase: \"queued\",\n\t\t\t\tcreatedAt: input.now.toISOString(),\n\t\t\t\tleaseUntil: new Date(input.now.getTime() + input.leaseMs).toISOString(),\n\t\t\t\thardDeadline: new Date(input.now.getTime() + input.hardDeadlineMs).toISOString(),\n\t\t\t\tentriesTotal: null,\n\t\t\t\tlogicalBytesTotal: null,\n\t\t\t\tcompressedBytes: null,\n\t\t\t\tstreamSha256: null,\n\t\t\t\tfailureCode: null,\n\t\t\t\tcompletedAt: null,\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tdb.insert(s.sessionTransferAttempts).values(values).run();\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as Error).message.includes(\"uq_session_transfer_active_instance\"))\n\t\t\t\t\treturn { kind: \"busy\" };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"created\",\n\t\t\t\tattempt: this.getAttempt(values.id) as SessionTransferAttempt,\n\t\t\t};\n\t\t},\n\n\t\t/** @internal */\n\t\tverifyAttempt(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tgrantId: string;\n\t\t\t/** @internal */\n\t\t\tattemptId: string;\n\t\t\t/** @internal */\n\t\t\ttoken: string;\n\t\t}): SessionTransferAttempt | null {\n\t\t\tconst grant = this.getGrant(input.grantId);\n\t\t\tconst attempt = this.getAttempt(input.attemptId);\n\t\t\tif (\n\t\t\t\t!grant ||\n\t\t\t\t!attempt ||\n\t\t\t\tgrant.instanceId !== input.instanceId ||\n\t\t\t\tattempt.instanceId !== input.instanceId ||\n\t\t\t\tattempt.grantId !== grant.id\n\t\t\t)\n\t\t\t\treturn null;\n\t\t\treturn verifyOpaqueToken(input.token, grant.tokenHash, \"hex\") ? attempt : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tupdateAttempt(\n\t\t\tid: string,\n\t\t\tpatch: Partial<\n\t\t\t\tOmit<SessionTransferAttempt, \"id\" | \"grantId\" | \"instanceId\" | \"createdAt\" | \"state\">\n\t\t\t>,\n\t\t): SessionTransferAttempt | null {\n\t\t\tdb.update(s.sessionTransferAttempts)\n\t\t\t\t.set(patch)\n\t\t\t\t.where(eq(s.sessionTransferAttempts.id, id))\n\t\t\t\t.run();\n\t\t\treturn this.getAttempt(id);\n\t\t},\n\n\t\t/** @internal */\n\t\trenew(\n\t\t\tid: string,\n\t\t\tinput: {\n\t\t\t\t/** @internal */\n\t\t\t\tnow: Date;\n\t\t\t\t/** @internal */\n\t\t\t\tleaseMs: number;\n\t\t\t},\n\t\t): SessionTransferAttempt | null {\n\t\t\tconst attempt = this.getAttempt(id);\n\t\t\tif (!attempt || !isActivePhase(attempt.phase)) return attempt;\n\t\t\tconst nextLease = Math.min(\n\t\t\t\tinput.now.getTime() + input.leaseMs,\n\t\t\t\tDate.parse(attempt.hardDeadline),\n\t\t\t);\n\t\t\treturn this.updateAttempt(id, { leaseUntil: new Date(nextLease).toISOString() });\n\t\t},\n\n\t\t/** @internal */\n\t\tacknowledge(input: {\n\t\t\t/** @internal */\n\t\t\tattemptId: string;\n\t\t\t/** @internal */\n\t\t\tnow: Date;\n\t\t\t/** @internal */\n\t\t\ttombstoneMs: number;\n\t\t}): SessionTransferAttempt | null {\n\t\t\tconst attempt = this.getAttempt(input.attemptId);\n\t\t\tif (!attempt) return null;\n\t\t\tif (attempt.phase === \"consumed\") return attempt;\n\t\t\tif (\n\t\t\t\tattempt.phase !== \"awaiting_ack\" ||\n\t\t\t\tattempt.compressedBytes === null ||\n\t\t\t\t!attempt.streamSha256\n\t\t\t)\n\t\t\t\treturn null;\n\t\t\tconst completedAt = input.now.toISOString();\n\t\t\tdb.update(s.sessionTransferAttempts)\n\t\t\t\t.set({ phase: \"consumed\", completedAt })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.sessionTransferAttempts.id, attempt.id),\n\t\t\t\t\t\teq(s.sessionTransferAttempts.phase, \"awaiting_ack\"),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\tdb.update(s.sessionTransferGrants)\n\t\t\t\t.set({\n\t\t\t\t\tconsumedAt: completedAt,\n\t\t\t\t\ttombstoneUntil: new Date(input.now.getTime() + input.tombstoneMs).toISOString(),\n\t\t\t\t})\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.sessionTransferGrants.id, attempt.grantId),\n\t\t\t\t\t\tisNull(s.sessionTransferGrants.consumedAt),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn this.getAttempt(attempt.id);\n\t\t},\n\n\t\t/** @internal */\n\t\trevokeProcess(instanceId: string): void {\n\t\t\tdb.delete(s.sessionTransferGrants)\n\t\t\t\t.where(eq(s.sessionTransferGrants.instanceId, instanceId))\n\t\t\t\t.run();\n\t\t},\n\n\t\t/** @internal */\n\t\tcleanup(now: Date): void {\n\t\t\tconst cutoff = now.toISOString();\n\t\t\tdb.delete(s.sessionTransferGrants)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\tor(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\tisNull(s.sessionTransferGrants.consumedAt),\n\t\t\t\t\t\t\t\tlt(s.sessionTransferGrants.expiresAt, cutoff),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\tisNotNull(s.sessionTransferGrants.tombstoneUntil),\n\t\t\t\t\t\t\t\tlt(s.sessionTransferGrants.tombstoneUntil, cutoff),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tnotExists(\n\t\t\t\t\t\t\tdb\n\t\t\t\t\t\t\t\t.select({ id: s.sessionTransferAttempts.id })\n\t\t\t\t\t\t\t\t.from(s.sessionTransferAttempts)\n\t\t\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\t\teq(s.sessionTransferAttempts.grantId, s.sessionTransferGrants.id),\n\t\t\t\t\t\t\t\t\t\tinArray(s.sessionTransferAttempts.phase, ACTIVE_PHASES),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t},\n\t};\n}\n","import { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nexport type OpaqueTokenHashEncoding = \"base64url\" | \"hex\";\n\nexport function generateOpaqueToken(byteLength = 32): string {\n\treturn randomBytes(byteLength).toString(\"base64url\");\n}\n\nexport function createOpaqueToken(): string {\n\treturn generateOpaqueToken();\n}\n\nexport function hashOpaqueToken(\n\ttoken: string,\n\tencoding: OpaqueTokenHashEncoding = \"base64url\",\n): string {\n\treturn createHash(\"sha256\").update(token, \"utf8\").digest(encoding);\n}\n\nexport function verifyOpaqueToken(\n\ttoken: string,\n\texpectedHash: string,\n\tencoding: OpaqueTokenHashEncoding = \"base64url\",\n): boolean {\n\tconst actual = Buffer.from(hashOpaqueToken(token, encoding), encoding);\n\tconst expected = Buffer.from(expectedHash, encoding);\n\treturn actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n\nexport function isoFromNow(ms: number, now = new Date()): string {\n\treturn new Date(now.getTime() + ms).toISOString();\n}\n","import type {\n\tInstalledSkillCatalogDetail,\n\tInstalledSkillCatalogItem,\n\tSkillCatalogDetail,\n\tSkillCatalogItem,\n\tSkillOptionSummary,\n\tSkillSelection,\n\tSkillUsageProcessSummary,\n\tSkillUsageSummary,\n} from \"@leitwerk-dev/protocol\";\nimport { verifyCanonicalPiResourceBundle } from \"@leitwerk-dev/worker-protocol\";\nimport { and, asc, count, desc, eq, isNotNull, max, notExists, notInArray, sql } from \"drizzle-orm\";\nimport type { ImportedExtensionSkill } from \"../skills/extension-importer.js\";\nimport { explicitSkillReferenceIds, referencedSkillIds } from \"../skills/skill-dependencies.js\";\nimport { isSkillModelInvocable } from \"../skills/skill-frontmatter.js\";\nimport type { ImportedRepositorySkill, ImportedSkill } from \"../skills/source-importer.js\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport {\n\tprocessInstances,\n\tprocessSkills,\n\tskillCatalogEntries,\n\tskillInvocations,\n\tskillRevisionDependencies,\n\tskillRevisions,\n\tskills,\n} from \"./schema.js\";\n\nfunction revisionForBundle(db: LeitwerkDb, item: ImportedSkill, timestamp: string): string {\n\tconst existing = db\n\t\t.select({ id: skillRevisions.id })\n\t\t.from(skillRevisions)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(skillRevisions.skillId, item.skillId),\n\t\t\t\teq(skillRevisions.bundleDigest, item.bundle.digest),\n\t\t\t),\n\t\t)\n\t\t.get();\n\tif (existing) return existing.id;\n\tconst id = generateId(\"skillrev\");\n\tdb.insert(skillRevisions)\n\t\t.values({\n\t\t\tid,\n\t\t\tskillId: item.skillId,\n\t\t\tbundleDigest: item.bundle.digest,\n\t\t\tbundleBytes: Buffer.from(item.bundle.bytes),\n\t\t\tsourceRevision: item.sourceRevision,\n\t\t\tprovenance: item.provenance ?? null,\n\t\t\timportedAt: timestamp,\n\t\t})\n\t\t.run();\n\treturn id;\n}\n\nfunction emptyUsage(): SkillUsageSummary {\n\treturn {\n\t\tattachedAllTime: 0,\n\t\tattachedLast30Days: 0,\n\t\tinvokedAllTime: 0,\n\t\tinvokedLast30Days: 0,\n\t};\n}\n\nfunction usageBySkill(db: LeitwerkDb): Map<string, SkillUsageSummary> {\n\tconst result = new Map<string, SkillUsageSummary>();\n\tconst usage = (skillId: string) => result.get(skillId) ?? emptyUsage();\n\tconst cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();\n\tfor (const row of db\n\t\t.select({\n\t\t\tskillId: processSkills.skillId,\n\t\t\tallTime: count(),\n\t\t\tlast30Days: sql<number>`sum(case when ${processInstances.createdAt} >= ${cutoff} then 1 else 0 end)`,\n\t\t})\n\t\t.from(processSkills)\n\t\t.innerJoin(processInstances, eq(processSkills.instanceId, processInstances.id))\n\t\t.groupBy(processSkills.skillId)\n\t\t.all()) {\n\t\tresult.set(row.skillId, {\n\t\t\t...usage(row.skillId),\n\t\t\tattachedAllTime: row.allTime,\n\t\t\tattachedLast30Days: row.last30Days,\n\t\t});\n\t}\n\tfor (const row of db\n\t\t.select({\n\t\t\tskillId: skillInvocations.skillId,\n\t\t\tallTime: count(),\n\t\t\tlast30Days: sql<number>`sum(case when ${skillInvocations.invokedAt} >= ${cutoff} then 1 else 0 end)`,\n\t\t})\n\t\t.from(skillInvocations)\n\t\t.groupBy(skillInvocations.skillId)\n\t\t.all()) {\n\t\tresult.set(row.skillId, {\n\t\t\t...usage(row.skillId),\n\t\t\tinvokedAllTime: row.allTime,\n\t\t\tinvokedLast30Days: row.last30Days,\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction processUsage(db: LeitwerkDb, skillId: string): SkillUsageProcessSummary[] {\n\treturn db\n\t\t.select({\n\t\t\tinstanceId: processSkills.instanceId,\n\t\t\ttitle: sql<string>`coalesce(${processInstances.title}, ${processInstances.externalId}, ${processInstances.id})`,\n\t\t\tattachedAt: processInstances.createdAt,\n\t\t\tinvocationCount: count(skillInvocations.skillId),\n\t\t\tlastInvokedAt: max(skillInvocations.invokedAt),\n\t\t})\n\t\t.from(processSkills)\n\t\t.innerJoin(processInstances, eq(processSkills.instanceId, processInstances.id))\n\t\t.leftJoin(\n\t\t\tskillInvocations,\n\t\t\tand(\n\t\t\t\teq(skillInvocations.instanceId, processSkills.instanceId),\n\t\t\t\teq(skillInvocations.skillId, processSkills.skillId),\n\t\t\t),\n\t\t)\n\t\t.where(eq(processSkills.skillId, skillId))\n\t\t.groupBy(\n\t\t\tprocessSkills.instanceId,\n\t\t\tprocessInstances.title,\n\t\t\tprocessInstances.externalId,\n\t\t\tprocessInstances.id,\n\t\t\tprocessInstances.createdAt,\n\t\t)\n\t\t.orderBy(desc(processInstances.createdAt))\n\t\t.all();\n}\n\nfunction skillMarkdown(skillId: string, bytes: Uint8Array, digest: string): string {\n\tconst file = verifyCanonicalPiResourceBundle(bytes, digest).find(\n\t\t(candidate) => candidate.path === `skills/${skillId}/SKILL.md`,\n\t);\n\treturn file ? Buffer.from(file.content).toString(\"utf8\") : \"\";\n}\n\nfunction pruneNeverInstalledCatalogEntries(db: LeitwerkDb): void {\n\tdb.delete(skillCatalogEntries)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(skillCatalogEntries.available, false),\n\t\t\t\tnotExists(\n\t\t\t\t\tdb\n\t\t\t\t\t\t.select({ id: skillRevisions.id })\n\t\t\t\t\t\t.from(skillRevisions)\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(skillRevisions.skillId, skillCatalogEntries.skillId),\n\t\t\t\t\t\t\t\teq(skillRevisions.bundleDigest, skillCatalogEntries.bundleDigest),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\t.run();\n}\n\nfunction recordRevisionDependencies(\n\tdb: LeitwerkDb,\n\trevisionId: string,\n\tmarkdown: string,\n\tdependencyIds = explicitSkillReferenceIds(markdown),\n): void {\n\tdb.delete(skillRevisionDependencies)\n\t\t.where(eq(skillRevisionDependencies.skillRevisionId, revisionId))\n\t\t.run();\n\tfor (const [position, dependencySkillId] of dependencyIds.entries()) {\n\t\tdb.insert(skillRevisionDependencies)\n\t\t\t.values({ skillRevisionId: revisionId, dependencySkillId, position })\n\t\t\t.run();\n\t}\n}\n\nfunction activateSkill(\n\tdb: LeitwerkDb,\n\titem: ImportedSkill,\n\tregistrationKind: \"configuration\" | \"catalog\" | \"extension\",\n\ttimestamp: string,\n\tmarkdown = skillMarkdown(item.skillId, item.bundle.bytes, item.bundle.digest),\n): string {\n\tdb.insert(skills)\n\t\t.values({\n\t\t\tid: item.skillId,\n\t\t\tlabel: item.label,\n\t\t\tdescription: item.description,\n\t\t\tactiveRevisionId: null,\n\t\t\tregistrationKind,\n\t\t\tcreatedAt: timestamp,\n\t\t\tupdatedAt: timestamp,\n\t\t})\n\t\t.onConflictDoNothing()\n\t\t.run();\n\tconst revisionId = revisionForBundle(db, item, timestamp);\n\trecordRevisionDependencies(db, revisionId, markdown, item.provenance?.dependencies);\n\tdb.update(skills)\n\t\t.set({\n\t\t\tlabel: item.label,\n\t\t\tdescription: item.description,\n\t\t\tactiveRevisionId: revisionId,\n\t\t\tregistrationKind,\n\t\t\townerExtensionId: item.provenance?.extensionId ?? null,\n\t\t\tupdatedAt: timestamp,\n\t\t})\n\t\t.where(eq(skills.id, item.skillId))\n\t\t.run();\n\treturn revisionId;\n}\n\nfunction reconcileSkills(\n\tdb: LeitwerkDb,\n\timported: readonly ImportedSkill[],\n\tregistrationKind: \"configuration\" | \"extension\",\n): void {\n\tconst timestamp = now();\n\tconst ids = imported.map((item) => item.skillId);\n\tdb.update(skills)\n\t\t.set({ activeRevisionId: null, updatedAt: timestamp })\n\t\t.where(and(eq(skills.registrationKind, registrationKind), notInArray(skills.id, ids)))\n\t\t.run();\n\tfor (const item of imported) activateSkill(db, item, registrationKind, timestamp);\n}\n\nfunction catalogView(db: LeitwerkDb): {\n\t/** @internal */\n\tavailableSkills: SkillCatalogItem[];\n\t/** @internal */\n\tinstalledSkills: InstalledSkillCatalogItem[];\n} {\n\tconst candidates = db.select().from(skillCatalogEntries).all();\n\tconst usage = usageBySkill(db);\n\tconst installedRows = db\n\t\t.select({\n\t\t\tid: skills.id,\n\t\t\tlabel: skills.label,\n\t\t\tdescription: skills.description,\n\t\t\tactiveRevisionId: skillRevisions.id,\n\t\t\tactiveSourceRevision: skillRevisions.sourceRevision,\n\t\t\tactiveDigest: skillRevisions.bundleDigest,\n\t\t\tactiveBundleBytes: skillRevisions.bundleBytes,\n\t\t\tregistrationKind: skills.registrationKind,\n\t\t\townerExtensionId: skills.ownerExtensionId,\n\t\t\tprovenance: skillRevisions.provenance,\n\t\t})\n\t\t.from(skills)\n\t\t.innerJoin(skillRevisions, eq(skills.activeRevisionId, skillRevisions.id))\n\t\t.orderBy(asc(skills.label), asc(skills.id))\n\t\t.all();\n\tconst installedById = new Map(installedRows.map((row) => [row.id, row]));\n\tconst extensionIds = new Set(\n\t\tdb\n\t\t\t.select({ id: skills.id })\n\t\t\t.from(skills)\n\t\t\t.where(eq(skills.registrationKind, \"extension\"))\n\t\t\t.all()\n\t\t\t.map((skill) => skill.id),\n\t);\n\tconst availableSkills = candidates.map((candidate) => {\n\t\tconst active = installedById.get(candidate.skillId);\n\t\tconst registered = Boolean(\n\t\t\tactive?.registrationKind === \"catalog\" && active.activeDigest === candidate.bundleDigest,\n\t\t);\n\t\treturn {\n\t\t\trepositoryId: candidate.repositoryId,\n\t\t\tid: candidate.skillId,\n\t\t\tlabel: candidate.label,\n\t\t\tdescription: candidate.description,\n\t\t\tsourcePath: candidate.sourcePath,\n\t\t\tsourceRevision: candidate.sourceRevision,\n\t\t\tregistered,\n\t\t\tupdateAvailable: Boolean(\n\t\t\t\tcandidate.available && active?.registrationKind === \"catalog\" && !registered,\n\t\t\t),\n\t\t\tconflict:\n\t\t\t\tcandidate.available &&\n\t\t\t\t(active?.registrationKind === \"configuration\" || extensionIds.has(candidate.skillId)),\n\t\t\tstale: !candidate.available,\n\t\t\tmodelInvocable: isSkillModelInvocable(\n\t\t\t\tskillMarkdown(candidate.skillId, candidate.bundleBytes, candidate.bundleDigest),\n\t\t\t),\n\t\t\tusage: usage.get(candidate.skillId) ?? emptyUsage(),\n\t\t};\n\t});\n\tconst installedSkills = installedRows.map((skill) => {\n\t\tconst matching = candidates.filter((candidate) => candidate.skillId === skill.id);\n\t\tconst available = matching.filter((candidate) => candidate.available);\n\t\tconst activeSource = matching.filter(\n\t\t\t(candidate) => candidate.bundleDigest === skill.activeDigest,\n\t\t);\n\t\treturn {\n\t\t\tid: skill.id,\n\t\t\tlabel: skill.label,\n\t\t\tdescription: skill.description,\n\t\t\tactiveRevisionId: skill.activeRevisionId,\n\t\t\tactiveSourceRevision: skill.activeSourceRevision,\n\t\t\tregistrationKind: skill.registrationKind,\n\t\t\t...(skill.ownerExtensionId\n\t\t\t\t? { ownerExtensionId: skill.ownerExtensionId, provenance: skill.provenance }\n\t\t\t\t: {}),\n\t\t\tsourceRepositoryId:\n\t\t\t\tskill.registrationKind === \"extension\"\n\t\t\t\t\t? null\n\t\t\t\t\t: matching.length === 1\n\t\t\t\t\t\t? (matching[0]?.repositoryId ?? null)\n\t\t\t\t\t\t: activeSource.length === 1\n\t\t\t\t\t\t\t? (activeSource[0]?.repositoryId ?? null)\n\t\t\t\t\t\t\t: null,\n\t\t\tupdateAvailable:\n\t\t\t\tskill.registrationKind === \"catalog\" &&\n\t\t\t\tavailable.length === 1 &&\n\t\t\t\tavailable[0]?.bundleDigest !== skill.activeDigest,\n\t\t\tmodelInvocable: isSkillModelInvocable(\n\t\t\t\tskillMarkdown(skill.id, skill.activeBundleBytes, skill.activeDigest),\n\t\t\t),\n\t\t\tusage: usage.get(skill.id) ?? emptyUsage(),\n\t\t};\n\t});\n\treturn { availableSkills, installedSkills };\n}\n\n/** @internal */\nexport function createSkillRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tlistAvailable(): SkillOptionSummary[] {\n\t\t\treturn db\n\t\t\t\t.select({ id: skills.id, label: skills.label, description: skills.description })\n\t\t\t\t.from(skills)\n\t\t\t\t.where(isNotNull(skills.activeRevisionId))\n\t\t\t\t.orderBy(asc(skills.label), asc(skills.id))\n\t\t\t\t.all();\n\t\t},\n\t\t/** @internal */\n\t\tresolveActive(ids: readonly string[]): SkillSelection[] {\n\t\t\tconst activeSkills = db\n\t\t\t\t.select({\n\t\t\t\t\tid: skills.id,\n\t\t\t\t\trevisionId: skillRevisions.id,\n\t\t\t\t\tregistrationKind: skills.registrationKind,\n\t\t\t\t})\n\t\t\t\t.from(skills)\n\t\t\t\t.innerJoin(skillRevisions, eq(skills.activeRevisionId, skillRevisions.id))\n\t\t\t\t.all();\n\t\t\tconst byId = new Map(activeSkills.map((skill) => [skill.id, skill]));\n\t\t\tconst dependencies = new Map<string, string[]>();\n\t\t\tfor (const dependency of db.select().from(skillRevisionDependencies).all()) {\n\t\t\t\tconst ids = dependencies.get(dependency.skillRevisionId) ?? [];\n\t\t\t\tids[dependency.position] = dependency.dependencySkillId;\n\t\t\t\tdependencies.set(dependency.skillRevisionId, ids);\n\t\t\t}\n\t\t\tconst resolved = new Map<string, SkillSelection>();\n\t\t\tconst visiting = new Set<string>();\n\t\t\tconst add = (id: string): void => {\n\t\t\t\tif (resolved.has(id) || visiting.has(id)) return;\n\t\t\t\tconst skill = byId.get(id);\n\t\t\t\tif (!skill) throw new Error(`Unknown or unavailable skill '${id}'`);\n\t\t\t\tvisiting.add(id);\n\t\t\t\tfor (const dependencyId of dependencies.get(skill.revisionId) ?? []) {\n\t\t\t\t\tif (skill.registrationKind === \"extension\" && !byId.has(dependencyId))\n\t\t\t\t\t\tthrow new Error(`Missing dependency '${dependencyId}' for skill '${id}'`);\n\t\t\t\t\tif (dependencyId !== id && byId.has(dependencyId)) add(dependencyId);\n\t\t\t\t}\n\t\t\t\tvisiting.delete(id);\n\t\t\t\tresolved.set(id, { skillId: id, revisionId: skill.revisionId });\n\t\t\t};\n\t\t\tfor (const id of ids) add(id);\n\t\t\treturn [...resolved.values()];\n\t\t},\n\t\t/** @internal */\n\t\treconcile(imported: readonly ImportedSkill[]): void {\n\t\t\treconcileSkills(db, imported, \"configuration\");\n\t\t},\n\t\t/** Reconcile all loaded extension packs in the caller's startup transaction. @internal */\n\t\treconcileExtensions(imported: readonly ImportedExtensionSkill[]): void {\n\t\t\tconst byId = new Map(imported.map((item) => [item.skillId, item]));\n\t\t\tif (byId.size !== imported.length) throw new Error(\"Duplicate extension skill ID\");\n\t\t\tfor (const item of imported) {\n\t\t\t\tconst current = db.select().from(skills).where(eq(skills.id, item.skillId)).get();\n\t\t\t\tif (\n\t\t\t\t\tcurrent &&\n\t\t\t\t\t(current.registrationKind !== \"extension\" ||\n\t\t\t\t\t\tcurrent.ownerExtensionId !== item.provenance.extensionId)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Skill '${item.skillId}' is already owned by '${current.ownerExtensionId ?? current.registrationKind}'`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tfor (const dependency of item.provenance.dependencies) {\n\t\t\t\t\tif (byId.get(dependency)?.provenance.extensionId !== item.provenance.extensionId) {\n\t\t\t\t\t\tthrow new Error(`Missing pack dependency '${dependency}' for skill '${item.skillId}'`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treconcileSkills(db, imported, \"extension\");\n\t\t},\n\t\t/** @internal */\n\t\tbackfillDependencies(): void {\n\t\t\tfor (const revision of db.select().from(skillRevisions).all()) {\n\t\t\t\trecordRevisionDependencies(\n\t\t\t\t\tdb,\n\t\t\t\t\trevision.id,\n\t\t\t\t\tskillMarkdown(revision.skillId, revision.bundleBytes, revision.bundleDigest),\n\t\t\t\t\trevision.provenance?.dependencies,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\t/** @internal */\n\t\tmarkUnconfiguredCatalogEntries(configuredRepositoryIds: readonly string[]): void {\n\t\t\tdb.update(skillCatalogEntries)\n\t\t\t\t.set({ available: false })\n\t\t\t\t.where(notInArray(skillCatalogEntries.repositoryId, [...configuredRepositoryIds]))\n\t\t\t\t.run();\n\t\t\tpruneNeverInstalledCatalogEntries(db);\n\t\t},\n\t\t/** @internal */\n\t\tmergeCatalog(repositoryId: string, imported: readonly ImportedRepositorySkill[]): void {\n\t\t\tconst timestamp = now();\n\t\t\tdb.update(skillCatalogEntries)\n\t\t\t\t.set({ available: false })\n\t\t\t\t.where(eq(skillCatalogEntries.repositoryId, repositoryId))\n\t\t\t\t.run();\n\t\t\tfor (const item of imported) {\n\t\t\t\tconst values = {\n\t\t\t\t\tlabel: item.label,\n\t\t\t\t\tdescription: item.description,\n\t\t\t\t\tsourcePath: item.sourcePath,\n\t\t\t\t\tsourceRevision: item.sourceRevision ?? \"\",\n\t\t\t\t\tbundleDigest: item.bundle.digest,\n\t\t\t\t\tbundleBytes: Buffer.from(item.bundle.bytes),\n\t\t\t\t\tdiscoveredAt: timestamp,\n\t\t\t\t\tavailable: true,\n\t\t\t\t};\n\t\t\t\tdb.insert(skillCatalogEntries)\n\t\t\t\t\t.values({ repositoryId, skillId: item.skillId, ...values })\n\t\t\t\t\t.onConflictDoUpdate({\n\t\t\t\t\t\ttarget: [skillCatalogEntries.repositoryId, skillCatalogEntries.skillId],\n\t\t\t\t\t\tset: values,\n\t\t\t\t\t})\n\t\t\t\t\t.run();\n\t\t\t}\n\t\t\tpruneNeverInstalledCatalogEntries(db);\n\t\t},\n\t\t/** @internal */\n\t\tregisterCatalogEntry(repositoryId: string, skillId: string): string {\n\t\t\tconst candidates = db\n\t\t\t\t.select()\n\t\t\t\t.from(skillCatalogEntries)\n\t\t\t\t.where(eq(skillCatalogEntries.available, true))\n\t\t\t\t.all();\n\t\t\tconst availableIds = new Set(candidates.map((candidate) => candidate.skillId));\n\t\t\tconst installedIds = new Set(\n\t\t\t\tdb\n\t\t\t\t\t.select({ id: skills.id })\n\t\t\t\t\t.from(skills)\n\t\t\t\t\t.where(isNotNull(skills.activeRevisionId))\n\t\t\t\t\t.all()\n\t\t\t\t\t.map((skill) => skill.id),\n\t\t\t);\n\t\t\tconst visiting = new Set<string>();\n\t\t\tconst timestamp = now();\n\n\t\t\tconst install = (id: string, requestedRepositoryId?: string): string | null => {\n\t\t\t\tif (!requestedRepositoryId && installedIds.has(id)) return null;\n\t\t\t\tif (visiting.has(id)) return null;\n\t\t\t\tconst matches = candidates.filter((candidate) => candidate.skillId === id);\n\t\t\t\tconst candidate = requestedRepositoryId\n\t\t\t\t\t? matches.find((match) => match.repositoryId === requestedRepositoryId)\n\t\t\t\t\t: matches.length === 1\n\t\t\t\t\t\t? matches[0]\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!requestedRepositoryId && matches.length > 1) {\n\t\t\t\t\tthrow new Error(`Remote skill '${id}' has conflicting repository candidates`);\n\t\t\t\t}\n\t\t\t\tif (!candidate) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Remote skill '${requestedRepositoryId ? `${requestedRepositoryId}/` : \"\"}${id}' is no longer available`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst current = db.select().from(skills).where(eq(skills.id, id)).get();\n\t\t\t\tif (\n\t\t\t\t\tcurrent?.registrationKind === \"extension\" ||\n\t\t\t\t\t(current?.activeRevisionId && current.registrationKind === \"configuration\")\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Skill '${id}' is managed by ${current.ownerExtensionId ?? \"configuration\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tvisiting.add(id);\n\t\t\t\tconst markdown = skillMarkdown(id, candidate.bundleBytes, candidate.bundleDigest);\n\t\t\t\tfor (const dependencyId of referencedSkillIds(markdown, availableIds)) {\n\t\t\t\t\tif (dependencyId !== id) install(dependencyId);\n\t\t\t\t}\n\t\t\t\tvisiting.delete(id);\n\n\t\t\t\tconst revisionId = activateSkill(\n\t\t\t\t\tdb,\n\t\t\t\t\t{\n\t\t\t\t\t\tskillId: id,\n\t\t\t\t\t\tlabel: candidate.label,\n\t\t\t\t\t\tdescription: candidate.description,\n\t\t\t\t\t\tbundle: { digest: candidate.bundleDigest, bytes: candidate.bundleBytes },\n\t\t\t\t\t\tsourceRevision: candidate.sourceRevision,\n\t\t\t\t\t},\n\t\t\t\t\t\"catalog\",\n\t\t\t\t\ttimestamp,\n\t\t\t\t\tmarkdown,\n\t\t\t\t);\n\t\t\t\tinstalledIds.add(id);\n\t\t\t\treturn revisionId;\n\t\t\t};\n\n\t\t\tconst revisionId = install(skillId, repositoryId);\n\t\t\tif (!revisionId)\n\t\t\t\tthrow new Error(`Remote skill '${repositoryId}/${skillId}' was not installed`);\n\t\t\treturn revisionId;\n\t\t},\n\t\t/** @internal */\n\t\tremove(skillId: string): boolean {\n\t\t\tconst current = db.select().from(skills).where(eq(skills.id, skillId)).get();\n\t\t\tif (!current?.activeRevisionId || current.registrationKind !== \"catalog\") return false;\n\t\t\tdb.update(skills)\n\t\t\t\t.set({ activeRevisionId: null, updatedAt: now() })\n\t\t\t\t.where(eq(skills.id, skillId))\n\t\t\t\t.run();\n\t\t\treturn true;\n\t\t},\n\t\t/** @internal */\n\t\tcatalog() {\n\t\t\treturn catalogView(db);\n\t\t},\n\t\t/** @internal */\n\t\tgetCatalogDetail(repositoryId: string, skillId: string): SkillCatalogDetail | null {\n\t\t\tconst item = catalogView(db).availableSkills.find(\n\t\t\t\t(candidate) => candidate.repositoryId === repositoryId && candidate.id === skillId,\n\t\t\t);\n\t\t\tif (!item) return null;\n\t\t\tconst candidate = db\n\t\t\t\t.select({\n\t\t\t\t\tbytes: skillCatalogEntries.bundleBytes,\n\t\t\t\t\tdigest: skillCatalogEntries.bundleDigest,\n\t\t\t\t})\n\t\t\t\t.from(skillCatalogEntries)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(skillCatalogEntries.repositoryId, repositoryId),\n\t\t\t\t\t\teq(skillCatalogEntries.skillId, skillId),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.get();\n\t\t\tif (!candidate) return null;\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tskillMarkdown: skillMarkdown(skillId, candidate.bytes, candidate.digest),\n\t\t\t\tprocesses: processUsage(db, skillId),\n\t\t\t};\n\t\t},\n\t\t/** @internal */\n\t\tgetInstalledDetail(skillId: string): InstalledSkillCatalogDetail | null {\n\t\t\tconst item = catalogView(db).installedSkills.find((candidate) => candidate.id === skillId);\n\t\t\tif (!item) return null;\n\t\t\tconst revision = db\n\t\t\t\t.select({ bytes: skillRevisions.bundleBytes, digest: skillRevisions.bundleDigest })\n\t\t\t\t.from(skillRevisions)\n\t\t\t\t.where(eq(skillRevisions.id, item.activeRevisionId))\n\t\t\t\t.get();\n\t\t\tif (!revision) return null;\n\t\t\tconst revisions = db\n\t\t\t\t.select({\n\t\t\t\t\tid: skillRevisions.id,\n\t\t\t\t\tsourceRevision: skillRevisions.sourceRevision,\n\t\t\t\t\timportedAt: skillRevisions.importedAt,\n\t\t\t\t\tprovenance: skillRevisions.provenance,\n\t\t\t\t})\n\t\t\t\t.from(skillRevisions)\n\t\t\t\t.where(eq(skillRevisions.skillId, skillId))\n\t\t\t\t.all()\n\t\t\t\t.map((candidate) => ({\n\t\t\t\t\t...candidate,\n\t\t\t\t\tactive: candidate.id === item.activeRevisionId,\n\t\t\t\t}))\n\t\t\t\t.sort((left, right) => right.importedAt.localeCompare(left.importedAt));\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tskillMarkdown: skillMarkdown(skillId, revision.bytes, revision.digest),\n\t\t\t\tprocesses: processUsage(db, skillId),\n\t\t\t\trevisions,\n\t\t\t};\n\t\t},\n\t\t/** @internal */\n\t\trecordInvocations(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tturnRecordId: string;\n\t\t\t/** @internal */\n\t\t\tinvocations: readonly {\n\t\t\t\t/** @internal */\n\t\t\t\tskillId: string;\n\t\t\t\t/** @internal */\n\t\t\t\tinvokedAt: string;\n\t\t\t}[];\n\t\t}): void {\n\t\t\tconst selections = db\n\t\t\t\t.select()\n\t\t\t\t.from(processSkills)\n\t\t\t\t.where(eq(processSkills.instanceId, input.instanceId))\n\t\t\t\t.all();\n\t\t\tconst uniqueInvocations = new Map(\n\t\t\t\tinput.invocations.map((invocation) => [invocation.skillId, invocation]),\n\t\t\t);\n\t\t\tfor (const invocation of uniqueInvocations.values()) {\n\t\t\t\tconst selection = selections.find((row) => row.skillId === invocation.skillId);\n\t\t\t\tif (!selection) continue;\n\t\t\t\tdb.insert(skillInvocations)\n\t\t\t\t\t.values({\n\t\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\t\tturnRecordId: input.turnRecordId,\n\t\t\t\t\t\tskillId: invocation.skillId,\n\t\t\t\t\t\tskillRevisionId: selection.skillRevisionId,\n\t\t\t\t\t\tinvokedAt: invocation.invokedAt,\n\t\t\t\t\t})\n\t\t\t\t\t.onConflictDoNothing()\n\t\t\t\t\t.run();\n\t\t\t}\n\t\t},\n\t};\n}\n","import { SAFE_SKILL_ID_PATTERN } from \"./skill-id.js\";\n\nconst EXPLICIT_SKILL_REFERENCE =\n\t/\\/([A-Za-z0-9][A-Za-z0-9._-]{0,83})|`([A-Za-z0-9][A-Za-z0-9._-]{0,83})`/g;\n\nexport function explicitSkillReferenceIds(markdown: string): string[] {\n\tconst references = new Set<string>();\n\tfor (const match of markdown.matchAll(EXPLICIT_SKILL_REFERENCE)) {\n\t\tlet id = match[1] ?? match[2];\n\t\twhile (id?.endsWith(\".\")) id = id.slice(0, -1);\n\t\tif (id && SAFE_SKILL_ID_PATTERN.test(id)) references.add(id);\n\t}\n\treturn [...references];\n}\n\nexport function referencedSkillIds(\n\tmarkdown: string,\n\tavailableSkillIds: ReadonlySet<string>,\n): string[] {\n\treturn explicitSkillReferenceIds(markdown).filter((id) => availableSkillIds.has(id));\n}\n","import { parse as parseYaml } from \"yaml\";\n\n/** @internal */\nexport function skillFrontmatter(markdown: string): Record<string, unknown> | null {\n\tconst header = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/.exec(markdown);\n\tif (!header) return null;\n\ttry {\n\t\tconst parsed = parseYaml(header[1]);\n\t\treturn parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function isSkillModelInvocable(markdown: string): boolean {\n\treturn skillFrontmatter(markdown)?.[\"disable-model-invocation\"] !== true;\n}\n\n/** @internal */\nexport function skillMetadata(markdown: string): {\n\tname: string | null;\n\tdescription: string | null;\n} {\n\tconst metadata = skillFrontmatter(markdown);\n\tconst text = (key: string): string | null => {\n\t\tconst value = metadata?.[key];\n\t\treturn typeof value === \"string\" ? value.trim() || null : null;\n\t};\n\treturn { name: text(\"name\"), description: text(\"description\") };\n}\n","import { and, desc, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface TicketDestinationRecent {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tactorKey: string;\n\t/** @internal */\n\ttoolName: string;\n\t/** @internal */\n\tdestinationId: string;\n\t/** @internal */\n\tcreatedAt: string;\n\t/** @internal */\n\tupdatedAt: string;\n}\n\nfunction map(row: typeof s.ticketDestinationRecents.$inferSelect): TicketDestinationRecent {\n\treturn { ...row };\n}\n\n/** @internal */\nexport function createTicketDestinationRecentRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tlist(actorKey: string, toolName: string, limit = 5): TicketDestinationRecent[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.ticketDestinationRecents)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.ticketDestinationRecents.actorKey, actorKey),\n\t\t\t\t\t\teq(s.ticketDestinationRecents.toolName, toolName),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(\n\t\t\t\t\tdesc(s.ticketDestinationRecents.updatedAt),\n\t\t\t\t\tdesc(s.ticketDestinationRecents.createdAt),\n\t\t\t\t)\n\t\t\t\t.limit(limit)\n\t\t\t\t.all()\n\t\t\t\t.map(map);\n\t\t},\n\n\t\t/** @internal */\n\t\trecord(input: {\n\t\t\t/** @internal */\n\t\t\tactorKey: string;\n\t\t\t/** @internal */\n\t\t\ttoolName: string;\n\t\t\t/** @internal */\n\t\t\tdestinationId: string;\n\t\t\t/** @internal */\n\t\t\tlimit?: number;\n\t\t}): TicketDestinationRecent {\n\t\t\tconst match = and(\n\t\t\t\teq(s.ticketDestinationRecents.actorKey, input.actorKey),\n\t\t\t\teq(s.ticketDestinationRecents.toolName, input.toolName),\n\t\t\t\teq(s.ticketDestinationRecents.destinationId, input.destinationId),\n\t\t\t);\n\t\t\tconst existing = db.select().from(s.ticketDestinationRecents).where(match).get();\n\t\t\tconst updatedAt = now();\n\t\t\tlet result: TicketDestinationRecent;\n\t\t\tif (existing) {\n\t\t\t\tdb.update(s.ticketDestinationRecents).set({ updatedAt }).where(match).run();\n\t\t\t\tresult = { ...map(existing), updatedAt };\n\t\t\t} else {\n\t\t\t\tconst row = {\n\t\t\t\t\tid: generateId(\"tdr\"),\n\t\t\t\t\tactorKey: input.actorKey,\n\t\t\t\t\ttoolName: input.toolName,\n\t\t\t\t\tdestinationId: input.destinationId,\n\t\t\t\t\tcreatedAt: updatedAt,\n\t\t\t\t\tupdatedAt,\n\t\t\t\t};\n\t\t\t\tdb.insert(s.ticketDestinationRecents).values(row).run();\n\t\t\t\tresult = row;\n\t\t\t}\n\t\t\tconst stale = db\n\t\t\t\t.select({ id: s.ticketDestinationRecents.id })\n\t\t\t\t.from(s.ticketDestinationRecents)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.ticketDestinationRecents.actorKey, input.actorKey),\n\t\t\t\t\t\teq(s.ticketDestinationRecents.toolName, input.toolName),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(\n\t\t\t\t\tdesc(s.ticketDestinationRecents.updatedAt),\n\t\t\t\t\tdesc(s.ticketDestinationRecents.createdAt),\n\t\t\t\t)\n\t\t\t\t.all()\n\t\t\t\t.slice(input.limit ?? 5);\n\t\t\tfor (const entry of stale) {\n\t\t\t\tdb.delete(s.ticketDestinationRecents)\n\t\t\t\t\t.where(eq(s.ticketDestinationRecents.id, entry.id))\n\t\t\t\t\t.run();\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","import type {\n\tProcessTurnType,\n\tTurnStartKind,\n\tTurnStartRecord,\n\tTurnStartRecordState,\n} from \"@leitwerk-dev/domain\";\nimport { and, eq } from \"drizzle-orm\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { type HistoryWindow, historyWindow } from \"./history-window.js\";\nimport { generateId, mappedItemRef, now, parsePersistedJson } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\nfunction map(row: typeof s.turnStartRecords.$inferSelect): TurnStartRecord {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tturnId: row.turnId,\n\t\tturnType: row.turnType as Extract<ProcessTurnType, \"llm\" | \"automatic\">,\n\t\tproposedTurnRecordId: row.proposedTurnRecordId,\n\t\tstartKind: row.startKind as TurnStartKind,\n\t\trecoveryTurnRecordId: row.recoveryTurnRecordId ?? null,\n\t\tcontinuation: row.continuationJson\n\t\t\t? parsePersistedJson(row.continuationJson, \"turn start continuation\")\n\t\t\t: null,\n\t\tstate: parsePersistedJson<TurnStartRecordState>(row.stateJson, \"turn start state\"),\n\t\titeration: mappedItemRef(row),\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n}\n\n/** @internal */\nexport function createTurnStartRecordRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(\n\t\t\tinput: Omit<TurnStartRecord, \"id\" | \"createdAt\" | \"updatedAt\"> & {\n\t\t\t\t/** @internal */\n\t\t\t\tid?: string;\n\t\t\t},\n\t\t): TurnStartRecord {\n\t\t\tconst ts = now();\n\t\t\tconst id = input.id ?? generateId(\"tsr\");\n\t\t\tconst value = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tturnType: input.turnType,\n\t\t\t\tproposedTurnRecordId: input.proposedTurnRecordId,\n\t\t\t\tstartKind: input.startKind,\n\t\t\t\trecoveryTurnRecordId: input.recoveryTurnRecordId,\n\t\t\t\tcontinuationJson: input.continuation ? JSON.stringify(input.continuation) : null,\n\t\t\t\tstateJson: JSON.stringify(input.state),\n\t\t\t\tcreatedAt: ts,\n\t\t\t\tupdatedAt: ts,\n\t\t\t\tmappedRunId: input.iteration?.runId ?? null,\n\t\t\t\tmappedItemKey: input.iteration?.itemKey ?? null,\n\t\t\t\tmappedItemIndex: input.iteration?.itemIndex ?? null,\n\t\t\t};\n\t\t\tdb.insert(s.turnStartRecords).values(value).run();\n\t\t\treturn map(value);\n\t\t},\n\t\t/** @internal */\n\t\tgetById(id: string): TurnStartRecord | null {\n\t\t\tconst value = db.select().from(s.turnStartRecords).where(eq(s.turnStartRecords.id, id)).get();\n\t\t\treturn value ? map(value) : null;\n\t\t},\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string, window?: HistoryWindow): TurnStartRecord[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.turnStartRecords)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.turnStartRecords.instanceId, instanceId),\n\t\t\t\t\t\thistoryWindow(s.turnStartRecords.createdAt, window),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.all()\n\t\t\t\t.map(map);\n\t\t},\n\t\t/** @internal */\n\t\tcompareAndSetState(input: {\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\texpectedKind: TurnStartRecordState[\"kind\"];\n\t\t\t/** @internal */\n\t\t\tstate: TurnStartRecordState;\n\t\t}): TurnStartRecord | null {\n\t\t\tconst current = this.getById(input.id);\n\t\t\tif (!current || current.state.kind !== input.expectedKind) return null;\n\t\t\tconst state = {\n\t\t\t\t...input.state,\n\t\t\t\tautomaticRetry: input.state.automaticRetry ?? current.state.automaticRetry,\n\t\t\t};\n\t\t\tconst result = db\n\t\t\t\t.update(s.turnStartRecords)\n\t\t\t\t.set({ stateJson: JSON.stringify(state), updatedAt: now() })\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.turnStartRecords.id, input.id),\n\t\t\t\t\t\teq(s.turnStartRecords.stateJson, JSON.stringify(current.state)),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\treturn result.changes === 1 ? this.getById(input.id) : null;\n\t\t},\n\t};\n}\n","import type { WorkerBootstrapReceipt, WorkerLease, WorkerState } from \"@leitwerk-dev/domain\";\nimport { and, asc, eq, isNull } from \"drizzle-orm\";\nimport type { SQLiteUpdateSetSource } from \"drizzle-orm/sqlite-core\";\nimport type { LeitwerkDb } from \"./database.js\";\nimport { type HistoryWindow, historyWindow } from \"./history-window.js\";\nimport { generateId, now } from \"./repo-helpers.js\";\nimport * as s from \"./schema.js\";\n\n/** @internal */\nexport interface CreateWorkerLeaseInput {\n\t/** @internal */\n\tinstanceId: string;\n\t/** @internal */\n\tworkerId: string;\n\t/** @internal */\n\tstate: WorkerState;\n\t/** @internal */\n\tserverEpoch?: string | null;\n\t/** @internal */\n\tconnectTokenHash?: string | null;\n\t/** @internal */\n\tsnapshotTokenHash?: string | null;\n\t/** @internal */\n\tmodelPolicyFingerprint?: string | null;\n\t/** @internal */\n\tbootstrapReceipt?: WorkerBootstrapReceipt | null;\n\t/** @internal */\n\tturnStartRecordId?: string | null;\n}\n\n/** @internal */\nexport interface UpdateWorkerLeaseInput {\n\t/** @internal */\n\tstate?: WorkerState;\n\t/** @internal */\n\tserverEpoch?: string | null;\n\t/** @internal */\n\tconnectTokenHash?: string | null;\n\t/** @internal */\n\tsnapshotTokenHash?: string | null;\n\t/** @internal */\n\tmodelPolicyFingerprint?: string | null;\n\t/** @internal */\n\tlastHeartbeatAt?: string | null;\n\t/** @internal */\n\tconnectedAt?: string | null;\n\t/** @internal */\n\tworkspacePreparationStartedAt?: string | null;\n\t/** @internal */\n\treadyAt?: string | null;\n\t/** @internal */\n\texitedAt?: string | null;\n}\n\nfunction rowToWorkerLease(row: typeof s.workerLeases.$inferSelect): WorkerLease {\n\treturn {\n\t\tid: row.id,\n\t\tinstanceId: row.instanceId,\n\t\tworkerId: row.workerId,\n\t\tturnStartRecordId: row.turnStartRecordId ?? null,\n\t\tstate: row.state as WorkerState,\n\t\tserverEpoch: row.serverEpoch ?? null,\n\t\tconnectTokenHash: row.connectTokenHash ?? null,\n\t\tsnapshotTokenHash: row.snapshotTokenHash ?? null,\n\t\tmodelPolicyFingerprint: row.modelPolicyFingerprint ?? null,\n\t\tbootstrapReceipt: row.bootstrapReceiptJson\n\t\t\t? (JSON.parse(row.bootstrapReceiptJson) as WorkerBootstrapReceipt)\n\t\t\t: null,\n\t\tlastHeartbeatAt: row.lastHeartbeatAt,\n\t\tstartedAt: row.startedAt,\n\t\tconnectedAt: row.connectedAt ?? null,\n\t\tworkspacePreparationStartedAt: row.workspacePreparationStartedAt ?? null,\n\t\treadyAt: row.readyAt ?? null,\n\t\texitedAt: row.exitedAt,\n\t};\n}\n\n/** @internal */\nexport function createWorkerLeaseRepo(db: LeitwerkDb) {\n\treturn {\n\t\t/** @internal */\n\t\tcreate(input: CreateWorkerLeaseInput): WorkerLease {\n\t\t\tconst id = generateId(\"wls\");\n\t\t\tconst ts = now();\n\t\t\tconst values = {\n\t\t\t\tid,\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tstate: input.state,\n\t\t\t\tserverEpoch: input.serverEpoch ?? null,\n\t\t\t\tconnectTokenHash: input.connectTokenHash ?? null,\n\t\t\t\tsnapshotTokenHash: input.snapshotTokenHash ?? null,\n\t\t\t\tmodelPolicyFingerprint: input.modelPolicyFingerprint ?? null,\n\t\t\t\tbootstrapReceiptJson: null,\n\t\t\t\tturnStartRecordId: input.turnStartRecordId ?? null,\n\t\t\t\tlastHeartbeatAt: null as string | null,\n\t\t\t\tstartedAt: ts,\n\t\t\t\tconnectedAt: null as string | null,\n\t\t\t\tworkspacePreparationStartedAt: null as string | null,\n\t\t\t\treadyAt: null as string | null,\n\t\t\t\texitedAt: null as string | null,\n\t\t\t};\n\t\t\tdb.insert(s.workerLeases).values(values).run();\n\t\t\treturn rowToWorkerLease(values);\n\t\t},\n\n\t\t/** @internal */\n\t\tgetByInstance(instanceId: string): WorkerLease | null {\n\t\t\tconst row = db\n\t\t\t\t.select()\n\t\t\t\t.from(s.workerLeases)\n\t\t\t\t.where(and(eq(s.workerLeases.instanceId, instanceId), isNull(s.workerLeases.exitedAt)))\n\t\t\t\t.get();\n\t\t\treturn row ? rowToWorkerLease(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tgetById(id: string): WorkerLease | null {\n\t\t\tconst row = db.select().from(s.workerLeases).where(eq(s.workerLeases.id, id)).get();\n\t\t\treturn row ? rowToWorkerLease(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tlistByInstance(instanceId: string, window?: HistoryWindow): WorkerLease[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.workerLeases)\n\t\t\t\t.where(\n\t\t\t\t\tand(\n\t\t\t\t\t\teq(s.workerLeases.instanceId, instanceId),\n\t\t\t\t\t\thistoryWindow(s.workerLeases.startedAt, window),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.orderBy(asc(s.workerLeases.startedAt), asc(s.workerLeases.id))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToWorkerLease);\n\t\t},\n\n\t\t/** @internal */\n\t\tlistActive(): WorkerLease[] {\n\t\t\treturn db\n\t\t\t\t.select()\n\t\t\t\t.from(s.workerLeases)\n\t\t\t\t.where(isNull(s.workerLeases.exitedAt))\n\t\t\t\t.all()\n\t\t\t\t.map(rowToWorkerLease);\n\t\t},\n\n\t\t/** @internal */\n\t\tupdate(id: string, input: UpdateWorkerLeaseInput): WorkerLease | null {\n\t\t\tconst setValues: SQLiteUpdateSetSource<typeof s.workerLeases> = {\n\t\t\t\tstate: input.state,\n\t\t\t\tserverEpoch: input.serverEpoch,\n\t\t\t\tconnectTokenHash: input.connectTokenHash,\n\t\t\t\tsnapshotTokenHash: input.snapshotTokenHash,\n\t\t\t\tmodelPolicyFingerprint: input.modelPolicyFingerprint,\n\t\t\t\tlastHeartbeatAt: input.lastHeartbeatAt,\n\t\t\t\tconnectedAt: input.connectedAt,\n\t\t\t\tworkspacePreparationStartedAt: input.workspacePreparationStartedAt,\n\t\t\t\treadyAt: input.readyAt,\n\t\t\t\texitedAt: input.exitedAt,\n\t\t\t};\n\n\t\t\tdb.update(s.workerLeases).set(setValues).where(eq(s.workerLeases.id, id)).run();\n\t\t\tconst row = db.select().from(s.workerLeases).where(eq(s.workerLeases.id, id)).get();\n\t\t\treturn row ? rowToWorkerLease(row) : null;\n\t\t},\n\n\t\t/** @internal */\n\t\tobserveTimestamp(\n\t\t\tid: string,\n\t\t\tfield: \"connectedAt\" | \"workspacePreparationStartedAt\" | \"readyAt\",\n\t\t): WorkerLease | null {\n\t\t\tconst column = s.workerLeases[field];\n\t\t\tdb.update(s.workerLeases)\n\t\t\t\t.set({ [field]: now() })\n\t\t\t\t.where(and(eq(s.workerLeases.id, id), isNull(column)))\n\t\t\t\t.run();\n\t\t\treturn this.getById(id);\n\t\t},\n\n\t\t/** @internal */\n\t\tupdateHeartbeat(workerId: string): boolean {\n\t\t\tconst result = db\n\t\t\t\t.update(s.workerLeases)\n\t\t\t\t.set({ lastHeartbeatAt: now() })\n\t\t\t\t.where(eq(s.workerLeases.workerId, workerId))\n\t\t\t\t.run();\n\t\t\treturn result.changes > 0;\n\t\t},\n\n\t\t/** Stores the first receipt only. Exact replay is accepted; changed receipts are rejected. @internal */\n\t\tcompareAndSetBootstrapReceipt(\n\t\t\tid: string,\n\t\t\treceipt: WorkerBootstrapReceipt,\n\t\t): \"stored\" | \"replay\" | \"changed\" | \"missing\" {\n\t\t\tconst existing = db.select().from(s.workerLeases).where(eq(s.workerLeases.id, id)).get();\n\t\t\tif (!existing) return \"missing\";\n\t\t\tconst encoded = JSON.stringify(receipt);\n\t\t\tif (existing.bootstrapReceiptJson !== null)\n\t\t\t\treturn existing.bootstrapReceiptJson === encoded ? \"replay\" : \"changed\";\n\t\t\tconst result = db\n\t\t\t\t.update(s.workerLeases)\n\t\t\t\t.set({ bootstrapReceiptJson: encoded })\n\t\t\t\t.where(and(eq(s.workerLeases.id, id), isNull(s.workerLeases.bootstrapReceiptJson)))\n\t\t\t\t.run();\n\t\t\treturn result.changes === 1 ? \"stored\" : \"changed\";\n\t\t},\n\t};\n}\n","import type { TurnProgressReport, TurnProgressStepStatus } from \"@leitwerk-dev/domain\";\nimport { createDurableWsFrame } from \"@leitwerk-dev/protocol\";\nimport type { RepositoryBundle } from \"./db/repositories.js\";\nimport type { Broadcaster } from \"./ws/broadcast.js\";\n\nconst STEP_STATUSES = new Set<TurnProgressStepStatus>([\n\t\"incomplete\",\n\t\"in_progress\",\n\t\"completed\",\n\t\"failed\",\n]);\nconst LINK_KINDS = new Set([\"pull_request\", \"merge_request\", \"commit\", \"pipeline\", \"other\"]);\n\nfunction text(value: unknown, max: number): string {\n\treturn typeof value === \"string\" ? value.trim().slice(0, max) : \"\";\n}\n\nfunction safeExternalUrl(value: unknown): string {\n\tconst candidate = text(value, 2_000);\n\ttry {\n\t\tconst url = new URL(candidate);\n\t\treturn (url.protocol === \"https:\" || url.protocol === \"http:\") && !url.username && !url.password\n\t\t\t? url.toString()\n\t\t\t: \"\";\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nexport function normalizeTurnProgressLinks(\n\tvalue: unknown,\n): NonNullable<TurnProgressReport[\"links\"]> | null {\n\tconst linkIds = new Set<string>();\n\tconst rawLinks = value === undefined ? [] : value;\n\tif (!Array.isArray(rawLinks) || rawLinks.length > 20) return null;\n\tconst links = rawLinks.flatMap((value) => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return [];\n\t\tconst link = value as Record<string, unknown>;\n\t\tconst id = text(link.id, 80);\n\t\tconst label = text(link.label, 240);\n\t\tconst url = safeExternalUrl(link.url);\n\t\tconst kind = text(link.kind, 40);\n\t\tif (!id || linkIds.has(id) || !label || !url) return [];\n\t\tif (kind && !LINK_KINDS.has(kind)) return [];\n\t\tlinkIds.add(id);\n\t\treturn [\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tlabel,\n\t\t\t\turl,\n\t\t\t\t...(kind ? { kind: kind as NonNullable<TurnProgressReport[\"links\"]>[number][\"kind\"] } : {}),\n\t\t\t},\n\t\t];\n\t});\n\tif (links.length !== rawLinks.length) return null;\n\treturn links;\n}\n\nexport function normalizeTurnProgressReport(value: unknown): TurnProgressReport | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst raw = value as Record<string, unknown>;\n\tconst title = text(raw.title, 160);\n\tconst summary = text(raw.summary, 2000);\n\tif (!title || !Array.isArray(raw.steps) || raw.steps.length > 50) return null;\n\tconst ids = new Set<string>();\n\tconst steps = raw.steps.flatMap((value) => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return [];\n\t\tconst step = value as Record<string, unknown>;\n\t\tconst id = text(step.id, 80);\n\t\tconst label = text(step.label, 240);\n\t\tconst status = step.status;\n\t\tif (!id || ids.has(id) || !label || !STEP_STATUSES.has(status as TurnProgressStepStatus)) {\n\t\t\treturn [];\n\t\t}\n\t\tids.add(id);\n\t\treturn [\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tlabel,\n\t\t\t\tstatus: status as TurnProgressStepStatus,\n\t\t\t\t...(text(step.detail, 1_000) ? { detail: text(step.detail, 1_000) } : {}),\n\t\t\t},\n\t\t];\n\t});\n\tif (steps.length !== raw.steps.length || (steps.length === 0 && !summary)) return null;\n\tconst links = normalizeTurnProgressLinks(raw.links);\n\tif (!links) return null;\n\treturn {\n\t\ttitle,\n\t\tsteps,\n\t\t...(summary ? { summary } : {}),\n\t\t...(links.length > 0 ? { links } : {}),\n\t};\n}\n\nexport function recordTurnProgress(\n\tdeps: Pick<RepositoryBundle, \"processes\" | \"turnRecords\" | \"events\"> & {\n\t\tbroadcaster: Broadcaster;\n\t},\n\tinput: { instanceId: string; turnRecordId: string; report: unknown },\n): boolean {\n\tconst process = deps.processes.getById(input.instanceId);\n\tconst turnRecord = deps.turnRecords.getById(input.turnRecordId);\n\tconst report = normalizeTurnProgressReport(input.report);\n\tif (\n\t\t!process ||\n\t\t!turnRecord ||\n\t\tturnRecord.instanceId !== input.instanceId ||\n\t\tturnRecord.status !== \"running\" ||\n\t\tprocess.selectedTurnId !== turnRecord.turnId ||\n\t\t!report\n\t)\n\t\treturn false;\n\tconst revision =\n\t\tdeps.events.listByInstanceTurnRecordEventTypes(input.instanceId, input.turnRecordId, [\n\t\t\t\"turn.progress\",\n\t\t]).length + 1;\n\tdeps.events.create({\n\t\tinstanceId: input.instanceId,\n\t\teventType: \"turn.progress\",\n\t\tdata: { turnRecordId: input.turnRecordId, revision, report },\n\t});\n\tdeps.broadcaster.broadcast(\n\t\tcreateDurableWsFrame({\n\t\t\ttype: \"process.event\",\n\t\t\tinstanceId: input.instanceId,\n\t\t\tpayload: { eventType: \"turn_progress\", level: \"info\", message: \"Turn progress updated\" },\n\t\t}),\n\t);\n\treturn true;\n}\n","import { trimToNull } from \"@leitwerk-dev/domain\";\nimport { isLlmTurnDefinition } from \"@leitwerk-dev/process-sdk\";\nimport { assertValidModelRequirements, compareModelProfileIds } from \"@leitwerk-dev/protocol\";\nimport type { LeitwerkConfig } from \"../config/config-types.js\";\nimport type { ProcessActionRegistry } from \"../process-action-registry.js\";\nimport { getProcessGraph, type ProcessGraphRegistry } from \"../process-graph.js\";\nimport type {\n\tPolicyProcess,\n\tPolicyProfile,\n\tPolicyRequirementLayer,\n\tPolicySnapshot,\n} from \"./types.js\";\n\nexport interface ProcessModelPolicyConfigurationIssue {\n\treadonly code: \"unknown_llm_turn\";\n\treadonly processId: string;\n\treadonly turnId: string;\n}\n\nexport class ProcessModelPolicyConfigurationError extends Error {\n\treadonly issues: readonly ProcessModelPolicyConfigurationIssue[];\n\n\tconstructor(issues: readonly ProcessModelPolicyConfigurationIssue[]) {\n\t\tsuper(\"Invalid process model policy configuration\");\n\t\tthis.name = \"ProcessModelPolicyConfigurationError\";\n\t\tthis.issues = issues;\n\t}\n}\n\nexport function constructPolicySnapshot(input: {\n\tconfig: LeitwerkConfig;\n\tprocessGraphs: ProcessGraphRegistry;\n\tprocessActionRegistry: Pick<ProcessActionRegistry, \"getTurnDefinition\">;\n\tcapabilities?: (\n\t\tproviderId: string,\n\t\tmodelId: string,\n\t) => Readonly<Record<string, boolean | \"unknown\">>;\n}): PolicySnapshot {\n\tconst configSnapshot = structuredClone(input.config);\n\tconst profiles: PolicyProfile[] = configSnapshot.pi.model_profiles.map((profile) => ({\n\t\tid: profile.id,\n\t\tprovider: profile.provider,\n\t\tmodelId: profile.model_id,\n\t\tthinkingLevel: profile.thinking_level ?? \"off\",\n\t\tproviderOptions: profile.provider_options ?? {},\n\t\tlabels: [...new Set(profile.labels ?? [])].sort(compareModelProfileIds),\n\t\tdefault: profile.default ?? false,\n\t\tcapabilities: structuredClone(input.capabilities?.(profile.provider, profile.model_id) ?? {}),\n\t}));\n\tconst processIds = new Set([\n\t\t...input.processGraphs.keys(),\n\t\t...Object.keys(configSnapshot.process_configs ?? {}),\n\t]);\n\tconst processesById = new Map<string, PolicyProcess>();\n\tfor (const processId of processIds) {\n\t\tconst graph = input.processGraphs.has(processId)\n\t\t\t? getProcessGraph(input.processGraphs, processId)\n\t\t\t: null;\n\t\tconst config = configSnapshot.process_configs?.[processId];\n\t\tconst requirements: PolicyRequirementLayer[] = [];\n\t\tconst turnRequirements: Record<string, PolicyRequirementLayer[]> = {};\n\t\tconst add = (\n\t\t\tlayers: PolicyRequirementLayer[],\n\t\t\torigin: string,\n\t\t\tvalue: import(\"@leitwerk-dev/protocol\").ModelRequirements | undefined,\n\t\t) => {\n\t\t\tif (value === undefined) return;\n\t\t\tassertValidModelRequirements(value);\n\t\t\tlayers.push({ origin, requirements: structuredClone(value) });\n\t\t};\n\t\tadd(\n\t\t\trequirements,\n\t\t\t`process:${processId}`,\n\t\t\tinput.processGraphs.get(processId)?.modelRequirements,\n\t\t);\n\t\tadd(\n\t\t\trequirements,\n\t\t\t`process_configs.${processId}.model_requirements`,\n\t\t\tconfig?.model_requirements,\n\t\t);\n\t\tconst llmTurnIds = new Set<string>();\n\t\tconst purposeProfileIdsByTurn: Record<string, string> = {};\n\t\tconst descriptions: Record<string, string> = {};\n\t\tconst pathTypes: Record<string, string> = {};\n\t\tfor (const [turnId, turn] of graph?.turns ?? []) {\n\t\t\tconst declared = input.processGraphs.get(processId)?.turns.get(turnId)?.definition;\n\t\t\tif (turn.turnType !== \"llm\") {\n\t\t\t\tif (declared && \"modelRequirements\" in declared)\n\t\t\t\t\tthrow new Error(`Model requirements require an LLM turn: ${processId}/${turnId}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst layers: PolicyRequirementLayer[] = [];\n\t\t\tadd(\n\t\t\t\tlayers,\n\t\t\t\t`turn:${processId}/${turnId}`,\n\t\t\t\tdeclared?.kind === \"llm\" ? declared.modelRequirements : undefined,\n\t\t\t);\n\t\t\tadd(\n\t\t\t\tlayers,\n\t\t\t\t`process_configs.${processId}.turn_configs.${turnId}.model_requirements`,\n\t\t\t\tconfig?.turn_configs?.[turnId]?.model_requirements,\n\t\t\t);\n\t\t\tturnRequirements[turnId] = layers;\n\t\t\tllmTurnIds.add(turnId);\n\t\t\tconst definition = input.processActionRegistry.getTurnDefinition(processId, turnId);\n\t\t\tpathTypes[turnId] =\n\t\t\t\tdefinition && isLlmTurnDefinition(definition) ? definition.branchType : \"primary\";\n\t\t\tif (definition && isLlmTurnDefinition(definition) && definition.modelPurpose) {\n\t\t\t\tconst purposeProfileId = trimToNull(\n\t\t\t\t\tconfigSnapshot.pi[definition.modelPurpose].model_profile,\n\t\t\t\t);\n\t\t\t\tif (purposeProfileId) purposeProfileIdsByTurn[turnId] = purposeProfileId;\n\t\t\t}\n\t\t\tdescriptions[turnId] =\n\t\t\t\tdefinition && isLlmTurnDefinition(definition)\n\t\t\t\t\t? (trimToNull(definition.description) ?? turnId)\n\t\t\t\t\t: turnId;\n\t\t}\n\t\tconst allowed = config?.allowed_model_profiles\n\t\t\t? new Set(config.allowed_model_profiles.map((id) => id.trim()).filter(Boolean))\n\t\t\t: null;\n\t\tprocessesById.set(processId, {\n\t\t\tid: processId,\n\t\t\trequirements,\n\t\t\tturnRequirements,\n\t\t\tallowedProfileIds: allowed,\n\t\t\tdefaultProfileId: trimToNull(config?.default_model_profile),\n\t\t\tturnProfileIds: Object.fromEntries(\n\t\t\t\tObject.entries(config?.turn_configs ?? {}).map(([turnId, turnConfig]) => [\n\t\t\t\t\tturnId,\n\t\t\t\t\ttrimToNull(turnConfig.model_profile),\n\t\t\t\t]),\n\t\t\t),\n\t\t\tllmTurnIds,\n\t\t\tpurposeProfileIdsByTurn,\n\t\t\tturnDescriptions: descriptions,\n\t\t\tturnPathTypes: pathTypes,\n\t\t});\n\t}\n\tconst configurationIssues: ProcessModelPolicyConfigurationIssue[] = [];\n\tfor (const [processId, processConfig] of Object.entries(configSnapshot.process_configs ?? {})) {\n\t\tconst llmTurnIds = processesById.get(processId)?.llmTurnIds ?? new Set();\n\t\tfor (const turnId of Object.keys(processConfig.turn_configs ?? {})) {\n\t\t\tif (!llmTurnIds.has(turnId)) {\n\t\t\t\tconfigurationIssues.push({ code: \"unknown_llm_turn\", processId, turnId });\n\t\t\t}\n\t\t}\n\t}\n\tif (configurationIssues.length > 0)\n\t\tthrow new ProcessModelPolicyConfigurationError(configurationIssues);\n\treturn {\n\t\tdefaultProfileId: configSnapshot.pi.default_model_profile,\n\t\tprofiles,\n\t\tprofilesById: new Map(profiles.map((profile) => [profile.id, profile])),\n\t\tprocessesById,\n\t\tworkerStaticConfig: {\n\t\t\tpi: {\n\t\t\t\t...configSnapshot.pi,\n\t\t\t\tmodel_profiles: configSnapshot.pi.model_profiles\n\t\t\t\t\t.map(({ labels: _labels, default: _default, ...profile }) => profile)\n\t\t\t\t\t.sort((a, b) => compareModelProfileIds(a.id, b.id)),\n\t\t\t},\n\t\t\tworkers: configSnapshot.workers,\n\t\t\tprocessPi: Object.fromEntries(\n\t\t\t\tObject.entries(configSnapshot.process_configs ?? {}).map(([id, value]) => [\n\t\t\t\t\tid,\n\t\t\t\t\tvalue.pi ?? null,\n\t\t\t\t]),\n\t\t\t),\n\t\t},\n\t};\n}\n","import type { ProcessFlowView } from \"@leitwerk-dev/domain\";\nimport {\n\tbuildProcessFlowView,\n\tgetProcessGraph,\n\ttype ProcessGraphRegistry,\n} from \"@leitwerk-dev/process-sdk\";\n\nexport {\n\tgetProcessGraph,\n\tgetProcessTurnGraph,\n\tgetTurnTransitionsForProcessGraph,\n\thasProcessGraph,\n\tisTurnAvailableForProcessGraph,\n\tlistLlmTurnIdsForProcessGraph,\n\ttype ProcessGraphRegistry,\n\ttype ProcessGraphView,\n\tserializeProcessGraph,\n\ttoProcessGraphView,\n\tvalidateProcessGraphProducts,\n\tvalidateProcessGraphTurnTransitions,\n} from \"@leitwerk-dev/process-sdk\";\n\n/** Build the spine-first flow view for a process from the graph registry. */\nexport function buildProcessFlowViewForProcess(\n\tregistry: ProcessGraphRegistry,\n\tprocessId: string,\n): ProcessFlowView {\n\treturn buildProcessFlowView(getProcessGraph(registry, processId));\n}\n","import type { DurableModelSelection, TurnStartRecord } from \"@leitwerk-dev/domain\";\nimport { trimToNull } from \"@leitwerk-dev/domain\";\nimport { profileRejections, rankedProfiles, requirementLayers } from \"./requirements.js\";\nimport type {\n\tExistingTurnSelection,\n\tModelConfiguration,\n\tModelOverride,\n\tPolicyProcess,\n\tPolicySnapshot,\n\tProcessModelAvailabilitySnapshot,\n\tProcessModelPolicyEvaluation,\n\tSkippedModelPreference,\n\tValidModelConfiguration,\n} from \"./types.js\";\nimport { isPinnedModelSelection, provenanceKindForSource } from \"./types.js\";\n\nfunction processPolicy(snapshot: PolicySnapshot, processId: string): PolicyProcess {\n\treturn (\n\t\tsnapshot.processesById.get(processId) ?? {\n\t\t\tid: processId,\n\t\t\trequirements: [],\n\t\t\tturnRequirements: {},\n\t\t\tallowedProfileIds: null,\n\t\t\tdefaultProfileId: null,\n\t\t\tturnProfileIds: {},\n\t\t\tllmTurnIds: new Set(),\n\t\t\tpurposeProfileIdsByTurn: {},\n\t\t\tturnDescriptions: {},\n\t\t\tturnPathTypes: {},\n\t\t}\n\t);\n}\n\nexport function validateSelection(\n\tsnapshot: PolicySnapshot,\n\tprocessId: string,\n\tselection: DurableModelSelection | null,\n\tavailability?: ProcessModelAvailabilitySnapshot,\n\tturnId?: string,\n): ProcessModelPolicyEvaluation {\n\tif (!selection)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"model_required\",\n\t\t\tselection: null,\n\t\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t\t};\n\tconst profile = snapshot.profilesById.get(selection.modelProfileId);\n\tif (!profile)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"unknown_model_profile\",\n\t\t\tmodelProfileId: selection.modelProfileId,\n\t\t\tselection,\n\t\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t\t};\n\tconst policy = processPolicy(snapshot, processId);\n\tconst rejections = profileRejections(policy, profile, turnId);\n\tif (rejections.length)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"model_profile_not_allowed\",\n\t\t\tmodelProfileId: profile.id,\n\t\t\tprocessId,\n\t\t\trejections,\n\t\t\tselection,\n\t\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t\t};\n\tif (availability) {\n\t\tconst status = availability.profiles.find((candidate) => candidate.profileId === profile.id);\n\t\tif (!status || status.availability !== \"available\") {\n\t\t\tconst stale = !status || status.availability === \"stale\";\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: stale ? \"model_stale\" : \"model_unavailable\",\n\t\t\t\treason: status?.safeReason ?? null,\n\t\t\t\tselection,\n\t\t\t\tavailabilityRevision: availability.revision,\n\t\t\t};\n\t\t}\n\t}\n\treturn {\n\t\tok: true,\n\t\tselection,\n\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t};\n}\n\nfunction candidate(\n\tmodelProfileId: string | null | undefined,\n\tsource:\n\t\t| \"instance_turn_config\"\n\t\t| \"process_config_turn\"\n\t\t| \"instance_default\"\n\t\t| \"process_config_default\"\n\t\t| \"catalog_default\"\n\t\t| \"scoped_purpose_default\"\n\t\t| \"marked_default\"\n\t\t| \"automatic\"\n\t\t| \"fixed_purpose\",\n): DurableModelSelection | null {\n\tconst id = trimToNull(modelProfileId);\n\treturn id\n\t\t? { modelProfileId: id, provenance: { kind: provenanceKindForSource(source), source } }\n\t\t: null;\n}\n\nfunction resolvedDefault(\n\tsnapshot: PolicySnapshot,\n\tconfiguration: ValidModelConfiguration,\n): DurableModelSelection | null {\n\tconst policy = processPolicy(snapshot, configuration.processId);\n\tconst instanceDefault = candidate(configuration.defaultProfileId, \"instance_default\");\n\tif (instanceDefault) return instanceDefault;\n\tconst configured = candidate(policy.defaultProfileId, \"process_config_default\");\n\tif (configured) return configured;\n\treturn candidate(snapshot.defaultProfileId, \"catalog_default\");\n}\n\nexport function resolveDefault(\n\tsnapshot: PolicySnapshot,\n\tconfiguration: ValidModelConfiguration,\n\tavailability?: ProcessModelAvailabilitySnapshot,\n): ProcessModelPolicyEvaluation {\n\treturn validateSelection(\n\t\tsnapshot,\n\t\tconfiguration.processId,\n\t\tresolvedDefault(snapshot, configuration),\n\t\tavailability,\n\t);\n}\n\nfunction invalidConfiguration(\n\tconfiguration: Extract<ModelConfiguration, { kind: \"invalid\" }>,\n): ProcessModelPolicyEvaluation {\n\treturn {\n\t\tok: false,\n\t\tcode: \"invalid_model_configuration\",\n\t\tsource: \"configuration\",\n\t\tselection: null,\n\t\tissues: configuration.issues,\n\t};\n}\n\nexport function resolveTurn(\n\tsnapshot: PolicySnapshot,\n\tconfiguration: ModelConfiguration,\n\tturnId: string,\n\tpreservePinnedSelection: boolean,\n\texistingSelection: ExistingTurnSelection,\n\toverride: ModelOverride,\n\tavailability?: ProcessModelAvailabilitySnapshot,\n): ProcessModelPolicyEvaluation {\n\tconst policy = processPolicy(snapshot, configuration.processId);\n\tif (!policy.llmTurnIds.has(turnId)) return { ok: true, selection: null };\n\tif (configuration.kind === \"invalid\") return invalidConfiguration(configuration);\n\tconst validate = (selection: DurableModelSelection | null) =>\n\t\tvalidateSelection(snapshot, configuration.processId, selection, availability, turnId);\n\t// A configured code-defined purpose is authoritative over launch/action overrides.\n\tconst purposeProfileId = policy.purposeProfileIdsByTurn[turnId];\n\tif (purposeProfileId) return validate(candidate(purposeProfileId, \"fixed_purpose\"));\n\tif (existingSelection.kind === \"invalid\" && existingSelection.turnId === turnId)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"invalid_model_configuration\",\n\t\t\tsource: \"selection_provenance\",\n\t\t\tselection: null,\n\t\t\tissues: existingSelection.issues,\n\t\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t\t};\n\tif (override.kind === \"clear\") {\n\t\texistingSelection = { kind: \"none\" };\n\t}\n\tif (override.kind === \"profile\")\n\t\treturn validate({\n\t\t\tmodelProfileId: override.profileId,\n\t\t\tprovenance: { kind: \"explicit\", source: override.source },\n\t\t});\n\tif (\n\t\texistingSelection.kind === \"selected\" &&\n\t\tpreservePinnedSelection &&\n\t\texistingSelection.turnId === turnId &&\n\t\tisPinnedModelSelection(existingSelection.selection)\n\t)\n\t\treturn validate(existingSelection.selection);\n\ttry {\n\t\tconst skippedPreferences: SkippedModelPreference[] = [];\n\t\tconst explain = (result: ProcessModelPolicyEvaluation): ProcessModelPolicyEvaluation => ({\n\t\t\t...result,\n\t\t\tskippedPreferences,\n\t\t});\n\t\tconst preferences = [\n\t\t\t() => candidate(configuration.turnProfileIds.get(turnId), \"instance_turn_config\"),\n\t\t\t() => candidate(configuration.defaultProfileId, \"instance_default\"),\n\t\t\t() => candidate(policy.scopedProfileIdForTurn?.(turnId), \"scoped_purpose_default\"),\n\t\t\t() => candidate(policy.turnProfileIds[turnId], \"process_config_turn\"),\n\t\t\t() => candidate(policy.defaultProfileId, \"process_config_default\"),\n\t\t\t() => candidate(snapshot.defaultProfileId, \"catalog_default\"),\n\t\t];\n\t\tfor (const getPreference of preferences) {\n\t\t\tconst preference = getPreference();\n\t\t\tif (!preference) continue;\n\t\t\tconst result = validate(preference);\n\t\t\tif (\n\t\t\t\t!result.ok &&\n\t\t\t\tresult.code === \"model_profile_not_allowed\" &&\n\t\t\t\tpreference.provenance.source !== \"instance_turn_config\"\n\t\t\t) {\n\t\t\t\tskippedPreferences.push({\n\t\t\t\t\tprofileId: preference.modelProfileId,\n\t\t\t\t\tsource: preference.provenance.source,\n\t\t\t\t\trejections: result.rejections ?? [],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn explain(result);\n\t\t}\n\t\tconst ranked = rankedProfiles(policy, snapshot.profiles, turnId);\n\t\tif (!ranked.profiles.length)\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"model_required\",\n\t\t\t\tselection: null,\n\t\t\t\tskippedPreferences,\n\t\t\t\t...(availability ? { availabilityRevision: availability.revision } : {}),\n\t\t\t\trequirements: requirementLayers(policy, turnId),\n\t\t\t};\n\t\treturn {\n\t\t\t...explain(\n\t\t\t\tvalidate(candidate(ranked.profiles[0]?.id, ranked.marked ? \"marked_default\" : \"automatic\")),\n\t\t\t),\n\t\t\tranking: {\n\t\t\t\tkind: ranked.marked ? \"marked_defaults\" : \"cost_id\",\n\t\t\t\ttiedProfileIds: ranked.tiedProfileIds,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"invalid_model_configuration\",\n\t\t\tsource: \"configuration\",\n\t\t\tselection: null,\n\t\t\tissues: [],\n\t\t\tmessage: error instanceof Error ? error.message : \"Invalid scoped settings\",\n\t\t};\n\t}\n}\n\nexport function recoverPreparation(\n\tsnapshot: PolicySnapshot,\n\tcause: \"availability_transition\" | \"startup_reconciliation\",\n\tconfiguration: ModelConfiguration,\n\tcurrentStart: TurnStartRecord,\n\tavailability: ProcessModelAvailabilitySnapshot,\n): ProcessModelPolicyEvaluation {\n\tconst state = currentStart.state;\n\tif (\n\t\tstate.kind !== \"preparation_failed\" ||\n\t\t(state.code !== \"model_unavailable\" && state.code !== \"model_stale\") ||\n\t\tstate.availabilityRevision === undefined ||\n\t\t(cause === \"availability_transition\" && state.availabilityRevision >= availability.revision)\n\t)\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"model_unavailable\",\n\t\t\treason: \"This start is not eligible for automatic model recovery\",\n\t\t\tselection: null,\n\t\t\tavailabilityRevision: availability.revision,\n\t\t};\n\tconst profileId = trimToNull(state.requestedModelProfileId);\n\tconst provenance = state.modelSelectionProvenance;\n\treturn validateSelection(\n\t\tsnapshot,\n\t\tconfiguration.processId,\n\t\tprofileId && provenance ? { modelProfileId: profileId, provenance } : null,\n\t\tavailability,\n\t\tcurrentStart.turnId,\n\t);\n}\n","import { compareModelProfileIds, modelCostRank } from \"@leitwerk-dev/protocol\";\nimport type { PolicyProcess, PolicyProfile } from \"./types.js\";\n\n/** @internal */\nexport function requirementLayers(policy: PolicyProcess, turnId?: string) {\n\treturn policy.requirements.concat(turnId ? (policy.turnRequirements[turnId] ?? []) : []);\n}\n\n/** Stable policy evidence; availability never participates. @internal */\nexport function profileRejections(policy: PolicyProcess, profile: PolicyProfile, turnId?: string) {\n\tconst rejections: { origin: string; code: string; values: readonly string[] }[] = [];\n\tif (policy.allowedProfileIds && !policy.allowedProfileIds.has(profile.id))\n\t\trejections.push({\n\t\t\torigin: `process_configs.${policy.id}.allowed_model_profiles`,\n\t\t\tcode: \"profile_not_allowed\",\n\t\t\tvalues: [profile.id],\n\t\t});\n\tconst labels = new Set(profile.labels);\n\tfor (const { origin, requirements: r } of requirementLayers(policy, turnId)) {\n\t\tif (r.profiles && !r.profiles.includes(profile.id))\n\t\t\trejections.push({ origin, code: \"profile_not_allowed\", values: r.profiles });\n\t\tconst missing = r.labels?.all_of?.filter((label) => !labels.has(label)) ?? [];\n\t\tif (missing.length) rejections.push({ origin, code: \"missing_labels\", values: missing });\n\t\tif (r.labels?.any_of && !r.labels.any_of.some((label) => labels.has(label)))\n\t\t\trejections.push({ origin, code: \"no_matching_labels\", values: r.labels.any_of });\n\t\tconst forbidden = r.labels?.none_of?.filter((label) => labels.has(label)) ?? [];\n\t\tif (forbidden.length) rejections.push({ origin, code: \"forbidden_labels\", values: forbidden });\n\t\tfor (const capability of r.capabilities ?? []) {\n\t\t\tif (profile.capabilities[capability] !== true)\n\t\t\t\trejections.push({\n\t\t\t\t\torigin,\n\t\t\t\t\tcode:\n\t\t\t\t\t\tprofile.capabilities[capability] === false\n\t\t\t\t\t\t\t? \"unsupported_capability\"\n\t\t\t\t\t\t\t: \"unknown_capability\",\n\t\t\t\t\tvalues: [capability],\n\t\t\t\t});\n\t\t}\n\t}\n\treturn rejections;\n}\n\n/** @internal */\nexport function rankedProfiles(\n\tpolicy: PolicyProcess,\n\tprofiles: readonly PolicyProfile[],\n\tturnId?: string,\n) {\n\tconst eligible = profiles.filter((profile) => !profileRejections(policy, profile, turnId).length);\n\tconst marked = eligible.filter((profile) => profile.default);\n\tconst relevant = new Set(\n\t\trequirementLayers(policy, turnId).flatMap(({ requirements: r }) => [\n\t\t\t...(r.labels?.all_of ?? []),\n\t\t\t...(r.labels?.any_of ?? []),\n\t\t]),\n\t);\n\tconst unrelated = (profile: PolicyProfile) =>\n\t\tnew Set(profile.labels.filter((label) => !relevant.has(label))).size;\n\tconst ranked = (marked.length ? marked : eligible).sort(\n\t\t(a, b) =>\n\t\t\t(marked.length ? unrelated(a) - unrelated(b) : 0) ||\n\t\t\tmodelCostRank(a.labels) - modelCostRank(b.labels) ||\n\t\t\tcompareModelProfileIds(a.id, b.id),\n\t);\n\tconst minUnrelated = Math.min(...marked.map(unrelated));\n\treturn {\n\t\ttiedProfileIds: marked\n\t\t\t.filter((profile) => unrelated(profile) === minUnrelated)\n\t\t\t.map((profile) => profile.id),\n\t\tmarked: marked.length > 0,\n\t\tprofiles: ranked,\n\t};\n}\n","import type {\n\tDurableModelSelection,\n\tLaunchModelConfigInput,\n\tModelSelectionKind,\n\tProcessInstance,\n\tProcessSelectedTurnModelSource,\n\tTurnStartKind,\n\tTurnStartRecord,\n} from \"@leitwerk-dev/domain\";\nimport type { LaunchPlanPreparationResultLike, ProcessLaunchPlan } from \"@leitwerk-dev/process-sdk\";\nimport type {\n\tLauncherModelConfigSchema,\n\tProcessModelConfigurationView,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { ModelStatusCacheSnapshot } from \"../model-providers/model-status-cache.js\";\n\n/** @internal */\nexport type ProcessModelAvailabilitySnapshot = ModelStatusCacheSnapshot;\n\n/** @internal */\nexport type PersistedModelConfigurationIssue = Readonly<\n\tExtract<ProcessModelConfigurationView[\"state\"], { kind: \"blocked\" }>[\"issues\"][number]\n>;\n\nexport interface ValidModelConfiguration {\n\treadonly kind: \"valid\";\n\treadonly processId: string;\n\treadonly defaultProfileId?: string;\n\treadonly turnProfileIds: ReadonlyMap<string, string>;\n}\n\nexport interface InvalidModelConfiguration {\n\treadonly kind: \"invalid\";\n\treadonly processId: string;\n\treadonly issues: readonly PersistedModelConfigurationIssue[];\n}\n\nexport type ModelConfiguration = ValidModelConfiguration | InvalidModelConfiguration;\n\n/** @internal */\nexport type PersistedModelRelationalIssue =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly code: \"model_config_requires_llm_turn\";\n\t\t\t/** @internal */\n\t\t\treadonly turnId: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly code: \"selected_model_requires_selected_turn\";\n\t\t\t/** @internal */\n\t\t\treadonly modelProfileId: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly code: \"selected_model_requires_llm_turn\";\n\t\t\t/** @internal */\n\t\t\treadonly turnId: string;\n\t\t\t/** @internal */\n\t\t\treadonly modelProfileId: string;\n\t };\n\n/** @internal */\nexport type PersistedModelSelectionIssue = {\n\t/** @internal */\n\treadonly code: \"contradictory_provenance\";\n\t/** @internal */\n\treadonly turnId: string;\n\t/** @internal */\n\treadonly modelProfileId: string;\n\t/** @internal */\n\treadonly kind: ModelSelectionKind;\n\t/** @internal */\n\treadonly source: ProcessSelectedTurnModelSource;\n};\n\n/** @internal */\nexport type PersistedModelIntegrityIssue =\n\t| PersistedModelConfigurationIssue\n\t| PersistedModelRelationalIssue\n\t| PersistedModelSelectionIssue;\n\n/** @internal */\nexport type PersistedModelIntegrity =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"valid\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"malformed\";\n\t\t\t/** @internal */\n\t\t\treadonly issues: readonly PersistedModelIntegrityIssue[];\n\t };\n\nexport type ExistingTurnSelection =\n\t| { readonly kind: \"none\" }\n\t| {\n\t\t\treadonly kind: \"selected\";\n\t\t\treadonly turnId: string;\n\t\t\treadonly selection: DurableModelSelection;\n\t }\n\t| {\n\t\t\treadonly kind: \"invalid\";\n\t\t\treadonly turnId: string;\n\t\t\treadonly issues: readonly PersistedModelSelectionIssue[];\n\t };\n\nexport type ModelOverride =\n\t| { readonly kind: \"inherit\" }\n\t| { readonly kind: \"clear\" }\n\t| {\n\t\t\treadonly kind: \"profile\";\n\t\t\treadonly profileId: string;\n\t\t\treadonly source: Extract<\n\t\t\t\tProcessSelectedTurnModelSource,\n\t\t\t\t\"action_override\" | \"launch_override\"\n\t\t\t>;\n\t };\n\n/** @internal */\ntype ProcessModelPolicyFailureBase = {\n\t/** @internal */\n\treadonly ranking?: ModelRankingEvidence;\n\t/** @internal */\n\treadonly skippedPreferences?: readonly SkippedModelPreference[];\n\t/** @internal */\n\treadonly ok: false;\n\t/** @internal */\n\treadonly selection: DurableModelSelection | null;\n\t/** @internal */\n\treadonly availabilityRevision?: number;\n};\n\n/** @internal */\nexport type ProcessModelPolicyFailure = ProcessModelPolicyFailureBase &\n\t(\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"model_required\";\n\t\t\t\t/** Effective hard constraints when no eligible model exists. @internal */\n\t\t\t\treadonly requirements?: readonly PolicyRequirementLayer[];\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"unknown_model_profile\";\n\t\t\t\t/** @internal */\n\t\t\t\treadonly modelProfileId: string;\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"model_profile_not_allowed\";\n\t\t\t\t/** @internal */\n\t\t\t\treadonly modelProfileId: string;\n\t\t\t\t/** @internal */\n\t\t\t\treadonly processId: string;\n\t\t\t\t/** @internal */\n\t\t\t\treadonly rejections?: readonly ModelRequirementRejection[];\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"model_unavailable\" | \"model_stale\";\n\t\t\t\t/** @internal */\n\t\t\t\treadonly reason: string | null;\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"invalid_model_configuration\";\n\t\t\t\t/** @internal */\n\t\t\t\treadonly source: \"configuration\" | \"selection_provenance\";\n\t\t\t\t/** @internal */\n\t\t\t\treadonly message?: string;\n\t\t\t\t/** @internal */\n\t\t\t\treadonly issues: readonly (\n\t\t\t\t\t| PersistedModelConfigurationIssue\n\t\t\t\t\t| PersistedModelSelectionIssue\n\t\t\t\t)[];\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\treadonly code: \"stale_evaluation_snapshot\";\n\t\t }\n\t);\n/** @internal */\nexport interface ProcessModelPolicyResolution {\n\t/** @internal */\n\treadonly ranking?: ModelRankingEvidence;\n\t/** @internal */\n\treadonly skippedPreferences?: readonly SkippedModelPreference[];\n\t/** @internal */\n\treadonly ok: true;\n\t/** @internal */\n\treadonly selection: DurableModelSelection | null;\n\t/** @internal */\n\treadonly availabilityRevision?: number;\n}\n/** @internal */\nexport type ProcessModelPolicyEvaluation = ProcessModelPolicyResolution | ProcessModelPolicyFailure;\n\n/** @internal */\nexport interface ProjectedModelProfile {\n\t/** Independent of cached availability. @internal */\n\treadonly policyReason?: string;\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly providerId: string;\n\t/** @internal */\n\treadonly modelId: string;\n\t/** @internal */\n\treadonly thinkingLevel: string;\n\t/** @internal */\n\treadonly labels?: readonly string[];\n\t/** @internal */\n\treadonly default?: boolean;\n\t/** @internal */\n\treadonly availability: \"available\" | \"unavailable\" | \"stale\";\n\t/** @internal */\n\treadonly safeReason: string | null;\n\t/** @internal */\n\treadonly checkedAt: string | null;\n}\n\n/** @internal */\nexport type ProjectedModelDefault = Readonly<ProcessModelConfigurationView[\"defaultModel\"]>;\n\n/** @internal */\nexport type ProjectedModelResolutionSource = ProcessSelectedTurnModelSource | \"none\";\n\n/** @internal */\nexport interface ProjectedLauncherModelSchema {\n\t/** Excluded candidates with policy origins, keyed by turn; empty key denotes the process preference. @internal */\n\treadonly excludedProfiles?: Readonly<Record<string, readonly ProjectedModelProfile[]>>;\n\t/** @internal */\n\treadonly profilesByTurn?: Readonly<Record<string, readonly ProjectedModelProfile[]>>;\n\t/** @internal */\n\treadonly profiles: readonly ProjectedModelProfile[];\n\t/** @internal */\n\treadonly turns: LauncherModelConfigSchema[\"llmTurns\"];\n}\n\n/** @internal */\nexport interface ProjectedLauncherModelPreview {\n\t/** @internal */\n\treadonly defaultModel: {\n\t\t/** @internal */\n\t\treadonly source: ProjectedModelDefault[\"source\"];\n\t\t/** @internal */\n\t\treadonly profile: ProjectedModelProfile | null;\n\t};\n\t/** @internal */\n\treadonly turns: readonly {\n\t\t/** @internal */\n\t\treadonly turnId: string;\n\t\t/** @internal */\n\t\treadonly description: string;\n\t\t/** @internal */\n\t\treadonly effective: {\n\t\t\t/** @internal */\n\t\t\treadonly explanation?: string;\n\t\t\t/** @internal */\n\t\t\treadonly ranking?: ModelRankingEvidence;\n\t\t\t/** @internal */\n\t\t\treadonly error?: string;\n\t\t\t/** @internal */\n\t\t\treadonly source: ProjectedModelResolutionSource;\n\t\t\t/** @internal */\n\t\t\treadonly profile: ProjectedModelProfile | null;\n\t\t};\n\t}[];\n}\n\n/** @internal */\ntype ProjectedTurnModelConfiguration = Readonly<ProcessModelConfigurationView[\"turns\"][number]>;\n\n/** @internal */\nexport type ProjectedProcessModelConfiguration = Readonly<\n\tOmit<\n\t\tProcessModelConfigurationView,\n\t\t\"availableProfiles\" | \"profilesByTurn\" | \"excludedProfiles\" | \"turns\"\n\t>\n> &\n\tPick<ProjectedLauncherModelSchema, \"profiles\" | \"profilesByTurn\" | \"excludedProfiles\"> & {\n\t\t/** @internal */\n\t\treadonly turns: readonly Readonly<\n\t\t\tProjectedTurnModelConfiguration &\n\t\t\t\tRequired<\n\t\t\t\t\tPick<\n\t\t\t\t\t\tProjectedTurnModelConfiguration,\n\t\t\t\t\t\t\"fixedModelProfileId\" | \"effectiveModelProfileId\" | \"effectiveSource\"\n\t\t\t\t\t>\n\t\t\t\t>\n\t\t>[];\n\t};\n\n/** @internal */\nexport interface ProcessModelPolicyProjectionByKind {\n\t/** @internal */\n\treadonly profile_options: readonly ProjectedModelProfile[];\n\t/** @internal */\n\treadonly compatible_profiles: readonly string[];\n\t/** @internal */\n\treadonly launcher_schema: ProjectedLauncherModelSchema;\n\t/** @internal */\n\treadonly launcher_preview: ProjectedLauncherModelPreview;\n\t/** @internal */\n\treadonly process_configuration: ProjectedProcessModelConfiguration;\n}\n\n/** @internal */\nexport type ProcessModelPolicyEvaluationSubject =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"process_turn\";\n\t\t\t/** @internal */\n\t\t\treadonly process: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\treadonly turnId: string;\n\t\t\t/** @internal */\n\t\t\treadonly availability?: ProcessModelAvailabilitySnapshot;\n\t\t\t/** @internal */\n\t\t\treadonly startKind?: TurnStartKind;\n\t\t\t/** True only when selecting the first turn of a persisted process. @internal */\n\t\t\treadonly initialSelection?: boolean;\n\t\t\t/** @internal */\n\t\t\treadonly modelOverride?: string | null;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"launch_plan_turn\";\n\t\t\t/** @internal */\n\t\t\treadonly plan: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\treadonly turnId: string;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"runtime_selection\";\n\t\t\t/** Explicit validation scope. @internal */\n\t\t\treadonly target: ModelPolicyTarget;\n\t\t\t/** @internal */\n\t\t\treadonly processId: string;\n\t\t\t/** @internal */\n\t\t\treadonly selection: DurableModelSelection | null;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"preparation_recovery\";\n\t\t\t/** @internal */\n\t\t\treadonly cause: \"availability_transition\" | \"startup_reconciliation\";\n\t\t\t/** @internal */\n\t\t\treadonly process: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\treadonly currentStart: TurnStartRecord;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t };\n\n/** @internal */\nexport type ProcessModelPolicyProjectionSubject =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"profile_options\";\n\t\t\t/** @internal */\n\t\t\treadonly target: ModelPolicyTarget;\n\t\t\t/** @internal */\n\t\t\treadonly processId: string;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"compatible_profiles\";\n\t\t\t/** @internal */\n\t\t\treadonly target: ModelPolicyTarget;\n\t\t\t/** @internal */\n\t\t\treadonly processId: string;\n\t\t\t/** @internal */\n\t\t\treadonly providerId: string;\n\t\t\t/** @internal */\n\t\t\treadonly modelId: string;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"launcher_schema\";\n\t\t\t/** @internal */\n\t\t\treadonly processId: string;\n\t\t\t/** @internal */\n\t\t\treadonly availability?: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"launcher_preview\";\n\t\t\t/** @internal */\n\t\t\treadonly plan?: ProcessLaunchPlan;\n\t\t\t/** @internal */\n\t\t\treadonly processId: string;\n\t\t\t/** @internal */\n\t\t\treadonly modelConfig: LaunchModelConfigInput;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"process_configuration\";\n\t\t\t/** @internal */\n\t\t\treadonly process: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\treadonly availability: ProcessModelAvailabilitySnapshot;\n\t };\n\n/** @internal */\nexport type ProcessModelPolicyProjectionKind = ProcessModelPolicyProjectionSubject[\"kind\"];\n/** @internal */\nexport type ProcessModelPolicyProjectionSubjectFor<K extends ProcessModelPolicyProjectionKind> =\n\tExtract<\n\t\tProcessModelPolicyProjectionSubject,\n\t\t{\n\t\t\t/** @internal */\n\t\t\treadonly kind: K;\n\t\t}\n\t>;\n\n/** @internal */\nexport interface ProcessModelPolicyFingerprintSubject {\n\t/** @internal */\n\treadonly process: ProcessInstance;\n\t/** @internal */\n\treadonly currentStart: TurnStartRecord;\n}\n\n/** @internal */\nexport interface PrepareLaunchPlanOptions {\n\t/** @internal */\n\treadonly modelConfig?: LaunchModelConfigInput;\n\t/** @internal */\n\treadonly replaceModelConfig?: boolean;\n\t/** @internal */\n\treadonly invalidModelConfig?: \"reject\" | \"retain\";\n}\n\n/** @internal */\nexport interface ServerProcessModelPolicy {\n\t/** @internal */\n\tprepareLaunchPlan(\n\t\tlaunchPlan: ProcessLaunchPlan,\n\t\topts?: PrepareLaunchPlanOptions,\n\t): LaunchPlanPreparationResultLike;\n\t/** @internal */\n\tinspectPersistedState(process: ProcessInstance): PersistedModelIntegrity;\n\t/** @internal */\n\tevaluate(request: ProcessModelPolicyEvaluationSubject): ProcessModelPolicyEvaluation;\n\t/** @internal */\n\tproject<K extends ProcessModelPolicyProjectionKind>(\n\t\trequest: ProcessModelPolicyProjectionSubjectFor<K>,\n\t): ProcessModelPolicyProjectionByKind[K];\n\t/** @internal */\n\tfingerprint(request: ProcessModelPolicyFingerprintSubject): string;\n}\n/** @internal */\nexport type ModelPolicyTarget =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"process_default\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly kind: \"turn\";\n\t\t\t/** @internal */\n\t\t\treadonly turnId: string;\n\t };\n/** @internal */\nexport interface ModelRankingEvidence {\n\t/** @internal */\n\treadonly kind: \"marked_defaults\" | \"cost_id\";\n\t/** Equal-specificity marked defaults; ordered by the actual cost/ID tie-break. @internal */\n\treadonly tiedProfileIds: readonly string[];\n}\n/** @internal */\nexport interface SkippedModelPreference {\n\t/** @internal */\n\treadonly profileId: string;\n\t/** @internal */\n\treadonly source: ProcessSelectedTurnModelSource;\n\t/** @internal */\n\treadonly rejections: readonly ModelRequirementRejection[];\n}\n/** @internal */\nexport interface ModelRequirementRejection {\n\t/** @internal */ readonly origin: string;\n\t/** @internal */ readonly code: string;\n\t/** @internal */ readonly values: readonly string[];\n}\nexport interface PolicyProfile {\n\treadonly labels: readonly string[];\n\treadonly default: boolean;\n\treadonly capabilities: Readonly<Record<string, boolean | \"unknown\">>;\n\treadonly id: string;\n\treadonly provider: string;\n\treadonly modelId: string;\n\treadonly thinkingLevel: string;\n\treadonly providerOptions: Readonly<Record<string, unknown>>;\n}\n/** @internal */\nexport interface PolicyRequirementLayer {\n\t/** @internal */\n\treadonly origin: string;\n\t/** @internal */\n\treadonly requirements: import(\"@leitwerk-dev/protocol\").ModelRequirements;\n}\nexport interface PolicyProcess {\n\treadonly requirements: readonly PolicyRequirementLayer[];\n\treadonly turnRequirements: Readonly<Record<string, readonly PolicyRequirementLayer[]>>;\n\treadonly id: string;\n\treadonly allowedProfileIds: ReadonlySet<string> | null;\n\treadonly defaultProfileId: string | null;\n\treadonly turnProfileIds: Readonly<Record<string, string | null>>;\n\treadonly llmTurnIds: ReadonlySet<string>;\n\treadonly purposeProfileIdsByTurn: Readonly<Record<string, string>>;\n\treadonly scopedProfileIdForTurn?: (turnId: string) => string | null;\n\treadonly turnDescriptions: Readonly<Record<string, string>>;\n\treadonly turnPathTypes: Readonly<Record<string, string>>;\n}\nexport interface PolicySnapshot {\n\treadonly defaultProfileId: string;\n\treadonly profiles: readonly PolicyProfile[];\n\treadonly profilesById: ReadonlyMap<string, PolicyProfile>;\n\treadonly processesById: ReadonlyMap<string, PolicyProcess>;\n\treadonly workerStaticConfig: unknown;\n}\nexport function provenanceKindForSource(\n\tsource: import(\"@leitwerk-dev/domain\").ProcessSelectedTurnModelSource | null | undefined,\n): import(\"@leitwerk-dev/domain\").ModelSelectionProvenance[\"kind\"] {\n\treturn source === \"action_override\" ||\n\t\tsource === \"launch_override\" ||\n\t\tsource === \"instance_turn_config\" ||\n\t\tsource === \"instance_default\"\n\t\t? \"explicit\"\n\t\t: \"inherited\";\n}\n\n/** Launch/action choices stay pinned when inherited defaults are refreshed. @internal */\nexport function isPinnedModelSelection(\n\tselection: DurableModelSelection | null | undefined,\n): boolean {\n\treturn (\n\t\tselection?.provenance.source === \"action_override\" ||\n\t\tselection?.provenance.source === \"launch_override\"\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport type { PolicySnapshot, ProcessModelPolicyFingerprintSubject } from \"./types.js\";\n\nfunction canonical(value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map(canonical);\n\tif (typeof value !== \"object\" || value === null) return value;\n\treturn Object.fromEntries(\n\t\tObject.entries(value as Record<string, unknown>)\n\t\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t\t.map(([key, child]) => [key, canonical(child)]),\n\t);\n}\n\nexport function fingerprintPolicy(\n\tsnapshot: PolicySnapshot,\n\trequest: ProcessModelPolicyFingerprintSubject,\n): string {\n\tconst start = request.currentStart;\n\tconst prepared =\n\t\tstart.state.kind === \"starting\" ||\n\t\tstart.state.kind === \"accepted\" ||\n\t\tstart.state.kind === \"bootstrap_failed\"\n\t\t\t? { ...start.state.start, availabilityRevision: undefined }\n\t\t\t: null;\n\tconst material = canonical({\n\t\tversion: 3,\n\t\tworkerStaticConfig: snapshot.workerStaticConfig,\n\t\tprocess: {\n\t\t\tid: request.process.id,\n\t\t\tprocessId: request.process.processId,\n\t\t\tselectedTurnId: request.process.selectedTurnId,\n\t\t},\n\t\tstart: {\n\t\t\tid: start.id,\n\t\t\tturnId: start.turnId,\n\t\t\tturnType: start.turnType,\n\t\t\tproposedTurnRecordId: start.proposedTurnRecordId,\n\t\t\tstartKind: start.startKind,\n\t\t\trecoveryTurnRecordId: start.recoveryTurnRecordId,\n\t\t\tcontinuation: start.continuation,\n\t\t\tprepared,\n\t\t},\n\t});\n\treturn createHash(\"sha256\").update(JSON.stringify(material), \"utf8\").digest(\"hex\");\n}\n","import {\n\ttype LaunchModelConfigInput,\n\ttype ProcessInstance,\n\ttype ProcessSelectedTurnModelSource,\n\tparseStrictInstanceTurnConfigsJson,\n\ttrimToNull,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tExistingTurnSelection,\n\tModelConfiguration,\n\tModelOverride,\n\tPersistedModelConfigurationIssue,\n\tValidModelConfiguration,\n} from \"./types.js\";\nimport { provenanceKindForSource } from \"./types.js\";\n\ntype PersistedModelConfigurationInput = Pick<\n\tProcessInstance,\n\t\"processId\" | \"defaultModelProfileId\" | \"turnConfigsJson\"\n>;\n\n/** The sole persisted turn-configuration parser for model-policy requests. */\nexport function modelConfigurationFromPersistedInput(\n\tinput: PersistedModelConfigurationInput,\n): ModelConfiguration {\n\tconst parsed = parseStrictInstanceTurnConfigsJson(input.processId, input.turnConfigsJson);\n\tif (!parsed.ok) {\n\t\tconst issue: PersistedModelConfigurationIssue = {\n\t\t\tcode: parsed.error.code,\n\t\t\treason: parsed.error.reason,\n\t\t\t...(parsed.error.turnId !== undefined ? { turnId: parsed.error.turnId } : {}),\n\t\t};\n\t\treturn { kind: \"invalid\", processId: input.processId, issues: [issue] };\n\t}\n\treturn modelConfigurationFromLaunchInput(input.processId, {\n\t\tdefaultModelProfileId: input.defaultModelProfileId,\n\t\tturnConfigs: parsed.value,\n\t});\n}\n\nexport function modelConfigurationFromProcess(process: ProcessInstance): ModelConfiguration {\n\treturn modelConfigurationFromPersistedInput(process);\n}\n\n/** Constructs validated configuration from structured model input. */\nexport function modelConfigurationFromLaunchInput(\n\tprocessId: string,\n\tmodelConfig: LaunchModelConfigInput,\n): ValidModelConfiguration {\n\treturn {\n\t\tkind: \"valid\",\n\t\tprocessId,\n\t\tdefaultProfileId: trimToNull(modelConfig.defaultModelProfileId) ?? undefined,\n\t\tturnProfileIds: new Map(\n\t\t\tObject.entries(modelConfig.turnConfigs ?? {}).flatMap(([turnId, config]) => {\n\t\t\t\tconst profileId = trimToNull(config.modelProfileId);\n\t\t\t\treturn profileId ? [[turnId, profileId] as const] : [];\n\t\t\t}),\n\t\t),\n\t};\n}\n\nexport function existingTurnSelectionFromProcess(process: ProcessInstance): ExistingTurnSelection {\n\tconst profileId = trimToNull(process.selectedTurnModelProfileId);\n\t// An orphaned profile is stale metadata, not an active selection.\n\tif (!process.selectedTurnId || !profileId) return { kind: \"none\" };\n\tconst source = process.selectedTurnModelSource ?? \"legacy_persisted\";\n\tconst derivedKind = provenanceKindForSource(source);\n\tif (process.selectedTurnModelKind && process.selectedTurnModelKind !== derivedKind) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\tturnId: process.selectedTurnId,\n\t\t\tissues: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"contradictory_provenance\",\n\t\t\t\t\tturnId: process.selectedTurnId,\n\t\t\t\t\tmodelProfileId: profileId,\n\t\t\t\t\tkind: process.selectedTurnModelKind,\n\t\t\t\t\tsource,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"selected\",\n\t\tturnId: process.selectedTurnId,\n\t\tselection: {\n\t\t\tmodelProfileId: profileId,\n\t\t\tprovenance: {\n\t\t\t\tkind: process.selectedTurnModelKind ?? derivedKind,\n\t\t\t\tsource,\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport function modelOverride(\n\tvalue: string | null | undefined,\n\tprovided: boolean,\n\tsource: Extract<ProcessSelectedTurnModelSource, \"action_override\" | \"launch_override\">,\n): ModelOverride {\n\tif (!provided) return { kind: \"inherit\" };\n\tconst profileId = trimToNull(value);\n\treturn profileId ? { kind: \"profile\", profileId, source } : { kind: \"clear\" };\n}\n","import { type ProcessInstance, trimToNull } from \"@leitwerk-dev/domain\";\nimport { existingTurnSelectionFromProcess, modelConfigurationFromProcess } from \"./input.js\";\nimport type {\n\tPersistedModelIntegrity,\n\tPersistedModelIntegrityIssue,\n\tPolicySnapshot,\n} from \"./types.js\";\n\n/**\n * Inspects only durable encoding and relational invariants. Catalog membership,\n * allowlists, provider availability, and credentials are deliberately excluded:\n * those are properties of the current server configuration, not persisted data.\n */\nexport function inspectPersistedModelIntegrity(\n\tsnapshot: PolicySnapshot,\n\tprocess: ProcessInstance,\n): PersistedModelIntegrity {\n\tconst issues: PersistedModelIntegrityIssue[] = [];\n\tconst configuration = modelConfigurationFromProcess(process);\n\tif (configuration.kind === \"invalid\") {\n\t\tissues.push(...configuration.issues);\n\t} else {\n\t\tconst llmTurnIds = snapshot.processesById.get(process.processId)?.llmTurnIds ?? new Set();\n\t\tfor (const turnId of configuration.turnProfileIds.keys()) {\n\t\t\tif (!llmTurnIds.has(turnId)) {\n\t\t\t\tissues.push({ code: \"model_config_requires_llm_turn\", turnId });\n\t\t\t}\n\t\t}\n\t}\n\n\tconst selectedProfileId = trimToNull(process.selectedTurnModelProfileId);\n\tif (selectedProfileId) {\n\t\tif (!process.selectedTurnId) {\n\t\t\tconst isPendingLaunchSelection =\n\t\t\t\tprocess.lifecycleStatus === \"discovered\" &&\n\t\t\t\tprocess.planRevision === 0 &&\n\t\t\t\tprocess.selectedTurnModelKind === \"explicit\" &&\n\t\t\t\tprocess.selectedTurnModelSource === \"launch_override\";\n\t\t\tif (!isPendingLaunchSelection)\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: \"selected_model_requires_selected_turn\",\n\t\t\t\t\tmodelProfileId: selectedProfileId,\n\t\t\t\t});\n\t\t} else {\n\t\t\tconst llmTurnIds = snapshot.processesById.get(process.processId)?.llmTurnIds ?? new Set();\n\t\t\tif (!llmTurnIds.has(process.selectedTurnId)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: \"selected_model_requires_llm_turn\",\n\t\t\t\t\tturnId: process.selectedTurnId,\n\t\t\t\t\tmodelProfileId: selectedProfileId,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst selection = existingTurnSelectionFromProcess(process);\n\t\t\t\tif (selection.kind === \"invalid\") issues.push(...selection.issues);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn issues.length === 0 ? { kind: \"valid\" } : { kind: \"malformed\", issues };\n}\n","import {\n\ttype LaunchModelConfigInput,\n\tnormalizeLaunchModelConfigInput,\n\tparseStrictInstanceTurnConfigsJson,\n\tserializeInstanceTurnConfigs,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tLaunchPlanPreparationIssue,\n\tLaunchPlanPreparationIssueCode,\n\tLaunchPlanPreparationResultLike,\n\tProcessLaunchPlan,\n} from \"@leitwerk-dev/process-sdk\";\nimport { resolveDefault, resolveTurn, validateSelection } from \"./evaluate.js\";\nimport { modelConfigurationFromLaunchInput } from \"./input.js\";\nimport type {\n\tPolicySnapshot,\n\tPrepareLaunchPlanOptions,\n\tProcessModelPolicyEvaluation,\n} from \"./types.js\";\n\ntype ModelTarget =\n\t| { readonly kind: \"default_model\" }\n\t| { readonly kind: \"turn_model\"; readonly turnId: string }\n\t| { readonly kind: \"selected_turn_model\"; readonly turnId: string | null };\n\nfunction target(kind: ModelTarget[\"kind\"], turnId?: string | null): ModelTarget {\n\tif (kind === \"turn_model\") return { kind, turnId: turnId ?? \"\" };\n\tif (kind === \"selected_turn_model\") return { kind, turnId: turnId ?? null };\n\treturn { kind };\n}\n\nfunction targetLabel(modelTarget: ModelTarget): string {\n\tswitch (modelTarget.kind) {\n\t\tcase \"default_model\":\n\t\t\treturn \"default model\";\n\t\tcase \"turn_model\":\n\t\t\treturn `turn '${modelTarget.turnId}'`;\n\t\tcase \"selected_turn_model\":\n\t\t\treturn modelTarget.turnId ? `selected turn '${modelTarget.turnId}'` : \"selected turn model\";\n\t}\n}\n\nfunction issue(code: LaunchPlanPreparationIssueCode, message: string): LaunchPlanPreparationIssue {\n\treturn { code, message };\n}\n\nfunction mergeModelConfig(\n\tbase: LaunchModelConfigInput,\n\toverride: LaunchModelConfigInput,\n): LaunchModelConfigInput {\n\tconst normalizedBase = normalizeLaunchModelConfigInput(base);\n\tconst normalizedOverride = normalizeLaunchModelConfigInput(override);\n\tconst overrideTurnConfigs = normalizedOverride.turnConfigs ?? {};\n\treturn {\n\t\tdefaultModelProfileId:\n\t\t\tnormalizedOverride.defaultModelProfileId ?? normalizedBase.defaultModelProfileId ?? null,\n\t\tturnConfigs:\n\t\t\tObject.keys(overrideTurnConfigs).length > 0\n\t\t\t\t? overrideTurnConfigs\n\t\t\t\t: (normalizedBase.turnConfigs ?? {}),\n\t};\n}\n\nfunction issueForPolicy(\n\tresult: Exclude<ProcessModelPolicyEvaluation, { ok: true }>,\n\tprocessId: string,\n\tmodelTarget: ModelTarget,\n): LaunchPlanPreparationIssue {\n\tconst profileId = result.selection?.modelProfileId ?? \"\";\n\tif (result.code === \"unknown_model_profile\") {\n\t\treturn issue(\n\t\t\tresult.code,\n\t\t\t`Unknown model profile '${profileId}' for ${targetLabel(modelTarget)}`,\n\t\t);\n\t}\n\tif (result.code === \"model_profile_not_allowed\") {\n\t\treturn issue(\n\t\t\tresult.code,\n\t\t\t`Model profile '${profileId}' is not allowed for process '${processId}' (${targetLabel(modelTarget)})`,\n\t\t);\n\t}\n\tconst turnId = modelTarget.kind === \"selected_turn_model\" ? (modelTarget.turnId ?? \"\") : \"\";\n\treturn issue(\"model_required\", `A model is required for turn '${turnId}'`);\n}\n\n/** Validates, resolves, and sanitizes all model configuration carried by a launch plan. */\nexport function prepareLaunchPlan(\n\tsnapshot: PolicySnapshot,\n\tlaunchPlan: ProcessLaunchPlan,\n\topts: PrepareLaunchPlanOptions = {},\n): LaunchPlanPreparationResultLike {\n\tif (launchPlan.processId !== launchPlan.processInput.processId) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tlaunchPlan,\n\t\t\tmodelConfig: normalizeLaunchModelConfigInput(opts.modelConfig ?? {}),\n\t\t\terrors: [\n\t\t\t\tissue(\n\t\t\t\t\t\"process_id_mismatch\",\n\t\t\t\t\t`Launch plan process '${launchPlan.processId}' does not match input process '${launchPlan.processInput.processId}'`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tconst invalidMode = opts.invalidModelConfig ?? \"reject\";\n\tconst warnings: LaunchPlanPreparationIssue[] = [];\n\tconst errors: LaunchPlanPreparationIssue[] = [];\n\tconst report = (issue: LaunchPlanPreparationIssue | null): void => {\n\t\tif (!issue) return;\n\t\tif (invalidMode === \"reject\") errors.push(issue);\n\t\telse warnings.push(issue);\n\t};\n\tconst parsed = parseStrictInstanceTurnConfigsJson(\n\t\tlaunchPlan.processId,\n\t\tlaunchPlan.processInput.turnConfigsJson,\n\t);\n\tif (!parsed.ok) {\n\t\tconst message =\n\t\t\tparsed.error.reason === \"invalid_json\"\n\t\t\t\t? \"turnConfigsJson must be valid JSON\"\n\t\t\t\t: parsed.error.reason === \"not_object\"\n\t\t\t\t\t? \"turnConfigsJson must be an object\"\n\t\t\t\t\t: `turnConfigsJson.${parsed.error.turnId ?? \"<unknown>\"} must be an object`;\n\t\terrors.push(issue(parsed.error.code, message));\n\t}\n\tconst baseConfig: LaunchModelConfigInput = {\n\t\tdefaultModelProfileId: launchPlan.processInput.defaultModelProfileId ?? null,\n\t\tturnConfigs: parsed.ok ? parsed.value : {},\n\t};\n\tconst normalized = normalizeLaunchModelConfigInput(\n\t\tmergeModelConfig(\n\t\t\topts.replaceModelConfig ? { defaultModelProfileId: null, turnConfigs: {} } : baseConfig,\n\t\t\topts.modelConfig ?? {},\n\t\t),\n\t);\n\tconst policy = snapshot.processesById.get(launchPlan.processId);\n\tconst llmTurns = policy?.llmTurnIds ?? new Set<string>();\n\tconst validTurns: Record<string, { modelProfileId: string }> = {};\n\tconst defaultModelProfileId = normalized.defaultModelProfileId ?? null;\n\tconst modelIssue = (\n\t\tprofileId: string | null,\n\t\tmodelTarget: ModelTarget,\n\t): LaunchPlanPreparationIssue | null => {\n\t\tif (!profileId) return null;\n\t\tconst result = validateSelection(\n\t\t\tsnapshot,\n\t\t\tlaunchPlan.processId,\n\t\t\t{\n\t\t\t\tmodelProfileId: profileId,\n\t\t\t\tprovenance: { kind: \"explicit\", source: \"instance_default\" },\n\t\t\t},\n\t\t\tundefined,\n\t\t\tmodelTarget.kind === \"default_model\" ? undefined : (modelTarget.turnId ?? undefined),\n\t\t);\n\t\treturn result.ok ? null : issueForPolicy(result, launchPlan.processId, modelTarget);\n\t};\n\treport(modelIssue(defaultModelProfileId, target(\"default_model\")));\n\tfor (const [turnId, config] of Object.entries(normalized.turnConfigs ?? {})) {\n\t\tconst profileId = config.modelProfileId?.trim() || null;\n\t\tif (!llmTurns.has(turnId)) {\n\t\t\terrors.push(\n\t\t\t\tissue(\n\t\t\t\t\t\"unknown_llm_turn\",\n\t\t\t\t\t`Turn '${turnId}' is not a known LLM turn for process '${launchPlan.processId}'`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (profileId) {\n\t\t\treport(modelIssue(profileId, target(\"turn_model\", turnId)));\n\t\t\tvalidTurns[turnId] = { modelProfileId: profileId };\n\t\t}\n\t}\n\n\tconst selectedTurnId = launchPlan.startTurnId ?? launchPlan.processInput.selectedTurnId;\n\tconst selectedModelProfileId = launchPlan.processInput.selectedTurnModelProfileId?.trim() || null;\n\tconst selectedTurnIssue: LaunchPlanPreparationIssue | null = !selectedModelProfileId\n\t\t? null\n\t\t: !selectedTurnId\n\t\t\t? issue(\n\t\t\t\t\t\"selected_turn_model_requires_selected_turn\",\n\t\t\t\t\t`Selected turn model profile '${selectedModelProfileId}' requires a selected turn`,\n\t\t\t\t)\n\t\t\t: !llmTurns.has(selectedTurnId)\n\t\t\t\t? issue(\n\t\t\t\t\t\t\"selected_turn_model_requires_llm_turn\",\n\t\t\t\t\t\t`Selected turn model profile '${selectedModelProfileId}' requires selected turn '${selectedTurnId}' to be an LLM turn`,\n\t\t\t\t\t)\n\t\t\t\t: modelIssue(selectedModelProfileId, target(\"selected_turn_model\", selectedTurnId));\n\treport(selectedTurnIssue);\n\n\tconst modelConfig = { defaultModelProfileId, turnConfigs: validTurns };\n\tlet initialDefaultModelProfileId = null;\n\tconst configuration = modelConfigurationFromLaunchInput(launchPlan.processId, modelConfig);\n\tconst defaultResult = resolveDefault(snapshot, configuration);\n\tif (defaultResult.ok)\n\t\tinitialDefaultModelProfileId = defaultResult.selection?.modelProfileId ?? null;\n\tif (selectedTurnId && !selectedModelProfileId && errors.length === 0 && warnings.length === 0) {\n\t\tconst turnResult = resolveTurn(\n\t\t\tsnapshot,\n\t\t\tconfiguration,\n\t\t\tselectedTurnId,\n\t\t\tfalse,\n\t\t\t{ kind: \"none\" },\n\t\t\t{ kind: \"inherit\" },\n\t\t);\n\t\tif (!turnResult.ok) {\n\t\t\treport(\n\t\t\t\tissueForPolicy(\n\t\t\t\t\tturnResult,\n\t\t\t\t\tlaunchPlan.processId,\n\t\t\t\t\ttarget(\"selected_turn_model\", selectedTurnId),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\tconst rejectedLaunchPlan = parsed.ok\n\t\t\t? {\n\t\t\t\t\t...launchPlan,\n\t\t\t\t\tprocessInput: {\n\t\t\t\t\t\t...launchPlan.processInput,\n\t\t\t\t\t\tdefaultModelProfileId: normalized.defaultModelProfileId ?? null,\n\t\t\t\t\t\tturnConfigsJson: serializeInstanceTurnConfigs(normalized.turnConfigs ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: launchPlan;\n\t\treturn { ok: false, launchPlan: rejectedLaunchPlan, modelConfig: normalized, errors };\n\t}\n\treturn {\n\t\tok: true,\n\t\tmodelConfig,\n\t\twarnings,\n\t\tlaunchPlan: {\n\t\t\t...launchPlan,\n\t\t\tprocessInput: {\n\t\t\t\t...launchPlan.processInput,\n\t\t\t\tdefaultModelProfileId,\n\t\t\t\tselectedTurnModelProfileId: selectedModelProfileId,\n\t\t\t\tselectedTurnModelKind: selectedModelProfileId ? \"explicit\" : null,\n\t\t\t\tselectedTurnModelSource: selectedModelProfileId ? \"launch_override\" : null,\n\t\t\t\tinitialDefaultModelProfileId,\n\t\t\t\tturnConfigsJson: serializeInstanceTurnConfigs(validTurns),\n\t\t\t},\n\t\t},\n\t};\n}\n","import { trimToNull } from \"@leitwerk-dev/domain\";\nimport { compareModelProfileIds, modelCostRank } from \"@leitwerk-dev/protocol\";\nimport { presentProcessModelPolicyFailure } from \"../process-model-policy-presenter.js\";\nimport { resolveDefault, resolveTurn } from \"./evaluate.js\";\nimport {\n\texistingTurnSelectionFromProcess,\n\tmodelConfigurationFromLaunchInput,\n\tmodelConfigurationFromProcess,\n} from \"./input.js\";\nimport { profileRejections } from \"./requirements.js\";\nimport type {\n\tPolicySnapshot,\n\tProcessModelPolicyProjectionByKind,\n\tProcessModelPolicyProjectionKind,\n\tProcessModelPolicyProjectionSubject,\n\tProcessModelPolicyProjectionSubjectFor,\n\tProjectedModelDefault,\n\tValidModelConfiguration,\n} from \"./types.js\";\n\nfunction defaultProjection(\n\tsnapshot: PolicySnapshot,\n\tconfiguration: ValidModelConfiguration,\n): ProjectedModelDefault {\n\tconst policy = snapshot.processesById.get(configuration.processId);\n\tconst { selection } = resolveDefault(snapshot, configuration);\n\treturn {\n\t\tprocessConfigModelProfileId: trimToNull(policy?.defaultProfileId),\n\t\tinstanceModelProfileId: configuration.defaultProfileId ?? null,\n\t\teffectiveModelProfileId: selection?.modelProfileId ?? null,\n\t\tsource:\n\t\t\tselection?.provenance.source === \"instance_default\"\n\t\t\t\t? \"instance\"\n\t\t\t\t: selection?.provenance.source === \"process_config_default\"\n\t\t\t\t\t? \"process_config\"\n\t\t\t\t\t: selection\n\t\t\t\t\t\t? \"catalog_default\"\n\t\t\t\t\t\t: \"none\",\n\t};\n}\n\nexport function projectPolicy<K extends ProcessModelPolicyProjectionKind>(\n\tsnapshot: PolicySnapshot,\n\trequest: ProcessModelPolicyProjectionSubjectFor<K>,\n): ProcessModelPolicyProjectionByKind[K];\nexport function projectPolicy(\n\tsnapshot: PolicySnapshot,\n\trequest: ProcessModelPolicyProjectionSubject,\n): ProcessModelPolicyProjectionByKind[ProcessModelPolicyProjectionKind] {\n\tconst processId =\n\t\trequest.kind === \"process_configuration\" ? request.process.processId : request.processId;\n\tconst policy = snapshot.processesById.get(processId);\n\tconst targetTurnId =\n\t\t\"target\" in request && request.target.kind === \"turn\" ? request.target.turnId : undefined;\n\tif (request.kind === \"compatible_profiles\") {\n\t\treturn snapshot.profiles\n\t\t\t.filter(\n\t\t\t\t(profile) =>\n\t\t\t\t\tprofile.provider === request.providerId &&\n\t\t\t\t\tprofile.modelId === request.modelId &&\n\t\t\t\t\t(!policy || !profileRejections(policy, profile, targetTurnId).length),\n\t\t\t)\n\t\t\t.map((profile) => profile.id);\n\t}\n\tconst catalog = [...snapshot.profiles]\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tmodelCostRank(a.labels) - modelCostRank(b.labels) || compareModelProfileIds(a.id, b.id),\n\t\t)\n\t\t.map((profile) => {\n\t\t\tconst status = request.availability?.profiles.find(\n\t\t\t\t(candidate) => candidate.profileId === profile.id,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tsource: profile,\n\t\t\t\tid: profile.id,\n\t\t\t\tproviderId: profile.provider,\n\t\t\t\tmodelId: profile.modelId,\n\t\t\t\tthinkingLevel: profile.thinkingLevel,\n\t\t\t\tlabels: profile.labels,\n\t\t\t\tdefault: profile.default,\n\t\t\t\tavailability: status?.availability ?? (\"stale\" as const),\n\t\t\t\tsafeReason: status?.safeReason ?? null,\n\t\t\t\tcheckedAt: status?.checkedAt ?? null,\n\t\t\t};\n\t\t});\n\tconst projectProfiles = (turnId?: string) => {\n\t\tconst projected = catalog.map(({ source, ...option }) => {\n\t\t\tconst rejections = policy ? profileRejections(policy, source, turnId) : [];\n\t\t\treturn {\n\t\t\t\t...option,\n\t\t\t\tpolicyReason:\n\t\t\t\t\trejections.map((r) => `${r.code} (${r.values.join(\", \")}) from ${r.origin}`).join(\"; \") ||\n\t\t\t\t\tundefined,\n\t\t\t};\n\t\t});\n\t\treturn {\n\t\t\tprofiles: projected.filter((profile) => !profile.policyReason),\n\t\t\texcludedProfiles: projected.filter((profile) => profile.policyReason),\n\t\t};\n\t};\n\tconst processProfiles = projectProfiles(targetTurnId);\n\tconst { profiles } = processProfiles;\n\n\tif (request.kind === \"profile_options\") return profiles;\n\n\tconst profileMaps = () => {\n\t\tconst turns = [...(policy?.llmTurnIds ?? [])].map(\n\t\t\t(turnId) => [turnId, projectProfiles(turnId)] as const,\n\t\t);\n\t\treturn {\n\t\t\tprofilesByTurn: Object.fromEntries(turns.map(([id, value]) => [id, value.profiles])),\n\t\t\texcludedProfiles: Object.fromEntries([\n\t\t\t\t[\"\", processProfiles.excludedProfiles],\n\t\t\t\t...turns.map(([id, value]) => [id, value.excludedProfiles]),\n\t\t\t]),\n\t\t};\n\t};\n\tif (request.kind === \"launcher_schema\") {\n\t\treturn {\n\t\t\t...profileMaps(),\n\t\t\tprofiles,\n\t\t\tturns: [...(policy?.llmTurnIds ?? [])].map((turnId) => ({\n\t\t\t\tturnId,\n\t\t\t\tdescription: policy?.turnDescriptions[turnId] ?? turnId,\n\t\t\t})),\n\t\t};\n\t}\n\n\tconst configuration =\n\t\trequest.kind === \"launcher_preview\"\n\t\t\t? modelConfigurationFromLaunchInput(processId, request.modelConfig)\n\t\t\t: modelConfigurationFromProcess(request.process);\n\tif (configuration.kind === \"invalid\") {\n\t\treturn {\n\t\t\tstate: { kind: \"blocked\", issues: configuration.issues },\n\t\t\tprofiles,\n\t\t\tdefaultModel: {\n\t\t\t\tprocessConfigModelProfileId: null,\n\t\t\t\tinstanceModelProfileId: null,\n\t\t\t\teffectiveModelProfileId: null,\n\t\t\t\tsource: \"none\",\n\t\t\t},\n\t\t\tturns: [],\n\t\t\teffectiveSelectedTurn: null,\n\t\t};\n\t}\n\n\tconst defaultModel = defaultProjection(snapshot, configuration);\n\tconst turns = [...(policy?.llmTurnIds ?? [])].map((turnId) => {\n\t\tconst instanceModelProfileId = configuration.turnProfileIds.get(turnId) ?? null;\n\t\tconst processConfigModelProfileId = trimToNull(policy?.turnProfileIds[turnId]);\n\t\tconst resolved = resolveTurn(\n\t\t\tsnapshot,\n\t\t\tconfiguration,\n\t\t\tturnId,\n\t\t\tfalse,\n\t\t\t{ kind: \"none\" },\n\t\t\t{ kind: \"inherit\" },\n\t\t\trequest.availability,\n\t\t);\n\t\treturn {\n\t\t\tturnId,\n\t\t\texplanation: resolved.skippedPreferences?.length\n\t\t\t\t? `Automatic — skipped ${resolved.skippedPreferences.map((preference) => `${preference.profileId}: ${preference.rejections.map((r) => `${r.code} (${r.values.join(\", \")}) from ${r.origin}`).join(\"; \")}`).join(\"; \")}`\n\t\t\t\t: undefined,\n\t\t\tranking: resolved.ranking,\n\t\t\teffectiveModelProfileId: resolved.selection?.modelProfileId ?? null,\n\t\t\teffectiveSource: resolved.selection?.provenance.source ?? (\"none\" as const),\n\t\t\t...(!resolved.ok ? { effectiveError: presentProcessModelPolicyFailure(resolved) } : {}),\n\t\t\tdescription: policy?.turnDescriptions[turnId] ?? turnId,\n\t\t\tpathType: policy?.turnPathTypes[turnId] ?? \"primary\",\n\t\t\tprocessConfigModelProfileId,\n\t\t\tinstanceModelProfileId,\n\t\t\tfixedModelProfileId: policy?.purposeProfileIdsByTurn[turnId] ?? null,\n\t\t\teffectiveConfiguredModelProfileId:\n\t\t\t\tpolicy?.purposeProfileIdsByTurn[turnId] ??\n\t\t\t\tinstanceModelProfileId ??\n\t\t\t\tprocessConfigModelProfileId,\n\t\t\tsource: instanceModelProfileId\n\t\t\t\t? (\"instance\" as const)\n\t\t\t\t: processConfigModelProfileId\n\t\t\t\t\t? (\"process_config\" as const)\n\t\t\t\t\t: (\"default\" as const),\n\t\t};\n\t});\n\n\tif (request.kind === \"launcher_preview\") {\n\t\tconst profilesById = new Map(\n\t\t\tcatalog.map(({ source: _source, ...profile }) => [profile.id, profile]),\n\t\t);\n\t\treturn {\n\t\t\tdefaultModel: {\n\t\t\t\tsource: defaultModel.source,\n\t\t\t\tprofile: profilesById.get(defaultModel.effectiveModelProfileId ?? \"\") ?? null,\n\t\t\t},\n\t\t\tturns: turns.map((turn) => ({\n\t\t\t\tturnId: turn.turnId,\n\t\t\t\tdescription: turn.description,\n\t\t\t\teffective: {\n\t\t\t\t\texplanation: turn.explanation,\n\t\t\t\t\tranking: turn.ranking,\n\t\t\t\t\tsource: turn.effectiveSource,\n\t\t\t\t\t...(turn.effectiveError ? { error: turn.effectiveError } : {}),\n\t\t\t\t\tprofile: profilesById.get(turn.effectiveModelProfileId ?? \"\") ?? null,\n\t\t\t\t},\n\t\t\t})),\n\t\t};\n\t}\n\n\tconst selectedTurn = existingTurnSelectionFromProcess(request.process);\n\treturn {\n\t\tstate: { kind: \"ready\" },\n\t\t...profileMaps(),\n\t\tprofiles,\n\t\tdefaultModel,\n\t\tturns,\n\t\teffectiveSelectedTurn:\n\t\t\tselectedTurn.kind === \"selected\"\n\t\t\t\t? {\n\t\t\t\t\t\tturnId: selectedTurn.turnId,\n\t\t\t\t\t\tdescription: policy?.turnDescriptions[selectedTurn.turnId] ?? selectedTurn.turnId,\n\t\t\t\t\t\tmodelProfileId: selectedTurn.selection.modelProfileId,\n\t\t\t\t\t\tsource: selectedTurn.selection.provenance.source,\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t};\n}\n","import type { LaunchPlanPreparationIssue } from \"@leitwerk-dev/process-sdk\";\nimport type {\n\tLauncherModelConfigPreview,\n\tLauncherModelConfigSchema,\n\tModelProfileOptionSummary,\n\tProcessModelConfigurationView,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport type {\n\tProcessModelPolicyEvaluation,\n\tProjectedLauncherModelPreview,\n\tProjectedLauncherModelSchema,\n\tProjectedModelProfile,\n\tProjectedProcessModelConfiguration,\n} from \"./process-model-policy/index.js\";\n\ntype ProcessModelPolicyFailure = Exclude<ProcessModelPolicyEvaluation, { ok: true }>;\n\nexport function presentLaunchPlanPreparationIssues(\n\tissues: readonly LaunchPlanPreparationIssue[],\n): readonly { code: \"invalid_model_config\"; message: string }[] {\n\treturn issues.map((issue) => ({\n\t\tcode: \"invalid_model_config\" as const,\n\t\tmessage: issue.message,\n\t}));\n}\n\nexport function presentProcessModelPolicyFailure(failure: ProcessModelPolicyFailure): string {\n\tswitch (failure.code) {\n\t\tcase \"model_required\":\n\t\t\treturn `No model satisfies this turn's requirements${failure.requirements?.length ? `: ${failure.requirements.map((layer) => `${layer.origin} ${JSON.stringify(layer.requirements)}`).join(\"; \")}` : \"\"}`;\n\t\tcase \"unknown_model_profile\":\n\t\t\treturn `Unknown model profile '${failure.modelProfileId}'`;\n\t\tcase \"model_profile_not_allowed\":\n\t\t\treturn `Model profile '${failure.modelProfileId}' is not allowed for process '${failure.processId}'${failure.rejections?.length ? `: ${failure.rejections.map((r) => `${r.code} (${r.values.join(\", \")}) from ${r.origin}`).join(\"; \")}` : \"\"}`;\n\t\tcase \"model_stale\":\n\t\t\treturn failure.reason ?? \"Model status has not been refreshed\";\n\t\tcase \"model_unavailable\":\n\t\t\treturn failure.reason ?? \"The selected model is unavailable\";\n\t\tcase \"invalid_model_configuration\":\n\t\t\treturn (\n\t\t\t\tfailure.message ??\n\t\t\t\t(failure.source === \"selection_provenance\"\n\t\t\t\t\t? \"Persisted model selection provenance is invalid\"\n\t\t\t\t\t: \"Persisted model configuration is invalid\")\n\t\t\t);\n\t\tcase \"stale_evaluation_snapshot\":\n\t\t\treturn \"Model availability changed repeatedly during evaluation\";\n\t}\n}\n\nexport function presentModelProfileOption(\n\tprofile: ProjectedModelProfile,\n): ModelProfileOptionSummary {\n\tconst thinkingLevel = profile.thinkingLevel.trim();\n\treturn {\n\t\tid: profile.id,\n\t\t...(profile.policyReason ? { policyReason: profile.policyReason } : {}),\n\t\tlabels: profile.labels ?? [],\n\t\tdefault: profile.default ?? false,\n\t\tlabel: `${profile.id} — ${profile.providerId}/${profile.modelId}`,\n\t\tdescription:\n\t\t\tthinkingLevel && thinkingLevel.toLowerCase() !== \"off\"\n\t\t\t\t? `Thinking level: ${thinkingLevel}`\n\t\t\t\t: \"Thinking disabled\",\n\t\tavailability: profile.availability,\n\t\tsafeReason: profile.safeReason ?? \"Model status has not been refreshed\",\n\t\tcheckedAt: profile.checkedAt,\n\t};\n}\n\nfunction presentProfileMap(\n\tprofiles: Readonly<Record<string, readonly ProjectedModelProfile[]>> = {},\n) {\n\treturn Object.fromEntries(\n\t\tObject.entries(profiles).map(([id, options]) => [id, options.map(presentModelProfileOption)]),\n\t);\n}\n\nexport function presentLauncherModelConfigSchema(\n\tprojection: ProjectedLauncherModelSchema,\n): LauncherModelConfigSchema {\n\treturn {\n\t\tavailableProfiles: projection.profiles.map(presentModelProfileOption),\n\t\tprofilesByTurn: presentProfileMap(projection.profilesByTurn),\n\t\texcludedProfiles: presentProfileMap(projection.excludedProfiles),\n\t\tllmTurns: projection.turns.map((turn) => ({ ...turn })),\n\t};\n}\n\nexport function presentLauncherModelConfigPreview(\n\tprojection: ProjectedLauncherModelPreview,\n): LauncherModelConfigPreview {\n\treturn {\n\t\tdefaultModel: {\n\t\t\tsource:\n\t\t\t\tprojection.defaultModel.source === \"instance\"\n\t\t\t\t\t? \"instance_default\"\n\t\t\t\t\t: projection.defaultModel.source === \"process_config\"\n\t\t\t\t\t\t? \"process_config_default\"\n\t\t\t\t\t\t: projection.defaultModel.source,\n\t\t\tprofile: projection.defaultModel.profile\n\t\t\t\t? presentModelProfileOption(projection.defaultModel.profile)\n\t\t\t\t: null,\n\t\t},\n\t\tturns: projection.turns.map((turn) => ({\n\t\t\tturnId: turn.turnId,\n\t\t\tdescription: turn.description,\n\t\t\teffective: {\n\t\t\t\t...(turn.effective.explanation ? { explanation: turn.effective.explanation } : {}),\n\t\t\t\t...(turn.effective.error ? { error: turn.effective.error } : {}),\n\t\t\t\tsource: turn.effective.source,\n\t\t\t\tprofile: turn.effective.profile ? presentModelProfileOption(turn.effective.profile) : null,\n\t\t\t},\n\t\t})),\n\t};\n}\n\nexport function presentProcessModelConfiguration(\n\tprojection: ProjectedProcessModelConfiguration,\n): ProcessModelConfigurationView {\n\treturn {\n\t\tstate: projection.state,\n\t\texcludedProfiles: presentProfileMap(projection.excludedProfiles),\n\t\tprofilesByTurn: presentProfileMap(projection.profilesByTurn),\n\t\tavailableProfiles: projection.profiles.map(presentModelProfileOption),\n\t\teffectiveSelectedTurn: projection.effectiveSelectedTurn,\n\t\tdefaultModel: projection.defaultModel,\n\t\tturns: projection.turns,\n\t};\n}\n","import type { ModelStatusCacheSnapshot } from \"../model-providers/model-status-cache.js\";\n\nexport type StableAvailabilityEvaluation<T> =\n\t| { ok: true; availability: ModelStatusCacheSnapshot; value: T }\n\t| { ok: false; availability: ModelStatusCacheSnapshot };\n\n/** Evaluates against one availability revision, retrying once when that revision changes. */\nexport async function evaluateAtStableAvailabilityRevision<T>(input: {\n\tavailability: ModelStatusCacheSnapshot;\n\tgetModelAvailabilitySnapshot: () => ModelStatusCacheSnapshot;\n\tevaluate: (availability: ModelStatusCacheSnapshot) => T | Promise<T>;\n\tbeforeRetry?: () => void | Promise<void>;\n}): Promise<StableAvailabilityEvaluation<T>> {\n\tlet availability = input.availability;\n\tfor (let attempt = 0; attempt < 2; attempt += 1) {\n\t\tconst value = await input.evaluate(availability);\n\t\tconst current = input.getModelAvailabilitySnapshot();\n\t\tif (current.revision === availability.revision) {\n\t\t\treturn { ok: true, availability, value };\n\t\t}\n\t\tavailability = current;\n\t\tif (attempt === 0) await input.beforeRetry?.();\n\t}\n\treturn { ok: false, availability };\n}\n","import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport type { ProcessLaunchPlan } from \"@leitwerk-dev/process-sdk\";\nimport type { LeitwerkConfig } from \"../config/config-types.js\";\nimport type { ProcessActionRegistry } from \"../process-action-registry.js\";\nimport type { ProcessGraphRegistry } from \"../process-graph.js\";\nimport type { ScopedSettingsService } from \"../scoped-settings-service.js\";\nimport { constructPolicySnapshot, ProcessModelPolicyConfigurationError } from \"./construct.js\";\nimport { recoverPreparation, resolveTurn, validateSelection } from \"./evaluate.js\";\nimport { fingerprintPolicy } from \"./fingerprint.js\";\nimport {\n\texistingTurnSelectionFromProcess,\n\tmodelConfigurationFromPersistedInput,\n\tmodelConfigurationFromProcess,\n\tmodelOverride,\n} from \"./input.js\";\nimport { inspectPersistedModelIntegrity } from \"./integrity.js\";\nimport { prepareLaunchPlan } from \"./launch.js\";\nimport { projectPolicy } from \"./project.js\";\nimport type {\n\tPolicySnapshot,\n\tPrepareLaunchPlanOptions,\n\tProcessModelPolicyEvaluation,\n\tProcessModelPolicyEvaluationSubject,\n\tProcessModelPolicyFingerprintSubject,\n\tProcessModelPolicyProjectionByKind,\n\tProcessModelPolicyProjectionKind,\n\tProcessModelPolicyProjectionSubject,\n\tProcessModelPolicyProjectionSubjectFor,\n\tServerProcessModelPolicy,\n} from \"./types.js\";\n\nexport type { StableAvailabilityEvaluation } from \"./stable-availability.js\";\nexport { evaluateAtStableAvailabilityRevision } from \"./stable-availability.js\";\nexport type {\n\tPersistedModelIntegrity,\n\tPersistedModelIntegrityIssue,\n\tPrepareLaunchPlanOptions,\n\tProcessModelAvailabilitySnapshot,\n\tProcessModelPolicyEvaluation,\n\tProcessModelPolicyEvaluationSubject,\n\tProcessModelPolicyFingerprintSubject,\n\tProcessModelPolicyProjectionKind,\n\tProcessModelPolicyProjectionSubject,\n\tProcessModelPolicyProjectionSubjectFor,\n\tProjectedLauncherModelPreview,\n\tProjectedLauncherModelSchema,\n\tProjectedModelDefault,\n\tProjectedModelProfile,\n\tProjectedModelResolutionSource,\n\tProjectedProcessModelConfiguration,\n\tServerProcessModelPolicy,\n} from \"./types.js\";\nexport { isPinnedModelSelection } from \"./types.js\";\nexport { ProcessModelPolicyConfigurationError };\n\nfunction evaluateSubject(\n\tsnapshot: PolicySnapshot,\n\trequest: ProcessModelPolicyEvaluationSubject,\n): ProcessModelPolicyEvaluation {\n\tif (request.kind === \"process_turn\") {\n\t\treturn resolveTurn(\n\t\t\tsnapshot,\n\t\t\tmodelConfigurationFromProcess(request.process),\n\t\t\trequest.turnId,\n\t\t\trequest.initialSelection === true ||\n\t\t\t\trequest.startKind === \"retry\" ||\n\t\t\t\trequest.startKind === \"startup_retry\" ||\n\t\t\t\trequest.startKind === \"continue\",\n\t\t\texistingTurnSelectionFromProcess(request.process),\n\t\t\tmodelOverride(\n\t\t\t\trequest.modelOverride,\n\t\t\t\tObject.hasOwn(request, \"modelOverride\"),\n\t\t\t\t\"action_override\",\n\t\t\t),\n\t\t\trequest.availability,\n\t\t);\n\t}\n\tif (request.kind === \"launch_plan_turn\") {\n\t\tconst selected = request.plan.processInput.selectedTurnModelProfileId ?? null;\n\t\treturn resolveTurn(\n\t\t\tsnapshot,\n\t\t\tmodelConfigurationFromPersistedInput({\n\t\t\t\tprocessId: request.plan.processId,\n\t\t\t\tdefaultModelProfileId: request.plan.processInput.defaultModelProfileId,\n\t\t\t\tturnConfigsJson: request.plan.processInput.turnConfigsJson,\n\t\t\t}),\n\t\t\trequest.turnId,\n\t\t\tfalse,\n\t\t\t{ kind: \"none\" },\n\t\t\tmodelOverride(selected, selected !== null, \"launch_override\"),\n\t\t\trequest.availability,\n\t\t);\n\t}\n\tif (request.kind === \"runtime_selection\") {\n\t\treturn validateSelection(\n\t\t\tsnapshot,\n\t\t\trequest.processId,\n\t\t\trequest.selection,\n\t\t\trequest.availability,\n\t\t\trequest.target.kind === \"turn\" ? request.target.turnId : undefined,\n\t\t);\n\t}\n\treturn recoverPreparation(\n\t\tsnapshot,\n\t\trequest.cause,\n\t\tmodelConfigurationFromProcess(request.process),\n\t\trequest.currentStart,\n\t\trequest.availability,\n\t);\n}\n\n/** Constructs the immutable, server-owned process model policy once at startup. */\nexport function createServerProcessModelPolicy(input: {\n\tconfig: LeitwerkConfig;\n\tprocessGraphs: ProcessGraphRegistry;\n\tprocessActionRegistry: Pick<ProcessActionRegistry, \"getTurnDefinition\">;\n\tcapabilities?: (\n\t\tproviderId: string,\n\t\tmodelId: string,\n\t) => Readonly<Record<string, boolean | \"unknown\">>;\n\tscopedSettings?: Pick<ScopedSettingsService, \"modelDefault\">;\n}): ServerProcessModelPolicy {\n\tconst snapshot = constructPolicySnapshot(input);\n\tfunction scopedSnapshot(\n\t\tprocessId: string,\n\t\tprocess?: ProcessInstance,\n\t\tplan?: ProcessLaunchPlan,\n\t): PolicySnapshot {\n\t\tif (!input.scopedSettings) return snapshot;\n\t\tconst policy = snapshot.processesById.get(processId);\n\t\tif (!policy) return snapshot;\n\t\tconst processesById = new Map(snapshot.processesById);\n\t\tprocessesById.set(processId, {\n\t\t\t...policy,\n\t\t\tscopedProfileIdForTurn: (turnId) =>\n\t\t\t\tinput.scopedSettings?.modelDefault(processId, turnId, process, plan) ?? null,\n\t\t});\n\t\treturn { ...snapshot, processesById };\n\t}\n\tfunction projectionSnapshot(request: ProcessModelPolicyProjectionSubject): PolicySnapshot {\n\t\treturn request.kind === \"process_configuration\"\n\t\t\t? scopedSnapshot(request.process.processId, request.process)\n\t\t\t: request.kind === \"launcher_preview\"\n\t\t\t\t? scopedSnapshot(request.processId, undefined, request.plan)\n\t\t\t\t: snapshot;\n\t}\n\n\treturn Object.freeze({\n\t\tprepareLaunchPlan: (launchPlan: ProcessLaunchPlan, opts?: PrepareLaunchPlanOptions) =>\n\t\t\tprepareLaunchPlan(\n\t\t\t\tscopedSnapshot(launchPlan.processId, undefined, launchPlan),\n\t\t\t\tlaunchPlan,\n\t\t\t\topts,\n\t\t\t),\n\t\tinspectPersistedState: (process: ProcessInstance) =>\n\t\t\tinspectPersistedModelIntegrity(snapshot, process),\n\t\tevaluate: (request: ProcessModelPolicyEvaluationSubject) =>\n\t\t\tevaluateSubject(\n\t\t\t\trequest.kind === \"process_turn\" || request.kind === \"preparation_recovery\"\n\t\t\t\t\t? scopedSnapshot(request.process.processId, request.process)\n\t\t\t\t\t: request.kind === \"launch_plan_turn\"\n\t\t\t\t\t\t? scopedSnapshot(request.plan.processId, undefined, request.plan)\n\t\t\t\t\t\t: snapshot,\n\t\t\t\trequest,\n\t\t\t),\n\t\tproject: <K extends ProcessModelPolicyProjectionKind>(\n\t\t\trequest: ProcessModelPolicyProjectionSubjectFor<K>,\n\t\t) =>\n\t\t\tprojectPolicy(projectionSnapshot(request), request) as ProcessModelPolicyProjectionByKind[K],\n\t\tfingerprint: (request: ProcessModelPolicyFingerprintSubject) =>\n\t\t\tfingerprintPolicy(snapshot, request),\n\t});\n}\n","import type {\n\tLaunchChecklistStep,\n\tLaunchChecklistStepStatus,\n\tLaunchRun,\n\tProcessInstance,\n} from \"@leitwerk-dev/domain\";\nimport { SafeLaunchPreparationError } from \"@leitwerk-dev/process-sdk\";\nimport type { RepositoryBundle } from \"./db/repositories.js\";\nimport type { Broadcaster } from \"./ws/broadcast.js\";\n\nconst CORE_STEPS = [\n\t[\"validate_request\", \"Validate launch request\"],\n\t[\"resolve_models_skills\", \"Resolve models and skills\"],\n\t[\"create_process\", \"Create process\"],\n\t[\"choose_title\", \"Choose process title\"],\n\t[\"start_worker\", \"Request worker\"],\n\t[\"connect_worker\", \"Start worker\"],\n\t[\"prepare_workspace\", \"Prepare runtime\"],\n\t[\"start_first_turn\", \"Start first turn\"],\n] as const;\n\nconst STATUS_RANK: Record<LaunchChecklistStepStatus, number> = {\n\tpending: 0,\n\tin_progress: 1,\n\tcompleted: 2,\n\tskipped: 2,\n\tfailed: 2,\n};\n\nexport const STARTUP_STEP_IDS = [\n\t\"start_worker\",\n\t\"connect_worker\",\n\t\"prepare_workspace\",\n\t\"start_first_turn\",\n] as const;\n\n/** @internal */\nexport type LaunchStageFailure<TFailure> = {\n\t/** @internal */\n\tsafeSummary: string;\n\t/** @internal */\n\tvalue: TFailure;\n};\n\n/** @internal */\nexport type LaunchResolution<TResolved, TFailure> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"resolved\";\n\t\t\t/** @internal */\n\t\t\tvalue: TResolved;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"skipped\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"failed\";\n\t\t\t/** @internal */\n\t\t\tfailure: LaunchStageFailure<TFailure>;\n\t };\n\n/** @internal */\nexport interface LaunchPipelineCheck {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\trun(input: {\n\t\t/** @internal */\n\t\tsignal: AbortSignal;\n\t\t/** @internal */\n\t\tlogger: {\n\t\t\t/** @internal */\n\t\t\tinfo(message: string): void;\n\t\t\t/** @internal */\n\t\t\twarn(message: string): void;\n\t\t};\n\t}): Promise<void>;\n}\n\n/** @internal */\nexport type LaunchCommit<TResult, TFailure> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"committed\";\n\t\t\t/** @internal */\n\t\t\tresult: TResult;\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\tstartTurnId: string | null;\n\t\t\t/** @internal */\n\t\t\treused: boolean;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"committed_with_reaction_error\";\n\t\t\t/** @internal */\n\t\t\tresult: TResult;\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\tstartTurnId: string | null;\n\t\t\t/** @internal */\n\t\t\tsafeSummary: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"failed\";\n\t\t\t/** @internal */\n\t\t\tfailure: LaunchStageFailure<TFailure>;\n\t };\n\n/** @internal */\nexport interface LaunchAdapter<TResolved, TPrepared, TResult, TFailure> {\n\t/** @internal */\n\tresolve(): Promise<LaunchResolution<TResolved, TFailure>>;\n\t/** @internal */\n\tpreparationChecks?(resolved: TResolved): readonly LaunchPipelineCheck[];\n\t/** @internal */\n\tpreparationCheckFailure?(error: unknown, safeSummary: string): TFailure;\n\t/** @internal */\n\tprepare(resolved: TResolved): Promise<\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: true;\n\t\t\t\t/** @internal */\n\t\t\t\tvalue: TPrepared;\n\t\t }\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tok: false;\n\t\t\t\t/** @internal */\n\t\t\t\tfailure: LaunchStageFailure<TFailure>;\n\t\t }\n\t>;\n\t/** @internal */\n\tcommit(\n\t\tprepared: TPrepared,\n\t\tctx: {\n\t\t\t/** @internal */\n\t\t\tlaunchRunId: string;\n\t\t},\n\t): Promise<LaunchCommit<TResult, TFailure>>;\n\t/** @internal */\n\tunexpectedFailure?(error: unknown): LaunchStageFailure<TFailure>;\n}\n\n/** @internal */\nexport type LaunchPipelineRunResult<TResult, TFailure> =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"skipped\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"failed\";\n\t\t\t/** @internal */\n\t\t\tfailure: LaunchStageFailure<TFailure>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"committed\" | \"committed_with_reaction_error\";\n\t\t\t/** @internal */\n\t\t\tresult: TResult;\n\t\t\t/** @internal */\n\t\t\tprocess: ProcessInstance;\n\t\t\t/** @internal */\n\t\t\treused: boolean;\n\t };\n\nexport function presentPipelineResult<TResult, TFailure>(\n\tlaunchRunId: string,\n\tresult: LaunchPipelineRunResult<TResult, TFailure>,\n\tskippedError: string | null,\n): { launchRunId: string; process: ProcessInstance | null; error: string | null } {\n\tif (result.kind === \"failed\") {\n\t\treturn { launchRunId, process: null, error: result.failure.safeSummary };\n\t}\n\tif (result.kind === \"skipped\") return { launchRunId, process: null, error: skippedError };\n\treturn {\n\t\tlaunchRunId,\n\t\tprocess: result.process,\n\t\terror:\n\t\t\tresult.kind === \"committed_with_reaction_error\"\n\t\t\t\t? \"Process was created, but the worker could not be started cleanly. Review the process error and retry startup.\"\n\t\t\t\t: null,\n\t};\n}\n\n/** @internal */\nexport interface LaunchPipeline {\n\t/** @internal */\n\topen(input: {\n\t\t/** @internal */\n\t\tlauncherId: string | null;\n\t\t/** @internal */\n\t\tidempotencyKey?: string | null;\n\t\t/** @internal */\n\t\torigin: LaunchRun[\"origin\"];\n\t\t/** @internal */\n\t\tbroadcast?: boolean;\n\t}): {\n\t\t/** @internal */\n\t\tlaunchRunId: string;\n\t\t/** @internal */\n\t\texisting: boolean;\n\t};\n\t/** @internal */\n\tupdate(id: string, fn: (run: LaunchRun) => LaunchRun): LaunchRun;\n\t/** @internal */\n\trun<TResolved, TPrepared, TResult, TFailure>(\n\t\tlaunchRunId: string,\n\t\tadapter: LaunchAdapter<TResolved, TPrepared, TResult, TFailure>,\n\t): Promise<LaunchPipelineRunResult<TResult, TFailure>>;\n}\n\nexport function initialLaunchSteps(): LaunchChecklistStep[] {\n\treturn CORE_STEPS.map(([id, label]) => ({ id, label, status: \"pending\" }));\n}\n\nexport function transitionLaunchStep(\n\trun: LaunchRun,\n\tid: string,\n\tstatus: LaunchChecklistStepStatus,\n\tsafeSummary?: string,\n): LaunchRun {\n\tconst timestamp = new Date().toISOString();\n\treturn {\n\t\t...run,\n\t\tsteps: run.steps.map((item) => {\n\t\t\tif (item.id !== id || STATUS_RANK[status] < STATUS_RANK[item.status]) return item;\n\t\t\tif (STATUS_RANK[status] === STATUS_RANK[item.status] && item.status !== status) return item;\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tstatus,\n\t\t\t\t...(status === \"in_progress\" && !item.startedAt ? { startedAt: timestamp } : {}),\n\t\t\t\t...([\"completed\", \"failed\", \"skipped\"].includes(status) && !item.completedAt\n\t\t\t\t\t? { completedAt: timestamp }\n\t\t\t\t\t: {}),\n\t\t\t\t...(safeSummary ? { safeSummary } : {}),\n\t\t\t};\n\t\t}),\n\t};\n}\n\nexport function finishLaunchRun(run: LaunchRun, status: \"failed\" | \"cancelled\"): LaunchRun {\n\treturn { ...run, status, completedAt: run.completedAt ?? new Date().toISOString() };\n}\n\nexport function failLaunchRun(run: LaunchRun, stepId: string, summary: string): LaunchRun {\n\tconst timestamp = new Date().toISOString();\n\treturn finishLaunchRun(\n\t\t{\n\t\t\t...run,\n\t\t\tsteps: run.steps.map((step) =>\n\t\t\t\tstep.id === stepId\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...step,\n\t\t\t\t\t\t\tstatus: \"failed\" as const,\n\t\t\t\t\t\t\tstartedAt: step.startedAt ?? timestamp,\n\t\t\t\t\t\t\tcompletedAt: step.completedAt ?? timestamp,\n\t\t\t\t\t\t\tsafeSummary: summary,\n\t\t\t\t\t\t}\n\t\t\t\t\t: step,\n\t\t\t),\n\t\t},\n\t\t\"failed\",\n\t);\n}\n\nexport function completeCommittedLaunch(\n\trun: LaunchRun,\n\tprocess: ProcessInstance,\n\tstartTurnId: string | null,\n\ttitleGenerationAvailable: boolean | undefined,\n\treactionError?: string,\n): LaunchRun {\n\tlet next = transitionLaunchStep(run, \"resolve_models_skills\", \"completed\");\n\tnext = transitionLaunchStep(next, \"create_process\", \"completed\");\n\tnext = transitionLaunchStep(\n\t\tnext,\n\t\t\"choose_title\",\n\t\tprocess.title ? \"completed\" : titleGenerationAvailable ? \"in_progress\" : \"skipped\",\n\t);\n\tif (\n\t\t!startTurnId ||\n\t\t(process.selectedTurnId !== null &&\n\t\t\tprocess.lifecycleStatus === \"waiting\" &&\n\t\t\tprocess.currentExecution === null)\n\t) {\n\t\tfor (const id of STARTUP_STEP_IDS) next = transitionLaunchStep(next, id, \"skipped\");\n\t}\n\tnext = { ...next, instanceId: process.id, status: \"starting\" };\n\treturn reactionError\n\t\t? failLaunchRun(next, \"start_worker\", reactionError)\n\t\t: completeLaunchWhenReady(next);\n}\n\nexport function completeLaunchWhenReady(run: LaunchRun): LaunchRun {\n\tif (run.status === \"failed\" || run.status === \"cancelled\") return run;\n\tconst ready = run.steps\n\t\t.filter((item) => [...STARTUP_STEP_IDS, \"choose_title\"].includes(item.id))\n\t\t.every((item) => [\"completed\", \"skipped\", \"failed\"].includes(item.status));\n\treturn ready\n\t\t? { ...run, status: \"completed\", completedAt: run.completedAt ?? new Date().toISOString() }\n\t\t: { ...run, status: \"starting\" };\n}\n\nfunction withChecks(run: LaunchRun, checks: readonly LaunchPipelineCheck[]): LaunchRun {\n\tif (checks.length === 0) return run;\n\treturn {\n\t\t...run,\n\t\tsteps: [\n\t\t\trun.steps[0] as LaunchChecklistStep,\n\t\t\t...checks.map(\n\t\t\t\t(check) =>\n\t\t\t\t\trun.steps.find((item) => item.id === `check:${check.id}`) ?? {\n\t\t\t\t\t\tid: `check:${check.id}`,\n\t\t\t\t\t\tlabel: check.label,\n\t\t\t\t\t\tstatus: \"pending\" as const,\n\t\t\t\t\t},\n\t\t\t),\n\t\t\t...run.steps.slice(1).filter((item) => !item.id.startsWith(\"check:\")),\n\t\t],\n\t};\n}\n\nfunction activeStepId(run: LaunchRun): string {\n\treturn run.steps.find((item) => item.status === \"in_progress\")?.id ?? \"validate_request\";\n}\n\nexport function createLaunchPipeline(deps: {\n\tlaunchRuns: RepositoryBundle[\"launchRuns\"];\n\tbroadcaster: Broadcaster;\n\ttitleGenerationAvailable?: boolean;\n\tlogger?: { info(message: string): void; warn(message: string): void };\n}): LaunchPipeline {\n\tconst logger = deps.logger ?? { info() {}, warn() {} };\n\tfunction broadcast(run: LaunchRun): void {\n\t\tdeps.broadcaster.sendDurable(\n\t\t\t\"launch.updated\",\n\t\t\t{ launchRunId: run.id, instanceId: run.instanceId },\n\t\t\trun.instanceId ?? undefined,\n\t\t);\n\t}\n\tfunction mutate(id: string, fn: (run: LaunchRun) => LaunchRun): LaunchRun {\n\t\tconst run = deps.launchRuns.update(id, fn);\n\t\tif (!run) throw new Error(`Launch run '${id}' does not exist`);\n\t\tbroadcast(run);\n\t\treturn run;\n\t}\n\tfunction fail<T>(id: string, stepId: string, failure: LaunchStageFailure<T>) {\n\t\tmutate(id, (run) => failLaunchRun(run, stepId, failure.safeSummary));\n\t\treturn { kind: \"failed\" as const, failure };\n\t}\n\n\treturn {\n\t\topen(input) {\n\t\t\tconst existing = input.idempotencyKey\n\t\t\t\t? deps.launchRuns.getByIdempotencyKey(input.idempotencyKey)\n\t\t\t\t: null;\n\t\t\tif (existing) return { launchRunId: existing.id, existing: true };\n\t\t\tconst { broadcast: shouldBroadcast = true, ...createInput } = input;\n\t\t\tconst run = deps.launchRuns.create({ ...createInput, steps: initialLaunchSteps() });\n\t\t\tif (shouldBroadcast) broadcast(run);\n\t\t\treturn { launchRunId: run.id, existing: false };\n\t\t},\n\n\t\tupdate: mutate,\n\n\t\tasync run<TResolved, TPrepared, TResult, TFailure>(\n\t\t\tlaunchRunId: string,\n\t\t\tadapter: LaunchAdapter<TResolved, TPrepared, TResult, TFailure>,\n\t\t): Promise<LaunchPipelineRunResult<TResult, TFailure>> {\n\t\t\ttry {\n\t\t\t\tmutate(launchRunId, (run) => transitionLaunchStep(run, \"validate_request\", \"in_progress\"));\n\t\t\t\tconst resolution = await adapter.resolve();\n\t\t\t\tif (resolution.kind === \"skipped\") {\n\t\t\t\t\tmutate(launchRunId, (run) =>\n\t\t\t\t\t\tfinishLaunchRun(transitionLaunchStep(run, \"validate_request\", \"skipped\"), \"cancelled\"),\n\t\t\t\t\t);\n\t\t\t\t\treturn { kind: \"skipped\" };\n\t\t\t\t}\n\t\t\t\tif (resolution.kind === \"failed\")\n\t\t\t\t\treturn fail(launchRunId, \"validate_request\", resolution.failure);\n\t\t\t\tmutate(launchRunId, (run) => transitionLaunchStep(run, \"validate_request\", \"completed\"));\n\n\t\t\t\tconst checks = adapter.preparationChecks?.(resolution.value) ?? [];\n\t\t\t\tmutate(launchRunId, (run) => withChecks(run, checks));\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tfor (const check of checks) {\n\t\t\t\t\tconst id = `check:${check.id}`;\n\t\t\t\t\tmutate(launchRunId, (run) => transitionLaunchStep(run, id, \"in_progress\"));\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait check.run({ signal: controller.signal, logger });\n\t\t\t\t\t\tmutate(launchRunId, (run) => transitionLaunchStep(run, id, \"completed\"));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t\tif (!(error instanceof SafeLaunchPreparationError)) {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Launch preparation failed; correlationId=${launchRunId}; check=${check.id}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst safeSummary =\n\t\t\t\t\t\t\terror instanceof SafeLaunchPreparationError\n\t\t\t\t\t\t\t\t? error.safeSummary\n\t\t\t\t\t\t\t\t: \"The preparation check did not complete. Verify access and try again.\";\n\t\t\t\t\t\treturn fail(launchRunId, id, {\n\t\t\t\t\t\t\tsafeSummary,\n\t\t\t\t\t\t\tvalue: adapter.preparationCheckFailure\n\t\t\t\t\t\t\t\t? adapter.preparationCheckFailure(error, safeSummary)\n\t\t\t\t\t\t\t\t: (error as TFailure),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmutate(launchRunId, (run) =>\n\t\t\t\t\ttransitionLaunchStep(run, \"resolve_models_skills\", \"in_progress\"),\n\t\t\t\t);\n\t\t\t\tconst prepared = await adapter.prepare(resolution.value);\n\t\t\t\tif (!prepared.ok) return fail(launchRunId, \"resolve_models_skills\", prepared.failure);\n\t\t\t\tmutate(launchRunId, (run) => {\n\t\t\t\t\tlet next = transitionLaunchStep(run, \"resolve_models_skills\", \"completed\");\n\t\t\t\t\tnext = transitionLaunchStep(next, \"create_process\", \"in_progress\");\n\t\t\t\t\treturn next;\n\t\t\t\t});\n\t\t\t\tconst committed = await adapter.commit(prepared.value, { launchRunId });\n\t\t\t\tif (committed.kind === \"failed\")\n\t\t\t\t\treturn fail(launchRunId, \"create_process\", committed.failure);\n\t\t\t\tmutate(launchRunId, (run) =>\n\t\t\t\t\tcompleteCommittedLaunch(\n\t\t\t\t\t\trun,\n\t\t\t\t\t\tcommitted.process,\n\t\t\t\t\t\tcommitted.startTurnId,\n\t\t\t\t\t\tdeps.titleGenerationAvailable,\n\t\t\t\t\t\tcommitted.kind === \"committed_with_reaction_error\" ? committed.safeSummary : undefined,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tkind: committed.kind,\n\t\t\t\t\tresult: committed.result,\n\t\t\t\t\tprocess: committed.process,\n\t\t\t\t\treused: committed.kind === \"committed\" ? committed.reused : false,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tlogger.warn(`Unexpected launch failure; correlationId=${launchRunId}`);\n\t\t\t\tconst run = deps.launchRuns.getById(launchRunId);\n\t\t\t\tconst failure = adapter.unexpectedFailure?.(error) ?? {\n\t\t\t\t\tsafeSummary: \"The launch could not be completed. Try again.\",\n\t\t\t\t\tvalue: error as TFailure,\n\t\t\t\t};\n\t\t\t\treturn fail(launchRunId, run ? activeStepId(run) : \"validate_request\", failure);\n\t\t\t} finally {\n\t\t\t\tdeps.launchRuns.deleteReplay(launchRunId);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { type PiResourceBundle, sha256Digest } from \"@leitwerk-dev/worker-protocol\";\nimport { positiveBound as positiveSafeInteger } from \"../model-providers/provider-boundary-utils.js\";\n\nconst DEFAULT_MAX_ENTRIES = 64;\nconst DEFAULT_MAX_BYTES = 256 * 1024 * 1024;\n\ninterface CacheEntry {\n\treadonly digest: string;\n\treadonly bytes: Uint8Array;\n\tpins: number;\n}\n\n/** @internal */\nexport interface PiResourceBundleCacheOptions {\n\t/** @internal */\n\treadonly maxEntries?: number;\n\t/** @internal */\n\treadonly maxBytes?: number;\n}\n\n/** @internal */\nexport interface PiResourceBundleCacheStats {\n\t/** @internal */\n\treadonly entries: number;\n\t/** @internal */\n\treadonly bytes: number;\n\t/** @internal */\n\treadonly pinnedEntries: number;\n\t/** @internal */\n\treadonly pins: number;\n}\n\n/** @internal */\nexport interface PiResourceBundleCacheGcResult {\n\t/** @internal */\n\treadonly removedDigests: readonly string[];\n\t/** @internal */\n\treadonly removedBytes: number;\n}\n\n/** @internal */\nexport interface PiResourceBundleCache {\n\t/** @internal */\n\tput(bundle: PiResourceBundle): void;\n\t/** @internal */\n\tget(digest: string): PiResourceBundle | null;\n\t/** @internal */\n\thas(digest: string): boolean;\n\t/** @internal */\n\tpin(digest: string): boolean;\n\t/** @internal */\n\tunpin(digest: string): boolean;\n\t/** @internal */\n\tgc(): PiResourceBundleCacheGcResult;\n\t/** @internal */\n\tstats(): PiResourceBundleCacheStats;\n}\n\n/** In-memory operational cache. Bundles are immutable copies and pins are reference-counted. @internal */\nexport function createPiResourceBundleCache(\n\toptions: PiResourceBundleCacheOptions = {},\n): PiResourceBundleCache {\n\tconst maxEntries = positiveSafeInteger(options.maxEntries, DEFAULT_MAX_ENTRIES, \"maxEntries\");\n\tconst maxBytes = positiveSafeInteger(options.maxBytes, DEFAULT_MAX_BYTES, \"maxBytes\");\n\tconst entries = new Map<string, CacheEntry>();\n\tlet totalBytes = 0;\n\n\tfunction touch(entry: CacheEntry): void {\n\t\tentries.delete(entry.digest);\n\t\tentries.set(entry.digest, entry);\n\t}\n\n\tfunction oldestUnpinned(excluding?: string): CacheEntry | null {\n\t\tfor (const entry of entries.values()) {\n\t\t\tif (entry.digest !== excluding && entry.pins === 0) return entry;\n\t\t}\n\t\treturn null;\n\t}\n\n\tfunction remove(entry: CacheEntry): void {\n\t\tif (!entries.delete(entry.digest)) return;\n\t\ttotalBytes -= entry.bytes.byteLength;\n\t}\n\n\tfunction enforceBounds(newDigest: string): void {\n\t\twhile (entries.size > maxEntries || totalBytes > maxBytes) {\n\t\t\tconst candidate = oldestUnpinned(newDigest);\n\t\t\tif (!candidate) {\n\t\t\t\tconst inserted = entries.get(newDigest);\n\t\t\t\tif (inserted?.pins === 0) remove(inserted);\n\t\t\t\tthrow new Error(\"Pi resource bundle cache capacity is exhausted by pinned bundles\");\n\t\t\t}\n\t\t\tremove(candidate);\n\t\t}\n\t}\n\n\treturn {\n\t\tput(bundle: PiResourceBundle): void {\n\t\t\tif (typeof bundle.digest !== \"string\" || sha256Digest(bundle.bytes) !== bundle.digest) {\n\t\t\t\tthrow new Error(\"Pi resource bundle digest does not match its bytes\");\n\t\t\t}\n\t\t\tif (bundle.bytes.byteLength > maxBytes) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Pi resource bundle size ${bundle.bytes.byteLength} exceeds cache byte limit ${maxBytes}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst existing = entries.get(bundle.digest);\n\t\t\tif (existing) {\n\t\t\t\ttouch(existing);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst bytes = Uint8Array.from(bundle.bytes);\n\t\t\tconst entry: CacheEntry = {\n\t\t\t\tdigest: bundle.digest,\n\t\t\t\tbytes,\n\t\t\t\tpins: 0,\n\t\t\t};\n\t\t\tentries.set(entry.digest, entry);\n\t\t\ttotalBytes += entry.bytes.byteLength;\n\t\t\tenforceBounds(entry.digest);\n\t\t},\n\n\t\tget(digest: string): PiResourceBundle | null {\n\t\t\tconst entry = entries.get(digest);\n\t\t\tif (!entry) return null;\n\t\t\ttouch(entry);\n\t\t\treturn { digest: entry.digest, bytes: Uint8Array.from(entry.bytes) };\n\t\t},\n\n\t\thas: (digest: string): boolean => entries.has(digest),\n\n\t\tpin(digest: string): boolean {\n\t\t\tconst entry = entries.get(digest);\n\t\t\tif (!entry) return false;\n\t\t\tentry.pins += 1;\n\t\t\ttouch(entry);\n\t\t\treturn true;\n\t\t},\n\n\t\tunpin(digest: string): boolean {\n\t\t\tconst entry = entries.get(digest);\n\t\t\tif (!entry || entry.pins === 0) return false;\n\t\t\tentry.pins -= 1;\n\t\t\ttouch(entry);\n\t\t\treturn true;\n\t\t},\n\n\t\tgc(): PiResourceBundleCacheGcResult {\n\t\t\tconst removed = [...entries.values()].filter((entry) => entry.pins === 0);\n\t\t\tlet removedBytes = 0;\n\t\t\tfor (const entry of removed) {\n\t\t\t\tremovedBytes += entry.bytes.byteLength;\n\t\t\t\tremove(entry);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tremovedDigests: removed.map((entry) => entry.digest),\n\t\t\t\tremovedBytes,\n\t\t\t};\n\t\t},\n\n\t\tstats(): PiResourceBundleCacheStats {\n\t\t\tconst values = [...entries.values()];\n\t\t\treturn {\n\t\t\t\tentries: entries.size,\n\t\t\t\tbytes: totalBytes,\n\t\t\t\tpinnedEntries: values.filter((entry) => entry.pins > 0).length,\n\t\t\t\tpins: values.reduce((total, entry) => total + entry.pins, 0),\n\t\t\t};\n\t\t},\n\t};\n}\n","import type { ProviderCredentialStatus } from \"@leitwerk-dev/process-sdk\";\n\nexport function positiveBound(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved < 1) {\n\t\tthrow new Error(`${name} must be a positive safe integer`);\n\t}\n\treturn resolved;\n}\n\nexport async function withTimeout<T>(\n\twork: Promise<T>,\n\ttimeoutMs: number,\n\tsentinelMessage: string = \"timeout\",\n): Promise<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\treturn await Promise.race([\n\t\t\twork,\n\t\t\tnew Promise<T>((_resolve, reject) => {\n\t\t\t\ttimer = setTimeout(() => reject(new Error(sentinelMessage)), timeoutMs);\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tif (timer) clearTimeout(timer);\n\t}\n}\n\nexport function validateCredentialStatus(\n\tvalue: ProviderCredentialStatus,\n\tmessage: string = \"invalid credential status\",\n): ProviderCredentialStatus {\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\ttypeof value.available !== \"boolean\" ||\n\t\t!(value.revision === null || (Number.isSafeInteger(value.revision) && value.revision >= 0))\n\t) {\n\t\tthrow new Error(message);\n\t}\n\treturn value;\n}\n","import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport type { RepositoryBundle } from \"../db/repositories.js\";\nimport type { PiResourceBundleCache } from \"./bundle-cache.js\";\n\n/** @internal */\nexport interface PiResourceBundlePinReconciler {\n\t/** @internal */\n\treconcile(process: ProcessInstance): {\n\t\t/** @internal */\n\t\tmissingDigest: string | null;\n\t};\n}\n\nfunction pinnedDigest(\n\tprocess: ProcessInstance,\n\tturnStarts: Pick<RepositoryBundle[\"turnStarts\"], \"getById\">,\n\tturnRecords: Pick<RepositoryBundle[\"turnRecords\"], \"getById\">,\n): string | null {\n\tif (process.currentExecution?.kind !== \"worker_start\") return null;\n\tconst start = turnStarts.getById(process.currentExecution.id);\n\tif (!start || start.instanceId !== process.id || start.turnType !== \"llm\") return null;\n\tif (start.state.kind !== \"starting\" && start.state.kind !== \"accepted\") return null;\n\tif (start.state.start.kind !== \"llm\") return null;\n\treturn start.state.kind === \"starting\" ||\n\t\tturnRecords.getById(start.state.turnRecordId)?.status === \"running\"\n\t\t? start.state.start.piResourceSnapshotDigest\n\t\t: null;\n}\n\n/** Keeps only the current live LLM start's resource bundle retained in this server. @internal */\nexport function createPiResourceBundlePinReconciler(\n\tdeps: Pick<RepositoryBundle, \"turnStarts\" | \"turnRecords\"> & {\n\t\t/** @internal */\n\t\tbundleCache: PiResourceBundleCache;\n\t},\n): PiResourceBundlePinReconciler {\n\tconst pinnedByInstance = new Map<string, string>();\n\n\treturn {\n\t\treconcile(process) {\n\t\t\tconst next = pinnedDigest(process, deps.turnStarts, deps.turnRecords);\n\t\t\tconst previous = pinnedByInstance.get(process.id) ?? null;\n\t\t\tif (previous === next) {\n\t\t\t\treturn { missingDigest: next && !deps.bundleCache.has(next) ? next : null };\n\t\t\t}\n\t\t\tif (previous) deps.bundleCache.unpin(previous);\n\t\t\tpinnedByInstance.delete(process.id);\n\t\t\tif (!next) {\n\t\t\t\treturn { missingDigest: null };\n\t\t\t}\n\t\t\tif (!deps.bundleCache.pin(next)) {\n\t\t\t\treturn { missingDigest: next };\n\t\t\t}\n\t\t\tpinnedByInstance.set(process.id, next);\n\t\t\treturn { missingDigest: null };\n\t\t},\n\t};\n}\n","import { lstat, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { CatalogPiContribution } from \"@leitwerk-dev/extension-runtime\";\nimport {\n\tcanonicalizeJson,\n\tcanonicalJsonStringify,\n\tcreateCanonicalPiResourceBundle,\n\tPI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,\n\ttype PiResourceBundle,\n\ttype PiResourceManifest,\n\ttype PiResourceSnapshotCompatibility,\n\ttype PiResourceSnapshotModel,\n\ttype PiResourceSnapshotWorkerConfig,\n\tsha256Digest,\n\tvalidateResourceRelativePath,\n} from \"@leitwerk-dev/worker-protocol\";\nimport { build } from \"esbuild\";\nimport {\n\tcompareResourcePaths,\n\ttype PiResourceLayer,\n\ttype PiResourceLimits,\n\tResourceCollector,\n\tvalidatePhysicalSourcePath,\n} from \"./resource-collector.js\";\n\nexport {\n\tPI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,\n\ttype PiResourceFileProvenance,\n\ttype PiResourceProvenanceKind,\n\ttype PiResourceSnapshotCompatibility,\n\ttype PiResourceSnapshotModel,\n\ttype PiResourceSnapshotWorkerConfig,\n} from \"@leitwerk-dev/worker-protocol\";\n\n/** @internal */\ntype JsonObject = Record<string, unknown>;\n\n/** @internal */\nexport type PiResourceAssemblyLimits = PiResourceLimits;\n\n/** @internal */\nexport interface AssemblePiResourceSnapshotInput {\n\t/** Immutable resource fragments pinned to the process. @internal */\n\treadonly resourceLayers?: readonly PiResourceLayer[];\n\t/** Catalog dependency order is preserved in generated numeric extension paths. @internal */\n\treadonly piContributions: readonly CatalogPiContribution[];\n\t/** @internal */\n\treadonly model: PiResourceSnapshotModel;\n\t/** @internal */\n\treadonly providerOptions: Readonly<Record<string, string>>;\n\t/** @internal */\n\treadonly providerWorkerConfig: PiResourceSnapshotWorkerConfig | null;\n\t/** @internal */\n\treadonly piSettings: JsonObject;\n\t/** Non-secret Pi model definitions and overrides. Defaults to an empty provider map. @internal */\n\treadonly piModels?: JsonObject;\n\t/** @internal */\n\treadonly declaredCredentialPaths: readonly string[];\n\t/** @internal */\n\treadonly compatibility: PiResourceSnapshotCompatibility;\n\t/** @internal */\n\treadonly systemPrompt?: string | null;\n\t/** @internal */\n\treadonly appendSystemPrompt?: string | null;\n\t/** @internal */\n\treadonly limits?: PiResourceAssemblyLimits;\n}\n\n/** @internal */\nexport type PiResourceGeneratedMetadata = PiResourceManifest;\n\n/** @internal */\nexport interface AssembledPiResourceSnapshot {\n\t/** @internal */\n\treadonly bundle: PiResourceBundle;\n\t/** @internal */\n\treadonly generated: PiResourceGeneratedMetadata;\n\t/** @internal */\n\treadonly files: readonly {\n\t\t/** @internal */\n\t\treadonly path: string;\n\t\t/** @internal */\n\t\treadonly sha256: string;\n\t\t/** @internal */\n\t\treadonly size: number;\n\t}[];\n}\n\nfunction jsonBytes(value: unknown, location: string): Uint8Array {\n\treturn Buffer.from(`${canonicalJsonStringify(value, location)}\\n`, \"utf8\");\n}\n\nconst FORBIDDEN_SECRET_KEYS = new Set([\n\t\"apikey\",\n\t\"accesstoken\",\n\t\"refreshtoken\",\n\t\"brokertoken\",\n\t\"clientsecret\",\n\t\"privatekey\",\n\t\"password\",\n\t\"secret\",\n\t\"authorization\",\n]);\n\nfunction assertNoCredentialFields(value: unknown, location: string): void {\n\tif (Array.isArray(value)) {\n\t\tvalue.forEach((item, index) => {\n\t\t\tassertNoCredentialFields(item, `${location}[${index}]`);\n\t\t});\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null) return;\n\tfor (const [key, nested] of Object.entries(value)) {\n\t\tconst normalizedKey = key.toLowerCase().replaceAll(/[^a-z0-9]/g, \"\");\n\t\tif (FORBIDDEN_SECRET_KEYS.has(normalizedKey)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${location}.${key} is credential-bearing and cannot enter a Pi resource snapshot`,\n\t\t\t);\n\t\t}\n\t\tassertNoCredentialFields(nested, `${location}.${key}`);\n\t}\n}\n\nfunction safeExtensionSegment(ownerExtensionId: string): string {\n\tconst normalized =\n\t\townerExtensionId\n\t\t\t.normalize(\"NFKD\")\n\t\t\t.replaceAll(/[^A-Za-z0-9._-]+/g, \"-\")\n\t\t\t.replaceAll(/^-+|-+$/g, \"\") || \"extension\";\n\tif (Buffer.byteLength(normalized, \"utf8\") <= 56) return normalized;\n\treturn `${normalized.slice(0, 43)}-${sha256Digest(Buffer.from(ownerExtensionId)).slice(0, 12)}`;\n}\n\nfunction extensionSnapshotPath(contribution: CatalogPiContribution, index: number): string {\n\tconst prefix = String(index * 10).padStart(3, \"0\");\n\treturn validateResourceRelativePath(\n\t\t`extensions/${prefix}-${safeExtensionSegment(contribution.ownerExtensionId)}.js`,\n\t);\n}\n\nconst PI_CORE_EXTERNALS = [\"@earendil-works/pi-ai\", \"@earendil-works/pi-coding-agent\"];\n\n/**\n * Builds a normal Pi extension around a Leitwerk contribution. The contribution is\n * bundled so its relative imports survive snapshot materialization; Pi itself stays\n * external so it is shared with the worker image.\n */\nasync function buildPiExtensionWrapper(entryPath: string): Promise<Uint8Array> {\n\tconst result = await build({\n\t\tabsWorkingDir: path.dirname(entryPath),\n\t\tbundle: true,\n\t\tstdin: {\n\t\t\tcontents: `\nimport contribution from ${JSON.stringify(entryPath)};\nimport { readFileSync } from \"node:fs\";\n\nfunction readGenerated() {\n return JSON.parse(readFileSync(new URL(\"../generated.json\", import.meta.url), \"utf8\"));\n}\n\nfunction credentialBag(generated) {\n let values;\n const load = () => {\n if (values) return values;\n values = {};\n for (const credentialPath of generated.declaredCredentialPaths) {\n if (typeof credentialPath !== \"string\" || credentialPath.startsWith(\"/\") || credentialPath.includes(\"..\") || credentialPath.includes(\"\\\\\\\\\")) {\n throw new Error(\"Invalid declared Pi credential path\");\n }\n const credential = JSON.parse(readFileSync(new URL(\"../\" + credentialPath, import.meta.url), \"utf8\"));\n if (credential && typeof credential === \"object\" && !Array.isArray(credential)) Object.assign(values, credential);\n }\n return values;\n };\n return {\n get(key) { const value = load()[key]; return typeof value === \"string\" ? value : undefined; },\n require(key) { const value = this.get(key); if (value === undefined) throw new Error(\"Required Pi worker secret '\" + key + \"' is unavailable\"); return value; },\n keys() { return Object.keys(load()).filter((key) => typeof load()[key] === \"string\").sort(); },\n };\n}\n\nexport default async function leitwerkPiExtension(pi) {\n if (typeof contribution !== \"function\") throw new Error(\"Leitwerk Pi worker entry must default-export a function\");\n const generated = readGenerated();\n const workerConfig = generated.providerWorkerConfig === null ? null : generated.providerWorkerConfig?.value;\n const report = (event) => {\n if (!event || typeof event !== \"object\" || Array.isArray(event)) throw new Error(\"Pi worker report must be an object\");\n pi.events?.emit?.(\"leitwerk:provider-report\", event);\n };\n await contribution(pi, {\n model: { providerId: generated.model.providerId, modelId: generated.model.modelId },\n options: { ...generated.providerOptions },\n workerConfig,\n secrets: credentialBag(generated),\n report,\n });\n}\n`,\n\t\t\tresolveDir: path.dirname(entryPath),\n\t\t\tsourcefile: \"leitwerk-pi-wrapper.js\",\n\t\t},\n\t\tformat: \"esm\",\n\t\tplatform: \"node\",\n\t\ttarget: \"node22\",\n\t\twrite: false,\n\t\tminify: true,\n\t\tsourcemap: false,\n\t\tlegalComments: \"none\",\n\t\texternal: PI_CORE_EXTERNALS,\n\t});\n\tconst output = result.outputFiles[0];\n\tif (!output) throw new Error(`Pi extension wrapper did not produce output for '${entryPath}'`);\n\treturn output.contents;\n}\n\nfunction normalizeCredentialPaths(paths: readonly string[]): readonly string[] {\n\tconst seen = new Set<string>();\n\tconst normalized = paths.map((credentialPath) => {\n\t\tconst result = validateResourceRelativePath(credentialPath);\n\t\tif (seen.has(result)) throw new Error(`Duplicate declared credential path '${result}'`);\n\t\tseen.add(result);\n\t\treturn result;\n\t});\n\treturn normalized.sort(compareResourcePaths);\n}\n\nfunction assertCredentialPathsDoNotOverlap(\n\tcredentialPaths: readonly string[],\n\timmutablePaths: Iterable<string>,\n): void {\n\tconst files = [...immutablePaths];\n\tfor (const credentialPath of credentialPaths) {\n\t\tfor (const immutablePath of files) {\n\t\t\tif (\n\t\t\t\tcredentialPath === immutablePath ||\n\t\t\t\tcredentialPath.startsWith(`${immutablePath}/`) ||\n\t\t\t\timmutablePath.startsWith(`${credentialPath}/`)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Declared credential path '${credentialPath}' overlaps immutable resource '${immutablePath}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction requireNonEmptyString(value: unknown, location: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tthrow new Error(`${location} must be a non-empty string`);\n\t}\n}\n\nfunction validateAssemblyInput(input: AssemblePiResourceSnapshotInput): void {\n\trequireNonEmptyString(input.model.profileId, \"model.profileId\");\n\trequireNonEmptyString(input.model.providerId, \"model.providerId\");\n\trequireNonEmptyString(input.model.modelId, \"model.modelId\");\n\trequireNonEmptyString(input.model.thinkingLevel, \"model.thinkingLevel\");\n\trequireNonEmptyString(input.compatibility.workerApiVersion, \"compatibility.workerApiVersion\");\n\trequireNonEmptyString(input.compatibility.piVersion, \"compatibility.piVersion\");\n\tif (input.compatibility.protocolVersion !== undefined) {\n\t\trequireNonEmptyString(input.compatibility.protocolVersion, \"compatibility.protocolVersion\");\n\t}\n\tfor (const [fieldId, value] of Object.entries(input.providerOptions)) {\n\t\tif (fieldId.trim() === \"\" || typeof value !== \"string\") {\n\t\t\tthrow new Error(\"providerOptions must contain non-empty field ids and string values\");\n\t\t}\n\t}\n\tif (\n\t\tinput.providerWorkerConfig &&\n\t\t(!Number.isSafeInteger(input.providerWorkerConfig.version) ||\n\t\t\tinput.providerWorkerConfig.version < 1)\n\t) {\n\t\tthrow new Error(\"providerWorkerConfig.version must be a positive safe integer\");\n\t}\n\tif (input.systemPrompt !== undefined && input.systemPrompt !== null) {\n\t\tif (typeof input.systemPrompt !== \"string\") throw new Error(\"systemPrompt must be a string\");\n\t}\n\tif (input.appendSystemPrompt !== undefined && input.appendSystemPrompt !== null) {\n\t\tif (typeof input.appendSystemPrompt !== \"string\") {\n\t\t\tthrow new Error(\"appendSystemPrompt must be a string\");\n\t\t}\n\t}\n}\n\n/** Assemble one immutable, non-secret, canonical Pi resource snapshot. @internal */\nexport async function assemblePiResourceSnapshot(\n\tinput: AssemblePiResourceSnapshotInput,\n): Promise<AssembledPiResourceSnapshot> {\n\tvalidateAssemblyInput(input);\n\tassertNoCredentialFields(input.piSettings, \"piSettings\");\n\tassertNoCredentialFields(input.piModels ?? {}, \"piModels\");\n\tassertNoCredentialFields(input.providerOptions, \"providerOptions\");\n\tassertNoCredentialFields(input.providerWorkerConfig?.value ?? {}, \"providerWorkerConfig.value\");\n\tconst collector = new ResourceCollector(input.limits);\n\tconst seenOwners = new Set<string>();\n\tconst workerSourceIdentities = new Map<string, string>();\n\tconst workerSourceRealPaths = new Map<string, string>();\n\n\tconst settings = { ...input.piSettings, packages: [], defaultProjectTrust: \"never\" };\n\tcollector.addBytes(\"settings.json\", jsonBytes(settings, \"settings.json\"));\n\tcollector.addBytes(\"models.json\", jsonBytes(input.piModels ?? { providers: {} }, \"models.json\"));\n\tif (input.systemPrompt !== undefined && input.systemPrompt !== null) {\n\t\tcollector.addBytes(\"SYSTEM.md\", Buffer.from(input.systemPrompt, \"utf8\"));\n\t}\n\tif (input.appendSystemPrompt !== undefined && input.appendSystemPrompt !== null) {\n\t\tcollector.addBytes(\"APPEND_SYSTEM.md\", Buffer.from(input.appendSystemPrompt, \"utf8\"));\n\t}\n\n\tfor (const layer of input.resourceLayers ?? []) collector.addBundle(layer.bundle, layer.owner);\n\n\tfor (const [index, contribution] of input.piContributions.entries()) {\n\t\tif (seenOwners.has(contribution.ownerExtensionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Extension '${contribution.ownerExtensionId}' appears more than once in Pi contributions`,\n\t\t\t);\n\t\t}\n\t\tseenOwners.add(contribution.ownerExtensionId);\n\t\tconst baseOwner = {\n\t\t\townerExtensionId: contribution.ownerExtensionId,\n\t\t\tpackageName: contribution.packageName,\n\t\t};\n\t\tif (contribution.workerEntryPath) {\n\t\t\tvalidatePhysicalSourcePath(contribution.workerEntryPath);\n\t\t\tconst source = await lstat(contribution.workerEntryPath);\n\t\t\tif (source.isSymbolicLink() || !source.isFile()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Pi resource source must be a regular file: ${contribution.workerEntryPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst identity = `${source.dev}:${source.ino}`;\n\t\t\tconst physicalPath = await realpath(contribution.workerEntryPath);\n\t\t\tconst first = workerSourceIdentities.get(identity) ?? workerSourceRealPaths.get(physicalPath);\n\t\t\tif (first) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Physical Pi resource file is included more than once: ${contribution.workerEntryPath} (first: ${first})`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tworkerSourceIdentities.set(identity, contribution.workerEntryPath);\n\t\t\tworkerSourceRealPaths.set(physicalPath, contribution.workerEntryPath);\n\t\t\tconst snapshotPath = extensionSnapshotPath(contribution, index);\n\t\t\tcollector.addBytes(\n\t\t\t\tsnapshotPath,\n\t\t\t\tawait buildPiExtensionWrapper(contribution.workerEntryPath),\n\t\t\t\t{ kind: \"extension\", ...baseOwner },\n\t\t\t);\n\t\t}\n\t\tfor (const skillDirectory of contribution.resources.skillDirectories) {\n\t\t\tawait collector.addDirectory(skillDirectory, \"skills\", { kind: \"skill\", ...baseOwner });\n\t\t}\n\t\tfor (const promptDirectory of contribution.resources.promptDirectories) {\n\t\t\tawait collector.addDirectory(promptDirectory, \"prompts\", { kind: \"prompt\", ...baseOwner });\n\t\t}\n\t}\n\n\tconst credentialPaths = normalizeCredentialPaths(input.declaredCredentialPaths);\n\tassertCredentialPathsDoNotOverlap(credentialPaths, [...collector.files.keys(), \"generated.json\"]);\n\tconst provenance = collector.provenance\n\t\t.slice()\n\t\t.sort((left, right) => compareResourcePaths(left.snapshotPath, right.snapshotPath));\n\tconst generated = {\n\t\tschemaVersion: PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,\n\t\tmodel: { ...input.model },\n\t\tproviderOptions: { ...input.providerOptions },\n\t\tproviderWorkerConfig: input.providerWorkerConfig\n\t\t\t? {\n\t\t\t\t\tversion: input.providerWorkerConfig.version,\n\t\t\t\t\tvalue: canonicalizeJson(\n\t\t\t\t\t\tinput.providerWorkerConfig.value,\n\t\t\t\t\t\t\"providerWorkerConfig.value\",\n\t\t\t\t\t) as JsonObject,\n\t\t\t\t}\n\t\t\t: null,\n\t\tdeclaredCredentialPaths: credentialPaths,\n\t\tcompatibility: { ...input.compatibility },\n\t\tprovenance,\n\t} satisfies PiResourceGeneratedMetadata;\n\tcollector.addBytes(\"generated.json\", jsonBytes(generated, \"generated.json\"));\n\n\tconst resourceFiles = collector.toResourceFiles();\n\tconst bundle = createCanonicalPiResourceBundle(resourceFiles);\n\treturn {\n\t\tbundle,\n\t\tgenerated,\n\t\tfiles: collector.provenance\n\t\t\t.map(({ snapshotPath, sha256, size }) => ({ path: snapshotPath, sha256, size }))\n\t\t\t.sort((left, right) => compareResourcePaths(left.path, right.path)),\n\t};\n}\n","import { type ProcessInstance, trimToNull } from \"@leitwerk-dev/domain\";\nimport { isHumanTurnDefinition } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tcreateEphemeralWsFrame,\n\tWS_PROCESS_TYPES,\n\ttype WsPayloadByType,\n} from \"@leitwerk-dev/protocol\";\nimport type { ProcessSelectedTurnSummary } from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { RepositoryBundle } from \"./db/repositories.js\";\nimport type {\n\tProcessActionRegistry,\n\tVisibleProcessActionSummary,\n} from \"./process-action-registry.js\";\nimport { resolveCurrentExecutionTurnRecordId } from \"./process-execution.js\";\nimport type { ProcessGraphRegistry } from \"./process-graph.js\";\nimport type { Broadcaster } from \"./ws/broadcast.js\";\n\nexport interface ProcessOperatorAttentionDeps\n\textends Pick<RepositoryBundle, \"projects\" | \"futureExecutions\" | \"turnRecords\" | \"turnStarts\"> {\n\tprocessGraphs: ProcessGraphRegistry;\n\tprocessActionRegistry?: ProcessActionRegistry;\n}\n\nexport interface AttentionToastBroadcastDeps extends ProcessOperatorAttentionDeps {\n\tbroadcaster: Broadcaster;\n\ttoastTtlMs?: number;\n}\n\nexport type AttentionToastKind = \"action_required\" | \"error\";\n\ntype ProcessToastFramePayload = WsPayloadByType[typeof WS_PROCESS_TYPES.TOAST];\n\nexport function getProcessDisplayName(\n\tdeps: Pick<ProcessOperatorAttentionDeps, \"processActionRegistry\">,\n\tprocessId: string,\n): string | null {\n\treturn deps.processActionRegistry?.getProcessDisplayName(processId) ?? null;\n}\n\nexport function listCurrentVisibleActions(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): VisibleProcessActionSummary[] {\n\tif (!deps.processActionRegistry) {\n\t\treturn [];\n\t}\n\tconst projects = deps.projects.listByInstance(process.id);\n\tconst { params, state } = deps.processActionRegistry.resolveContextData(\n\t\tprocess.processId,\n\t\tprocess,\n\t);\n\tconst ctx = {\n\t\tprocess,\n\t\tprojects,\n\t\tparams,\n\t\tstate,\n\t\tasync transition() {},\n\t\temitEvent() {},\n\t\treadSemanticTurnResultMarkdown() {\n\t\t\treturn null;\n\t\t},\n\t\treadProductTurnResultMarkdown() {\n\t\t\treturn null;\n\t\t},\n\t\tqueueInput() {},\n\t};\n\treturn deps.processActionRegistry.listVisibleActions(process.processId, ctx);\n}\n\nexport function listVisibleActionsForProcess(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): VisibleProcessActionSummary[] {\n\tif (!deps.processActionRegistry) {\n\t\treturn [];\n\t}\n\tif (\n\t\tprocess.lifecycleStatus !== \"waiting\" ||\n\t\tdeps.futureExecutions.getScheduledActionByInstance(process.id)\n\t) {\n\t\treturn [];\n\t}\n\treturn listCurrentVisibleActions(deps, process);\n}\n\nexport function getSelectedTurnSummaryForProcess(\n\tdeps: Pick<ProcessOperatorAttentionDeps, \"processActionRegistry\" | \"projects\">,\n\tprocess: ProcessInstance,\n): ProcessSelectedTurnSummary | null {\n\tif (!deps.processActionRegistry) {\n\t\treturn null;\n\t}\n\treturn deps.processActionRegistry.getSelectedTurnSummary(\n\t\tprocess.processId,\n\t\tprocess,\n\t\tdeps.projects.listByInstance(process.id),\n\t);\n}\n\nfunction getSelectedTurnDescription(\n\tdeps: Pick<ProcessOperatorAttentionDeps, \"processActionRegistry\" | \"projects\">,\n\tprocess: ProcessInstance,\n): string {\n\tconst selectedTurnSummary = getSelectedTurnSummaryForProcess(deps, process);\n\tif (selectedTurnSummary?.description) {\n\t\treturn selectedTurnSummary.description;\n\t}\n\tconst selectedTurnId = trimToNull(process.selectedTurnId);\n\tif (\n\t\tselectedTurnId &&\n\t\tdeps.processActionRegistry?.getTurnDefinition(process.processId, selectedTurnId)?.description\n\t) {\n\t\treturn (\n\t\t\tdeps.processActionRegistry.getTurnDefinition(process.processId, selectedTurnId)\n\t\t\t\t?.description ?? selectedTurnId\n\t\t);\n\t}\n\treturn selectedTurnId ?? \"Current step\";\n}\n\nfunction getProcessAttentionLabel(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): string {\n\treturn (\n\t\ttrimToNull(process.title) ??\n\t\ttrimToNull(process.externalId) ??\n\t\ttrimToNull(getProcessDisplayName(deps, process.processId)) ??\n\t\tprocess.processId\n\t);\n}\n\nfunction selectedTurnRequiresActionAttention(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): boolean {\n\tif (!process.selectedTurnId) {\n\t\treturn true;\n\t}\n\tconst turnDef = deps.processActionRegistry?.getTurnDefinition(\n\t\tprocess.processId,\n\t\tprocess.selectedTurnId,\n\t);\n\treturn !turnDef || !isHumanTurnDefinition(turnDef) || turnDef.operatorAttention !== \"passive\";\n}\n\nfunction buildActionRequiredToast(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): Omit<ProcessToastFramePayload, \"instanceId\" | \"ttlMs\"> | null {\n\tif (process.lifecycleStatus !== \"waiting\") {\n\t\treturn null;\n\t}\n\tif (!selectedTurnRequiresActionAttention(deps, process)) {\n\t\treturn null;\n\t}\n\tconst actions = listVisibleActionsForProcess(deps, process);\n\tif (actions.length === 0) {\n\t\treturn null;\n\t}\n\tconst processLabel = getProcessAttentionLabel(deps, process);\n\tconst turnDescription = getSelectedTurnDescription(deps, process);\n\treturn {\n\t\tlevel: \"warn\",\n\t\teventType: \"action_required\",\n\t\tmessage: `${processLabel} · ${turnDescription} needs a decision`,\n\t\tdedupeKey: `${process.id}:action_required:${process.selectedTurnId ?? \"none\"}`,\n\t};\n}\n\nfunction buildErrorAttentionToast(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n\tinput: { errorCode?: string | null } = {},\n): Omit<ProcessToastFramePayload, \"instanceId\" | \"ttlMs\"> | null {\n\tif (process.lifecycleStatus !== \"error\") {\n\t\treturn null;\n\t}\n\tconst processLabel = getProcessAttentionLabel(deps, process);\n\tconst turnDescription = getSelectedTurnDescription(deps, process);\n\tconst currentTurnRecordId = resolveCurrentExecutionTurnRecordId(process, deps.turnStarts);\n\tconst failedTurnRecord = currentTurnRecordId\n\t\t? deps.turnRecords.getById(currentTurnRecordId)\n\t\t: null;\n\tif (failedTurnRecord?.instanceId === process.id && failedTurnRecord.status === \"failed\") {\n\t\treturn {\n\t\t\tlevel: \"error\",\n\t\t\teventType: \"turn_failed\",\n\t\t\tmessage: `${processLabel} · ${turnDescription} failed and needs recovery`,\n\t\t\tdedupeKey: `${process.id}:turn_failed:${failedTurnRecord.id}`,\n\t\t};\n\t}\n\treturn {\n\t\tlevel: \"error\",\n\t\teventType: \"worker_failed\",\n\t\tmessage: `${processLabel} · ${turnDescription} needs attention`,\n\t\tdedupeKey: `${process.id}:worker_failed:${process.selectedTurnId ?? \"none\"}:${input.errorCode ?? \"unknown\"}`,\n\t};\n}\n\nexport function buildProcessAttentionToast(\n\tdeps: ProcessOperatorAttentionDeps,\n\tinput: {\n\t\tprocess: ProcessInstance;\n\t\tkind: AttentionToastKind;\n\t\terrorCode?: string | null;\n\t},\n): Omit<ProcessToastFramePayload, \"instanceId\" | \"ttlMs\"> | null {\n\tif (input.kind === \"action_required\") {\n\t\treturn buildActionRequiredToast(deps, input.process);\n\t}\n\treturn buildErrorAttentionToast(deps, input.process, { errorCode: input.errorCode });\n}\n\nexport function broadcastProcessAttentionToast(\n\tdeps: AttentionToastBroadcastDeps,\n\tinput: {\n\t\tprocess: ProcessInstance;\n\t\tkind: AttentionToastKind;\n\t\terrorCode?: string | null;\n\t},\n): boolean {\n\tconst toast = buildProcessAttentionToast(deps, input);\n\tif (!toast) {\n\t\treturn false;\n\t}\n\tconst payload: ProcessToastFramePayload = {\n\t\tinstanceId: input.process.id,\n\t\t...toast,\n\t\tttlMs: deps.toastTtlMs ?? 6_000,\n\t};\n\tdeps.broadcaster.broadcast(\n\t\tcreateEphemeralWsFrame({\n\t\t\ttype: WS_PROCESS_TYPES.TOAST,\n\t\t\tpayload,\n\t\t\tinstanceId: input.process.id,\n\t\t}),\n\t);\n\treturn true;\n}\n","import type { ProcessInstance, TurnStartRecord } from \"@leitwerk-dev/domain\";\n\nexport function resolveCurrentExecutionTurnRecordId(\n\tprocess: Pick<ProcessInstance, \"currentExecution\"> | null | undefined,\n\tturnStarts: { getById(id: string): TurnStartRecord | null },\n): string | null {\n\tif (process?.currentExecution?.kind !== \"worker_start\") return null;\n\tconst start = turnStarts.getById(process.currentExecution.id);\n\treturn start?.state.kind === \"accepted\" ? start.state.turnRecordId : null;\n}\n","import type { ResolvedWorkerImage } from \"@leitwerk-dev/worker-runners/types\";\nimport type { LeitwerkConfig, WorkerRuntimeProfileConfig } from \"./config/config-types.js\";\n\n/**\n * Per-component runtime profile selection input. `profile` is the component's\n * configured `worker_runtime_profile`, or `undefined` when it declares none.\n */\n/** @internal */\nexport interface ComponentRuntimeProfileSelection {\n\t/** @internal */\n\tcomponent: string;\n\t/** @internal */\n\tprofile?: string;\n}\n\n/** @internal */\nexport interface RuntimeProfileSelectionInput {\n\t/** @internal */\n\tprocessId: string;\n\t/** `process_configs.<processId>.worker_runtime_profile`, if set. @internal */\n\tprocessOverride?: string;\n\t/** Per-component profile selections for the process's projects. @internal */\n\tcomponentProfiles: ComponentRuntimeProfileSelection[];\n\t/** Runner-specific default profile (`kubernetes.default_worker_runtime_profile` wins in Kubernetes mode). @internal */\n\tdefaultProfile?: string;\n\t/** Configured `worker_runtime_profiles` keyed by id. @internal */\n\tprofiles: Record<string, WorkerRuntimeProfileConfig>;\n}\n\n/** @internal */\nexport type RuntimeProfileSelectionResult =\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: true;\n\t\t\t/** @internal */\n\t\t\truntimeProfile: string;\n\t\t\t/** @internal */\n\t\t\timage: ResolvedWorkerImage;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tok: false;\n\t\t\t/** @internal */\n\t\t\terror: string;\n\t };\n\nfunction trimToUndefined(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") {\n\t\treturn undefined;\n\t}\n\tconst trimmed = value.trim();\n\treturn trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function defaultWorkerRuntimeProfile(config: LeitwerkConfig): string | null {\n\tif (config.workers.runner === \"local\") {\n\t\treturn config.workers.default_runtime_profile ?? \"local\";\n\t}\n\treturn (\n\t\t(config.workers.runner === \"kubernetes\"\n\t\t\t? config.kubernetes?.default_worker_runtime_profile\n\t\t\t: undefined) ??\n\t\tconfig.workers.default_runtime_profile ??\n\t\tnull\n\t);\n}\n\n/**\n * Selects the worker runtime profile for a process.\n *\n * Precedence (matching the Kubernetes plan so both runners agree):\n * 1. Process-level override wins.\n * 2. Otherwise inspect component profiles:\n * - none declared → fall back to the configured default.\n * - all components agree on one profile → use it.\n * - components disagree → reject before the worker starts.\n * 3. The resolved profile id must exist in `worker_runtime_profiles`.\n *\n * Repository branch content never reaches this function; image authority lives\n * entirely in leitwerk config.\n */\n/** @internal */\nexport function selectWorkerRuntimeProfile(\n\tinput: RuntimeProfileSelectionInput,\n): RuntimeProfileSelectionResult {\n\tconst override = trimToUndefined(input.processOverride);\n\tif (override) {\n\t\treturn resolveProfileImage(override, input.profiles);\n\t}\n\n\tconst declared = input.componentProfiles\n\t\t.map((entry) => ({ component: entry.component, profile: trimToUndefined(entry.profile) }))\n\t\t.filter(\n\t\t\t(entry): entry is { component: string; profile: string } => entry.profile !== undefined,\n\t\t);\n\n\tconst distinct = new Set(declared.map((entry) => entry.profile));\n\tif (distinct.size > 1) {\n\t\tconst summary = declared\n\t\t\t.map((entry) => `${entry.component}=${entry.profile}`)\n\t\t\t.sort()\n\t\t\t.join(\", \");\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Process '${input.processId}' has conflicting component worker runtime profiles (${summary}); set process_configs.${input.processId}.worker_runtime_profile to resolve`,\n\t\t};\n\t}\n\n\tif (distinct.size === 1) {\n\t\tconst [only] = distinct;\n\t\treturn resolveProfileImage(only, input.profiles);\n\t}\n\n\tconst fallback = trimToUndefined(input.defaultProfile);\n\tif (!fallback) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Process '${input.processId}' selects no worker runtime profile and no default worker runtime profile is configured`,\n\t\t};\n\t}\n\treturn resolveProfileImage(fallback, input.profiles);\n}\n\nfunction resolveProfileImage(\n\truntimeProfile: string,\n\tprofiles: Record<string, WorkerRuntimeProfileConfig>,\n): RuntimeProfileSelectionResult {\n\tconst profile = profiles[runtimeProfile];\n\tif (!profile) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Unknown worker runtime profile '${runtimeProfile}'; configure it under worker_runtime_profiles`,\n\t\t};\n\t}\n\treturn {\n\t\tok: true,\n\t\truntimeProfile,\n\t\timage: { reference: profile.image },\n\t};\n}\n\n/**\n * Builds {@link RuntimeProfileSelectionInput} from leitwerk config for a\n * process and the components it spans.\n */\n/** @internal */\nexport function buildRuntimeProfileSelectionInput(args: {\n\t/** @internal */\n\tconfig: LeitwerkConfig;\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tcomponentKeys: string[];\n\t/** The registered process definition requires Docker. @internal */\n\tdocker?: boolean;\n}): RuntimeProfileSelectionInput {\n\tconst { config, processId, componentKeys } = args;\n\tconst componentProfiles: ComponentRuntimeProfileSelection[] = componentKeys.map((component) => ({\n\t\tcomponent,\n\t\tprofile: config.components[component]?.worker_runtime_profile,\n\t}));\n\treturn {\n\t\tprocessId,\n\t\tprocessOverride: config.process_configs?.[processId]?.worker_runtime_profile,\n\t\tcomponentProfiles,\n\t\tdefaultProfile:\n\t\t\t(config.workers.runner === \"kubernetes\" && args.docker\n\t\t\t\t? config.kubernetes?.docker?.worker_runtime_profile\n\t\t\t\t: undefined) ??\n\t\t\tdefaultWorkerRuntimeProfile(config) ??\n\t\t\tundefined,\n\t\tprofiles: config.worker_runtime_profiles ?? {},\n\t};\n}\n","import { VERSION as PI_RUNTIME_VERSION } from \"@earendil-works/pi-coding-agent\";\nimport type {\n\tProcessInstance,\n\tResolvedTurnStart,\n\tTurnStartRecordState,\n} from \"@leitwerk-dev/domain\";\nimport { resolveOutcomeContract } from \"@leitwerk-dev/process-sdk\";\nimport { IPC_PROTOCOL_VERSION, WORKER_API_VERSION } from \"@leitwerk-dev/worker-protocol\";\nimport type { LeitwerkConfig } from \"../config/config-types.js\";\nimport type { RepositoryBundle } from \"../db/repositories.js\";\nimport type {\n\tModelStatusCache,\n\tModelStatusCacheSnapshot,\n} from \"../model-providers/model-status-cache.js\";\nimport { resolveRegisteredProviderOptions } from \"../model-providers/provider-options.js\";\nimport type { ModelProviderRegistry } from \"../model-providers/registry.js\";\nimport { assemblePiResourceSnapshot, type PiResourceBundleCache } from \"../pi-resources/index.js\";\nimport type { ServerProcessModelPolicy } from \"../process-model-policy/index.js\";\nimport { presentProcessModelPolicyFailure } from \"../process-model-policy-presenter.js\";\nimport type { ScopedSettingsService } from \"../scoped-settings-service.js\";\nimport {\n\tbuildRuntimeProfileSelectionInput,\n\tdefaultWorkerRuntimeProfile,\n\tselectWorkerRuntimeProfile,\n} from \"../worker-runtime-profile-selection.js\";\nimport type { Writes } from \"./writes/writes.js\";\n\nexport interface TurnStartPreflightDeps {\n\tprocessActionRegistry?: Pick<\n\t\timport(\"../process-action-registry.js\").ProcessActionRegistry,\n\t\t\"getTurnDefinition\" | \"resolveContextData\" | \"getProcessGraph\"\n\t>;\n\tmappedRuns?: Pick<RepositoryBundle[\"mappedRuns\"], \"getById\" | \"getItem\">;\n\tscopedSettings?: Pick<ScopedSettingsService, \"capture\">;\n\tprocessModelPolicy: ServerProcessModelPolicy;\n\tconfig: LeitwerkConfig;\n\tregistry: ModelProviderRegistry;\n\tmodelStatusCache: ModelStatusCache;\n\tpiContributions: Parameters<typeof assemblePiResourceSnapshot>[0][\"piContributions\"];\n\tbundleCache: PiResourceBundleCache;\n\tprojects: Pick<RepositoryBundle[\"projects\"], \"listByInstance\">;\n\tprocessSkills: Pick<RepositoryBundle[\"processSkills\"], \"listResourceLayers\">;\n}\n\nexport type TurnStartPreflightResult = { ok: true } | { ok: false; code: string; message: string };\n\nfunction previousProviderOptions(state: TurnStartRecordState): Record<string, string> {\n\tif (state.kind === \"preparation_failed\") return { ...state.providerOptions };\n\treturn state.start?.kind === \"llm\" ? { ...state.start.providerOptions } : {};\n}\n\nfunction previousProviderId(\n\tdeps: TurnStartPreflightDeps,\n\tstate: TurnStartRecordState,\n): string | null {\n\tif (state.kind !== \"preparation_failed\") {\n\t\treturn state.start?.kind === \"llm\" ? state.start.model.providerId : null;\n\t}\n\tconst profileId = state.requestedModelProfileId;\n\treturn profileId\n\t\t? (deps.config.pi.model_profiles.find((profile) => profile.id === profileId)?.provider ?? null)\n\t\t: null;\n}\n\nfunction resolveRuntimeProfile(\n\tdeps: TurnStartPreflightDeps,\n\tprocess: ProcessInstance,\n): { ok: true; id: string } | { ok: false; message: string } {\n\tif (deps.config.workers.runner === \"local\") {\n\t\treturn { ok: true, id: defaultWorkerRuntimeProfile(deps.config) ?? \"local\" };\n\t}\n\tconst selection = selectWorkerRuntimeProfile(\n\t\tbuildRuntimeProfileSelectionInput({\n\t\t\tconfig: deps.config,\n\t\t\tprocessId: process.processId,\n\t\t\tcomponentKeys: deps.projects.listByInstance(process.id).map((project) => project.key),\n\t\t\tdocker:\n\t\t\t\tdeps.processActionRegistry?.getProcessGraph(process.processId)?.runtime?.docker === true,\n\t\t}),\n\t);\n\treturn selection.ok\n\t\t? { ok: true, id: selection.runtimeProfile }\n\t\t: { ok: false, message: selection.error };\n}\n\nfunction resolveProviderWorkerConfig(\n\tprovider: ReturnType<ModelProviderRegistry[\"require\"]>,\n\toptions: Readonly<Record<string, string>>,\n): Extract<ResolvedTurnStart, { kind: \"llm\" }>[\"providerWorkerConfig\"] {\n\tif (provider.definition.worker.kind !== \"extension_pi_worker\") return null;\n\tconst definition = provider.definition.worker.config;\n\tif (!definition) return null;\n\tconst projected = definition.resolve({ config: provider.config, options });\n\tconst value = definition.schema.parse(projected);\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(\"Provider worker configuration must be a JSON object\");\n\t}\n\treturn { version: definition.version, value };\n}\n\nfunction resolveProviderPiModels(\n\tprovider: ReturnType<ModelProviderRegistry[\"require\"]>,\n): Record<string, unknown> {\n\tconst worker = provider.definition.worker;\n\treturn worker.kind === \"configured_pi_provider\"\n\t\t? worker.resolveModels({ config: provider.config })\n\t\t: { providers: {} };\n}\n\nfunction buildPiSettings(config: LeitwerkConfig): Record<string, unknown> {\n\t// Keep the immutable settings layer declarative. Runtime duration parsing and\n\t// request retries are still applied by the worker's standard Pi services.\n\treturn {\n\t\tretry: {\n\t\t\tenabled: config.pi.retry.enabled,\n\t\t\tmaxRetries: config.pi.retry.max_retries,\n\t\t\tbaseDelay: config.pi.retry.base_delay,\n\t\t\tprovider: {\n\t\t\t\ttimeout: config.pi.retry.provider.timeout,\n\t\t\t\tmaxRetries: config.pi.retry.provider.max_retries,\n\t\t\t\tmaxRetryDelay: config.pi.retry.provider.max_retry_delay,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Replaces placeholder LLM start states after the effective model has been\n * resolved but before the process/start transaction commits. Provider I/O is\n * deliberately absent: this consumes the bounded model-status cache only.\n */\nexport async function prepareCreatedTurnStarts(\n\tdeps: TurnStartPreflightDeps,\n\tprocess: ProcessInstance,\n\twrites: Writes,\n\texplicitProviderOptions?: Readonly<Record<string, string>>,\n\tavailabilitySnapshot?: ModelStatusCacheSnapshot,\n): Promise<TurnStartPreflightResult> {\n\tconst nextProcess = { ...process, ...writes.processPatch };\n\tconst availability = availabilitySnapshot ?? deps.modelStatusCache.snapshot();\n\n\tfor (const write of writes.turnStartWrites) {\n\t\tif (write.kind !== \"create\" || write.input.turnType !== \"llm\") continue;\n\t\tconst parkFailure = (\n\t\t\tfailure: Omit<Extract<TurnStartRecordState, { kind: \"preparation_failed\" }>, \"kind\">,\n\t\t) => {\n\t\t\twrite.input.state = { ...failure, kind: \"preparation_failed\" };\n\t\t\twrites.processPatch.lifecycleStatus = \"error\";\n\t\t\t// Reconcile obsolete workers without launching this failed start.\n\t\t\twrites.workerIntent = { kind: \"reconcile\" };\n\t\t};\n\n\t\tlet outcomeContract: Record<string, unknown> | undefined;\n\t\tif (deps.processActionRegistry) {\n\t\t\ttry {\n\t\t\t\tconst registry = deps.processActionRegistry;\n\t\t\t\tconst turn = registry.getTurnDefinition(nextProcess.processId, write.input.turnId);\n\t\t\t\tif (!turn || turn.kind !== \"llm\") throw new Error(\"Selected LLM turn is unavailable\");\n\t\t\t\tconst ref = write.input.iteration;\n\t\t\t\tconst pendingRun = writes.mappedRunWrites.find(\n\t\t\t\t\t(candidate) => candidate.kind === \"create\" && candidate.input.id === ref?.runId,\n\t\t\t\t);\n\t\t\t\tconst item = ref\n\t\t\t\t\t? pendingRun?.kind === \"create\"\n\t\t\t\t\t\t? pendingRun.input.items[ref.itemIndex]\n\t\t\t\t\t\t: deps.mappedRuns?.getItem(ref.runId, ref.itemIndex)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst count =\n\t\t\t\t\tpendingRun?.kind === \"create\"\n\t\t\t\t\t\t? pendingRun.input.items.length\n\t\t\t\t\t\t: ref\n\t\t\t\t\t\t\t? deps.mappedRuns?.getById(ref.runId)?.itemCount\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\tif (\n\t\t\t\t\tref &&\n\t\t\t\t\t(!item ||\n\t\t\t\t\t\titem.itemKey !== ref.itemKey ||\n\t\t\t\t\t\titem.itemIndex !== ref.itemIndex ||\n\t\t\t\t\t\tcount === undefined)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Frozen mapped item is unavailable\");\n\t\t\t\toutcomeContract = {\n\t\t\t\t\t...resolveOutcomeContract(\n\t\t\t\t\t\tturn,\n\t\t\t\t\t\tregistry.resolveContextData(nextProcess.processId, nextProcess),\n\t\t\t\t\t\tref && item\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...ref,\n\t\t\t\t\t\t\t\t\titem: JSON.parse(item.itemJson),\n\t\t\t\t\t\t\t\t\titemLabel: item.label,\n\t\t\t\t\t\t\t\t\titemCount: count!,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tcode: \"invalid_outcome_contract\",\n\t\t\t\t\tmessage: error instanceof Error ? error.message : \"Unable to resolve outcome contract\",\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Resolve the model and required settings without yielding. An edit while the\n\t\t// resource bundle is assembled belongs to the next start, not this snapshot.\n\t\tconst priorState = write.input.state;\n\t\tconst captured = priorState.automaticRetry\n\t\t\t? priorState.kind === \"preparation_failed\"\n\t\t\t\t? priorState.requestedModelProfileId && priorState.modelSelectionProvenance\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tmodelProfileId: priorState.requestedModelProfileId,\n\t\t\t\t\t\t\tprovenance: priorState.modelSelectionProvenance,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null\n\t\t\t\t: priorState.kind === \"starting\" &&\n\t\t\t\t\t\tpriorState.start.kind === \"llm\" &&\n\t\t\t\t\t\tpriorState.start.modelSelectionProvenance\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tmodelProfileId: priorState.start.model.profileId,\n\t\t\t\t\t\t\tprovenance: priorState.start.modelSelectionProvenance,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null\n\t\t\t: null;\n\t\tconst evaluated = captured\n\t\t\t? deps.processModelPolicy.evaluate({\n\t\t\t\t\tkind: \"runtime_selection\",\n\t\t\t\t\ttarget: { kind: \"turn\", turnId: write.input.turnId },\n\t\t\t\t\tprocessId: nextProcess.processId,\n\t\t\t\t\tselection: captured,\n\t\t\t\t\tavailability,\n\t\t\t\t})\n\t\t\t: deps.processModelPolicy.evaluate({\n\t\t\t\t\tkind: \"process_turn\",\n\t\t\t\t\tprocess: nextProcess,\n\t\t\t\t\tturnId: write.input.turnId,\n\t\t\t\t\tinitialSelection: true,\n\t\t\t\t\tstartKind: write.input.startKind,\n\t\t\t\t\tavailability,\n\t\t\t\t});\n\t\tif (!evaluated.ok) {\n\t\t\tconst code =\n\t\t\t\tevaluated.code === \"model_unavailable\" ||\n\t\t\t\tevaluated.code === \"model_stale\" ||\n\t\t\t\tevaluated.code === \"model_required\"\n\t\t\t\t\t? evaluated.code\n\t\t\t\t\t: \"invalid_model_configuration\";\n\t\t\tparkFailure({\n\t\t\t\trequestedModelProfileId: evaluated.selection?.modelProfileId ?? null,\n\t\t\t\tproviderOptions: previousProviderOptions(write.input.state),\n\t\t\t\tcode,\n\t\t\t\tsafeSummary: presentProcessModelPolicyFailure(evaluated),\n\t\t\t\t...(evaluated.selection\n\t\t\t\t\t? { modelSelectionProvenance: evaluated.selection.provenance }\n\t\t\t\t\t: {}),\n\t\t\t\tavailabilityRevision: availability.revision,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (evaluated.selection) {\n\t\t\tconst patch = {\n\t\t\t\tselectedTurnModelProfileId: evaluated.selection.modelProfileId,\n\t\t\t\tselectedTurnModelKind: evaluated.selection.provenance.kind,\n\t\t\t\tselectedTurnModelSource: evaluated.selection.provenance.source,\n\t\t\t};\n\t\t\tObject.assign(nextProcess, patch);\n\t\t\tObject.assign(writes.processPatch, patch);\n\t\t}\n\t\t// Automatic bootstrap recovery reuses the complete prepared execution, not current settings.\n\t\tif (captured && priorState.kind === \"starting\") continue;\n\t\tconst provenance =\n\t\t\tnextProcess.selectedTurnModelKind && nextProcess.selectedTurnModelSource\n\t\t\t\t? {\n\t\t\t\t\t\tkind: nextProcess.selectedTurnModelKind,\n\t\t\t\t\t\tsource: nextProcess.selectedTurnModelSource,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst requestedProfileId = nextProcess.selectedTurnModelProfileId?.trim() || null;\n\t\tlet scopedSettings: ReturnType<ScopedSettingsService[\"capture\"]>;\n\t\ttry {\n\t\t\tscopedSettings = deps.scopedSettings?.capture(\n\t\t\t\tnextProcess,\n\t\t\t\twrite.input.turnId,\n\t\t\t\tprovenance?.source === \"scoped_purpose_default\",\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tparkFailure({\n\t\t\t\trequestedModelProfileId: requestedProfileId,\n\t\t\t\tproviderOptions: {},\n\t\t\t\tcode: \"invalid_model_configuration\",\n\t\t\t\tsafeSummary:\n\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: \"Correct invalid scoped settings before retrying\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst retainedState = write.input.state;\n\t\tconst retainedOptions = previousProviderOptions(retainedState);\n\t\tif (\n\t\t\tretainedState.kind === \"preparation_failed\" &&\n\t\t\tretainedState.code === \"invalid_model_configuration\"\n\t\t) {\n\t\t\tparkFailure(retainedState);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!requestedProfileId) {\n\t\t\tparkFailure({\n\t\t\t\trequestedModelProfileId: null,\n\t\t\t\tproviderOptions: retainedOptions,\n\t\t\t\tcode: \"model_required\",\n\t\t\t\tsafeSummary: \"Choose a model before retrying startup\",\n\t\t\t\tavailabilityRevision: availability.revision,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst profile = deps.config.pi.model_profiles.find((item) => item.id === requestedProfileId);\n\t\tif (!profile) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"invalid_model_profile\",\n\t\t\t\tmessage: `Unknown model profile '${requestedProfileId}'`,\n\t\t\t};\n\t\t}\n\t\tconst provider = deps.registry.require(profile.provider);\n\t\tconst retainedProviderId = previousProviderId(deps, retainedState);\n\t\tconst recoveryOptions = explicitProviderOptions\n\t\t\t? { ...explicitProviderOptions }\n\t\t\t: retainedProviderId !== null && retainedProviderId !== provider.id\n\t\t\t\t? {}\n\t\t\t\t: retainedOptions;\n\t\tconst optionResult = resolveRegisteredProviderOptions({\n\t\t\tprovider,\n\t\t\texplicit: recoveryOptions,\n\t\t\tprofileDefaults: profile.provider_options ?? {},\n\t\t});\n\t\tif (!optionResult.ok) {\n\t\t\tconst onlyRequired = optionResult.issues.every((issue) => issue.code === \"required\");\n\t\t\tif (!onlyRequired) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tcode: \"invalid_provider_options\",\n\t\t\t\t\tmessage: optionResult.issues.map((issue) => issue.message).join(\"; \"),\n\t\t\t\t};\n\t\t\t}\n\t\t\tparkFailure({\n\t\t\t\trequestedModelProfileId: profile.id,\n\t\t\t\tproviderOptions: recoveryOptions,\n\t\t\t\tcode: \"provider_options_required\",\n\t\t\t\tsafeSummary: optionResult.issues.map((issue) => issue.message).join(\"; \"),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst runtimeProfile = resolveRuntimeProfile(deps, nextProcess);\n\t\t\tif (!runtimeProfile.ok) throw new Error(runtimeProfile.message);\n\t\t\tconst providerWorkerConfig = resolveProviderWorkerConfig(provider, optionResult.value);\n\t\t\tconst piSettings = buildPiSettings(deps.config);\n\t\t\tconst model = {\n\t\t\t\tprofileId: profile.id,\n\t\t\t\tproviderId: profile.provider,\n\t\t\t\tmodelId: profile.model_id,\n\t\t\t\tthinkingLevel: profile.thinking_level ?? \"off\",\n\t\t\t};\n\t\t\tconst resourceLayers = deps.processSkills.listResourceLayers(nextProcess.id);\n\t\t\tconst assembled = await assemblePiResourceSnapshot({\n\t\t\t\tresourceLayers,\n\t\t\t\tpiContributions: deps.piContributions,\n\t\t\t\tmodel,\n\t\t\t\tproviderOptions: optionResult.value,\n\t\t\t\tproviderWorkerConfig,\n\t\t\t\tpiSettings,\n\t\t\t\tpiModels: resolveProviderPiModels(provider),\n\t\t\t\tdeclaredCredentialPaths: [\n\t\t\t\t\t\"auth.json\",\n\t\t\t\t\t...(provider.definition.worker.kind === \"extension_pi_worker\"\n\t\t\t\t\t\t? (provider.definition.worker.credentialFiles ?? [])\n\t\t\t\t\t\t: []),\n\t\t\t\t],\n\t\t\t\tcompatibility: {\n\t\t\t\t\tworkerApiVersion: WORKER_API_VERSION,\n\t\t\t\t\tpiVersion: PI_RUNTIME_VERSION,\n\t\t\t\t\tprotocolVersion: IPC_PROTOCOL_VERSION,\n\t\t\t\t},\n\t\t\t});\n\t\t\tdeps.bundleCache.put(assembled.bundle);\n\t\t\twrite.input.state = {\n\t\t\t\tkind: \"starting\",\n\t\t\t\tstart: {\n\t\t\t\t\tkind: \"llm\",\n\t\t\t\t\t...(outcomeContract ? { outcomeContract } : {}),\n\t\t\t\t\t...(scopedSettings ? { scopedSettings } : {}),\n\t\t\t\t\tmodel,\n\t\t\t\t\t...(provenance ? { modelSelectionProvenance: provenance } : {}),\n\t\t\t\t\tavailabilityRevision: availability.revision,\n\t\t\t\t\tproviderOptions: { ...optionResult.value },\n\t\t\t\t\tproviderWorkerConfig,\n\t\t\t\t\tpiResourceSnapshotDigest: assembled.bundle.digest,\n\t\t\t\t\tworkerRuntimeProfileId: runtimeProfile.id,\n\t\t\t\t\tpiSettings,\n\t\t\t\t},\n\t\t\t};\n\t\t\twrites.processPatch.lifecycleStatus = \"active\";\n\t\t\twrites.workerIntent = { kind: \"restart_worker\" };\n\t\t} catch {\n\t\t\tparkFailure({\n\t\t\t\trequestedModelProfileId: profile.id,\n\t\t\t\tproviderOptions: { ...optionResult.value },\n\t\t\t\tcode: \"provider_preflight_failed\",\n\t\t\t\tsafeSummary: \"The provider could not prepare this worker start\",\n\t\t\t});\n\t\t}\n\t}\n\treturn { ok: true };\n}\n","import {\n\ttype ProviderOptionChoice,\n\ttype ProviderOptionsResolution,\n\ttype ProviderOptionValidationIssue,\n\tresolveProviderOptions,\n} from \"@leitwerk-dev/process-sdk\";\nimport { positiveBound, validateCredentialStatus, withTimeout } from \"./provider-boundary-utils.js\";\nimport type { ModelProviderCredentialStatusResolver, RegisteredModelProvider } from \"./registry.js\";\n\nconst DEFAULT_OPTION_CHOICE_TIMEOUT_MS = 5_000;\nconst DEFAULT_MAX_CHOICE_FIELDS = 64;\nconst DEFAULT_MAX_CHOICES_PER_FIELD = 256;\nconst DEFAULT_MAX_CHOICE_TEXT_LENGTH = 512;\n\n/** @internal */\nexport interface ResolveRegisteredProviderOptionsInput {\n\t/** @internal */\n\treadonly provider: RegisteredModelProvider;\n\t/** @internal */\n\treadonly explicit?: Readonly<Record<string, unknown>> | null;\n\t/** @internal */\n\treadonly profileDefaults?: Readonly<Record<string, unknown>> | null;\n}\n\n/**\n * Resolve structural option values. Dynamic choices are deliberately absent:\n * they are advisory UI data, not an allowlist or fallback source.\n */\n/** @internal */\nexport function resolveRegisteredProviderOptions(\n\tinput: ResolveRegisteredProviderOptionsInput,\n): ProviderOptionsResolution {\n\treturn resolveProviderOptions({\n\t\tdefinition: input.provider.definition.options,\n\t\tconfig: input.provider.config,\n\t\texplicit: input.explicit,\n\t\tprofileDefaults: input.profileDefaults,\n\t});\n}\n\n/** @internal */\nexport function validateConfiguredProviderOptions(input: {\n\t/** @internal */\n\treadonly provider: RegisteredModelProvider;\n\t/** @internal */\n\treadonly values: Readonly<Record<string, unknown>>;\n}): readonly ProviderOptionValidationIssue[] {\n\tconst result = resolveRegisteredProviderOptions({\n\t\tprovider: input.provider,\n\t\tprofileDefaults: input.values,\n\t});\n\tif (result.ok) {\n\t\treturn [];\n\t}\n\t// Required options may be supplied explicitly for an individual start. A\n\t// profile default is therefore allowed to omit them; all other structural\n\t// defects make startup configuration malformed.\n\treturn result.issues.filter((issue) => issue.code !== \"required\");\n}\n\n/** @internal */\nexport type ProviderOptionChoicesResult =\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: true;\n\t\t\t/** @internal */\n\t\t\treadonly choices: Readonly<Record<string, readonly ProviderOptionChoice[]>>;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\treadonly ok: false;\n\t\t\t/** @internal */\n\t\t\treadonly safeReason: string;\n\t };\n\n/** @internal */\nexport interface LoadProviderOptionChoicesInput {\n\t/** @internal */\n\treadonly provider: RegisteredModelProvider;\n\t/** @internal */\n\treadonly credentialStatus: ModelProviderCredentialStatusResolver;\n\t/** @internal */\n\treadonly timeoutMs?: number;\n\t/** @internal */\n\treadonly maxFields?: number;\n\t/** @internal */\n\treadonly maxChoicesPerField?: number;\n\t/** @internal */\n\treadonly maxTextLength?: number;\n}\n\n/** Fetch bounded advisory choices without making them part of option validation. @internal */\nexport async function loadProviderOptionChoices(\n\tinput: LoadProviderOptionChoicesInput,\n): Promise<ProviderOptionChoicesResult> {\n\tconst choicesLoader = input.provider.definition.options?.choices;\n\tif (!choicesLoader) {\n\t\treturn { ok: true, choices: {} };\n\t}\n\tconst timeoutMs = positiveBound(\n\t\tinput.timeoutMs,\n\t\tDEFAULT_OPTION_CHOICE_TIMEOUT_MS,\n\t\t\"Provider option choice timeout\",\n\t);\n\tconst maxFields = positiveBound(\n\t\tinput.maxFields,\n\t\tDEFAULT_MAX_CHOICE_FIELDS,\n\t\t\"Maximum choice fields\",\n\t);\n\tconst maxChoices = positiveBound(\n\t\tinput.maxChoicesPerField,\n\t\tDEFAULT_MAX_CHOICES_PER_FIELD,\n\t\t\"Maximum choices per field\",\n\t);\n\tconst maxTextLength = positiveBound(\n\t\tinput.maxTextLength,\n\t\tDEFAULT_MAX_CHOICE_TEXT_LENGTH,\n\t\t\"Maximum choice text length\",\n\t);\n\n\ttry {\n\t\tconst credentialStatus = validateCredentialStatus(\n\t\t\tawait withTimeout(Promise.resolve(input.credentialStatus(input.provider)), timeoutMs),\n\t\t);\n\t\tconst raw = await withTimeout(\n\t\t\tPromise.resolve(choicesLoader({ config: input.provider.config, credentialStatus })),\n\t\t\ttimeoutMs,\n\t\t);\n\t\tconst entries = Object.entries(raw);\n\t\tif (entries.length > maxFields) {\n\t\t\tthrow new Error(\"too many fields\");\n\t\t}\n\t\tconst fields = input.provider.definition.options?.fields ?? {};\n\t\tconst bounded: Record<string, readonly ProviderOptionChoice[]> = {};\n\t\tfor (const [fieldId, choices] of entries) {\n\t\t\tif (!(fieldId in fields) || !Array.isArray(choices) || choices.length > maxChoices) {\n\t\t\t\tthrow new Error(\"invalid field choices\");\n\t\t\t}\n\t\t\tbounded[fieldId] = choices.map((choice) => {\n\t\t\t\tif (\n\t\t\t\t\ttypeof choice?.value !== \"string\" ||\n\t\t\t\t\ttypeof choice?.label !== \"string\" ||\n\t\t\t\t\tchoice.value.length > maxTextLength ||\n\t\t\t\t\tchoice.label.length > maxTextLength\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"invalid choice\");\n\t\t\t\t}\n\t\t\t\treturn { value: choice.value, label: choice.label };\n\t\t\t});\n\t\t}\n\t\treturn { ok: true, choices: bounded };\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tsafeReason:\n\t\t\t\terror instanceof Error && error.message === \"timeout\"\n\t\t\t\t\t? \"Provider option choices timed out\"\n\t\t\t\t\t: \"Provider option choices are temporarily unavailable\",\n\t\t};\n\t}\n}\n","/** @internal */\nexport interface ProcessOperationCoordinator {\n\t/** @internal */\n\trunExclusive<T>(instanceId: string, operation: () => Promise<T> | T): Promise<T>;\n}\n\n/** @internal */\nexport function createProcessOperationCoordinator(): ProcessOperationCoordinator {\n\tconst tails = new Map<string, Promise<void>>();\n\n\treturn {\n\t\tasync runExclusive<T>(instanceId: string, operation: () => Promise<T> | T): Promise<T> {\n\t\t\tconst previous = tails.get(instanceId) ?? Promise.resolve();\n\t\t\tconst { promise: current, resolve: release } = Promise.withResolvers<void>();\n\t\t\ttails.set(instanceId, current);\n\n\t\t\tawait previous;\n\t\t\ttry {\n\t\t\t\treturn await operation();\n\t\t\t} finally {\n\t\t\t\trelease();\n\t\t\t\tif (tails.get(instanceId) === current) tails.delete(instanceId);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { BigIntStats } from \"node:fs\";\nimport {\n\tcopyFile,\n\ttype FileHandle,\n\tmkdir,\n\topen,\n\treadFile,\n\trename,\n\tstat,\n\tunlink,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { atomicWriteUtf8, isEnoent } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tcreateEmptyParsedInstanceTree,\n\tderiveParsedInstanceTree,\n\ttype ParsedInstanceTree,\n} from \"./instance-tree.js\";\nimport {\n\tcreateEmptyReadonlyPiSessionTree,\n\tparsePiSessionTreeContent,\n\ttype ReadonlyPiSessionTree,\n} from \"./pi-session-tree.js\";\n\n/**\n * A handle to a process session payload that exposes a change `signature`\n * before the reader pays the cost of parsing the full content.\n *\n * The two-step shape lets the reader skip re-parsing whenever the signature is\n * unchanged. Sources may capture content while producing a handle so its\n * signature and payload come from the same storage generation.\n */\n/** @internal */\nexport interface ProcessSessionSnapshotHandle {\n\t/** Opaque value that changes whenever the underlying session content changes. @internal */\n\tsignature: string;\n\t/** Loads the raw session JSONL content captured by this handle. @internal */\n\tload(): Promise<string>;\n}\n\n/**\n * Provides raw process session content without committing the server to a\n * particular storage location.\n *\n * Production read models use a server-owned latest-snapshot store fed by the\n * worker session-snapshot HTTP exchange. The store may be file-backed, but it\n * represents the server copy of the session JSONL rather than a requirement to\n * mount or inspect worker volumes.\n */\n/** @internal */\nexport interface ProcessSessionSource {\n\t/** Returns a handle for the instance, or `null` when no session exists yet. @internal */\n\treadSnapshotHandle(instanceId: string): Promise<ProcessSessionSnapshotHandle | null>;\n}\n\nexport interface WriteProcessSessionSnapshotResult {\n\tbytes: number;\n}\n\nexport interface ProcessSessionSnapshotStore extends ProcessSessionSource {\n\t/** Replaces the server's latest snapshot for this instance. */\n\twriteSnapshot(instanceId: string, content: string): Promise<WriteProcessSessionSnapshotResult>;\n\t/** Atomically replaces the server's latest snapshot with content from an existing file. */\n\twriteSnapshotFile(\n\t\tinstanceId: string,\n\t\tcontentPath: string,\n\t): Promise<WriteProcessSessionSnapshotResult>;\n\t/** Reads the raw latest snapshot, or `null` when no snapshot has been stored. */\n\treadRawSnapshot(instanceId: string): Promise<string | null>;\n\t/** Idempotently deletes the server-owned latest snapshot for this instance. */\n\tdeleteSnapshot(instanceId: string): Promise<void>;\n}\n\ninterface CachedSessionTree {\n\tsignature: string;\n\tpiTree: ReadonlyPiSessionTree;\n\tparsedTree: ParsedInstanceTree;\n}\n\n/** @internal */\nexport interface ProcessSessionTreeReadResult {\n\t/** @internal */\n\tsignature: string | null;\n\t/** @internal */\n\tpiTree: ReadonlyPiSessionTree;\n\t/** @internal */\n\tparsedTree: ParsedInstanceTree;\n}\n\n/**\n * Reads and caches parsed process session state from a {@link ProcessSessionSource}.\n *\n * All server read paths (primary-path snapshots, diagnostics, leaf-outcome\n * capture and failed-turn continuation) go through this seam so\n * the server never reads worker filesystems directly.\n */\n/** @internal */\nexport class ProcessSessionReader {\n\tprivate readonly sessionTreeCache = new Map<string, CachedSessionTree>();\n\tprivate readonly inFlightReads = new Map<string, Promise<CachedSessionTree>>();\n\n\t/** @internal */\n\tconstructor(private readonly source: ProcessSessionSource) {}\n\n\t/** @internal */\n\tasync readSessionTree(instanceId: string): Promise<ProcessSessionTreeReadResult> {\n\t\tfor (let attempt = 0; attempt < 3; attempt += 1) {\n\t\t\tconst handle = await this.source.readSnapshotHandle(instanceId);\n\t\t\tif (!handle) {\n\t\t\t\tthis.sessionTreeCache.delete(instanceId);\n\t\t\t\treturn {\n\t\t\t\t\tsignature: null,\n\t\t\t\t\tpiTree: createEmptyReadonlyPiSessionTree(instanceId),\n\t\t\t\t\tparsedTree: createEmptyParsedInstanceTree(),\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst cached = await this.readCachedSessionTree(instanceId, handle);\n\t\t\t\treturn {\n\t\t\t\t\tsignature: cached.signature,\n\t\t\t\t\tpiTree: cached.piTree,\n\t\t\t\t\tparsedTree: cached.parsedTree,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof ProcessSessionSnapshotChangedError) || attempt === 2) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Unable to read process session snapshot '${instanceId}'`);\n\t}\n\n\t/** @internal */\n\tasync readInstanceTree(instanceId: string): Promise<ParsedInstanceTree> {\n\t\treturn (await this.readSessionTree(instanceId)).parsedTree;\n\t}\n\n\t/** @internal */\n\tasync readPiSessionTree(instanceId: string): Promise<ReadonlyPiSessionTree> {\n\t\treturn (await this.readSessionTree(instanceId)).piTree;\n\t}\n\n\tprivate async readCachedSessionTree(\n\t\tinstanceId: string,\n\t\thandle: ProcessSessionSnapshotHandle,\n\t): Promise<CachedSessionTree> {\n\t\tconst cached = this.sessionTreeCache.get(instanceId);\n\t\tif (cached?.signature === handle.signature) {\n\t\t\treturn cached;\n\t\t}\n\t\tconst cacheKey = `${instanceId}:${handle.signature}`;\n\t\tconst inFlight = this.inFlightReads.get(cacheKey);\n\t\tif (inFlight) {\n\t\t\treturn inFlight;\n\t\t}\n\t\tconst promise = handle\n\t\t\t.load()\n\t\t\t.then((content) => {\n\t\t\t\tconst piTree = parsePiSessionTreeContent(instanceId, content);\n\t\t\t\tconst parsedTree = deriveParsedInstanceTree(piTree);\n\t\t\t\tconst next = { signature: handle.signature, piTree, parsedTree };\n\t\t\t\tthis.sessionTreeCache.set(instanceId, next);\n\t\t\t\treturn next;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.inFlightReads.delete(cacheKey);\n\t\t\t});\n\t\tthis.inFlightReads.set(cacheKey, promise);\n\t\treturn promise;\n\t}\n\n\t/** Returns the raw session JSONL, or `null` when no session exists yet. @internal */\n\tasync readRawContent(instanceId: string): Promise<string | null> {\n\t\tfor (let attempt = 0; attempt < 3; attempt += 1) {\n\t\t\tconst handle = await this.source.readSnapshotHandle(instanceId);\n\t\t\tif (!handle) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await handle.load();\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof ProcessSessionSnapshotChangedError) || attempt === 2) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Unable to read process session snapshot '${instanceId}'`);\n\t}\n}\n\nconst SAFE_SESSION_INSTANCE_ID = /^[A-Za-z0-9_.-]+$/;\n\nexport function isSafeSessionInstanceId(instanceId: string): boolean {\n\treturn SAFE_SESSION_INSTANCE_ID.test(instanceId) && instanceId !== \".\" && instanceId !== \"..\";\n}\n\nfunction assertSafeSessionInstanceId(instanceId: string): void {\n\tif (!isSafeSessionInstanceId(instanceId)) {\n\t\tthrow new Error(`Invalid process session instance id '${instanceId}'`);\n\t}\n}\n\nfunction resolveSessionSnapshotPath(rootDir: string, instanceId: string): string {\n\tassertSafeSessionInstanceId(instanceId);\n\treturn path.join(rootDir, `${instanceId}.jsonl`);\n}\n\nasync function atomicCopyFile(sourcePath: string, targetPath: string): Promise<void> {\n\tawait mkdir(path.dirname(targetPath), { recursive: true });\n\tconst tempPath = path.join(\n\t\tpath.dirname(targetPath),\n\t\t`.${path.basename(targetPath)}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tawait copyFile(sourcePath, tempPath);\n\t\tawait rename(tempPath, targetPath);\n\t} catch (error) {\n\t\tawait unlink(tempPath).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nclass ProcessSessionSnapshotChangedError extends Error {}\n\nfunction snapshotStatSignature(stats: BigIntStats): string {\n\treturn `stat:${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;\n}\n\nasync function statSnapshot(treeFile: string): Promise<string | null> {\n\ttry {\n\t\treturn snapshotStatSignature(await stat(treeFile, { bigint: true }));\n\t} catch (error) {\n\t\tif (isEnoent(error)) return null;\n\t\tthrow error;\n\t}\n}\n\nasync function loadSnapshotGeneration(\n\ttreeFile: string,\n\texpectedSignature: string,\n): Promise<string> {\n\tlet file: FileHandle;\n\ttry {\n\t\tfile = await open(treeFile, \"r\");\n\t} catch (error) {\n\t\tif (isEnoent(error)) throw new ProcessSessionSnapshotChangedError();\n\t\tthrow error;\n\t}\n\ttry {\n\t\tconst before = snapshotStatSignature(await file.stat({ bigint: true }));\n\t\tif (before !== expectedSignature) throw new ProcessSessionSnapshotChangedError();\n\t\tconst content = await file.readFile(\"utf8\");\n\t\tconst after = snapshotStatSignature(await file.stat({ bigint: true }));\n\t\tif (after !== expectedSignature) throw new ProcessSessionSnapshotChangedError();\n\t\treturn content;\n\t} finally {\n\t\tawait file.close();\n\t}\n}\n\n/**\n * Filesystem-backed source reading `<treeFilesDir>/<instanceId>.jsonl`.\n *\n * A nanosecond file-generation signature makes unchanged cache checks cheap.\n * Cache misses verify that the loaded bytes still belong to that generation;\n * the reader retries when a concurrent replacement wins the race.\n */\nexport function createFileBackedProcessSessionSnapshotStore(\n\ttreeFilesDir: string,\n): ProcessSessionSnapshotStore {\n\tconst rootDir = path.resolve(treeFilesDir);\n\tconst resolveTreeFile = (instanceId: string): string =>\n\t\tresolveSessionSnapshotPath(rootDir, instanceId);\n\treturn {\n\t\tasync readSnapshotHandle(instanceId) {\n\t\t\tconst treeFile = resolveTreeFile(instanceId);\n\t\t\tconst signature = await statSnapshot(treeFile);\n\t\t\tif (!signature) return null;\n\t\t\treturn {\n\t\t\t\tsignature,\n\t\t\t\tload: () => loadSnapshotGeneration(treeFile, signature),\n\t\t\t};\n\t\t},\n\t\tasync writeSnapshot(instanceId, content) {\n\t\t\tconst treeFile = resolveTreeFile(instanceId);\n\t\t\tawait atomicWriteUtf8(treeFile, content);\n\t\t\treturn { bytes: Buffer.byteLength(content, \"utf8\") };\n\t\t},\n\t\tasync writeSnapshotFile(instanceId, contentPath) {\n\t\t\tconst treeFile = resolveTreeFile(instanceId);\n\t\t\tawait atomicCopyFile(contentPath, treeFile);\n\t\t\treturn { bytes: (await stat(treeFile)).size };\n\t\t},\n\t\tasync readRawSnapshot(instanceId) {\n\t\t\tconst treeFile = resolveTreeFile(instanceId);\n\t\t\ttry {\n\t\t\t\treturn await readFile(treeFile, \"utf8\");\n\t\t\t} catch (error) {\n\t\t\t\tif (isEnoent(error)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tasync deleteSnapshot(instanceId) {\n\t\t\tawait unlink(resolveTreeFile(instanceId)).catch((error: unknown) => {\n\t\t\t\tif (!isEnoent(error)) throw error;\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport function createFilesystemSessionSource(treeFilesDir: string): ProcessSessionSource {\n\treturn createFileBackedProcessSessionSnapshotStore(treeFilesDir);\n}\n\n/** Convenience wiring a {@link ProcessSessionReader} over the local filesystem. */\nexport function createFilesystemSessionReader(treeFilesDir: string): ProcessSessionReader {\n\treturn new ProcessSessionReader(createFilesystemSessionSource(treeFilesDir));\n}\n","import {\n\ttype FileEntry,\n\tmigrateSessionEntries,\n\tparseSessionEntries,\n\ttype SessionEntry,\n\ttype SessionHeader,\n} from \"@earendil-works/pi-coding-agent\";\nimport { createReadonlyEntryTree } from \"@leitwerk-dev/protocol\";\n\n/** @internal */\nexport interface PiSessionTreeNode {\n\t/** @internal */\n\tentry: SessionEntry;\n\t/** @internal */\n\tchildren: PiSessionTreeNode[];\n\t/** @internal */\n\tlabel?: string;\n}\n\n/** @internal */\nexport interface ReadonlyPiSessionTree {\n\t/** Identifier of the parsed source (instance id or file path). @internal */\n\ttreeFile: string;\n\t/** @internal */\n\theader: SessionHeader | null;\n\t/** @internal */\n\tentries: SessionEntry[];\n\t/** @internal */\n\tleafId: string | null;\n\t/** @internal */\n\tgetEntry(id: string): SessionEntry | undefined;\n\t/** @internal */\n\tgetChildren(parentId: string): SessionEntry[];\n\t/** @internal */\n\tgetBranch(fromId?: string): SessionEntry[];\n\t/** @internal */\n\tgetTree(): PiSessionTreeNode[];\n}\n\nfunction isFileRecord(entry: unknown): entry is FileEntry {\n\treturn typeof entry === \"object\" && entry !== null && !Array.isArray(entry);\n}\n\nfunction isSessionHeader(entry: FileEntry): entry is SessionHeader {\n\treturn entry.type === \"session\";\n}\n\nfunction isSessionEntry(entry: FileEntry): entry is SessionEntry {\n\treturn (\n\t\ttypeof entry.type === \"string\" &&\n\t\tentry.type.trim() !== \"\" &&\n\t\tentry.type !== \"session\" &&\n\t\ttypeof entry.id === \"string\" &&\n\t\tentry.id.trim() !== \"\" &&\n\t\t(entry.parentId === null || typeof entry.parentId === \"string\") &&\n\t\ttypeof entry.timestamp === \"string\"\n\t);\n}\n\nexport function createEmptyReadonlyPiSessionTree(treeFile: string): ReadonlyPiSessionTree {\n\treturn {\n\t\ttreeFile,\n\t\theader: null,\n\t\tentries: [],\n\t\tleafId: null,\n\t\tgetEntry() {\n\t\t\treturn undefined;\n\t\t},\n\t\tgetChildren() {\n\t\t\treturn [];\n\t\t},\n\t\tgetBranch() {\n\t\t\treturn [];\n\t\t},\n\t\tgetTree() {\n\t\t\treturn [];\n\t\t},\n\t};\n}\n\nfunction createReadonlyPiSessionTree(\n\ttreeFile: string,\n\tfileEntries: FileEntry[],\n): ReadonlyPiSessionTree {\n\tfileEntries = fileEntries.filter(isFileRecord);\n\tmigrateSessionEntries(fileEntries);\n\n\tconst header = fileEntries.find(isSessionHeader) ?? null;\n\tconst entryTree = createReadonlyEntryTree(fileEntries.filter(isSessionEntry));\n\tconst { entries, leafId, getEntry, getChildren, getBranch } = entryTree;\n\tconst entriesById = new Map(entries.map((entry) => [entry.id, entry]));\n\tconst labelsByTargetId = new Map<string, string>();\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"label\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst targetId = typeof entry.targetId === \"string\" ? entry.targetId.trim() : \"\";\n\t\tif (!targetId) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof entry.label === \"string\" && entry.label.trim() !== \"\") {\n\t\t\tlabelsByTargetId.set(targetId, entry.label);\n\t\t} else {\n\t\t\tlabelsByTargetId.delete(targetId);\n\t\t}\n\t}\n\n\tconst buildTreeNode = (entry: SessionEntry, visited: Set<string>): PiSessionTreeNode => {\n\t\tvisited.add(entry.id);\n\t\treturn {\n\t\t\tentry,\n\t\t\tchildren: getChildren(entry.id)\n\t\t\t\t.filter((child) => !visited.has(child.id))\n\t\t\t\t.map((child) => buildTreeNode(child, visited)),\n\t\t\t...(labelsByTargetId.has(entry.id) ? { label: labelsByTargetId.get(entry.id) } : {}),\n\t\t};\n\t};\n\n\tconst getTree = (): PiSessionTreeNode[] => {\n\t\tconst visited = new Set<string>();\n\t\tconst rootEntries = entries.filter(\n\t\t\t(entry) => entry.parentId === null || !entriesById.has(entry.parentId),\n\t\t);\n\t\tconst roots = rootEntries.map((entry) => buildTreeNode(entry, visited));\n\t\tfor (const entry of entries) {\n\t\t\tif (visited.has(entry.id)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\troots.push(buildTreeNode(entry, visited));\n\t\t}\n\t\treturn roots;\n\t};\n\n\treturn {\n\t\ttreeFile,\n\t\theader,\n\t\tentries,\n\t\tleafId,\n\t\tgetEntry,\n\t\tgetChildren,\n\t\tgetBranch,\n\t\tgetTree,\n\t};\n}\n\n/**\n * Parses process session JSONL into a read-only Pi session tree.\n *\n * Pure: the caller owns reading the content. `sourceLabel` is surfaced as\n * `treeFile` for diagnostics.\n */\nexport function parsePiSessionTreeContent(\n\tsourceLabel: string,\n\tcontent: string,\n): ReadonlyPiSessionTree {\n\tif (content.trim() === \"\") {\n\t\treturn createEmptyReadonlyPiSessionTree(sourceLabel);\n\t}\n\treturn createReadonlyPiSessionTree(sourceLabel, parseSessionEntries(content));\n}\n","import type { PrimaryPathEntrySnapshot } from \"@leitwerk-dev/protocol\";\nimport { parsePiSessionTreeContent, type ReadonlyPiSessionTree } from \"./pi-session-tree.js\";\n\n/** @internal */\nexport interface ParsedInstanceTree {\n\t/** @internal */\n\tentriesById: Map<string, PrimaryPathEntrySnapshot>;\n\t/** @internal */\n\tlabelsByEntryId: Map<string, string>;\n}\n\nexport interface ParseInstanceTreeOptions {\n\t/** Identifier surfaced by the parsed tree. */\n\tsourceLabel: string;\n}\n\nexport function createEmptyParsedInstanceTree(): ParsedInstanceTree {\n\treturn {\n\t\tentriesById: new Map<string, PrimaryPathEntrySnapshot>(),\n\t\tlabelsByEntryId: new Map<string, string>(),\n\t};\n}\n\n/**\n * Derives the lightweight entry/label maps used by primary-path snapshots and\n * leaf-outcome capture from the canonical Pi session tree representation.\n */\nexport function deriveParsedInstanceTree(tree: ReadonlyPiSessionTree): ParsedInstanceTree {\n\tconst parsedTree = createEmptyParsedInstanceTree();\n\tconst { entriesById, labelsByEntryId } = parsedTree;\n\n\tfor (const entry of tree.entries) {\n\t\tif (entry.type === \"label\") {\n\t\t\tconst targetId = typeof entry.targetId === \"string\" ? entry.targetId.trim() : \"\";\n\t\t\tif (!targetId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst label = typeof entry.label === \"string\" ? entry.label.trim() : \"\";\n\t\t\tif (label) {\n\t\t\t\tlabelsByEntryId.set(targetId, label);\n\t\t\t} else {\n\t\t\t\tlabelsByEntryId.delete(targetId);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tentriesById.set(entry.id, entry as PrimaryPathEntrySnapshot);\n\t}\n\n\treturn parsedTree;\n}\n\n/**\n * Parses process session JSONL through the canonical Pi session parser, then\n * derives the lightweight projection used by legacy primary-path callers.\n */\nexport function parseInstanceTree(\n\tcontent: string,\n\toptions: ParseInstanceTreeOptions,\n): ParsedInstanceTree {\n\treturn deriveParsedInstanceTree(parsePiSessionTreeContent(options.sourceLabel, content));\n}\n","import {\n\tasUnknownRecord,\n\ttype ProcessEvent,\n\ttype ProcessTurnRecord,\n\treadNonBlankString,\n\ttrimToNull,\n} from \"@leitwerk-dev/domain\";\nimport {\n\tasWsEventPayloadRecord,\n\tbuildPrimaryPathOperationalTraceItem,\n\tcompareTimestampStrings,\n\tcreateLiveTurnProjection,\n\tcreateTurnContinuationIndex,\n\textractPiSessionMessageText,\n\tisPiSessionMessageEntryWithRecord,\n\tisToolResultTruncated,\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype PiSessionContentBlock,\n\ttype PiSessionEntry,\n\ttype PiSessionMessageRecord,\n\ttype PrimaryPathOperationalTraceItemSnapshot,\n\ttype PrimaryPathStreamingAssistantSnapshot,\n\ttype PrimaryPathTraceItemSnapshot,\n\treasoningPreviewTail,\n\ttype TurnPiInputPart,\n\ttype TurnPiInputSnapshot,\n\ttype TurnTracePreview,\n\ttype TurnTraceSnapshot,\n\ttype TurnTraceToolCallSnapshot,\n\ttruncateTextPreview,\n} from \"@leitwerk-dev/protocol\";\nimport type { ReadonlyPiSessionTree } from \"./pi-session-tree.js\";\n\nconst MULTI_PART_PI_INPUT_SEPARATOR =\n\t\"\\n\\n--- UI-added separator between Pi input messages ---\\n\\n\";\nconst PREVIEW_MAX_LENGTH = 520;\n\nfunction buildTurnPiInputSnapshot(parts: readonly TurnPiInputPart[]): TurnPiInputSnapshot | null {\n\tconst firstPart = parts[0];\n\tif (!firstPart) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tparts: [...parts],\n\t\tfullPrompt: parts.map((part) => part.text).join(MULTI_PART_PI_INPUT_SEPARATOR),\n\t\tcreatedAt: firstPart.createdAt,\n\t\tuserInput: null,\n\t};\n}\n\nfunction isContentBlock(value: unknown): value is PiSessionContentBlock {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) && \"type\" in value;\n}\n\nfunction normalizeContentBlocks(content: unknown): PiSessionContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [{ type: \"text\", text: content }];\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn [];\n\t}\n\treturn content.filter(isContentBlock);\n}\n\nfunction normalizeToolArguments(value: unknown): Record<string, unknown> | null {\n\tconst record = asUnknownRecord(value);\n\treturn record ? { ...record } : null;\n}\n\nfunction extractToolResultValue(message: PiSessionMessageRecord): unknown {\n\tif (\"details\" in message && message.details !== undefined) {\n\t\treturn message.details;\n\t}\n\tconst text = extractPiSessionMessageText(message.content).trim();\n\tif (text !== \"\") {\n\t\treturn text;\n\t}\n\treturn message.content ?? null;\n}\n\n/** @internal */\ntype TraceTurnRecord = Pick<\n\tProcessTurnRecord,\n\t\"id\" | \"turnType\" | \"forkPiEntryId\" | \"resultPiEntryId\" | \"startedAt\" | \"endedAt\" | \"status\"\n>;\n\n/** Pi sends custom messages to the model as user input; their details stay out of context. */\nfunction traceSessionEntries(tree: ReadonlyPiSessionTree): PiSessionEntry[] {\n\treturn tree.entries.map((entry) =>\n\t\tentry.type === \"custom_message\"\n\t\t\t? {\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tparentId: entry.parentId,\n\t\t\t\t\ttimestamp: entry.timestamp,\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\tmessage: { role: \"user\", content: entry.content },\n\t\t\t\t}\n\t\t\t: (entry as unknown as PiSessionEntry),\n\t);\n}\n\nfunction indexEventsByTurnRecordId(\n\tevents: readonly ProcessEvent[] = [],\n): Map<string, ProcessEvent[]> {\n\tconst index = new Map<string, ProcessEvent[]>();\n\tfor (const event of events) {\n\t\tconst turnRecordId = eventTurnRecordId(event);\n\t\tif (turnRecordId) {\n\t\t\tconst turnEvents = index.get(turnRecordId) ?? [];\n\t\t\tturnEvents.push(event);\n\t\t\tindex.set(turnRecordId, turnEvents);\n\t\t}\n\t}\n\treturn index;\n}\n\nfunction appendOperationalTraceItem(\n\ttraceItems: PrimaryPathTraceItemSnapshot[],\n\titem: PrimaryPathOperationalTraceItemSnapshot | null,\n): void {\n\tif (!item) {\n\t\treturn;\n\t}\n\tif (\n\t\ttraceItems.some(\n\t\t\t(existing) =>\n\t\t\t\texisting.kind === \"operational_event\" &&\n\t\t\t\texisting.eventType === item.eventType &&\n\t\t\t\texisting.message === item.message &&\n\t\t\t\texisting.timestamp === item.timestamp,\n\t\t)\n\t) {\n\t\treturn;\n\t}\n\ttraceItems.push(item);\n}\n\nfunction buildAssistantErrorTraceItem(\n\tentry: PiSessionEntry,\n\tmessage: PiSessionMessageRecord,\n): PrimaryPathOperationalTraceItemSnapshot | null {\n\tif (message.role !== \"assistant\" || message.stopReason !== \"error\") {\n\t\treturn null;\n\t}\n\tconst errorMessage = readNonBlankString(message.errorMessage);\n\tif (!errorMessage) {\n\t\treturn null;\n\t}\n\treturn buildPrimaryPathOperationalTraceItem({\n\t\teventType: \"pi.error\",\n\t\tdata: asWsEventPayloadRecord({\n\t\t\tmessage: errorMessage,\n\t\t\terrorMessage,\n\t\t\tprovider: readNonBlankString(message.provider),\n\t\t\tmodel: readNonBlankString(message.model),\n\t\t\ttimestamp: entry.timestamp,\n\t\t}),\n\t\tfallbackTimestamp: entry.timestamp,\n\t});\n}\n\nfunction buildCompactionEntryTraceItem(\n\tentry: PiSessionEntry,\n): PrimaryPathOperationalTraceItemSnapshot | null {\n\tif (entry.type !== \"compaction\") {\n\t\treturn null;\n\t}\n\tconst record = asUnknownRecord(entry);\n\tconst summary = typeof record?.summary === \"string\" ? record.summary.trim() : \"\";\n\treturn {\n\t\tkind: \"operational_event\",\n\t\teventType: \"pi.compaction.end\",\n\t\tseverity: \"success\",\n\t\ttitle: \"Context compacted\",\n\t\tmessage: summary ? `Pi compacted context. Summary:\\n${summary}` : \"Pi compacted context.\",\n\t\ttimestamp: entry.timestamp,\n\t};\n}\n\nfunction eventTurnRecordId(event: ProcessEvent): string | null {\n\treturn readNonBlankString(event.data.turnRecordId);\n}\n\nfunction compareOperationalTraceItems(\n\tleft: PrimaryPathOperationalTraceItemSnapshot,\n\tright: PrimaryPathOperationalTraceItemSnapshot,\n): number {\n\treturn (\n\t\tcompareTimestampStrings(left.timestamp, right.timestamp) ||\n\t\tleft.eventType.localeCompare(right.eventType) ||\n\t\tleft.message.localeCompare(right.message)\n\t);\n}\n\nfunction ensureSortedTraceItems(\n\ttraceItems: PrimaryPathTraceItemSnapshot[],\n): PrimaryPathTraceItemSnapshot[] {\n\tconst operationalTraceItems = traceItems\n\t\t.filter(\n\t\t\t(traceItem): traceItem is PrimaryPathOperationalTraceItemSnapshot =>\n\t\t\t\ttraceItem.kind === \"operational_event\",\n\t\t)\n\t\t.sort(compareOperationalTraceItems);\n\tlet nextOperationalIndex = 0;\n\treturn traceItems.map((traceItem) => {\n\t\tif (traceItem.kind !== \"operational_event\") {\n\t\t\treturn traceItem;\n\t\t}\n\t\tconst nextOperationalTraceItem = operationalTraceItems[nextOperationalIndex];\n\t\tnextOperationalIndex += 1;\n\t\treturn nextOperationalTraceItem ?? traceItem;\n\t});\n}\n\nfunction buildTurnTraceFromSlice(input: {\n\tturnRecordId: string;\n\tturnSlice: readonly PiSessionEntry[];\n\tevents?: readonly ProcessEvent[];\n}): TurnTraceSnapshot | undefined {\n\tconst { turnSlice } = input;\n\n\tconst promptParts: TurnPiInputPart[] = [];\n\tconst assistant: PrimaryPathStreamingAssistantSnapshot = {\n\t\ttext: \"\",\n\t\tthinking: \"\",\n\t\tlastUpdatedAt: null,\n\t};\n\tconst toolCalls: TurnTraceToolCallSnapshot[] = [];\n\tconst toolCallsById = new Map<string, TurnTraceToolCallSnapshot>();\n\tconst traceItems: PrimaryPathTraceItemSnapshot[] = [];\n\tlet usage: TurnTraceSnapshot[\"usage\"] = null;\n\n\tconst ensureToolCall = (toolInput: {\n\t\ttoolCallId: string;\n\t\ttoolName: string;\n\t\tstartedAt: string;\n\t\targuments: Record<string, unknown> | null;\n\t}): TurnTraceToolCallSnapshot => {\n\t\tconst existing = toolCallsById.get(toolInput.toolCallId);\n\t\tif (existing) {\n\t\t\tif (!existing.arguments && toolInput.arguments) {\n\t\t\t\texisting.arguments = toolInput.arguments;\n\t\t\t}\n\t\t\treturn existing;\n\t\t}\n\t\tconst toolCall: TurnTraceToolCallSnapshot = {\n\t\t\ttoolCallId: toolInput.toolCallId,\n\t\t\ttoolName: toolInput.toolName,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt: toolInput.startedAt,\n\t\t\tcompletedAt: null,\n\t\t\targuments: toolInput.arguments,\n\t\t\tisError: false,\n\t\t\tresultText: null,\n\t\t\ttruncated: false,\n\t\t};\n\t\ttoolCalls.push(toolCall);\n\t\ttoolCallsById.set(toolInput.toolCallId, toolCall);\n\t\ttraceItems.push({ kind: \"tool_call\", toolCallId: toolInput.toolCallId });\n\t\treturn toolCall;\n\t};\n\n\tfor (const entry of turnSlice) {\n\t\tif (!isPiSessionMessageEntryWithRecord(entry)) {\n\t\t\tappendOperationalTraceItem(traceItems, buildCompactionEntryTraceItem(entry));\n\t\t\tcontinue;\n\t\t}\n\t\tconst message = entry.message as PiSessionMessageRecord;\n\t\tappendOperationalTraceItem(traceItems, buildAssistantErrorTraceItem(entry, message));\n\t\tconst role = trimToNull(message.role);\n\t\tif (role === \"user\") {\n\t\t\tconst promptText = extractPiSessionMessageText(message.content);\n\t\t\tif (promptText.trim() !== \"\") {\n\t\t\t\tpromptParts.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\ttext: promptText,\n\t\t\t\t\tcreatedAt: entry.timestamp,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (role === \"assistant\") {\n\t\t\tfor (const block of normalizeContentBlocks(message.content)) {\n\t\t\t\tif (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n\t\t\t\t\tif (block.thinking.length > 0) {\n\t\t\t\t\t\tassistant.thinking += block.thinking;\n\t\t\t\t\t\tassistant.lastUpdatedAt = entry.timestamp;\n\t\t\t\t\t\ttraceItems.push({ kind: \"thinking\", text: block.thinking });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCallId = trimToNull(block.id);\n\t\t\t\t\tconst toolName = trimToNull(block.name);\n\t\t\t\t\tif (!toolCallId || !toolName) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tensureToolCall({\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tstartedAt: entry.timestamp,\n\t\t\t\t\t\targuments: normalizeToolArguments(block.arguments),\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\t\t\tassistant.text += block.text;\n\t\t\t\t\tassistant.lastUpdatedAt = entry.timestamp;\n\t\t\t\t}\n\t\t\t}\n\t\t\tusage = mergeUsageSnapshots(usage, normalizeUsageSnapshot(message.usage));\n\t\t\tcontinue;\n\t\t}\n\t\tif (role !== \"toolResult\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst toolCallId = trimToNull(message.toolCallId);\n\t\tconst toolName = trimToNull(message.toolName) ?? \"tool\";\n\t\tif (!toolCallId) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst toolCall = ensureToolCall({\n\t\t\ttoolCallId,\n\t\t\ttoolName,\n\t\t\tstartedAt: entry.timestamp,\n\t\t\targuments: null,\n\t\t});\n\t\tconst resultValue = extractToolResultValue(message);\n\t\tconst resultContent = message.content ?? null;\n\t\tconst rawResultText = extractPiSessionMessageText(resultContent);\n\t\tconst resultText = rawResultText.trim() === \"\" ? null : rawResultText;\n\t\tconst resultDetails = \"details\" in message ? message.details : null;\n\t\tconst truncated = isToolResultTruncated({ resultText, resultDetails, resultValue });\n\t\ttoolCall.status = \"completed\";\n\t\ttoolCall.completedAt = entry.timestamp;\n\t\ttoolCall.isError = message.isError === true;\n\t\ttoolCall.resultText = resultText;\n\t\ttoolCall.truncated = truncated;\n\t}\n\n\tfor (const event of input.events ?? []) {\n\t\tif (eventTurnRecordId(event) === input.turnRecordId) {\n\t\t\tappendOperationalTraceItem(\n\t\t\t\ttraceItems,\n\t\t\t\tbuildPrimaryPathOperationalTraceItem({\n\t\t\t\t\teventType: event.eventType,\n\t\t\t\t\tdata: asWsEventPayloadRecord(event.data),\n\t\t\t\t\tfallbackTimestamp: event.createdAt,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (\n\t\tassistant.text === \"\" &&\n\t\tassistant.thinking === \"\" &&\n\t\ttoolCalls.length === 0 &&\n\t\tusage === null &&\n\t\tpromptParts.length === 0 &&\n\t\ttraceItems.length === 0\n\t) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tassistant,\n\t\ttoolCalls,\n\t\ttraceItems: ensureSortedTraceItems(traceItems),\n\t\tusage,\n\t\tpiInput: buildTurnPiInputSnapshot(promptParts),\n\t};\n}\n\nexport function buildTurnTraceFromSession(input: {\n\ttree: ReadonlyPiSessionTree;\n\tturnRecord: TraceTurnRecord;\n\tevents?: readonly ProcessEvent[];\n}): TurnTraceSnapshot | undefined {\n\tif (input.turnRecord.turnType !== \"llm\") {\n\t\treturn undefined;\n\t}\n\tconst continuationIndex = createTurnContinuationIndex(traceSessionEntries(input.tree));\n\treturn buildTurnTraceFromSlice({\n\t\tturnRecordId: input.turnRecord.id,\n\t\tturnSlice: continuationIndex.buildSlice(input.turnRecord, {\n\t\t\tendedAt: input.turnRecord.endedAt,\n\t\t}),\n\t\tevents: input.events,\n\t});\n}\n\nfunction hasAdditionalRecordedActivity(recorded: TurnTraceSnapshot, session: TurnTraceSnapshot) {\n\tif (\n\t\t!session.assistant.text.includes(recorded.assistant.text) ||\n\t\t!session.assistant.thinking.includes(recorded.assistant.thinking)\n\t)\n\t\treturn true;\n\tconst sessionTools = new Map(session.toolCalls.map((tool) => [tool.toolCallId, tool]));\n\treturn recorded.toolCalls.some((tool) => {\n\t\tconst saved = sessionTools.get(tool.toolCallId);\n\t\treturn (\n\t\t\t!saved ||\n\t\t\t(tool.status === \"completed\" && saved.status !== \"completed\") ||\n\t\t\t(tool.resultText !== null && !saved.resultText?.includes(tool.resultText))\n\t\t);\n\t});\n}\n\n/** Prefer recorded activity when the retained session omits part of the turn. */\nexport function buildCommittedTurnTrace(input: {\n\ttree: ReadonlyPiSessionTree;\n\tturnRecord: TraceTurnRecord;\n\tevents: readonly ProcessEvent[];\n}): TurnTraceSnapshot {\n\tconst sessionTrace = buildTurnTraceFromSession(input);\n\tconst trace = createLiveTurnProjection(\n\t\tinput.events.filter((event) => eventTurnRecordId(event) === input.turnRecord.id),\n\t).snapshot(sessionTrace?.piInput ?? null);\n\tif (sessionTrace && !hasAdditionalRecordedActivity(trace, sessionTrace)) return sessionTrace;\n\ttrace.usage ??= sessionTrace?.usage ?? null;\n\tfor (const item of sessionTrace?.traceItems ?? []) {\n\t\tif (item.kind === \"operational_event\") appendOperationalTraceItem(trace.traceItems, item);\n\t}\n\ttrace.traceItems = ensureSortedTraceItems(trace.traceItems);\n\treturn trace;\n}\n\n/** @internal */\nexport function buildTurnTracePreview(\n\tturnRecordId: string,\n\ttrace: TurnTraceSnapshot | undefined,\n): TurnTracePreview {\n\tconst assistantText = truncateTextPreview(trace?.assistant.text.trim() ?? \"\", PREVIEW_MAX_LENGTH);\n\tconst thinkingPreview = {\n\t\ttext: reasoningPreviewTail(trace?.assistant.thinking ?? \"\"),\n\t\ttruncated: (trace?.assistant.thinking.length ?? 0) > 1024,\n\t};\n\tconst piInput = trace?.piInput ?? null;\n\tconst userInputPreview = piInput?.fullPrompt\n\t\t? truncateTextPreview(piInput.fullPrompt.trim(), PREVIEW_MAX_LENGTH).text\n\t\t: null;\n\treturn {\n\t\tturnRecordId,\n\t\tassistantTextPreview: assistantText.text,\n\t\tassistantTextTruncated: assistantText.truncated,\n\t\tthinkingPreview: thinkingPreview.text,\n\t\tthinkingPreviewTruncated: thinkingPreview.truncated,\n\t\ttoolCallCount: trace?.toolCalls.length ?? 0,\n\t\ttraceItemCount: trace?.traceItems.length ?? 0,\n\t\thasReasoningDetails: Boolean(\n\t\t\ttrace &&\n\t\t\t\t(trace.assistant.thinking.trim() !== \"\" ||\n\t\t\t\t\ttrace.toolCalls.length > 0 ||\n\t\t\t\t\ttrace.traceItems.length > 0 ||\n\t\t\t\t\ttrace.piInput ||\n\t\t\t\t\ttrace.usage),\n\t\t),\n\t\tusage: trace?.usage ?? null,\n\t\tpiInput: piInput\n\t\t\t? {\n\t\t\t\t\tcreatedAt: piInput.createdAt,\n\t\t\t\t\tpartCount: piInput.parts.length,\n\t\t\t\t\tuserInputPreview,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n\n/** @internal */\ninterface TurnTraceCollectionInput {\n\t/** @internal */\n\ttree: ReadonlyPiSessionTree;\n\t/** @internal */\n\tturnRecords: readonly TraceTurnRecord[];\n\t/** @internal */\n\tevents?: readonly ProcessEvent[];\n}\n\nfunction visitTurnTraces(\n\tinput: TurnTraceCollectionInput,\n\tvisit: (turnRecordId: string, trace: TurnTraceSnapshot) => void,\n): void {\n\tconst continuationIndex = createTurnContinuationIndex(traceSessionEntries(input.tree));\n\tconst eventsByTurnRecordId = indexEventsByTurnRecordId(input.events);\n\tfor (const turnRecord of input.turnRecords) {\n\t\tif (turnRecord.turnType !== \"llm\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst trace = buildTurnTraceFromSlice({\n\t\t\tturnRecordId: turnRecord.id,\n\t\t\tturnSlice: continuationIndex.buildSlice(turnRecord, { endedAt: turnRecord.endedAt }),\n\t\t\tevents: eventsByTurnRecordId.get(turnRecord.id),\n\t\t});\n\t\tif (trace) {\n\t\t\tvisit(turnRecord.id, trace);\n\t\t}\n\t}\n}\n\nexport function buildTurnTracePreviewsFromSession(\n\tinput: TurnTraceCollectionInput,\n): Record<string, TurnTracePreview> {\n\tconst previews: Record<string, TurnTracePreview> = {};\n\tvisitTurnTraces(input, (turnRecordId, trace) => {\n\t\tpreviews[turnRecordId] = buildTurnTracePreview(turnRecordId, trace);\n\t});\n\treturn previews;\n}\n\n/** @internal */\nexport function buildTurnTraceIndexFromSession(\n\tinput: TurnTraceCollectionInput,\n): Record<string, TurnTraceSnapshot> {\n\tconst traces: Record<string, TurnTraceSnapshot> = {};\n\tvisitTurnTraces(input, (turnRecordId, trace) => {\n\t\ttraces[turnRecordId] = trace;\n\t});\n\treturn traces;\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport {\n\tDEFAULT_SESSION_TRANSFER_LIMITS,\n\ttype LeitwerkTransferManifestV1,\n\tparsePiSessionHeader,\n\ttype SessionTransferLimits,\n} from \"@leitwerk-dev/session-transfer\";\nimport type {\n\tPreparedProcessStateExport,\n\tProcessStateExporter,\n} from \"@leitwerk-dev/worker-runners\";\nimport type { LeitwerkConfig } from \"./config/config-types.js\";\nimport type {\n\tRepositoryBundle,\n\tSessionTransferAttempt,\n\tSessionTransferPhase,\n} from \"./db/repositories.js\";\nimport type { ProcessOperationCoordinator } from \"./process-operation-coordinator.js\";\nimport type { ProcessSessionSource } from \"./process-session-store.js\";\nimport type { SessionTransferHelperRelays } from \"./session-transfer-helper-relays.js\";\nimport { createWorkerStorageLayout } from \"./supervisor/worker-storage-layout.js\";\nimport type { WorkerSupervisor } from \"./supervisor/worker-supervisor.js\";\n\nconst GRANT_LIFETIME_MS = 60 * 60 * 1000;\nconst ATTEMPT_LEASE_MS = 90 * 1000;\nconst ATTEMPT_HARD_DEADLINE_MS = 60 * 60 * 1000;\nconst CONSUMED_TOMBSTONE_MS = 24 * 60 * 60 * 1000;\n\ninterface AttemptRuntime {\n\tcontroller: AbortController;\n\tprepared: PreparedProcessStateExport | null;\n\tstreamClaimed: boolean;\n}\n\n/** @internal */\ntype AttemptAuth = Parameters<RepositoryBundle[\"sessionTransfers\"][\"verifyAttempt\"]>[0];\n\nfunction isExportPending(attempt: SessionTransferAttempt): boolean {\n\treturn attempt.state === \"queued\" || attempt.state === \"exporting\";\n}\n\nexport function presentSessionTransferOperation(attempt: SessionTransferAttempt | null) {\n\treturn attempt\n\t\t? {\n\t\t\t\tattemptId: attempt.id,\n\t\t\t\tphase: attempt.phase,\n\t\t\t\tblocksManualTurns: isExportPending(attempt),\n\t\t\t}\n\t\t: null;\n}\n\nfunction relativeSessionCwd(input: {\n\tsourceCwd: string;\n\tworkspaceRoot: string;\n\trepositoryBacked: boolean;\n}): string | null {\n\tif (!input.repositoryBacked) return null;\n\tconst relative = path.relative(path.resolve(input.workspaceRoot), path.resolve(input.sourceCwd));\n\tif (relative === \"\") return \".\";\n\tif (relative === \"..\" || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n\t\tthrow new Error(\"Repository-backed Pi session cwd is outside the process workspace\");\n\t}\n\treturn relative.split(path.sep).join(\"/\");\n}\n\n/** @internal */\nexport function createSessionTransferService(deps: {\n\t/** @internal */\n\trepos: Pick<\n\t\tRepositoryBundle,\n\t\t\"processes\" | \"projects\" | \"leases\" | \"sessionTransfers\" | \"transaction\"\n\t>;\n\t/** @internal */\n\tprocessOperations: ProcessOperationCoordinator;\n\t/** @internal */\n\tsupervisor: WorkerSupervisor;\n\t/** @internal */\n\texporter: ProcessStateExporter;\n\t/** @internal */\n\thelperRelays: SessionTransferHelperRelays;\n\t/** @internal */\n\tsessionSource: ProcessSessionSource;\n\t/** @internal */\n\tconfig: LeitwerkConfig;\n\t/** @internal */\n\tlimits?: SessionTransferLimits;\n\t/** @internal */\n\tnow?: () => Date;\n\t/** @internal */\n\tlogger?: {\n\t\t/** @internal */\n\t\twarn(details: unknown, message: string): void;\n\t};\n\t/** @internal */\n\tonUpdated?: (attempt: SessionTransferAttempt) => void;\n\t/** @internal */\n\tisDeletionPending?: (instanceId: string) => boolean;\n}) {\n\tconst now = deps.now ?? (() => new Date());\n\tconst limits = deps.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;\n\tconst runtimes = new Map<string, AttemptRuntime>();\n\tconst exportWork = new Set<Promise<void>>();\n\tlet sweepTimer: NodeJS.Timeout | null = null;\n\n\tfunction publish(attempt: SessionTransferAttempt | null): SessionTransferAttempt | null {\n\t\tif (attempt && deps.onUpdated) {\n\t\t\ttry {\n\t\t\t\tdeps.onUpdated(attempt);\n\t\t\t} catch (error) {\n\t\t\t\tdeps.logger?.warn(\n\t\t\t\t\t{ error, attemptId: attempt.id },\n\t\t\t\t\t\"session transfer update broadcast failed\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn attempt;\n\t}\n\n\tfunction updatePhase(\n\t\tid: string,\n\t\tphase: SessionTransferPhase,\n\t\textra: Partial<Omit<SessionTransferAttempt, \"state\">> = {},\n\t): SessionTransferAttempt | null {\n\t\tconst current = deps.repos.sessionTransfers.getAttempt(id);\n\t\tif (!current || [\"consumed\", \"cancelled\", \"failed\"].includes(current.phase)) return current;\n\t\treturn publish(deps.repos.sessionTransfers.updateAttempt(id, { phase, ...extra }));\n\t}\n\n\tasync function snapshotManifest(\n\t\tattempt: SessionTransferAttempt,\n\t): Promise<LeitwerkTransferManifestV1> {\n\t\tconst process = deps.repos.processes.getById(attempt.instanceId);\n\t\tif (!process) throw new Error(\"Process was deleted\");\n\t\tconst handle = await deps.sessionSource.readSnapshotHandle(attempt.instanceId);\n\t\tif (!handle) throw new Error(\"Primary Pi session is unavailable\");\n\t\tconst header = parsePiSessionHeader(await handle.load());\n\t\tconst sourceCwd = typeof header.cwd === \"string\" ? header.cwd : \"\";\n\t\tif (!sourceCwd) throw new Error(\"Primary Pi session header has no cwd\");\n\t\tconst projects = deps.repos.projects.listByInstance(attempt.instanceId);\n\t\tconst storage = createWorkerStorageLayout(deps.config)(attempt.instanceId);\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tinstanceId: process.id,\n\t\t\tcreatedAt: now().toISOString(),\n\t\t\tsession: {\n\t\t\t\tsourceCwd,\n\t\t\t\tcwdRelativeToWorkspace: relativeSessionCwd({\n\t\t\t\t\tsourceCwd,\n\t\t\t\t\tworkspaceRoot: storage.workspaceRoot,\n\t\t\t\t\trepositoryBacked: projects.length > 0,\n\t\t\t\t}),\n\t\t\t},\n\t\t\tprojects: projects.map((project) => ({\n\t\t\t\tkey: project.key,\n\t\t\t\trelativePath: project.key,\n\t\t\t\tbranch: null,\n\t\t\t\thead: null,\n\t\t\t})),\n\t\t};\n\t}\n\n\tfunction transitionTerminal(\n\t\tattemptId: string,\n\t\tphase: \"failed\" | \"cancelled\",\n\t\tcode: string,\n\t): SessionTransferAttempt | null {\n\t\tconst current = deps.repos.sessionTransfers.getAttempt(attemptId);\n\t\tif (!current || [\"consumed\", \"cancelled\", \"failed\"].includes(current.phase)) return current;\n\t\tconst attempt = publish(\n\t\t\tdeps.repos.sessionTransfers.updateAttempt(attemptId, {\n\t\t\t\tphase,\n\t\t\t\tfailureCode: code,\n\t\t\t\tcompletedAt: now().toISOString(),\n\t\t\t}),\n\t\t);\n\t\tconst runtime = runtimes.get(attemptId);\n\t\truntime?.controller.abort(new Error(code));\n\t\truntimes.delete(attemptId);\n\t\treturn attempt;\n\t}\n\n\tfunction failAttempt(attemptId: string, code: string): void {\n\t\ttransitionTerminal(attemptId, \"failed\", code);\n\t}\n\n\tfunction launch(attempt: SessionTransferAttempt): void {\n\t\tconst runtime: AttemptRuntime = {\n\t\t\tcontroller: new AbortController(),\n\t\t\tprepared: null,\n\t\t\tstreamClaimed: false,\n\t\t};\n\t\truntimes.set(attempt.id, runtime);\n\t\tconst work = (async () => {\n\t\t\tupdatePhase(attempt.id, \"waiting_for_execution_chain\");\n\t\t\twhile (true) {\n\t\t\t\tconst reserved = await deps.processOperations.runExclusive(attempt.instanceId, () => {\n\t\t\t\t\tconst current = deps.repos.sessionTransfers.getAttempt(attempt.id);\n\t\t\t\t\tif (!current || current.state !== \"queued\") throw new Error(\"transfer_no_longer_queued\");\n\t\t\t\t\tconst process = deps.repos.processes.getById(attempt.instanceId);\n\t\t\t\t\tif (!process) throw new Error(\"process_deleted\");\n\t\t\t\t\tconst lease = deps.repos.leases.getByInstance(attempt.instanceId);\n\t\t\t\t\tconst stable = [\"waiting\", \"error\", \"completed\", \"aborted\"].includes(\n\t\t\t\t\t\tprocess.lifecycleStatus,\n\t\t\t\t\t);\n\t\t\t\t\tif (!stable || (lease && lease.state !== \"idle\" && lease.state !== \"failed\")) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tupdatePhase(attempt.id, \"stopping_worker\");\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (reserved) break;\n\t\t\t\tawait delay(250, undefined, { signal: runtime.controller.signal });\n\t\t\t}\n\n\t\t\truntime.controller.signal.throwIfAborted();\n\t\t\tawait deps.supervisor.stopWorker(attempt.instanceId, \"session_transfer\");\n\t\t\tif (deps.repos.leases.getByInstance(attempt.instanceId)) {\n\t\t\t\tthrow new Error(\"worker_lease_remains\");\n\t\t\t}\n\t\t\truntime.controller.signal.throwIfAborted();\n\t\t\tupdatePhase(attempt.id, \"starting_exporter\");\n\t\t\tconst manifest = await snapshotManifest(attempt);\n\t\t\truntime.controller.signal.throwIfAborted();\n\t\t\tupdatePhase(attempt.id, \"scanning\");\n\t\t\truntime.prepared = await deps.exporter.prepare({\n\t\t\t\tinstanceId: attempt.instanceId,\n\t\t\t\tmanifest,\n\t\t\t\tlimits,\n\t\t\t\tsignal: runtime.controller.signal,\n\t\t\t});\n\t\t\truntime.controller.signal.throwIfAborted();\n\t\t\tupdatePhase(attempt.id, \"ready_to_stream\", {\n\t\t\t\tentriesTotal: runtime.prepared.preflight.entriesTotal,\n\t\t\t\tlogicalBytesTotal: runtime.prepared.preflight.logicalBytesTotal,\n\t\t\t});\n\t\t})()\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tconst current = deps.repos.sessionTransfers.getAttempt(attempt.id);\n\t\t\t\tif (current && isExportPending(current)) {\n\t\t\t\t\tfailAttempt(attempt.id, error instanceof Error ? error.message : \"export_failed\");\n\t\t\t\t}\n\t\t\t\tdeps.logger?.warn({ error, attemptId: attempt.id }, \"session transfer export failed\");\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tconst current = deps.repos.sessionTransfers.getAttempt(attempt.id);\n\t\t\t\tif (current && !isExportPending(current)) {\n\t\t\t\t\truntimes.delete(attempt.id);\n\t\t\t\t}\n\t\t\t});\n\t\texportWork.add(work);\n\t\tvoid work.then(\n\t\t\t() => exportWork.delete(work),\n\t\t\t() => exportWork.delete(work),\n\t\t);\n\t}\n\n\tfunction cancelAttempt(attempt: SessionTransferAttempt, code: string): SessionTransferAttempt {\n\t\tif ([\"consumed\", \"cancelled\", \"failed\"].includes(attempt.phase)) return attempt;\n\t\treturn transitionTerminal(attempt.id, \"cancelled\", code) as SessionTransferAttempt;\n\t}\n\n\tfunction deadlineCode(attempt: SessionTransferAttempt): string | null {\n\t\tconst currentTime = now().getTime();\n\t\tif (Date.parse(attempt.hardDeadline) <= currentTime) return \"hard_deadline_expired\";\n\t\tif (Date.parse(attempt.leaseUntil) <= currentTime) return \"lease_expired\";\n\t\treturn null;\n\t}\n\n\tfunction cancelIfExpired(attempt: SessionTransferAttempt): SessionTransferAttempt {\n\t\tconst code = deadlineCode(attempt);\n\t\treturn (code ? cancelAttempt(attempt, code) : attempt) ?? attempt;\n\t}\n\n\tfunction sweep(): void {\n\t\tconst currentTime = now().getTime();\n\t\tdeps.helperRelays.sweep();\n\t\tfor (const attempt of deps.repos.sessionTransfers.listActive()) {\n\t\t\tif (Date.parse(attempt.hardDeadline) <= currentTime)\n\t\t\t\tcancelAttempt(attempt, \"hard_deadline_expired\");\n\t\t\telse if (Date.parse(attempt.leaseUntil) <= currentTime)\n\t\t\t\tcancelAttempt(attempt, \"lease_expired\");\n\t\t}\n\t\tdeps.repos.sessionTransfers.cleanup(now());\n\t}\n\n\treturn {\n\t\t/** @internal */\n\t\tasync createGrant(instanceId: string) {\n\t\t\treturn deps.processOperations.runExclusive(instanceId, async () => {\n\t\t\t\tif (deps.isDeletionPending?.(instanceId))\n\t\t\t\t\treturn {\n\t\t\t\t\t\t/** @internal */\n\t\t\t\t\t\tkind: \"deletion_pending\" as const,\n\t\t\t\t\t};\n\t\t\t\tif (!deps.repos.processes.getById(instanceId))\n\t\t\t\t\treturn {\n\t\t\t\t\t\t/** @internal */\n\t\t\t\t\t\tkind: \"not_found\" as const,\n\t\t\t\t\t};\n\t\t\t\tconst handle = await deps.sessionSource.readSnapshotHandle(instanceId);\n\t\t\t\tif (!handle) return { kind: \"not_found\" as const };\n\t\t\t\tconst created = deps.repos.sessionTransfers.createGrant({\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tnow: now(),\n\t\t\t\t\tlifetimeMs: GRANT_LIFETIME_MS,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tkind: \"created\" as const,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\tgrantId: created.grant.id,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\trawToken: created.rawToken,\n\t\t\t\t\t/** @internal */\n\t\t\t\t\texpiresAt: created.grant.expiresAt,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\t/** @internal */\n\t\tstartAttempt(input: {\n\t\t\t/** @internal */\n\t\t\tinstanceId: string;\n\t\t\t/** @internal */\n\t\t\tgrantId: string;\n\t\t\t/** @internal */\n\t\t\ttoken: string;\n\t\t}) {\n\t\t\tif (deps.isDeletionPending?.(input.instanceId)) return { kind: \"not_found\" as const };\n\t\t\tconst result = deps.repos.transaction((repos) =>\n\t\t\t\trepos.sessionTransfers.startAttempt({\n\t\t\t\t\t...input,\n\t\t\t\t\tnow: now(),\n\t\t\t\t\tleaseMs: ATTEMPT_LEASE_MS,\n\t\t\t\t\thardDeadlineMs: ATTEMPT_HARD_DEADLINE_MS,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (result.kind === \"created\") {\n\t\t\t\tpublish(result.attempt);\n\t\t\t\tlaunch(result.attempt);\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\t/** @internal */\n\t\theartbeat(input: AttemptAuth) {\n\t\t\tconst attempt = deps.repos.sessionTransfers.verifyAttempt(input);\n\t\t\tif (!attempt) return null;\n\t\t\tconst current = cancelIfExpired(attempt);\n\t\t\tif (current.phase === \"cancelled\" || current.phase === \"failed\") return current;\n\t\t\treturn (\n\t\t\t\tdeps.repos.sessionTransfers.renew(current.id, { now: now(), leaseMs: ATTEMPT_LEASE_MS }) ??\n\t\t\t\tcurrent\n\t\t\t);\n\t\t},\n\t\t/** @internal */\n\t\topenStream(input: AttemptAuth) {\n\t\t\tconst attempt = deps.repos.sessionTransfers.verifyAttempt(input);\n\t\t\tif (!attempt || deadlineCode(attempt)) {\n\t\t\t\tif (attempt) cancelIfExpired(attempt);\n\t\t\t\tthrow new Error(\"transfer_stream_unavailable\");\n\t\t\t}\n\t\t\tconst runtime = runtimes.get(attempt.id);\n\t\t\tif (!runtime?.prepared || attempt.phase !== \"ready_to_stream\" || runtime.streamClaimed) {\n\t\t\t\tthrow new Error(\"transfer_stream_unavailable\");\n\t\t\t}\n\t\t\truntime.streamClaimed = true;\n\t\t\tupdatePhase(attempt.id, \"streaming\");\n\t\t\tlet source: ReturnType<PreparedProcessStateExport[\"stream\"]>;\n\t\t\ttry {\n\t\t\t\tsource = runtime.prepared.stream({\n\t\t\t\t\tsignal: runtime.controller.signal,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tfailAttempt(attempt.id, error instanceof Error ? error.message : \"stream_failed\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst hash = createHash(\"sha256\");\n\t\t\tlet compressedBytes = 0;\n\t\t\tlet finished = false;\n\t\t\tconst meter = new Transform({\n\t\t\t\ttransform(chunk: Buffer, _encoding, callback) {\n\t\t\t\t\tcompressedBytes += chunk.length;\n\t\t\t\t\tif (compressedBytes > limits.maxCompressedBytes) {\n\t\t\t\t\t\tcallback(new Error(\"compressed_limit_exceeded\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\thash.update(chunk);\n\t\t\t\t\tcallback(null, chunk);\n\t\t\t\t},\n\t\t\t\tflush(callback) {\n\t\t\t\t\tif (runtime.controller.signal.aborted) {\n\t\t\t\t\t\tcallback(runtime.controller.signal.reason);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tupdatePhase(attempt.id, \"awaiting_ack\", {\n\t\t\t\t\t\tcompressedBytes,\n\t\t\t\t\t\tstreamSha256: hash.digest(\"hex\"),\n\t\t\t\t\t});\n\t\t\t\t\truntimes.delete(attempt.id);\n\t\t\t\t\tcallback();\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst abortStream = (): void => {\n\t\t\t\tif (!finished) failAttempt(attempt.id, \"stream_interrupted\");\n\t\t\t\truntimes.delete(attempt.id);\n\t\t\t};\n\t\t\tmeter.on(\"error\", (error) => {\n\t\t\t\tif (!finished) failAttempt(attempt.id, error.message || \"stream_failed\");\n\t\t\t\truntimes.delete(attempt.id);\n\t\t\t});\n\t\t\tmeter.on(\"close\", abortStream);\n\t\t\tvoid pipeline(source, meter, { signal: runtime.controller.signal }).catch(() => undefined);\n\t\t\treturn meter;\n\t\t},\n\t\t/** @internal */\n\t\tcancel(\n\t\t\tinput: AttemptAuth & {\n\t\t\t\t/** @internal */\n\t\t\t\tcode?: string;\n\t\t\t},\n\t\t) {\n\t\t\tconst attempt = deps.repos.sessionTransfers.verifyAttempt(input);\n\t\t\treturn attempt ? cancelAttempt(attempt, input.code ?? \"client_cancelled\") : null;\n\t\t},\n\t\t/** @internal */\n\t\tcancelForWeb(instanceId: string, attemptId: string) {\n\t\t\tconst attempt = deps.repos.sessionTransfers.getAttempt(attemptId);\n\t\t\tif (!attempt || attempt.instanceId !== instanceId) return null;\n\t\t\treturn attempt.phase === \"awaiting_ack\"\n\t\t\t\t? attempt\n\t\t\t\t: cancelAttempt(attempt, \"operator_cancelled\");\n\t\t},\n\t\t/** @internal */\n\t\tacknowledge(input: AttemptAuth) {\n\t\t\tconst attempt = deps.repos.sessionTransfers.verifyAttempt(input);\n\t\t\tif (!attempt) return null;\n\t\t\tif (attempt.phase === \"consumed\") return attempt;\n\t\t\tif (deadlineCode(attempt)) {\n\t\t\t\tcancelIfExpired(attempt);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst acknowledged = deps.repos.transaction((repos) =>\n\t\t\t\trepos.sessionTransfers.acknowledge({\n\t\t\t\t\tattemptId: attempt.id,\n\t\t\t\t\tnow: now(),\n\t\t\t\t\ttombstoneMs: CONSUMED_TOMBSTONE_MS,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn publish(acknowledged);\n\t\t},\n\t\t/** @internal */\n\t\tactiveForProcess(instanceId: string) {\n\t\t\treturn deps.repos.sessionTransfers.getActiveByInstance(instanceId);\n\t\t},\n\t\t/** @internal */\n\t\trevokeProcess(instanceId: string) {\n\t\t\tconst active = deps.repos.sessionTransfers.getActiveByInstance(instanceId);\n\t\t\tif (active) cancelAttempt(active, \"process_deleted\");\n\t\t\tdeps.repos.sessionTransfers.revokeProcess(instanceId);\n\t\t},\n\t\t/** @internal */\n\t\tasync reconcile() {\n\t\t\tawait deps.exporter.reconcile();\n\t\t\tfor (const attempt of deps.repos.sessionTransfers.listActive()) {\n\t\t\t\tif (attempt.phase === \"streaming\") {\n\t\t\t\t\tfailAttempt(attempt.id, \"server_restarted_during_stream\");\n\t\t\t\t} else if (attempt.phase !== \"awaiting_ack\") {\n\t\t\t\t\tdeps.repos.sessionTransfers.updateAttempt(attempt.id, { phase: \"queued\" });\n\t\t\t\t\tlaunch({ ...attempt, phase: \"queued\", state: \"queued\" });\n\t\t\t\t}\n\t\t\t}\n\t\t\tsweep();\n\t\t},\n\t\t/** @internal */\n\t\tstart() {\n\t\t\tif (!sweepTimer) sweepTimer = setInterval(sweep, 15_000);\n\t\t},\n\t\t/** @internal */\n\t\tasync stop() {\n\t\t\tif (sweepTimer) clearInterval(sweepTimer);\n\t\t\tsweepTimer = null;\n\t\t\tfor (const runtime of runtimes.values()) {\n\t\t\t\truntime.controller.abort(new Error(\"server_stopping\"));\n\t\t\t}\n\t\t\truntimes.clear();\n\t\t\tdeps.helperRelays.stop();\n\t\t\tconst results = await Promise.allSettled(exportWork);\n\t\t\tconst errors = results\n\t\t\t\t.filter((result) => result.status === \"rejected\")\n\t\t\t\t.map((result) => result.reason);\n\t\t\tif (errors.length) throw new AggregateError(errors, \"Session export cleanup failed\");\n\t\t},\n\t\t/** @internal */\n\t\thelperSpec: deps.helperRelays.helperSpec,\n\t\t/** @internal */\n\t\treportHelperPreflight: deps.helperRelays.reportHelperPreflight,\n\t\t/** @internal */\n\t\tacceptHelperStream: deps.helperRelays.acceptHelperStream,\n\t};\n}\n\n/** @internal */\nexport type SessionTransferService = ReturnType<typeof createSessionTransferService>;\n","import { existsSync, mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { expandPiAgentDir } from \"@leitwerk-dev/process-sdk/pi-config\";\nimport type { LeitwerkConfig } from \"../config/config-types.js\";\n\n/** @internal */\nexport interface WorkerTreePaths {\n\t/** @internal */\n\tprimaryTreeFile: string;\n\t/** @internal */\n\tworkspaceRoot: string;\n\t/** @internal */\n\tpiResourceBundlesDir: string;\n\t/** @internal */\n\tresume: boolean;\n}\n\n/** @internal */\nexport type WorkerStorageLayout = (instanceId: string) => WorkerTreePaths;\n\nfunction normalizeContainerMountPath(mountPath: string): string {\n\tconst trimmed = mountPath.trim();\n\tif (trimmed === \"\") {\n\t\treturn \"/state\";\n\t}\n\tconst withLeadingSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n\treturn path.posix.normalize(withLeadingSlash);\n}\n\nfunction joinContainerPath(mountPath: string, ...segments: string[]): string {\n\tconst normalized = normalizeContainerMountPath(mountPath);\n\treturn path.posix.join(normalized, ...segments);\n}\n\n/** @internal */\nexport function createLocalWorkerStorageLayout(input: {\n\t/** @internal */\n\tprocessWorkspacesDir: string;\n\t/** @internal */\n\ttreeFilesDir: string;\n}): WorkerStorageLayout {\n\treturn (instanceId) => {\n\t\tconst processWorkspacesDir = path.resolve(input.processWorkspacesDir);\n\t\tconst treeFilesDir = path.resolve(input.treeFilesDir);\n\t\tconst workspaceRoot = path.join(processWorkspacesDir, instanceId);\n\t\tconst primaryTreeFile = path.join(treeFilesDir, `${instanceId}.jsonl`);\n\t\tconst resume = existsSync(workspaceRoot) || existsSync(primaryTreeFile);\n\t\tmkdirSync(processWorkspacesDir, { recursive: true });\n\t\tmkdirSync(treeFilesDir, { recursive: true });\n\t\tmkdirSync(workspaceRoot, { recursive: true });\n\t\treturn {\n\t\t\tprimaryTreeFile,\n\t\t\tworkspaceRoot,\n\t\t\tpiResourceBundlesDir: path.join(workspaceRoot, \".leitwerk\", \"pi-resource-bundles\"),\n\t\t\tresume,\n\t\t};\n\t};\n}\n\n/** @internal */\nexport function createProcessVolumeWorkerStorageLayout(input: {\n\t/** @internal */\n\tmountPath: string;\n}): WorkerStorageLayout {\n\treturn () => ({\n\t\tworkspaceRoot: joinContainerPath(input.mountPath, \"workspace\"),\n\t\tprimaryTreeFile: joinContainerPath(input.mountPath, \"tree\", \"primary.jsonl\"),\n\t\tpiResourceBundlesDir: joinContainerPath(input.mountPath, \"pi-resource-bundles\"),\n\t\t// Server-opaque volumes may already contain the authoritative worker tree even\n\t\t// when the server has no fresh snapshot. Never tell the worker to initialize a\n\t\t// known-empty local session just because the server cannot inspect the volume.\n\t\tresume: true,\n\t});\n}\n\nfunction configuredProcessVolumeMountPath(config: LeitwerkConfig): string {\n\treturn config.workers.runner === \"kubernetes\"\n\t\t? (config.kubernetes?.process_volume.mount_path ?? \"/state\")\n\t\t: (config.docker?.process_volume.mount_path ?? \"/state\");\n}\n\nexport function resolveWorkerPiAgentDir(config: LeitwerkConfig, mountPath?: string): string {\n\treturn mountPath\n\t\t? joinContainerPath(mountPath, \"pi-agent\")\n\t\t: expandPiAgentDir(config.pi.agent_dir);\n}\n\n/** @internal */\nexport function createWorkerStorageLayout(config: LeitwerkConfig): WorkerStorageLayout {\n\tif (config.workers.runner === \"docker\" || config.workers.runner === \"kubernetes\") {\n\t\treturn createProcessVolumeWorkerStorageLayout({\n\t\t\tmountPath: configuredProcessVolumeMountPath(config),\n\t\t});\n\t}\n\treturn createLocalWorkerStorageLayout({\n\t\tprocessWorkspacesDir: config.storage.process_workspaces_dir,\n\t\ttreeFilesDir: config.storage.tree_files_dir,\n\t});\n}\n","import {\n\tasUnknownRecord as asRecord,\n\tCONTINUE_PROMPT_METADATA_KEY,\n\tDEFAULT_CONTINUE_PROMPT,\n\tformatProcessIdentifier as formatDefinition,\n\tinferTerminalRecordingFailedTurnRecoveryContext,\n\tnormalizeContinuePrompt,\n\ttype ProcessEvent,\n\ttype ProcessInput,\n\ttype ProcessInstance,\n\ttype ProcessTurnAnnotation,\n\ttype ProcessTurnRecord,\n\tparseProcessStateJsonLenient,\n\treadFailedTurnRecoveryContext,\n\ttrimString as stringValue,\n\ttrimToNull as stringValueOrNull,\n\ttype TurnStartRecord,\n\ttype WorkerLease,\n} from \"@leitwerk-dev/domain\";\nimport { parseStructuralProcessState } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tbuildActiveTimelineTurnSummary,\n\tbuildUsageSnapshotsByTurnRecordId,\n\ttype CompactActiveTurnSnapshot,\n\ttype CompactTurnSummary,\n\ttype CurrentProcessErrorSummary,\n\ttype CurrentTurnRecoverySummary,\n\tcreateLiveTurnProjection,\n\temptyCompactTurnSummary,\n\textractFirstUserPromptOnBranch,\n\textractInitialPromptFromParamsJson,\n\thasTurnContinuationProgress,\n\tmergeUsageSnapshots,\n\ttype PiSessionEntry,\n\ttype PrimaryPathSnapshot,\n\ttype PrimaryPathUiSnapshot,\n\ttype ProcessDetailUiSnapshotResponseBody,\n\ttype ProcessExternalTriggerSignal,\n\ttype ProcessExternalTriggerSummary,\n\ttype ProcessSelectedTurnSummary,\n\ttype ProcessTimelineInputSummary,\n\ttype ProcessTimelineSnapshot,\n\ttype ProcessTimelineTurnSummary,\n\ttype ProcessUiSnapshotProcess,\n\ttype ProcessUsageEstimateSnapshot,\n\tREASONING_PREVIEW_MAX_CHARS,\n\ttype ReadonlyEntryTree,\n\treasoningPreviewTail,\n\tresolveTurnContinuationUserPrompt,\n\ttype TurnReasoningDetailResponseBody,\n\ttype TurnTracePreview,\n\ttype TurnTraceSnapshot,\n\ttimelinePresentationForTurnType,\n} from \"@leitwerk-dev/protocol\";\nimport type { SessionSummary } from \"./db/turn-summary-repo.js\";\nimport { normalizeExternalObservation } from \"./external-source-reporting.js\";\nimport { getScheduledActionDetailForProcess } from \"./future-execution-presenter.js\";\nimport { physicalWorkerStarts } from \"./physical-worker-starts.js\";\nimport type { ReadonlyPiSessionTree } from \"./pi-session-tree.js\";\nimport { listVisibleActionsForProcess } from \"./process-action-presenter.js\";\nimport { pendingTurnWait } from \"./process-engine/turn-wait-state.js\";\nimport { resolveCurrentExecutionTurnRecordId } from \"./process-execution.js\";\nimport { buildProcessFlowViewForProcess, getProcessGraph } from \"./process-graph.js\";\nimport { presentProcessInstanceTree } from \"./process-instance-tree-presenter.js\";\nimport { presentProcessModelConfiguration } from \"./process-model-policy-presenter.js\";\nimport { getProcessDisplayName } from \"./process-operator-attention.js\";\nimport { presentProcessTurnNavigation } from \"./process-turn-navigation.js\";\nimport {\n\tbuildCommittedTurnTrace,\n\tbuildTurnTracePreviewsFromSession,\n} from \"./process-turn-trace.js\";\nimport {\n\tbuildProcessLaunchConfigurationView,\n\tbuildProcessRunDetailsView,\n\tgetSelectedTurnSummaryForProcess,\n\tprocessDefinesLeafOutcome,\n\ttype RouteDeps,\n} from \"./routes/process-route-helpers.js\";\nimport { presentSessionTransferOperation } from \"./session-transfer-service.js\";\nimport { buildStartupEvidence, presentProcessStartupSummary } from \"./startup-evidence.js\";\nimport { normalizeTurnProgressLinks, normalizeTurnProgressReport } from \"./turn-progress.js\";\n\nfunction compactPrimaryPathSnapshot(\n\tsnapshot: PrimaryPathSnapshot | PrimaryPathUiSnapshot,\n): PrimaryPathUiSnapshot {\n\tif (\"entriesOmitted\" in snapshot) return snapshot;\n\tconst active = snapshot.turnState.activeTurn;\n\tconst lastTool = active?.toolCalls.at(-1);\n\tconst activeTurn: CompactActiveTurnSnapshot | null = active\n\t\t? {\n\t\t\t\t...emptyCompactTurnSummary(),\n\t\t\t\tturnRecordId: active.turnRecordId,\n\t\t\t\tturnId: active.turnId,\n\t\t\t\tturnType: active.turnType,\n\t\t\t\tpathType: active.pathType,\n\t\t\t\tstartedAt: active.startedAt,\n\t\t\t\tassistant: {\n\t\t\t\t\t...active.assistant,\n\t\t\t\t\ttext: reasoningPreviewTail(active.assistant.text),\n\t\t\t\t\tthinking: reasoningPreviewTail(active.assistant.thinking),\n\t\t\t\t},\n\t\t\t\tcurrentTool: lastTool\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttoolCallId: lastTool.toolCallId,\n\t\t\t\t\t\t\ttoolName: lastTool.toolName,\n\t\t\t\t\t\t\tstatus: lastTool.status,\n\t\t\t\t\t\t\tisError: lastTool.isError,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttoolCallCount: active.toolCalls.length,\n\t\t\t\ttraceItemCount: active.traceItems.length,\n\t\t\t\tusage: active.usage,\n\t\t\t\tsummaryPending: false,\n\t\t\t}\n\t\t: null;\n\treturn {\n\t\t...snapshot,\n\t\tprimaryPathEntries: [],\n\t\tlabels: {},\n\t\tthroughEventSequence: 0,\n\t\tturnState: { ...snapshot.turnState, activeTurn },\n\t\tentryCount: snapshot.primaryPathEntries.length,\n\t\tentriesOmitted: true,\n\t};\n}\n\nexport function projectProcessForUiSnapshot(process: ProcessInstance): ProcessUiSnapshotProcess {\n\treturn {\n\t\tid: process.id,\n\t\tprocessId: process.processId,\n\t\tselectedTurnId: process.selectedTurnId,\n\t\tlifecycleStatus: process.lifecycleStatus,\n\t\tcurrentExecution: process.currentExecution,\n\t\tplanRevision: process.planRevision,\n\t\ttitle: process.title,\n\t\texternalId: process.externalId,\n\t\texternalUrl: process.externalUrl,\n\t\tinitialDefaultModelProfileId: process.initialDefaultModelProfileId ?? null,\n\t\tcreatedAt: process.createdAt,\n\t\tupdatedAt: process.updatedAt,\n\t\tclosedAt: process.closedAt ?? null,\n\t};\n}\n\nexport { buildStartupRecovery } from \"./startup-evidence.js\";\n\nfunction readPersistedModelSelectionWarning(\n\tprocess: Pick<ProcessInstance, \"lifecycleStatus\" | \"metadata\">,\n): string | null {\n\tif (process.lifecycleStatus === \"completed\" || process.lifecycleStatus === \"aborted\") return null;\n\tconst leitwerkMetadata = asRecord(process.metadata?._leitwerk);\n\tconst issue = asRecord(leitwerkMetadata?.persistedModelSelectionIssue);\n\treturn typeof issue?.summary === \"string\" ? issue.summary : null;\n}\n\nfunction paramsRecord(value: unknown): Record<string, unknown> {\n\treturn asRecord(value) ?? {};\n}\n\nfunction indexByTurnRecordId<T>(\n\trecords: readonly T[],\n\tkey: (record: T) => string | null,\n): Map<string, T> {\n\treturn new Map(\n\t\trecords.flatMap((record) => {\n\t\t\tconst id = key(record);\n\t\t\treturn id ? [[id, record] as const] : [];\n\t\t}),\n\t);\n}\n\nfunction turnRecordIdFromAnnotation(annotation: ProcessTurnAnnotation): string | null {\n\treturn (\n\t\tannotation.references.find((reference) => reference.kind === \"turn_record\")?.turnRecordId ??\n\t\tnull\n\t);\n}\n\nfunction outputFromTurnParams(\n\tparams: Record<string, unknown>,\n\toptions: { includeMarkdownFields: boolean },\n): string {\n\treturn (\n\t\t(options.includeMarkdownFields\n\t\t\t? stringValue(params.planMarkdown) ||\n\t\t\t\tstringValue(params.reviewMarkdown) ||\n\t\t\t\tstringValue(params.feedback)\n\t\t\t: stringValue(params.feedback)) || stringValue(params.summary)\n\t);\n}\n\nfunction summarizeTurnOutcome(\n\tturnId: string,\n\toutcome: string,\n\tparams: Record<string, unknown>,\n): string {\n\tconst summary = stringValue(params.summary);\n\tif (summary) return summary;\n\treturn `${formatDefinition(turnId)}: ${formatDefinition(outcome)}`;\n}\n\nfunction fallbackOutcomeFromTurnRecord(turnRecord: ProcessTurnRecord): string {\n\treturn [\"failed\", \"superseded\", \"succeeded\"].includes(turnRecord.status)\n\t\t? turnRecord.status\n\t\t: \"completed\";\n}\n\nfunction fallbackSummaryFromTurnRecord(turnRecord: ProcessTurnRecord): string {\n\tswitch (turnRecord.status) {\n\t\tcase \"failed\":\n\t\t\treturn (\n\t\t\t\tstringValue(turnRecord.errorSummary) || `${formatDefinition(turnRecord.turnId)} failed`\n\t\t\t);\n\t\tcase \"superseded\":\n\t\t\treturn `${formatDefinition(turnRecord.turnId)} superseded`;\n\t\tcase \"succeeded\":\n\t\t\treturn `${formatDefinition(turnRecord.turnId)} completed`;\n\t\tdefault:\n\t\t\treturn `Current step: ${formatDefinition(turnRecord.turnId ?? \"unknown\")}`;\n\t}\n}\n\nfunction annotationLabel(annotation: ProcessTurnAnnotation): string {\n\treturn (\n\t\tstringValue(paramsRecord(annotation.payload.eventDescription).summary) ||\n\t\tstringValue(annotation.payload.actionLabel) ||\n\t\tstringValue(annotation.payload.triggerLabel) ||\n\t\tstringValue(annotation.payload.label) ||\n\t\tstringValue(annotation.payload.actionId) ||\n\t\tstringValue(annotation.payload.acceptanceState)\n\t);\n}\n\nfunction annotationOutput(annotation: ProcessTurnAnnotation): string {\n\tconst fields = Array.isArray(annotation.payload.submittedFields)\n\t\t? annotation.payload.submittedFields\n\t\t: [];\n\tconst actor = paramsRecord(annotation.payload.actor);\n\tconst attribution = stringValue(actor.displayName) || stringValue(actor.id);\n\treturn [\n\t\tstringValue(paramsRecord(annotation.payload.eventDescription).markdown) ||\n\t\t\tstringValue(annotation.payload.triggerDescription) ||\n\t\t\tstringValue(annotation.payload.description),\n\t\tattribution ? `Actor:\\n${attribution}` : \"\",\n\t\t...fields.map((field: unknown) => {\n\t\t\tconst record = paramsRecord(field);\n\t\t\tconst label = stringValue(record.label) || stringValue(record.fieldId);\n\t\t\tconst value = stringValue(record.value);\n\t\t\treturn label && value ? `${label}:\\n${value}` : \"\";\n\t\t}),\n\t]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n}\n\ntype TimelineActionSource = ProcessTimelineTurnSummary[\"actionSource\"];\n\nfunction buildTurnProgressIndex(events: readonly ProcessEvent[]) {\n\tconst index = new Map<\n\t\tstring,\n\t\t{ progress: NonNullable<ProcessTimelineTurnSummary[\"progress\"]>; progressRecordedAt: string }\n\t>();\n\tconst revisions = new Map<string, number>();\n\tfor (const event of events) {\n\t\tif (event.eventType !== \"turn.progress\") continue;\n\t\tconst turnRecordId = stringValue(event.data.turnRecordId);\n\t\tconst report = normalizeTurnProgressReport(event.data.report);\n\t\tconst revision = Number(event.data.revision ?? 0);\n\t\tif (\n\t\t\tturnRecordId &&\n\t\t\treport &&\n\t\t\tNumber.isSafeInteger(revision) &&\n\t\t\trevision >= (revisions.get(turnRecordId) ?? -1)\n\t\t) {\n\t\t\trevisions.set(turnRecordId, revision);\n\t\t\tindex.set(turnRecordId, { progress: report, progressRecordedAt: event.createdAt });\n\t\t}\n\t}\n\treturn index;\n}\n\nfunction actionSourceFromAnnotation(annotation: ProcessTurnAnnotation): TimelineActionSource {\n\tconst source = annotation.payload.actionSource;\n\treturn source === \"ui\" || source === \"external\" || source === \"scheduled\" ? source : null;\n}\n\nfunction buildActionSourceIndex(\n\tannotations: readonly ProcessTurnAnnotation[],\n\tturnRecords: readonly ProcessTurnRecord[],\n): Map<string, Exclude<TimelineActionSource, null>> {\n\tconst sortedTurnRecords = [...turnRecords].sort(\n\t\t(left, right) =>\n\t\t\tleft.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),\n\t);\n\tconst turnRecordById = new Map(sortedTurnRecords.map((record) => [record.id, record]));\n\tconst direct = new Map<string, Exclude<TimelineActionSource, null>>();\n\tfor (const annotation of annotations) {\n\t\tconst turnRecordId = turnRecordIdFromAnnotation(annotation);\n\t\tconst source = actionSourceFromAnnotation(annotation);\n\t\tif (turnRecordId && source) direct.set(turnRecordId, source);\n\t}\n\tconst index = new Map(direct);\n\tfor (const annotation of annotations) {\n\t\tconst source = actionSourceFromAnnotation(annotation);\n\t\tconst targetId = stringValue(annotation.payload.targetTurnRecordId);\n\t\tif (source && turnRecordById.has(targetId) && !direct.has(targetId))\n\t\t\tindex.set(targetId, source);\n\t}\n\tfor (const record of sortedTurnRecords) {\n\t\tif (!index.has(record.id) && record.parentTurnRecordId) {\n\t\t\tconst source = index.get(record.parentTurnRecordId);\n\t\t\tif (source) index.set(record.id, source);\n\t\t}\n\t}\n\n\treturn index;\n}\n\nfunction effectiveTurnRecordForDisplay(\n\tturnRecord: ProcessTurnRecord,\n\tprocess: ProcessInstance,\n): ProcessTurnRecord {\n\tif (\n\t\tturnRecord.status !== \"running\" ||\n\t\t(process.lifecycleStatus !== \"completed\" && process.lifecycleStatus !== \"aborted\")\n\t) {\n\t\treturn turnRecord;\n\t}\n\treturn {\n\t\t...turnRecord,\n\t\tstatus: process.lifecycleStatus === \"completed\" ? \"succeeded\" : \"superseded\",\n\t\tendedAt: turnRecord.endedAt ?? process.updatedAt,\n\t};\n}\n\n/** @internal */\nexport function presentProcessTimelineTurns(input: {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tcurrentExecutionTurnRecordId?: string | null;\n\t/** @internal */\n\tturnRecords: readonly ProcessTurnRecord[];\n\t/** @internal */\n\tturnAnnotations: readonly ProcessTurnAnnotation[];\n\t/** @internal */\n\tevents: readonly ProcessEvent[];\n\t/** @internal */\n\tactiveTurn: PrimaryPathSnapshot[\"turnState\"][\"activeTurn\"] | CompactActiveTurnSnapshot;\n\t/** @internal */\n\tselectedTurnType: ProcessTurnRecord[\"turnType\"] | null;\n\t/** @internal */\n\tactiveModelProfileId?: string | null;\n}): ProcessTimelineTurnSummary[] {\n\tconst outcomeEventsByTurnRecordId = indexByTurnRecordId(\n\t\tinput.events.filter((event) => event.eventType === \"turn_outcome_recorded\"),\n\t\t(event) => stringValue(paramsRecord(event.data).turnRecordId),\n\t);\n\tconst progressByTurnRecordId = buildTurnProgressIndex(input.events);\n\tconst annotationMap = (annotationType: string) =>\n\t\tindexByTurnRecordId(\n\t\t\tinput.turnAnnotations.filter((annotation) => annotation.annotationType === annotationType),\n\t\t\tturnRecordIdFromAnnotation,\n\t\t);\n\tconst milestoneAnnotationsByTurnRecordId = annotationMap(\"turn_milestone\");\n\tconst acceptanceAnnotationsByTurnRecordId = annotationMap(\"acceptance_state\");\n\tconst externalTriggerAnnotationsByTurnRecordId = annotationMap(\"external_trigger\");\n\tconst actionSourceByTurnRecordId = buildActionSourceIndex(\n\t\tinput.turnAnnotations,\n\t\tinput.turnRecords,\n\t);\n\tconst turns: ProcessTimelineTurnSummary[] = [];\n\tconst sortedTurnRecords = [...input.turnRecords].sort((left, right) =>\n\t\tleft.startedAt.localeCompare(right.startedAt),\n\t);\n\tconst hasRunningTurn = sortedTurnRecords.some((turnRecord) => turnRecord.status === \"running\");\n\tconst retryReplacingFailedTurnRecordId =\n\t\t!input.activeTurn &&\n\t\t!hasRunningTurn &&\n\t\tinput.process.lifecycleStatus === \"active\" &&\n\t\tinput.currentExecutionTurnRecordId == null &&\n\t\ttypeof input.process.metadata?.retryFromTurnRecordId === \"string\"\n\t\t\t? input.process.metadata.retryFromTurnRecordId\n\t\t\t: null;\n\n\tfor (const durableTurnRecord of sortedTurnRecords) {\n\t\tif (\n\t\t\tretryReplacingFailedTurnRecordId === durableTurnRecord.id &&\n\t\t\tdurableTurnRecord.status === \"failed\" &&\n\t\t\tdurableTurnRecord.turnId === input.process.selectedTurnId\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst turnRecord = effectiveTurnRecordForDisplay(durableTurnRecord, input.process);\n\t\tconst common = {\n\t\t\tid: turnRecord.id,\n\t\t\tturnType: turnRecord.turnType,\n\t\t\tpathType: turnRecord.pathType,\n\t\t\tpresentation: timelinePresentationForTurnType(turnRecord.turnType),\n\t\t\tmodelProfileId: turnRecord.modelProfileId ?? null,\n\t\t\tactionSource: actionSourceByTurnRecordId.get(turnRecord.id) ?? null,\n\t\t\tattemptNumber: turnRecord.attemptNumber,\n\t\t\tparentTurnRecordId: turnRecord.parentTurnRecordId,\n\t\t\tstartedAt: turnRecord.startedAt,\n\t\t\tendedAt: turnRecord.endedAt,\n\t\t\t...progressByTurnRecordId.get(turnRecord.id),\n\t\t};\n\t\tif (turnRecord.status === \"running\") {\n\t\t\tturns.push({\n\t\t\t\t...common,\n\t\t\t\tturnId: turnRecord.turnId,\n\t\t\t\tdisplayTurn: turnRecord.turnId,\n\t\t\t\toutcome: \"in_progress\",\n\t\t\t\tsummary: `Current step: ${formatDefinition(turnRecord.turnId)}`,\n\t\t\t\toutput:\n\t\t\t\t\tinput.activeTurn?.turnRecordId === turnRecord.id\n\t\t\t\t\t\t? input.activeTurn.assistant.text.trim()\n\t\t\t\t\t\t: \"\",\n\t\t\t\tturnResultMarkdown: \"\",\n\t\t\t\tcreatedAt: turnRecord.startedAt,\n\t\t\t\tstatus: \"in_progress\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst turnResultMarkdown = stringValue(turnRecord.turnResultMarkdown);\n\t\tconst outcomeEvent = outcomeEventsByTurnRecordId.get(turnRecord.id);\n\t\tconst milestoneAnnotation = milestoneAnnotationsByTurnRecordId.get(turnRecord.id);\n\t\tconst actionAnnotation =\n\t\t\tacceptanceAnnotationsByTurnRecordId.get(turnRecord.id) ??\n\t\t\texternalTriggerAnnotationsByTurnRecordId.get(turnRecord.id);\n\t\tlet presentation: Pick<\n\t\t\tProcessTimelineTurnSummary,\n\t\t\t\"turnId\" | \"outcome\" | \"summary\" | \"output\" | \"createdAt\"\n\t\t> & { displayTurn?: string };\n\n\t\tconst recordedOutcome = outcomeEvent ?? (!actionAnnotation ? milestoneAnnotation : null);\n\t\tif (recordedOutcome) {\n\t\t\tconst data = \"data\" in recordedOutcome ? recordedOutcome.data : recordedOutcome.payload;\n\t\t\tconst turnId = stringValue(data.turnId) || turnRecord.turnId || \"turn\";\n\t\t\tconst outcome =\n\t\t\t\tstringValue(data.outcome) ||\n\t\t\t\tstringValue(milestoneAnnotation?.payload.outcome) ||\n\t\t\t\tfallbackOutcomeFromTurnRecord(turnRecord);\n\t\t\tconst params = paramsRecord(outcomeEvent?.data.params);\n\t\t\tpresentation = {\n\t\t\t\tturnId,\n\t\t\t\toutcome,\n\t\t\t\tsummary: summarizeTurnOutcome(turnId, outcome, params),\n\t\t\t\toutput: outputFromTurnParams(params, { includeMarkdownFields: !turnResultMarkdown }),\n\t\t\t\tcreatedAt: turnRecord.endedAt ?? recordedOutcome.createdAt ?? turnRecord.startedAt,\n\t\t\t};\n\t\t} else if (actionAnnotation) {\n\t\t\tconst label = annotationLabel(actionAnnotation);\n\t\t\tpresentation = {\n\t\t\t\tturnId: turnRecord.turnId,\n\t\t\t\tdisplayTurn: label || turnRecord.turnId,\n\t\t\t\toutcome: label || \"completed\",\n\t\t\t\tsummary:\n\t\t\t\t\tlabel ||\n\t\t\t\t\t(externalTriggerAnnotationsByTurnRecordId.has(turnRecord.id)\n\t\t\t\t\t\t? \"External event received\"\n\t\t\t\t\t\t: \"Operator action recorded\"),\n\t\t\t\toutput: annotationOutput(actionAnnotation),\n\t\t\t\tcreatedAt: actionAnnotation.createdAt ?? turnRecord.endedAt ?? turnRecord.startedAt,\n\t\t\t};\n\t\t} else {\n\t\t\tconst summary = fallbackSummaryFromTurnRecord(turnRecord);\n\t\t\tpresentation = {\n\t\t\t\tturnId: turnRecord.turnId,\n\t\t\t\toutcome: fallbackOutcomeFromTurnRecord(turnRecord),\n\t\t\t\tsummary,\n\t\t\t\toutput: turnResultMarkdown ? \"\" : stringValue(turnRecord.errorSummary) || summary,\n\t\t\t\tcreatedAt: turnRecord.endedAt ?? turnRecord.startedAt,\n\t\t\t};\n\t\t}\n\t\tconst payload = actionAnnotation?.payload ?? milestoneAnnotation?.payload;\n\t\tconst selectedTurnId =\n\t\t\tstringValue(payload?.selectedTurnIdAfter) || stringValue(payload?.causedSelectedTurnId);\n\t\tconst targetTurnRecordId = stringValue(payload?.targetTurnRecordId);\n\t\tturns.push({\n\t\t\t...common,\n\t\t\tresources:\n\t\t\t\tnormalizeTurnProgressLinks(\n\t\t\t\t\tparamsRecord(actionAnnotation?.payload.eventDescription).links,\n\t\t\t\t) ?? [],\n\t\t\t...(stringValue(actionAnnotation?.payload.sourceTurnRecordId)\n\t\t\t\t? { reviewedTurnRecordId: stringValue(actionAnnotation?.payload.sourceTurnRecordId) }\n\t\t\t\t: {}),\n\t\t\t...(selectedTurnId\n\t\t\t\t? {\n\t\t\t\t\t\ttransition: {\n\t\t\t\t\t\t\tselectedTurnId,\n\t\t\t\t\t\t\t...(targetTurnRecordId ? { targetTurnRecordId } : {}),\n\t\t\t\t\t\t\taccepted: Boolean(\n\t\t\t\t\t\t\t\ttargetTurnRecordId &&\n\t\t\t\t\t\t\t\t\tinput.turnRecords.some((record) => record.id === targetTurnRecordId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...presentation,\n\t\t\tdisplayTurn: presentation.displayTurn ?? presentation.turnId,\n\t\t\toutput: presentation.output.trim() || (turnResultMarkdown ? \"\" : presentation.summary),\n\t\t\tturnResultMarkdown,\n\t\t\tstatus: \"completed\",\n\t\t\tprogress: common.progress ?? null,\n\t\t\t...(stringValue(milestoneAnnotation?.payload.resultSummary)\n\t\t\t\t? { resultSummary: stringValue(milestoneAnnotation?.payload.resultSummary) }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\n\tif (\n\t\tinput.activeTurn &&\n\t\t!turns.some((turnRecord) => turnRecord.id === input.activeTurn?.turnRecordId)\n\t) {\n\t\tconst activeTurn = input.activeTurn;\n\t\tturns.push(\n\t\t\tbuildActiveTimelineTurnSummary(activeTurn, {\n\t\t\t\tsummary: `Current step: ${formatDefinition(activeTurn.turnId)}`,\n\t\t\t\toutput: activeTurn.assistant.text.trim(),\n\t\t\t\tactionSource: actionSourceByTurnRecordId.get(activeTurn.turnRecordId) ?? null,\n\t\t\t}),\n\t\t);\n\t} else if (\n\t\t!turns.some((turnRecord) => turnRecord.status === \"in_progress\") &&\n\t\tinput.process.lifecycleStatus === \"active\"\n\t) {\n\t\tconst turnId = input.process.selectedTurnId ?? \"unknown\";\n\t\tturns.push({\n\t\t\t...buildActiveTimelineTurnSummary(\n\t\t\t\t{\n\t\t\t\t\tturnRecordId: input.currentExecutionTurnRecordId ?? `current:${turnId}`,\n\t\t\t\t\tturnId,\n\t\t\t\t\tturnType: input.selectedTurnType ?? \"llm\",\n\t\t\t\t\tpathType: \"primary\",\n\t\t\t\t\tstartedAt: input.process.updatedAt,\n\t\t\t\t\tassistant: { text: \"\", thinking: \"\", lastUpdatedAt: null },\n\t\t\t\t},\n\t\t\t\t{ summary: `Current step: ${formatDefinition(turnId)}`, output: \"\" },\n\t\t\t),\n\t\t\tmodelProfileId:\n\t\t\t\tinput.activeModelProfileId === undefined\n\t\t\t\t\t? (input.process.selectedTurnModelProfileId ?? null)\n\t\t\t\t\t: input.activeModelProfileId,\n\t\t});\n\t}\n\n\treturn turns;\n}\n\nfunction buildTimelineInputSummary(input: ProcessInput): ProcessTimelineInputSummary {\n\treturn {\n\t\tid: input.id,\n\t\tsequence: input.sequence,\n\t\tsource: input.source,\n\t\tkind: input.kind,\n\t\tbodyMarkdown: input.bodyMarkdown,\n\t\treceivedAt: input.receivedAt,\n\t\tconsumedAt: input.consumedAt,\n\t};\n}\n\nfunction matchesTrigger(trigger: ProcessExternalTriggerSummary, event: ProcessEvent): boolean {\n\tconst armingId = stringValueOrNull(event.data.armingId);\n\tconst legacyTriggerId = stringValueOrNull(event.data.trigger);\n\treturn armingId === trigger.id || legacyTriggerId === trigger.id;\n}\n\nfunction setupDetail(event: ProcessEvent | null): string | null {\n\tif (!event) {\n\t\treturn null;\n\t}\n\tconst provider = asRecord(event.data.provider) ?? {};\n\tconst path = stringValueOrNull(event.data.path) ?? stringValueOrNull(provider.path);\n\tconst pollInterval =\n\t\tstringValueOrNull(event.data.pollInterval) ?? stringValueOrNull(provider.pollInterval);\n\tif (path && pollInterval) {\n\t\treturn `Watching ${path} · polling every ${pollInterval}.`;\n\t}\n\tif (path) {\n\t\treturn `Watching ${path}.`;\n\t}\n\tif (pollInterval) {\n\t\treturn `Polling every ${pollInterval}.`;\n\t}\n\treturn null;\n}\n\nfunction joinDetails(...parts: Array<string | null>): string | null {\n\tconst joined = parts.filter((part) => part && part.trim().length > 0).join(\" \");\n\treturn joined.length > 0 ? joined : null;\n}\n\n/** @internal */\nexport function buildExternalTriggerSignals(args: {\n\t/** @internal */\n\texternalTriggers: readonly ProcessExternalTriggerSummary[];\n\t/** @internal */\n\tevents: readonly ProcessEvent[];\n\t/** @internal */\n\tisWaitingForSelectedTurn: boolean;\n}): ProcessExternalTriggerSignal[] {\n\treturn args.externalTriggers.map((trigger) => {\n\t\tconst matchingEvents = args.events.filter((event) => matchesTrigger(trigger, event));\n\t\tconst latestEvent = matchingEvents.at(-1) ?? null;\n\t\tconst latestArmedEvent =\n\t\t\tmatchingEvents.findLast(\n\t\t\t\t(event) =>\n\t\t\t\t\tevent.eventType === \"external_trigger_listener_armed\" ||\n\t\t\t\t\tevent.eventType === \"external_source_armed\",\n\t\t\t) ?? null;\n\t\tconst latestConfiguredEvent = latestArmedEvent ?? latestEvent;\n\t\tconst configuredDetail = setupDetail(latestConfiguredEvent);\n\t\tlet state: ProcessExternalTriggerSignal[\"state\"] = \"waiting\";\n\t\tlet occurredAt: string | null = null;\n\t\tlet secondaryDetail = configuredDetail;\n\t\tif (\n\t\t\tlatestEvent?.eventType === \"external_trigger_failed\" ||\n\t\t\tlatestEvent?.eventType === \"external_source_failed\"\n\t\t) {\n\t\t\tstate = \"error\";\n\t\t\toccurredAt = latestEvent.createdAt;\n\t\t\tsecondaryDetail = joinDetails(stringValueOrNull(latestEvent.data.message), configuredDetail);\n\t\t} else if (args.isWaitingForSelectedTurn) {\n\t\t\tstate = \"armed\";\n\t\t\toccurredAt = latestArmedEvent?.createdAt ?? null;\n\t\t\tsecondaryDetail = configuredDetail ?? \"No trigger attempts recorded yet.\";\n\t\t} else if (\n\t\t\tlatestEvent?.eventType === \"external_trigger_consumed\" ||\n\t\t\tlatestEvent?.eventType === \"external_source_consumed\"\n\t\t) {\n\t\t\tstate = \"triggered\";\n\t\t\toccurredAt = latestEvent.createdAt;\n\t\t}\n\t\treturn { triggerId: trigger.id, state, occurredAt, secondaryDetail };\n\t});\n}\n\nconst PROCESS_ERROR_CATEGORY_LABELS: Record<string, string> = {\n\tllm_error: \"The model request failed\",\n\tgit_error: \"A git operation failed\",\n\tpi_crash: \"The agent crashed\",\n\tpipeline_error: \"The CI pipeline failed\",\n\tinfrastructure: \"An internal error occurred\",\n\tprotocol_error: \"An internal error occurred\",\n\toperator_abort: \"The process was stopped\",\n};\n\nconst PROCESS_ERROR_GUIDANCE: Record<string, string> = {\n\tllm_error:\n\t\t\"Retry once provider capacity or quota is available, or switch to a different model before continuing.\",\n\tgit_error: \"Check the repository state, then retry or restart the process.\",\n\tpipeline_error: \"Review the pipeline output, then retry once the issue is resolved.\",\n\tpi_crash: \"Inspect the latest state, then retry or restart the process.\",\n};\n\nconst DEFAULT_PROCESS_ERROR_SUMMARY =\n\t\"This process is parked in error and needs operator attention before it can continue.\";\nconst DEFAULT_PROCESS_ERROR_GUIDANCE =\n\t\"This process stopped before it produced a recoverable failed turn. Inspect the latest state, then retry or restart it when you are ready.\";\n\nfunction lowerFirst(value: string): string {\n\tconst second = value[1];\n\treturn second && second === second.toUpperCase() && second !== second.toLowerCase()\n\t\t? value\n\t\t: value.charAt(0).toLowerCase() + value.slice(1);\n}\n\nfunction findProviderMessage(value: unknown): string | null {\n\tconst record = asRecord(value);\n\tif (!record) return null;\n\tconst message = stringValueOrNull(record.message);\n\treturn message ?? (record.error === undefined ? null : findProviderMessage(record.error));\n}\n\nfunction extractProviderMessage(value: string): string | null {\n\tconst braceIndex = value.indexOf(\"{\");\n\tif (braceIndex < 0) return null;\n\ttry {\n\t\treturn findProviderMessage(JSON.parse(value.slice(braceIndex)));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function formatProcessErrorPresentation(\n\trawReason: string | null | undefined,\n\terrorClass?: string | null,\n): { summary: string; guidance: string; technicalDetail: string | null } {\n\tconst raw = (rawReason ?? \"\").trim();\n\tconst category = errorClass ? PROCESS_ERROR_CATEGORY_LABELS[errorClass] : undefined;\n\tconst guidance =\n\t\t(errorClass && PROCESS_ERROR_GUIDANCE[errorClass]) || DEFAULT_PROCESS_ERROR_GUIDANCE;\n\tif (!raw) {\n\t\treturn {\n\t\t\tsummary: category ?? DEFAULT_PROCESS_ERROR_SUMMARY,\n\t\t\tguidance,\n\t\t\ttechnicalDetail: null,\n\t\t};\n\t}\n\tconst withoutPrefix = raw.replace(/^Turn\\s+'[^']*'\\s+.*?failed:\\s*/i, \"\").trim() || raw;\n\tif (\n\t\t(!errorClass || errorClass === \"llm_error\") &&\n\t\twithoutPrefix.startsWith(\"Turn aborted by LLM:\")\n\t) {\n\t\tconst reason = withoutPrefix.slice(\"Turn aborted by LLM:\".length).trim();\n\t\treturn {\n\t\t\tsummary: reason\n\t\t\t\t? `The agent stopped this turn — ${lowerFirst(reason)}`\n\t\t\t\t: \"The agent stopped this turn\",\n\t\t\tguidance:\n\t\t\t\t\"Review the reported reason and resolve any blocker before continuing or retrying the turn.\",\n\t\t\ttechnicalDetail: raw,\n\t\t};\n\t}\n\tconst detail = extractProviderMessage(withoutPrefix) ?? withoutPrefix;\n\tconst summary =\n\t\tcategory && detail.toLowerCase() !== category.toLowerCase()\n\t\t\t? `${category} — ${lowerFirst(detail)}`\n\t\t\t: (category ?? detail);\n\treturn {\n\t\tsummary: summary || DEFAULT_PROCESS_ERROR_SUMMARY,\n\t\tguidance,\n\t\ttechnicalDetail: raw === summary ? null : raw,\n\t};\n}\n\n/** @internal */\nexport function buildCurrentTurnRecovery(input: {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tturnStarts: {\n\t\t/** @internal */\n\t\tgetById(id: string): import(\"@leitwerk-dev/domain\").TurnStartRecord | null;\n\t};\n\t/** @internal */\n\tturnRecords: readonly ProcessTurnRecord[];\n\t/** @internal */\n\tselectedTurnDescription: string | null;\n\t/** @internal */\n\tpiEntries: readonly PiSessionEntry[];\n\t/** @internal */\n\tcontinuation?: {\n\t\t/** @internal */\n\t\thasProgress: boolean;\n\t\t/** @internal */\n\t\tuserPrompt: string | null;\n\t};\n}): CurrentTurnRecoverySummary | null {\n\tif (input.process.lifecycleStatus !== \"error\") {\n\t\treturn null;\n\t}\n\tconst failedTurnRecordId = resolveCurrentExecutionTurnRecordId(input.process, input.turnStarts);\n\tif (!failedTurnRecordId) {\n\t\treturn null;\n\t}\n\tconst failedTurnRecord = input.turnRecords.find(\n\t\t(turnRecord) => turnRecord.id === failedTurnRecordId,\n\t);\n\tif (\n\t\t!failedTurnRecord ||\n\t\tfailedTurnRecord.status !== \"failed\" ||\n\t\tfailedTurnRecord.turnId !== input.process.selectedTurnId\n\t) {\n\t\treturn null;\n\t}\n\tconst recoveryContext =\n\t\treadFailedTurnRecoveryContext(input.process.metadata, failedTurnRecord.id) ??\n\t\tinferTerminalRecordingFailedTurnRecoveryContext(failedTurnRecord);\n\tconst continuationBounds = { endedAt: failedTurnRecord.endedAt };\n\tconst canContinue =\n\t\tfailedTurnRecord.turnType === \"llm\" &&\n\t\trecoveryContext !== null &&\n\t\t(input.continuation?.hasProgress ??\n\t\t\thasTurnContinuationProgress(input.piEntries, failedTurnRecord, continuationBounds));\n\tconst rawErrorSummary = stringValueOrNull(failedTurnRecord.errorSummary);\n\tconst presentation = formatProcessErrorPresentation(rawErrorSummary, failedTurnRecord.errorClass);\n\tconst acceptedStart =\n\t\tinput.process.currentExecution?.kind === \"worker_start\"\n\t\t\t? input.turnStarts.getById(input.process.currentExecution.id)\n\t\t\t: null;\n\tconst acceptedLlmStart =\n\t\tacceptedStart?.state.kind === \"accepted\" && acceptedStart.state.start.kind === \"llm\"\n\t\t\t? acceptedStart.state.start\n\t\t\t: null;\n\treturn {\n\t\tturnRecordId: failedTurnRecord.id,\n\t\ttitle: input.selectedTurnDescription ?? formatDefinition(failedTurnRecord.turnId),\n\t\tsummary: presentation.summary,\n\t\tguidance: presentation.guidance,\n\t\ttechnicalDetail: presentation.technicalDetail,\n\t\tdefaultContinuePrompt:\n\t\t\tinput.continuation?.userPrompt ??\n\t\t\tresolveTurnContinuationUserPrompt(input.piEntries, failedTurnRecord, continuationBounds) ??\n\t\t\tnormalizeContinuePrompt(input.process.metadata?.[CONTINUE_PROMPT_METADATA_KEY]) ??\n\t\t\trecoveryContext?.suggestedContinuePrompt ??\n\t\t\tDEFAULT_CONTINUE_PROMPT,\n\t\tcanContinue,\n\t\tsupportsModelOverride: failedTurnRecord.turnType === \"llm\",\n\t\tdefaultModelProfileId: acceptedLlmStart?.model.profileId ?? failedTurnRecord.modelProfileId,\n\t\tproviderOptions: acceptedLlmStart ? { ...acceptedLlmStart.providerOptions } : {},\n\t};\n}\n\n/** @internal */\nexport function buildCurrentProcessError(input: {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tevents: readonly ProcessEvent[];\n\t/** @internal */\n\tselectedTurnDescription: string | null;\n\t/** @internal */\n\tcurrentTurnRecovery: CurrentTurnRecoverySummary | null;\n}): CurrentProcessErrorSummary | null {\n\tif (input.process.lifecycleStatus !== \"error\" || input.currentTurnRecovery) {\n\t\treturn null;\n\t}\n\tconst wait = pendingTurnWait(input.process);\n\tif (wait?.status === \"error\")\n\t\treturn {\n\t\t\ttitle: input.selectedTurnDescription ?? \"Waiting condition\",\n\t\t\tsummary: wait.message ?? \"The waiting condition failed\",\n\t\t\tcanRetry: true,\n\t\t\tguidance:\n\t\t\t\t\"Fix the condition or its configuration, then retry. Readiness is checked before starting a worker.\",\n\t\t\ttechnicalDetail: null,\n\t\t};\n\tconst latestErrorEvent = input.events.findLast(\n\t\t(event) => event.eventType === \"lifecycle_parked\" || event.eventType === \"worker_failed\",\n\t);\n\tconst eventData = latestErrorEvent?.data ?? null;\n\tconst rawReason =\n\t\tstringValueOrNull(eventData?.reason) ??\n\t\tstringValueOrNull(eventData?.message) ??\n\t\t(eventData?.errorCode ? `Worker failed: ${String(eventData.errorCode)}` : null);\n\tconst errorClass = stringValueOrNull(eventData?.errorClass);\n\tconst presentation = formatProcessErrorPresentation(rawReason, errorClass);\n\treturn {\n\t\ttitle:\n\t\t\tinput.selectedTurnDescription ??\n\t\t\t(input.process.selectedTurnId\n\t\t\t\t? formatDefinition(input.process.selectedTurnId)\n\t\t\t\t: \"Process error\"),\n\t\tsummary: presentation.summary,\n\t\tguidance: presentation.guidance,\n\t\ttechnicalDetail: presentation.technicalDetail,\n\t};\n}\n\n/** @internal */\nexport function buildUsageEstimate(input: {\n\t/** @internal */\n\tturnRecords: readonly ProcessTurnRecord[];\n\t/** @internal */\n\tactiveTurn: PrimaryPathSnapshot[\"turnState\"][\"activeTurn\"] | CompactActiveTurnSnapshot;\n\t/** @internal */\n\tcurrentTurnRecordId: string | null;\n\t/** @internal */\n\tusageByTurnRecordId: Record<string, TurnTraceSnapshot[\"usage\"]>;\n\t/** @internal */\n\ttracePreviewsByTurnRecordId: Record<string, TurnTracePreview>;\n}): ProcessUsageEstimateSnapshot | null {\n\tlet usage: TurnTraceSnapshot[\"usage\"] = null;\n\tlet totalLlmTurnCount = 0;\n\tlet coveredTurnCount = 0;\n\tlet missingUsageTurnCount = 0;\n\tlet missingCostTurnCount = 0;\n\tlet includesLiveTurn = false;\n\n\tfor (const turnRecord of input.turnRecords) {\n\t\tif (turnRecord.turnType !== \"llm\") {\n\t\t\tcontinue;\n\t\t}\n\t\ttotalLlmTurnCount += 1;\n\t\tconst isActiveTurn = turnRecord.id === input.currentTurnRecordId;\n\t\tconst turnUsage =\n\t\t\t(isActiveTurn && input.activeTurn?.turnType === \"llm\" ? input.activeTurn.usage : null) ??\n\t\t\tinput.tracePreviewsByTurnRecordId[turnRecord.id]?.usage ??\n\t\t\tinput.usageByTurnRecordId[turnRecord.id] ??\n\t\t\tnull;\n\t\tif (!turnUsage) {\n\t\t\tmissingUsageTurnCount += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcoveredTurnCount += 1;\n\t\tif (!turnUsage.cost) {\n\t\t\tmissingCostTurnCount += 1;\n\t\t}\n\t\tif (isActiveTurn) {\n\t\t\tincludesLiveTurn = true;\n\t\t}\n\t\tusage = mergeUsageSnapshots(usage, turnUsage);\n\t}\n\n\tif (!usage || totalLlmTurnCount === 0) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tusage,\n\t\tincludesLiveTurn,\n\t\ttotalLlmTurnCount,\n\t\tcoveredTurnCount,\n\t\tmissingUsageTurnCount,\n\t\tmissingCostTurnCount,\n\t\tisPartial: missingUsageTurnCount > 0 || missingCostTurnCount > 0,\n\t};\n}\n\n/** @internal */\nexport function buildProcessUiSnapshotProjections(input: {\n\t/** @internal */\n\tprocess: ProcessInstance;\n\t/** @internal */\n\tturnStarts?: {\n\t\t/** @internal */\n\t\tgetById(id: string): TurnStartRecord | null;\n\t};\n\t/** @internal */\n\tstartupTurnStarts?: readonly TurnStartRecord[];\n\t/** @internal */\n\tworkerLeases?: readonly WorkerLease[];\n\t/** @internal */\n\tstartupObservations?: readonly import(\"@leitwerk-dev/domain\").StartupObservation[];\n\t/** @internal */\n\tturnRecords: readonly ProcessTurnRecord[];\n\t/** @internal */\n\tturnAnnotations: readonly ProcessTurnAnnotation[];\n\t/** @internal */\n\tevents: readonly ProcessEvent[];\n\t/** @internal */\n\tinputs: readonly ProcessInput[];\n\t/** @internal */\n\tselectedTurn: ProcessSelectedTurnSummary | null;\n\t/** @internal */\n\tprimaryPathSnapshot: PrimaryPathSnapshot | PrimaryPathUiSnapshot;\n\t/** @internal */\n\tsessionTree?: ReadonlyPiSessionTree;\n\t/** @internal */\n\tsessionSummary?: SessionSummary | null;\n\t/** @internal */\n\teventSummariesByTurnRecordId?: Record<string, CompactTurnSummary>;\n\t/** @internal */\n\teventUsageByTurnRecordId?: Record<string, TurnTraceSnapshot[\"usage\"]>;\n\t/** @internal */\n\tactiveModelProfileId?: string | null;\n}) {\n\tconst tracePreviewsByTurnRecordId = {\n\t\t...(input.sessionSummary?.tracePreviewsByTurnRecordId ??\n\t\t\t(input.sessionTree\n\t\t\t\t? buildTurnTracePreviewsFromSession({\n\t\t\t\t\t\ttree: input.sessionTree,\n\t\t\t\t\t\tturnRecords: input.turnRecords,\n\t\t\t\t\t\tevents: input.events,\n\t\t\t\t\t})\n\t\t\t\t: {})),\n\t};\n\tfor (const turn of input.turnRecords) {\n\t\tconst turnRecordId = turn.id;\n\t\tconst summary = input.eventSummariesByTurnRecordId?.[turnRecordId];\n\t\tif (turn.status === \"running\" || !summary || tracePreviewsByTurnRecordId[turnRecordId])\n\t\t\tcontinue;\n\t\ttracePreviewsByTurnRecordId[turnRecordId] = {\n\t\t\tturnRecordId,\n\t\t\tassistantTextPreview: summary.assistant.text,\n\t\t\tassistantTextTruncated: summary.assistant.text.length >= REASONING_PREVIEW_MAX_CHARS,\n\t\t\tthinkingPreview: summary.assistant.thinking,\n\t\t\tthinkingPreviewTruncated: summary.assistant.thinking.length >= REASONING_PREVIEW_MAX_CHARS,\n\t\t\ttoolCallCount: summary.toolCallCount,\n\t\t\ttraceItemCount: summary.traceItemCount,\n\t\t\thasReasoningDetails: Boolean(\n\t\t\t\tsummary.assistant.thinking || summary.traceItemCount || summary.usage,\n\t\t\t),\n\t\t\tusage: summary.usage,\n\t\t\tpiInput: null,\n\t\t};\n\t}\n\tconst currentLeafEntryId =\n\t\tinput.primaryPathSnapshot.currentLeaf?.entryId ??\n\t\tinput.primaryPathSnapshot.semanticEntryRefs.currentPrimaryPathLeaf?.entryId ??\n\t\tnull;\n\tconst prompt = {\n\t\t...(input.sessionSummary?.prompt ??\n\t\t\t(input.sessionTree\n\t\t\t\t? extractFirstUserPromptOnBranch(\n\t\t\t\t\t\tinput.sessionTree as unknown as ReadonlyEntryTree<PiSessionEntry>,\n\t\t\t\t\t\tcurrentLeafEntryId,\n\t\t\t\t\t)\n\t\t\t\t: { text: null, createdAt: null })),\n\t};\n\tprompt.text ??= extractInitialPromptFromParamsJson(input.process.paramsJson);\n\tconst activeTurn = input.primaryPathSnapshot.turnState.activeTurn;\n\tconst currentExecutionTurnRecordId = resolveCurrentExecutionTurnRecordId(\n\t\tinput.process,\n\t\tinput.turnStarts ?? { getById: () => null },\n\t);\n\tconst recovery = buildCurrentTurnRecovery({\n\t\tprocess: input.process,\n\t\tturnRecords: input.turnRecords,\n\t\tselectedTurnDescription: input.selectedTurn?.description ?? null,\n\t\tpiEntries: (input.sessionTree?.entries ?? []) as unknown as PiSessionEntry[],\n\t\tcontinuation:\n\t\t\tinput.sessionSummary?.continuationByTurnRecordId[currentExecutionTurnRecordId ?? \"\"],\n\t\tturnStarts: input.turnStarts ?? { getById: () => null },\n\t});\n\tconst startup = presentProcessStartupSummary(\n\t\tbuildStartupEvidence({\n\t\t\tevents: input.events,\n\t\t\tprocess: input.process,\n\t\t\tturnStarts: input.startupTurnStarts ?? [],\n\t\t\tleases: input.workerLeases ?? [],\n\t\t\tturnRecords: input.turnRecords,\n\t\t}),\n\t);\n\tstartup.workerStarts = physicalWorkerStarts({\n\t\tleases: input.workerLeases ?? [],\n\t\tturnStarts: input.startupTurnStarts ?? [],\n\t\tturnRecords: input.turnRecords,\n\t\tobservations: input.startupObservations ?? [],\n\t});\n\treturn {\n\t\t/** @internal */\n\t\tprocess: projectProcessForUiSnapshot(input.process),\n\t\t/** @internal */\n\t\tprimaryPath: compactPrimaryPathSnapshot(input.primaryPathSnapshot),\n\t\t/** @internal */\n\t\ttimeline: {\n\t\t\t/** @internal */\n\t\t\tprompt,\n\t\t\t/** @internal */\n\t\t\tturns: presentProcessTimelineTurns({\n\t\t\t\tprocess: input.process,\n\t\t\t\tturnRecords: input.turnRecords,\n\t\t\t\tturnAnnotations: input.turnAnnotations,\n\t\t\t\tevents: input.events,\n\t\t\t\tactiveTurn,\n\t\t\t\tcurrentExecutionTurnRecordId,\n\t\t\t\tselectedTurnType: input.selectedTurn?.kind ?? null,\n\t\t\t\tactiveModelProfileId: input.activeModelProfileId,\n\t\t\t}),\n\t\t\t/** @internal */\n\t\t\ttracePreviewsByTurnRecordId,\n\t\t\t/** @internal */\n\t\t\tinputs: input.inputs.map(buildTimelineInputSummary),\n\t\t\t/** @internal */\n\t\t\texternalTriggerSignals: buildExternalTriggerSignals({\n\t\t\t\texternalTriggers: input.selectedTurn?.externalTriggers ?? [],\n\t\t\t\tevents: input.events,\n\t\t\t\tisWaitingForSelectedTurn:\n\t\t\t\t\tinput.process.lifecycleStatus === \"waiting\" &&\n\t\t\t\t\t(input.selectedTurn?.turnId ?? null) === (input.process.selectedTurnId ?? null),\n\t\t\t}),\n\t\t} satisfies ProcessTimelineSnapshot,\n\t\t/** @internal */\n\t\trecovery,\n\t\t/** @internal */\n\t\tstartup,\n\t\t/** @internal */\n\t\tstartupRecovery: startup.recovery,\n\t\t/** @internal */\n\t\tprocessError: buildCurrentProcessError({\n\t\t\tprocess: input.process,\n\t\t\tevents: input.events,\n\t\t\tselectedTurnDescription: input.selectedTurn?.description ?? null,\n\t\t\tcurrentTurnRecovery: recovery,\n\t\t}),\n\t\t/** @internal */\n\t\tusageEstimate: buildUsageEstimate({\n\t\t\tturnRecords: input.turnRecords,\n\t\t\tactiveTurn,\n\t\t\tcurrentTurnRecordId: activeTurn?.turnRecordId ?? currentExecutionTurnRecordId,\n\t\t\tusageByTurnRecordId:\n\t\t\t\tinput.eventUsageByTurnRecordId ?? buildUsageSnapshotsByTurnRecordId(input.events),\n\t\t\ttracePreviewsByTurnRecordId,\n\t\t}),\n\t};\n}\n\ntype ProcessUiSnapshotDeps = Pick<\n\tRouteDeps,\n\t| \"executionInspections\"\n\t| \"processes\"\n\t| \"projects\"\n\t| \"inputs\"\n\t| \"events\"\n\t| \"turnRecords\"\n\t| \"mappedRuns\"\n\t| \"turnStarts\"\n\t| \"turnAnnotations\"\n\t| \"turnSummaries\"\n\t| \"leafOutcomeSnapshots\"\n\t| \"questionRequests\"\n\t| \"toolApprovalRequests\"\n\t| \"leases\"\n\t| \"startupObservations\"\n\t| \"futureExecutions\"\n\t| \"processGraphs\"\n\t| \"processActionRegistry\"\n\t| \"processUiRegistry\"\n\t| \"processModelPolicy\"\n\t| \"modelStatusCache\"\n\t| \"launcherService\"\n\t| \"sessionReader\"\n\t| \"sessionTransferService\"\n\t| \"externalSourceService\"\n\t| \"toolRenderers\"\n\t| \"config\"\n>;\n\nfunction includeRecord<T extends { id: string }>(\n\trecords: T[],\n\tid: string | null | undefined,\n\trepo: { getById(id: string): T | null },\n): void {\n\tif (!id || records.some((record) => record.id === id)) return;\n\tconst record = repo.getById(id);\n\tif (record) records.push(record);\n}\n\nexport class ProcessUiSnapshotAssembler {\n\tconstructor(private readonly deps: ProcessUiSnapshotDeps) {}\n\n\tasync assemble(\n\t\tinstanceId: string,\n\t\tbeforeTurnRecordId?: string,\n\t): Promise<ProcessDetailUiSnapshotResponseBody | null> {\n\t\tconst process = this.deps.processes.getById(instanceId);\n\t\tif (!process) {\n\t\t\treturn null;\n\t\t}\n\t\t// Capture every synchronous durable read before yielding so one response cannot\n\t\t// combine process/turn state from opposite sides of a concurrent mutation.\n\t\tconst projects = this.deps.projects.listByInstance(instanceId);\n\t\tconst before = beforeTurnRecordId ? this.deps.turnRecords.getById(beforeTurnRecordId) : null;\n\t\tif (beforeTurnRecordId && before?.instanceId !== instanceId) return null;\n\t\tconst page = this.deps.turnRecords.listPage(instanceId, before ?? undefined, 41);\n\t\tconst hasMore = page.length > 40;\n\t\tconst turnRecords = hasMore ? page.slice(1) : page;\n\t\tconst turnRecordIds = turnRecords.map((turn) => turn.id);\n\t\tconst window = {\n\t\t\tsince: hasMore ? turnRecords[0]?.startedAt : undefined,\n\t\t\tuntil: before?.startedAt,\n\t\t};\n\t\tconst mapped = {\n\t\t\truns: this.deps.mappedRuns?.listByInstance(instanceId) ?? [],\n\t\t\titems: this.deps.mappedRuns?.listItemsByInstance(instanceId) ?? [],\n\t\t};\n\t\tconst events = this.deps.events.listUiSnapshotEvents(instanceId, turnRecordIds);\n\t\tconst turnAnnotations = this.deps.turnAnnotations.listForTimeline(instanceId, window);\n\t\tconst inputs = this.deps.inputs.listByInstance(instanceId);\n\t\tconst leafOutcomeSnapshots = this.deps.leafOutcomeSnapshots.listByInstance(instanceId, window);\n\t\tconst questionRequests = this.deps.questionRequests.listByInstance(instanceId);\n\t\tconst toolApprovalRequests = this.deps.toolApprovalRequests.listByInstance(instanceId);\n\t\tconst workerLeases = this.deps.leases.listByInstance(instanceId, window);\n\t\tconst workerLease = this.deps.leases.getByInstance(instanceId);\n\t\tif (workerLease && !workerLeases.some((lease) => lease.id === workerLease.id)) {\n\t\t\tworkerLeases.push(workerLease);\n\t\t}\n\t\tconst startupTurnStarts = this.deps.turnStarts.listByInstance(instanceId, window);\n\t\t// A worker starts before its accepted turn. Keep boundary records even when\n\t\t// their timestamps precede the oldest turn on this page.\n\t\tfor (const turn of turnRecords) {\n\t\t\tincludeRecord(startupTurnStarts, turn.turnStartRecordId, this.deps.turnStarts);\n\t\t\tincludeRecord(workerLeases, turn.acceptedWorkerLeaseId, this.deps.leases);\n\t\t}\n\t\tconst selectedTurn = getSelectedTurnSummaryForProcess(this.deps, process);\n\t\tconst session = this.deps.turnSummaries.getSession(instanceId);\n\t\tconst summaries = this.deps.turnSummaries.listByInstance(instanceId, turnRecordIds);\n\t\tconst currentTurnRecordId = resolveCurrentExecutionTurnRecordId(process, this.deps.turnStarts);\n\t\tconst activeRecord = turnRecords.find(\n\t\t\t(turn) => turn.id === currentTurnRecordId && turn.status === \"running\",\n\t\t);\n\t\tconst activeTurn = activeRecord\n\t\t\t? {\n\t\t\t\t\t...(summaries[activeRecord.id] ?? emptyCompactTurnSummary()),\n\t\t\t\t\tturnRecordId: activeRecord.id,\n\t\t\t\t\tturnId: activeRecord.turnId,\n\t\t\t\t\tturnType: activeRecord.turnType,\n\t\t\t\t\tpathType: activeRecord.pathType,\n\t\t\t\t\tstartedAt: activeRecord.startedAt,\n\t\t\t\t\tsummaryPending: !summaries[activeRecord.id],\n\t\t\t\t}\n\t\t\t: null;\n\t\tconst structural = parseStructuralProcessState(parseProcessStateJsonLenient(process.stateJson));\n\t\tconst semanticEntryRefs = {\n\t\t\t...session?.primaryPath.semanticEntryRefs,\n\t\t\t...structural.semanticEntryRefs,\n\t\t};\n\t\tsemanticEntryRefs.rootEntry ??= session?.primaryPath.semanticEntryRefs.rootEntry ?? null;\n\t\tsemanticEntryRefs.currentPrimaryPathLeaf ??= session?.primaryPath.currentLeaf ?? null;\n\t\tconst primaryPath: PrimaryPathUiSnapshot = {\n\t\t\tinstanceId,\n\t\t\trebuiltAt: new Date().toISOString(),\n\t\t\tthroughEventSequence: this.deps.events.latestSequence(instanceId),\n\t\t\tprimaryPathEntries: [],\n\t\t\tlabels: {},\n\t\t\tentryCount: session?.primaryPath.entryCount ?? 0,\n\t\t\tentriesOmitted: true,\n\t\t\tcurrentLeaf: semanticEntryRefs.currentPrimaryPathLeaf,\n\t\t\tsemanticEntryRefs,\n\t\t\tturnAnnotations: session?.primaryPath.turnAnnotations ?? [],\n\t\t\tdetailRail: { keyPoints: [], futureTurns: [], currentPosition: null },\n\t\t\tturnState: {\n\t\t\t\tcurrentTurnRecordId,\n\t\t\t\tworkerState: workerLease?.state ?? null,\n\t\t\t\tisStreaming: activeTurn !== null,\n\t\t\t\tactiveTurn,\n\t\t\t},\n\t\t};\n\t\tconst modelConfiguration = presentProcessModelConfiguration(\n\t\t\tthis.deps.processModelPolicy.project({\n\t\t\t\tkind: \"process_configuration\",\n\t\t\t\tprocess,\n\t\t\t\tavailability: this.deps.modelStatusCache.snapshot(),\n\t\t\t}),\n\t\t);\n\t\tconst projections = buildProcessUiSnapshotProjections({\n\t\t\tprocess,\n\t\t\tturnStarts: this.deps.turnStarts,\n\t\t\tstartupTurnStarts,\n\t\t\tworkerLeases,\n\t\t\tstartupObservations: workerLeases.flatMap(\n\t\t\t\t(lease) => this.deps.startupObservations?.listByLease(lease.id) ?? [],\n\t\t\t),\n\t\t\tturnRecords,\n\t\t\tturnAnnotations,\n\t\t\tevents,\n\t\t\tinputs,\n\t\t\tselectedTurn,\n\t\t\tprimaryPathSnapshot: primaryPath,\n\t\t\tsessionSummary: session,\n\t\t\teventSummariesByTurnRecordId: summaries,\n\t\t\teventUsageByTurnRecordId: Object.fromEntries(\n\t\t\t\tObject.entries(summaries).map(([id, summary]) => [id, summary.usage]),\n\t\t\t),\n\t\t\tactiveModelProfileId: modelConfiguration.effectiveSelectedTurn?.modelProfileId ?? null,\n\t\t});\n\t\tfor (const current of this.deps.externalSourceService?.currentGenerations(instanceId) ?? []) {\n\t\t\tconst signal = projections.timeline.externalTriggerSignals.find(\n\t\t\t\t(signal) => signal.triggerId === current.id,\n\t\t\t);\n\t\t\tconst annotation = turnAnnotations.find(\n\t\t\t\t(annotation) =>\n\t\t\t\t\tannotation.annotationKey === `external_observation:${current.id}:${current.generation}`,\n\t\t\t);\n\t\t\tif (signal && annotation)\n\t\t\t\tObject.assign(signal, {\n\t\t\t\t\tobservation: normalizeExternalObservation(annotation.payload.observation) ?? undefined,\n\t\t\t\t\trefreshError: annotation.payload.refreshError,\n\t\t\t\t\trefreshedAt: annotation.payload.refreshedAt,\n\t\t\t\t});\n\t\t}\n\t\tif (hasMore && projections.usageEstimate) {\n\t\t\tprojections.usageEstimate.isPartial = true;\n\t\t\tprojections.usageEstimate.historyLimited = true;\n\t\t}\n\t\tconst runDetails = buildProcessRunDetailsView(this.deps, process, projects);\n\t\tconst navigation = presentProcessTurnNavigation({\n\t\t\tgraph: getProcessGraph(this.deps.processGraphs, process.processId),\n\t\t\tturns: projections.timeline.turns,\n\t\t\tselectedTurnId: process.selectedTurnId,\n\t\t\tlifecycleStatus: process.lifecycleStatus,\n\t\t\tturnRecords,\n\t\t\tmapped,\n\t\t});\n\n\t\treturn {\n\t\t\t...projections,\n\t\t\ttimeline: {\n\t\t\t\t...projections.timeline,\n\t\t\t\tturns: navigation.turns,\n\t\t\t\thistory: { beforeTurnRecordId: hasMore ? turnRecords[0].id : null },\n\t\t\t},\n\t\t\tplannedNextTurn: navigation.plannedNextTurn,\n\t\t\tinstanceTree: presentProcessInstanceTree({\n\t\t\t\tprocess,\n\t\t\t\tturnRecords,\n\t\t\t\tleases: workerLeases,\n\t\t\t\tobservations: this.deps.executionInspections.listContextFacts(instanceId, turnRecordIds),\n\t\t\t\tturnDetails: runDetails.turns,\n\t\t\t\tcurrentPiEntryId: session?.leafId ?? null,\n\t\t\t}),\n\t\t\tleafOutcomeSnapshots,\n\t\t\tquestionRequests,\n\t\t\ttoolApprovalRequests,\n\t\t\tprocessDisplayName: getProcessDisplayName(this.deps, process.processId),\n\t\t\tprocessFlow: buildProcessFlowViewForProcess(this.deps.processGraphs, process.processId),\n\t\t\tdefinesLeafOutcome: processDefinesLeafOutcome(this.deps, process),\n\t\t\tselectedTurn,\n\t\t\tscheduledAction: getScheduledActionDetailForProcess(this.deps, process),\n\t\t\tmodelConfiguration,\n\t\t\trunDetails,\n\t\t\tlaunchConfiguration: buildProcessLaunchConfigurationView(this.deps, process, projects),\n\t\t\tactions: listVisibleActionsForProcess(this.deps, process),\n\t\t\ttoolRenderers: [...(this.deps.toolRenderers?.values() ?? [])],\n\t\t\tpersistedModelSelectionWarning: readPersistedModelSelectionWarning(process),\n\t\t\tsession: { signature: session?.signature ?? null },\n\t\t\tsessionTransfer: presentSessionTransferOperation(\n\t\t\t\tthis.deps.sessionTransferService?.activeForProcess(process.id) ?? null,\n\t\t\t),\n\t\t};\n\t}\n\n\tasync assembleReasoningDetail(input: {\n\t\tinstanceId: string;\n\t\tturnRecordId: string;\n\t}): Promise<TurnReasoningDetailResponseBody | null> {\n\t\treturn (await this.readReasoningEvidence(input))?.detail ?? null;\n\t}\n\n\t/** Capture durable facts before loading the session, once for all detail projections. @internal */\n\tasync readReasoningEvidence(input: {\n\t\tinstanceId: string;\n\t\tturnRecordId: string;\n\t\tincludeSession?: boolean;\n\t}) {\n\t\tif (!this.deps.processes.getById(input.instanceId)) return null;\n\t\tconst turnRecord = this.deps.turnRecords.getById(input.turnRecordId);\n\t\tif (!turnRecord || turnRecord.instanceId !== input.instanceId) return null;\n\t\tconst throughEventSequence = this.deps.events.latestSequence(input.instanceId);\n\t\tconst events = this.deps.events.listByTurnRecord(input.instanceId, input.turnRecordId);\n\t\tconst live = turnRecord.status === \"running\";\n\t\tconst liveSignature = this.deps.turnSummaries.getSession(input.instanceId)?.signature ?? null;\n\t\tconst session =\n\t\t\t!live || input.includeSession\n\t\t\t\t? await this.deps.sessionReader.readSessionTree(input.instanceId)\n\t\t\t\t: null;\n\t\tconst trace =\n\t\t\t!live && session\n\t\t\t\t? buildCommittedTurnTrace({ tree: session.piTree, turnRecord, events })\n\t\t\t\t: createLiveTurnProjection(events).snapshot();\n\t\tif (!live) trace.usage ??= buildUsageSnapshotsByTurnRecordId(events)[turnRecord.id] ?? null;\n\t\tconst detail: TurnReasoningDetailResponseBody = {\n\t\t\tinstanceId: input.instanceId,\n\t\t\tturnRecordId: input.turnRecordId,\n\t\t\tsessionSignature: live ? liveSignature : (session?.signature ?? null),\n\t\t\tstate: live ? \"live\" : \"committed\",\n\t\t\tthroughEventSequence,\n\t\t\treasoning: trace,\n\t\t};\n\t\treturn { detail, turnRecord, events, session };\n\t}\n}\n","import type { ExternalEventDescription, ExternalObservationInput } from \"@leitwerk-dev/process-sdk\";\nimport { normalizeTurnProgressLinks } from \"./turn-progress.js\";\n\nexport function normalizeExternalEventDescription(value: unknown): ExternalEventDescription | null {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst raw = value as Record<string, unknown>;\n\tconst links = normalizeTurnProgressLinks(raw.links);\n\tif (typeof raw.summary !== \"string\" || !raw.summary.trim() || !links) return null;\n\treturn {\n\t\tsummary: raw.summary.trim().slice(0, 2000),\n\t\t...(typeof raw.markdown === \"string\" ? { markdown: raw.markdown } : {}),\n\t\t...(links.length ? { links } : {}),\n\t};\n}\n\nexport function normalizeExternalObservation(\n\tvalue: unknown,\n): ExternalObservationInput[\"observation\"] | null {\n\tconst description = normalizeExternalEventDescription(value);\n\tif (!description) return null;\n\tconst raw = value as Record<string, unknown>;\n\tif (\n\t\ttypeof raw.observedAt !== \"string\" ||\n\t\t!Number.isFinite(Date.parse(raw.observedAt)) ||\n\t\ttypeof raw.subject !== \"string\" ||\n\t\t!raw.subject.trim() ||\n\t\ttypeof raw.revision !== \"string\"\n\t)\n\t\treturn null;\n\treturn {\n\t\tsummary: description.summary,\n\t\t...(description.links ? { links: description.links } : {}),\n\t\tobservedAt: raw.observedAt,\n\t\tsubject: raw.subject,\n\t\trevision: raw.revision,\n\t};\n}\n","import type { FutureExecution, ProcessInstance } from \"@leitwerk-dev/domain\";\nimport type { ProcessLauncherService } from \"@leitwerk-dev/process-sdk\";\nimport { parseFutureActionPayloadJson, parseFutureLaunchPayloadJson } from \"@leitwerk-dev/protocol\";\nimport type {\n\tFutureActionSummary,\n\tFutureExecutionSummary,\n\tFutureLaunchSummary,\n\tScheduledActionDetail,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { RepositoryBundle } from \"./db/repositories.js\";\nimport { buildActionSummaryForProcess } from \"./process-action-presenter.js\";\nimport {\n\tlistCurrentVisibleActions,\n\ttype ProcessOperatorAttentionDeps,\n} from \"./process-operator-attention.js\";\n\nexport interface FutureExecutionPresenterDeps\n\textends Pick<RepositoryBundle, \"futureExecutions\" | \"processes\"> {\n\tlauncherService: ProcessLauncherService;\n}\n\nfunction futureSummaryState(execution: FutureExecution) {\n\treturn {\n\t\tid: execution.id,\n\t\tnextRunAt: execution.nextRunAt,\n\t\tstatus: execution.blockedReason ? (\"blocked\" as const) : (\"scheduled\" as const),\n\t\tmodelSelection: execution.modelSelection ?? null,\n\t\tblockedReason: execution.blockedReason ?? null,\n\t};\n}\n\nfunction futureActionLabel(label: string | null, fallback: string): string {\n\treturn typeof label === \"string\" && label.trim() !== \"\" ? label : fallback;\n}\n\nexport function buildFutureExecutionListView(\n\tdeps: FutureExecutionPresenterDeps,\n\texecution: FutureExecution,\n): FutureLaunchSummary | FutureActionSummary | null {\n\tconst summary = {\n\t\t...futureSummaryState(execution),\n\t\tscheduleKind: execution.scheduleKind,\n\t\tprocessId: execution.processId,\n\t\tcronExpression: execution.cronExpression,\n\t};\n\tif (execution.kind === \"launch\") {\n\t\tconst launcher = deps.launcherService\n\t\t\t.listUiLaunchers()\n\t\t\t.find((candidate) => candidate.id === execution.launcherId);\n\t\tconst parsedPayload = parseFutureLaunchPayloadJson(execution.payloadJson);\n\t\tif (!parsedPayload.ok) {\n\t\t\tconst launcherLabel = launcher?.label ?? execution.launcherId ?? execution.processId;\n\t\t\treturn {\n\t\t\t\t...summary,\n\t\t\t\tkind: \"launch\",\n\t\t\t\ttitle: launcher?.card.title ?? launcherLabel,\n\t\t\t\tsubtitle: `${launcherLabel} · invalid scheduled start`,\n\t\t\t\tlauncherId: execution.launcherId ?? execution.processId,\n\t\t\t\tlauncherLabel,\n\t\t\t\tlaunchTitle: null,\n\t\t\t\tlauncherInput: {},\n\t\t\t\tskillIds: [],\n\t\t\t\tmodelConfig: {},\n\t\t\t};\n\t\t}\n\t\tconst payload = parsedPayload.value;\n\t\tconst title =\n\t\t\ttypeof payload.launchPlan.processInput.title === \"string\" &&\n\t\t\tpayload.launchPlan.processInput.title.trim() !== \"\"\n\t\t\t\t? payload.launchPlan.processInput.title\n\t\t\t\t: typeof payload.launchPlan.processInput.externalId === \"string\" &&\n\t\t\t\t\t\tpayload.launchPlan.processInput.externalId.trim() !== \"\"\n\t\t\t\t\t? payload.launchPlan.processInput.externalId\n\t\t\t\t\t: (launcher?.card.title ?? launcher?.label ?? payload.launchPlan.processId);\n\t\tconst subtitle =\n\t\t\texecution.scheduleKind === \"cron\"\n\t\t\t\t? `${launcher?.label ?? payload.launchPlan.processId} · recurring cron`\n\t\t\t\t: `${launcher?.label ?? payload.launchPlan.processId} · scheduled start`;\n\t\treturn {\n\t\t\t...summary,\n\t\t\tkind: \"launch\",\n\t\t\ttitle,\n\t\t\tsubtitle,\n\t\t\tlauncherId: execution.launcherId ?? payload.launchPlan.launcherId,\n\t\t\tlauncherLabel: launcher?.label ?? payload.launchPlan.launcherId,\n\t\t\tlaunchTitle: payload.launchPlan.processInput.title,\n\t\t\tlauncherInput: payload.launcherInput,\n\t\t\tskillIds: [...payload.selectedSkillIds],\n\t\t\tmodelConfig: payload.modelConfig,\n\t\t};\n\t}\n\tif (!execution.instanceId || !execution.actionId) {\n\t\treturn null;\n\t}\n\tconst process = deps.processes.getById(execution.instanceId);\n\tconst parsedPayload = parseFutureActionPayloadJson(execution.payloadJson);\n\tconst payload = parsedPayload.ok ? parsedPayload.value : null;\n\tconst actionLabel = futureActionLabel(payload?.actionLabel ?? null, execution.actionId);\n\treturn {\n\t\t...summary,\n\t\tkind: \"action\",\n\t\ttitle: process?.title ?? process?.externalId ?? actionLabel,\n\t\tsubtitle: `${actionLabel} · ${payload ? \"scheduled action\" : \"invalid scheduled action\"}`,\n\t\tinstanceId: execution.instanceId,\n\t\tactionId: execution.actionId,\n\t\tactionLabel,\n\t\tnextTurnModelProfileId: payload?.nextTurnModelProfileId ?? null,\n\t};\n}\n\nexport function buildFutureExecutionSummaries(\n\tdeps: FutureExecutionPresenterDeps,\n\texecutions: readonly FutureExecution[],\n): FutureExecutionSummary[] {\n\treturn executions\n\t\t.map((execution) => buildFutureExecutionListView(deps, execution))\n\t\t.filter((execution): execution is FutureExecutionSummary => execution !== null);\n}\n\nexport function getScheduledActionDetailForProcess(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n): ScheduledActionDetail | null {\n\tif (!deps.processActionRegistry) {\n\t\treturn null;\n\t}\n\tconst scheduledAction = deps.futureExecutions.getScheduledActionByInstance(process.id);\n\tif (!scheduledAction?.actionId) {\n\t\treturn null;\n\t}\n\tconst action = deps.processActionRegistry.getAction(process.processId, scheduledAction.actionId);\n\tif (!action) {\n\t\treturn null;\n\t}\n\tconst parsedPayload = parseFutureActionPayloadJson(scheduledAction.payloadJson);\n\tif (!parsedPayload.ok) {\n\t\treturn null;\n\t}\n\tconst payload = parsedPayload.value;\n\tconst actionLabel = futureActionLabel(payload.actionLabel, action.label);\n\treturn {\n\t\t...futureSummaryState(scheduledAction),\n\t\tactionId: scheduledAction.actionId,\n\t\tactionLabel,\n\t\tinput: payload.input,\n\t\tnextTurnModelProfileId: payload.nextTurnModelProfileId,\n\t\taction: buildActionSummaryForProcess(deps, process, {\n\t\t\t...listCurrentVisibleActions(deps, process).find((candidate) => candidate.id === action.id),\n\t\t\tid: action.id,\n\t\t\tform: action.form,\n\t\t\tlabel: actionLabel.trim() ? actionLabel : action.label,\n\t\t\tsupportsScheduling: true,\n\t\t}),\n\t};\n}\n","import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport { isLlmTurnDefinition, type TurnDefinition } from \"@leitwerk-dev/process-sdk\";\nimport type {\n\tProcessActionPreviewSummary,\n\tProcessActionSummary,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { VisibleProcessActionSummary } from \"./process-action-registry.js\";\nimport {\n\tlistVisibleActionsForProcess as listVisibleAttentionActionsForProcess,\n\ttype ProcessOperatorAttentionDeps,\n} from \"./process-operator-attention.js\";\n\n/** @internal */\nexport function buildActionSummaryForProcess(\n\tdeps: Pick<ProcessOperatorAttentionDeps, \"processActionRegistry\">,\n\tprocess: ProcessInstance,\n\taction: Pick<VisibleProcessActionSummary, \"id\" | \"label\" | \"form\"> &\n\t\tPartial<Pick<VisibleProcessActionSummary, \"description\" | \"preview\">> & {\n\t\t\tsupportsScheduling?: boolean;\n\t\t},\n): ProcessActionSummary {\n\tconst actionId = action.id;\n\tconst preview =\n\t\taction.preview ??\n\t\tdeps.processActionRegistry?.resolveActionPreview(process.processId, process, actionId) ??\n\t\tnull;\n\tconst hasPurePlan =\n\t\ttypeof deps.processActionRegistry?.getAction(process.processId, actionId)?.plan === \"function\";\n\tconst turnDef = preview?.candidateSelectedTurnId\n\t\t? deps.processActionRegistry?.getTurnDefinition(\n\t\t\t\tprocess.processId,\n\t\t\t\tpreview.candidateSelectedTurnId,\n\t\t\t)\n\t\t: undefined;\n\tconst supportsScheduling =\n\t\taction.supportsScheduling ??\n\t\tBoolean(\n\t\t\thasPurePlan &&\n\t\t\t\tdeps.processActionRegistry?.resolveActionScheduling(process.processId, process, actionId),\n\t\t);\n\treturn {\n\t\tid: action.id,\n\t\tlabel: action.label,\n\t\tdescription: action.description ?? null,\n\t\tpreview: buildProcessActionPreviewSummary(preview, turnDef),\n\t\tsupportsScheduling,\n\t\tsupportsNextTurnModelOverride: Boolean(hasPurePlan && turnDef && isLlmTurnDefinition(turnDef)),\n\t\t...(action.form\n\t\t\t? {\n\t\t\t\t\tform: {\n\t\t\t\t\t\tid: action.form.id,\n\t\t\t\t\t\ttitle: action.form.title,\n\t\t\t\t\t\tsubmitLabel: action.form.submitLabel,\n\t\t\t\t\t\tfields: action.form.fields.map((field) => ({ ...field })),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/** @internal */\nexport function listVisibleActionsForProcess(\n\tdeps: ProcessOperatorAttentionDeps,\n\tprocess: ProcessInstance,\n) {\n\treturn listVisibleAttentionActionsForProcess(deps, process).map((action) =>\n\t\tbuildActionSummaryForProcess(deps, process, action),\n\t);\n}\n\nfunction buildProcessActionPreviewSummary(\n\tpreview: {\n\t\tcandidateSelectedTurnId: string | null;\n\t\tlifecycleStatus?: string | null;\n\t} | null,\n\tturnDef: TurnDefinition | undefined,\n): ProcessActionPreviewSummary | null {\n\tif (!preview) {\n\t\treturn null;\n\t}\n\tif (!preview.candidateSelectedTurnId) {\n\t\treturn {\n\t\t\tkind: \"terminal\",\n\t\t\tturnId: null,\n\t\t\tturnKind: null,\n\t\t\tdescription: preview.lifecycleStatus === \"aborted\" ? \"Abort process\" : \"Complete process\",\n\t\t};\n\t}\n\tif (!turnDef) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tkind: \"turn\",\n\t\tturnId: preview.candidateSelectedTurnId,\n\t\tturnKind: turnDef.kind,\n\t\tdescription: turnDef.description,\n\t};\n}\n","import {\n\ttype PhysicalWorkerStart,\n\ttype ProcessTurnRecord,\n\ttype StartupObservation,\n\tstartupInterval,\n\ttype TurnStartRecord,\n\ttype WorkerLease,\n} from \"@leitwerk-dev/domain\";\nexport function physicalWorkerStarts(input: {\n\tleases: readonly WorkerLease[];\n\tturnStarts: readonly TurnStartRecord[];\n\tturnRecords: readonly ProcessTurnRecord[];\n\tobservations: readonly StartupObservation[];\n}): PhysicalWorkerStart[] {\n\treturn input.leases.map((lease) => {\n\t\tconst start = input.turnStarts.find((start) => start.id === lease.turnStartRecordId);\n\t\tconst turn = input.turnRecords\n\t\t\t.filter(\n\t\t\t\t(turn) => turn.acceptedWorkerLeaseId === lease.id && turn.turnStartRecordId === start?.id,\n\t\t\t)\n\t\t\t.sort((a, b) => a.startedAt.localeCompare(b.startedAt))[0];\n\t\tconst observations = input.observations.filter((o) => o.workerLeaseId === lease.id);\n\t\tconst observation = (milestone: StartupObservation[\"milestone\"]) =>\n\t\t\tobservations.find((o) => o.milestone === milestone);\n\t\tconst receipt = (milestone: StartupObservation[\"milestone\"]) =>\n\t\t\tobservation(milestone)?.observedAt;\n\t\tconst source = (milestone: StartupObservation[\"milestone\"]) => observation(milestone)?.sourceAt;\n\t\treturn {\n\t\t\tworkerLeaseId: lease.id,\n\t\t\tworkerId: lease.workerId,\n\t\t\tturnStartRecordId: lease.turnStartRecordId ?? null,\n\t\t\tturnRecordId: turn?.id ?? null,\n\t\t\tstate: lease.state,\n\t\t\tobservations,\n\t\t\tintervals: {\n\t\t\t\tlaunchPreparation: startupInterval(start?.createdAt, lease.startedAt),\n\t\t\t\trequestToConnection: startupInterval(lease.startedAt, lease.connectedAt),\n\t\t\t\tconnectionToReadiness: startupInterval(lease.connectedAt, lease.readyAt),\n\t\t\t\treadinessToAcceptance: startupInterval(lease.readyAt, turn?.startedAt),\n\t\t\t\tacceptanceToPrompt: startupInterval(turn?.startedAt, receipt(\"prompt_started\")),\n\t\t\t\tpromptToFirstText: startupInterval(receipt(\"prompt_started\"), receipt(\"first_text\")),\n\t\t\t\ttotal: startupInterval(start?.createdAt, receipt(\"first_text\")),\n\t\t\t\tpvcRequest: startupInterval(receipt(\"pvc_requested\"), receipt(\"pvc_acknowledged\")),\n\t\t\t\tpodRequest: startupInterval(receipt(\"pod_requested\"), receipt(\"pod_acknowledged\")),\n\t\t\t\tbindingWindow: startupInterval(observation(\"pvc_bound\")?.notBefore, receipt(\"pvc_bound\")),\n\t\t\t\tcontainerObservedToConnection: startupInterval(\n\t\t\t\t\treceipt(\"container_started\"),\n\t\t\t\t\tlease.connectedAt,\n\t\t\t\t),\n\t\t\t\tscheduling: startupInterval(source(\"pod_created\"), source(\"pod_scheduled\"), \"kubernetes\"),\n\t\t\t\tschedulingToContainer: startupInterval(\n\t\t\t\t\tsource(\"pod_scheduled\"),\n\t\t\t\t\tsource(\"container_started\"),\n\t\t\t\t\t\"kubernetes\",\n\t\t\t\t),\n\t\t\t\timagePull: startupInterval(\n\t\t\t\t\tsource(\"image_pull_started\"),\n\t\t\t\t\tsource(\"image_pull_finished\"),\n\t\t\t\t\t\"kubernetes\",\n\t\t\t\t),\n\t\t\t},\n\t\t};\n\t});\n}\n","import {\n\ttype Actor,\n\tCONTINUE_PROMPT_METADATA_KEY,\n\tFAILED_TURN_RECOVERY_METADATA_KEY,\n\ttype ProcessInstance,\n\tSYSTEM_ACTOR,\n\ttype TurnStartRecord,\n} from \"@leitwerk-dev/domain\";\nimport type { DurableWsFrameInput } from \"@leitwerk-dev/protocol\";\nimport type {\n\tCompleteMappedItemInput,\n\tCreateMappedRunInput,\n} from \"../../db/mapped-llm-run-repo.js\";\nimport type {\n\tCreatePendingExternalSourceFireInput,\n\tUpdatePendingExternalSourceFireInput,\n} from \"../../db/pending-external-source-fire-repo.js\";\nimport type { CreateProcessEventInput } from \"../../db/process-event-repo.js\";\nimport type { UpdateProcessInstanceInput } from \"../../db/process-instance-repo.js\";\nimport type { CreateProcessLeafOutcomeSnapshotInput } from \"../../db/process-leaf-outcome-snapshot-repo.js\";\nimport type {\n\tCreateProcessProjectInput,\n\tUpdateProcessProjectInput,\n} from \"../../db/process-project-repo.js\";\nimport type {\n\tCreateProcessTurnAnnotationInput,\n\tUpdateProcessTurnAnnotationInput,\n} from \"../../db/process-turn-annotation-repo.js\";\nimport type {\n\tCreateProcessTurnRecordInput,\n\tUpdateProcessTurnRecordInput,\n} from \"../../db/process-turn-record-repo.js\";\nimport type { FutureExecutionTransitionPlan } from \"../../future-execution/transition-planner.js\";\nimport type { QueuedProcessInput } from \"../../process-input-dispatch.js\";\nimport type { DeferredProcessExtensionEvent } from \"./deferred-extension-events.js\";\n\n/** @internal */\nexport type DurableBroadcast = DurableWsFrameInput;\n\n/** @internal */\ntype CreateWrite<T> = {\n\t/** @internal */\n\tkind: \"create\";\n\t/** @internal */\n\tinput: T;\n};\n\n/** @internal */\ntype UpdateWrite<T> = {\n\t/** @internal */\n\tkind: \"update\";\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tinput: T;\n};\n\n/** @internal */\ntype DeleteWrite = {\n\t/** @internal */\n\tkind: \"delete\";\n\t/** @internal */\n\tid: string;\n};\n\n/** @internal */\nexport type TurnRecordWrite =\n\t| CreateWrite<CreateProcessTurnRecordInput>\n\t| UpdateWrite<UpdateProcessTurnRecordInput>;\n\n/** @internal */\nexport type TurnStartWrite =\n\t| CreateWrite<\n\t\t\tOmit<TurnStartRecord, \"id\" | \"createdAt\" | \"updatedAt\"> & {\n\t\t\t\t/** @internal */\n\t\t\t\tid?: string;\n\t\t\t}\n\t >\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"cas_state\";\n\t\t\t/** @internal */\n\t\t\tid: string;\n\t\t\t/** @internal */\n\t\t\texpectedKind: TurnStartRecord[\"state\"][\"kind\"];\n\t\t\t/** @internal */\n\t\t\tstate: TurnStartRecord[\"state\"];\n\t };\n\n/** @internal */\nexport type TurnAnnotationWrite =\n\t| CreateWrite<CreateProcessTurnAnnotationInput>\n\t| UpdateWrite<UpdateProcessTurnAnnotationInput>\n\t| DeleteWrite;\n\n/** Mapped-run writes, committed in order before turn starts. @internal */\nexport type MappedRunWrite =\n\t| CreateWrite<CreateMappedRunInput>\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"complete_item\";\n\t\t\t/** @internal */\n\t\t\tinput: CompleteMappedItemInput;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"abort_active\";\n\t };\n\n/** @internal */\nexport type LeafOutcomeSnapshotWrite = CreateWrite<CreateProcessLeafOutcomeSnapshotInput>;\n\n/** @internal */\nexport type WorkerIntent =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"reconcile\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"restart_worker\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"start_if_needed\";\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"abort_turn\";\n\t\t\t/** @internal */\n\t\t\treason: string;\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"stop_with_reason\";\n\t\t\t/** @internal */\n\t\t\treason: string;\n\t };\n\n/** @internal */\nexport type PendingExternalSourceFireWrite =\n\t| CreateWrite<CreatePendingExternalSourceFireInput>\n\t| UpdateWrite<UpdatePendingExternalSourceFireInput>\n\t| DeleteWrite;\n\n/** @internal */\nexport interface DecisionMetadata {\n\t/** @internal */\n\tnextTurnModelProfileId?: string | null;\n\t/** @internal */\n\tproviderOptions?: Readonly<Record<string, string>>;\n}\n\nconst METADATA_KEY_GROUPS = {\n\tretry: [\"retryForkPiEntryId\", \"retryFromTurnRecordId\"],\n\tcontinuation: [\n\t\t\"continueFromPiEntryId\",\n\t\t\"continueFromTurnRecordId\",\n\t\t\"continueSavedPrimaryLeafEntryId\",\n\t\tCONTINUE_PROMPT_METADATA_KEY,\n\t\tFAILED_TURN_RECOVERY_METADATA_KEY,\n\t],\n} as const;\n\n/** @internal */\nexport interface Writes {\n\t/** Internal scheduling writes do not count as process activity. @internal */\n\tpreserveUpdatedAt?: boolean;\n\t/** A fenced, successful server-side wait check. Never supplied by extensions. @internal */\n\twaitForAdmission?: string;\n\t/** @internal */\n\tprocessPatch: UpdateProcessInstanceInput;\n\t/** @internal */\n\tchangedFields: string[];\n\t/** @internal */\n\tprojectWrite?: {\n\t\t/** @internal */\n\t\tid: string;\n\t\t/** @internal */\n\t\tinput: UpdateProcessProjectInput;\n\t};\n\t/** Initial bindings, committed before the first worker start. @internal */\n\tinitialProjects?: CreateProcessProjectInput[];\n\t/** @internal */\n\tturnRecordWrites: TurnRecordWrite[];\n\t/** @internal */\n\tturnStartWrites: TurnStartWrite[];\n\t/** @internal */\n\tmappedRunWrites: MappedRunWrite[];\n\t/** @internal */\n\tturnAnnotationWrites: TurnAnnotationWrite[];\n\t/** @internal */\n\tleafOutcomeSnapshotWrites: LeafOutcomeSnapshotWrite[];\n\t/** @internal */\n\tevents: CreateProcessEventInput[];\n\t/** @internal */\n\tbroadcasts: DurableBroadcast[];\n\t/** @internal */\n\tqueuedInputs: QueuedProcessInput[];\n\t/** @internal */\n\textensionEvents: DeferredProcessExtensionEvent[];\n\t/** @internal */\n\tfutureExecutionPlans: FutureExecutionTransitionPlan[];\n\t/** @internal */\n\tpendingExternalSourceFireWrites: PendingExternalSourceFireWrite[];\n\t/** @internal */\n\tworkerIntent?: WorkerIntent;\n}\n\n/** @internal */\nexport interface WriteBuildFailure {\n\t/** @internal */\n\tok: false;\n\t/** @internal */\n\tcode: string;\n\t/** @internal */\n\tmessage: string;\n}\n\n/** @internal */\nexport type WriteBuildResult = Writes | WriteBuildFailure;\n\nexport function createWrites(init: Partial<Writes> = {}): Writes {\n\treturn {\n\t\t...(init.preserveUpdatedAt ? { preserveUpdatedAt: true } : {}),\n\t\t...(init.waitForAdmission ? { waitForAdmission: init.waitForAdmission } : {}),\n\t\tprocessPatch: init.processPatch ?? {},\n\t\tchangedFields: [...(init.changedFields ?? [])],\n\t\t...(init.projectWrite ? { projectWrite: init.projectWrite } : {}),\n\t\t...(init.initialProjects ? { initialProjects: [...init.initialProjects] } : {}),\n\t\tturnRecordWrites: [...(init.turnRecordWrites ?? [])],\n\t\tturnStartWrites: [...(init.turnStartWrites ?? [])],\n\t\tmappedRunWrites: [...(init.mappedRunWrites ?? [])],\n\t\tturnAnnotationWrites: [...(init.turnAnnotationWrites ?? [])],\n\t\tleafOutcomeSnapshotWrites: [...(init.leafOutcomeSnapshotWrites ?? [])],\n\t\tevents: [...(init.events ?? [])],\n\t\tbroadcasts: [...(init.broadcasts ?? [])],\n\t\tqueuedInputs: [...(init.queuedInputs ?? [])],\n\t\textensionEvents: [...(init.extensionEvents ?? [])],\n\t\tfutureExecutionPlans: [...(init.futureExecutionPlans ?? [])],\n\t\tpendingExternalSourceFireWrites: [...(init.pendingExternalSourceFireWrites ?? [])],\n\t\t...(init.workerIntent ? { workerIntent: init.workerIntent } : {}),\n\t};\n}\n\nexport function mergeWrites(...writesList: Array<Writes | undefined>): Writes {\n\tconst merged = createWrites();\n\tfor (const writes of writesList) {\n\t\tif (!writes) continue;\n\t\tObject.assign(merged.processPatch, writes.processPatch);\n\t\tif (writes.waitForAdmission) merged.waitForAdmission = writes.waitForAdmission;\n\t\tfor (const field of writes.changedFields) {\n\t\t\tif (!merged.changedFields.includes(field)) {\n\t\t\t\tmerged.changedFields.push(field);\n\t\t\t}\n\t\t}\n\t\tif (writes.projectWrite) {\n\t\t\tif (merged.projectWrite) throw new Error(\"Cannot merge multiple process-project writes\");\n\t\t\tmerged.projectWrite = writes.projectWrite;\n\t\t}\n\t\tif (writes.initialProjects) {\n\t\t\tif (merged.initialProjects)\n\t\t\t\tthrow new Error(\"Cannot merge multiple initial repository bindings\");\n\t\t\tmerged.initialProjects = writes.initialProjects;\n\t\t}\n\t\tmerged.turnRecordWrites.push(...writes.turnRecordWrites);\n\t\tmerged.turnStartWrites.push(...writes.turnStartWrites);\n\t\tmerged.mappedRunWrites.push(...writes.mappedRunWrites);\n\t\tmerged.turnAnnotationWrites.push(...writes.turnAnnotationWrites);\n\t\tmerged.leafOutcomeSnapshotWrites.push(...writes.leafOutcomeSnapshotWrites);\n\t\tmerged.events.push(...writes.events);\n\t\tmerged.broadcasts.push(...writes.broadcasts);\n\t\tmerged.queuedInputs.push(...writes.queuedInputs);\n\t\tmerged.extensionEvents.push(...writes.extensionEvents);\n\t\tmerged.futureExecutionPlans.push(...writes.futureExecutionPlans);\n\t\tmerged.pendingExternalSourceFireWrites.push(...writes.pendingExternalSourceFireWrites);\n\t\tif (writes.workerIntent) {\n\t\t\tmerged.workerIntent = writes.workerIntent;\n\t\t}\n\t}\n\treturn merged;\n}\n\nexport function isWriteBuildFailure<T>(value: T | WriteBuildFailure): value is WriteBuildFailure {\n\treturn typeof value === \"object\" && value !== null && \"ok\" in value && value.ok === false;\n}\n\nexport function applyProcessPatchField<K extends keyof UpdateProcessInstanceInput>(\n\twrites: Writes,\n\tprocess: Pick<ProcessInstance, K>,\n\tfield: K,\n\tvalue: UpdateProcessInstanceInput[K],\n) {\n\tif (process[field] === value) {\n\t\treturn;\n\t}\n\twrites.processPatch[field] = value;\n\tif (!writes.changedFields.includes(field as string)) {\n\t\twrites.changedFields.push(field as string);\n\t}\n}\n\nexport function applyMetadataPatch(\n\twrites: Writes,\n\tprocess: Pick<ProcessInstance, \"metadata\">,\n\tnextMetadata: Record<string, unknown> | null,\n) {\n\tif (JSON.stringify(process.metadata ?? null) === JSON.stringify(nextMetadata)) {\n\t\treturn;\n\t}\n\twrites.processPatch.metadata = nextMetadata;\n\tif (!writes.changedFields.includes(\"metadata\")) {\n\t\twrites.changedFields.push(\"metadata\");\n\t}\n}\n\nexport function updateProcessMetadata(\n\twrites: Writes,\n\tprocess: Pick<ProcessInstance, \"metadata\">,\n\tclearGroups: Array<keyof typeof METADATA_KEY_GROUPS> = [],\n\tupdate: (metadata: Record<string, unknown>) => void = () => {},\n): void {\n\tconst nextMetadata = process.metadata ? { ...process.metadata } : {};\n\tfor (const group of clearGroups) {\n\t\tfor (const key of METADATA_KEY_GROUPS[group]) delete nextMetadata[key];\n\t}\n\tupdate(nextMetadata);\n\tapplyMetadataPatch(writes, process, Object.keys(nextMetadata).length > 0 ? nextMetadata : null);\n}\n\nexport function appendProcessEvent(\n\twrites: Writes,\n\tprocess: Pick<ProcessInstance, \"id\">,\n\tinput: {\n\t\teventType: string;\n\t\tlevel: string;\n\t\tmessage: string;\n\t\tdata?: Record<string, unknown>;\n\t},\n): void {\n\twrites.events.push({\n\t\tinstanceId: process.id,\n\t\teventType: input.eventType,\n\t\t...(input.data ? { data: input.data } : {}),\n\t});\n\twrites.broadcasts.push({\n\t\ttype: \"process.event\",\n\t\tpayload: {\n\t\t\teventType: input.eventType,\n\t\t\tlevel: input.level,\n\t\t\tmessage: input.message,\n\t\t},\n\t\tinstanceId: process.id,\n\t});\n}\n\n/**\n * Stamps the acting principal onto the durable `data` blob of every persisted\n * event matching `eventType`. The actor lives only in the persisted event row\n * (not the short `process.event` broadcast summary), consistent with how other\n * event detail is surfaced. Defaults to `SYSTEM_ACTOR` so internal callers are\n * still attributed consistently. Returns the number of events stamped so callers\n * and tests can detect a silent no-op (e.g. when a targeted event type is no\n * longer produced).\n */\nexport function stampActorOnEvents(\n\twrites: Writes,\n\tactor: Actor | undefined,\n\teventType: string,\n): number {\n\tconst resolvedActor = actor ?? SYSTEM_ACTOR;\n\tlet stamped = 0;\n\tfor (const event of writes.events) {\n\t\tif (event.eventType === eventType) {\n\t\t\tevent.data = { ...(event.data ?? {}), actor: resolvedActor };\n\t\t\tstamped += 1;\n\t\t}\n\t}\n\treturn stamped;\n}\n\n/**\n * Stamps the acting principal onto queued inputs that do not already carry one.\n * Used by action execution so action-originated follow-up prompts inherit the\n * actor that triggered the action.\n */\nexport function stampActorOnQueuedInputs(writes: Writes, actor: Actor | undefined): void {\n\tif (!actor) {\n\t\treturn;\n\t}\n\twrites.queuedInputs = writes.queuedInputs.map((queuedInput) =>\n\t\tqueuedInput.actor ? queuedInput : { ...queuedInput, actor },\n\t);\n}\n","import type { ProcessInstance } from \"@leitwerk-dev/domain\";\nimport type { ProcessGraphRegistry, TurnWaitPredicate } from \"@leitwerk-dev/process-sdk\";\nimport { generateId } from \"../db/repo-helpers.js\";\nimport {\n\tapplyMetadataPatch,\n\ttype DecisionMetadata,\n\ttype TurnStartWrite,\n\ttype Writes,\n} from \"./writes/writes.js\";\n\nconst KEY = \"turnWait\";\n\n/** Durable scheduling state, separate from worker starts and turn attempts. */\nexport interface PendingTurnWait {\n\tid: string;\n\tturnId: string;\n\trevision: number;\n\tstatus: \"waiting\" | \"error\";\n\tnextCheckAt: number;\n\tfailures: number;\n\tmessage: string | null;\n\tstart: Extract<TurnStartWrite, { kind: \"create\" }>[\"input\"];\n\tmetadata?: DecisionMetadata;\n\tinitialSelection?: boolean;\n}\n\nexport function pendingTurnWait(\n\tprocess: Pick<ProcessInstance, \"metadata\">,\n): PendingTurnWait | null {\n\tconst value = process.metadata?.[KEY] as PendingTurnWait | undefined;\n\tif (!value) return null;\n\tif (\n\t\ttypeof value.id !== \"string\" ||\n\t\ttypeof value.turnId !== \"string\" ||\n\t\t!Number.isInteger(value.revision) ||\n\t\t!Number.isFinite(value.nextCheckAt) ||\n\t\t!value.start ||\n\t\tvalue.start.turnId !== value.turnId ||\n\t\t(value.status !== \"waiting\" && value.status !== \"error\")\n\t) {\n\t\tthrow new Error(\"Invalid persisted turn waiting state\");\n\t}\n\treturn value;\n}\n\nexport function turnWaitPredicate(\n\tgraphs: ProcessGraphRegistry,\n\tprocess: Pick<ProcessInstance, \"processId\" | \"selectedTurnId\">,\n): TurnWaitPredicate | undefined {\n\tif (!process.selectedTurnId) return undefined;\n\tconst turn = graphs.get(process.processId)?.turns.get(process.selectedTurnId)?.definition;\n\treturn turn?.kind === \"llm\" || turn?.kind === \"automatic\" ? turn.waitFor : undefined;\n}\n\nexport function writeTurnWait(\n\twrites: Writes,\n\tprocess: ProcessInstance,\n\twait: PendingTurnWait | null,\n): void {\n\tconst metadata = {\n\t\t...((Object.hasOwn(writes.processPatch, \"metadata\")\n\t\t\t? writes.processPatch.metadata\n\t\t\t: process.metadata) ?? {}),\n\t};\n\tif (wait) metadata[KEY] = wait;\n\telse delete metadata[KEY];\n\tapplyMetadataPatch(writes, process, Object.keys(metadata).length ? metadata : null);\n}\n\n/** Every start-producing engine path passes here before a start is persisted. */\nexport function deferTurnWaitStarts(\n\tgraphs: ProcessGraphRegistry,\n\tprocess: ProcessInstance,\n\twrites: Writes,\n\tmetadata?: DecisionMetadata,\n): void {\n\tconst next = { ...process, ...writes.processPatch };\n\tconst previous = pendingTurnWait(process);\n\tconst predicate = turnWaitPredicate(graphs, next);\n\tconst index = writes.turnStartWrites.findIndex(\n\t\t(write) => write.kind === \"create\" && write.input.turnId === next.selectedTurnId,\n\t);\n\tconst start = index >= 0 ? writes.turnStartWrites[index] : undefined;\n\tif (!predicate || !start || start.kind !== \"create\") {\n\t\tconst currentWait = pendingTurnWait(next);\n\t\tif (\n\t\t\tcurrentWait &&\n\t\t\t(next.selectedTurnId !== currentWait.turnId ||\n\t\t\t\tnext.lifecycleStatus === \"completed\" ||\n\t\t\t\tnext.lifecycleStatus === \"aborted\")\n\t\t)\n\t\t\twriteTurnWait(writes, process, null);\n\t\treturn;\n\t}\n\tif (writes.waitForAdmission === previous?.id && previous?.turnId === start.input.turnId) return;\n\t// Subsequent items belong to an already admitted mapped run. Explicit recovery still checks.\n\tif (start.input.iteration && start.input.startKind === \"selected_turn\") return;\n\twrites.turnStartWrites.splice(index, 1);\n\tconst wait: PendingTurnWait =\n\t\tprevious &&\n\t\tprevious.turnId === start.input.turnId &&\n\t\tstart.input.startKind === \"selected_turn\" &&\n\t\tprevious.status === \"waiting\"\n\t\t\t? previous\n\t\t\t: {\n\t\t\t\t\tid: generateId(\"wait\"),\n\t\t\t\t\tturnId: start.input.turnId,\n\t\t\t\t\trevision: 0,\n\t\t\t\t\tstatus: \"waiting\",\n\t\t\t\t\tnextCheckAt: 0,\n\t\t\t\t\tfailures: 0,\n\t\t\t\t\tmessage: null,\n\t\t\t\t\tstart: start.input,\n\t\t\t\t\tinitialSelection:\n\t\t\t\t\t\tprocess.selectedTurnId === null &&\n\t\t\t\t\t\tprocess.lifecycleStatus === \"discovered\" &&\n\t\t\t\t\t\tprocess.planRevision === 0,\n\t\t\t\t\t...(metadata ? { metadata } : {}),\n\t\t\t\t};\n\twriteTurnWait(writes, process, wait);\n\twrites.processPatch.currentExecution = null;\n\twrites.processPatch.lifecycleStatus = \"waiting\";\n\tfor (const field of [\"currentExecution\", \"lifecycleStatus\"])\n\t\tif (!writes.changedFields.includes(field)) writes.changedFields.push(field);\n\twrites.workerIntent = { kind: \"reconcile\" };\n}\n","import type {\n\tInspectionContextObservation,\n\tInspectionEvidence,\n\tPreparedTurnStart,\n\tProcessTurnRecord,\n\tWorkerLease,\n} from \"@leitwerk-dev/domain\";\nimport type { ExecutionContextOrigin, InspectionBoundary } from \"@leitwerk-dev/protocol\";\nimport type { ReadonlyPiSessionTree } from \"./pi-session-tree.js\";\n\ninterface LineageInput {\n\trecords: readonly ProcessTurnRecord[];\n\tleases: readonly WorkerLease[];\n\tobservations: readonly InspectionContextObservation[];\n\ttree?: ReadonlyPiSessionTree;\n}\n\n/** Recorded start receipts remain usable for executions predating inspection capture. */\nfunction preparedStart(input: LineageInput, record: ProcessTurnRecord): PreparedTurnStart | null {\n\tconst supplied = input.observations.find(\n\t\t(item) => item.turnRecordId === record.id && item.fact.kind === \"supplied_context\",\n\t);\n\tif (supplied?.fact.kind === \"supplied_context\" && supplied.fact.origin)\n\t\treturn supplied.fact.origin;\n\tconst receipt = input.leases.find(\n\t\t(lease) => lease.id === record.acceptedWorkerLeaseId,\n\t)?.bootstrapReceipt;\n\treturn receipt?.kind === \"llm\" && receipt.startRecordId === record.turnStartRecordId\n\t\t? receipt.preparedStart\n\t\t: null;\n}\n\n/** Pure ownership and ancestry projection; current workflow definitions are not an input. @internal */\nexport function createInspectionLineage(input: LineageInput) {\n\tconst records = new Map(input.records.map((record) => [record.id, record]));\n\tconst starts = new Map(\n\t\tinput.records\n\t\t\t.filter((record) => record.turnStartRecordId)\n\t\t\t.map((record) => [record.turnStartRecordId, record.id]),\n\t);\n\tconst candidates = new Map<string, Set<string>>();\n\tconst boundaryFor = (record: ProcessTurnRecord): string | null => {\n\t\tconst prepared = preparedStart(input, record);\n\t\treturn prepared?.forkPiEntryId ?? record.forkPiEntryId;\n\t};\n\tconst claim = (entryId: string, recordId: string) => {\n\t\tif (!records.has(recordId)) return;\n\t\tconst owners = candidates.get(entryId) ?? new Set<string>();\n\t\towners.add(recordId);\n\t\tcandidates.set(entryId, owners);\n\t};\n\tfor (const record of input.records) {\n\t\t// A failure before writing an entry can retain the inherited leaf as its result.\n\t\t// That reference does not transfer ownership of the parent's entry.\n\t\tif (record.resultPiEntryId && record.resultPiEntryId !== boundaryFor(record))\n\t\t\tclaim(record.resultPiEntryId, record.id);\n\t}\n\tfor (const item of input.observations)\n\t\tif (item.fact.kind === \"entry_link\") claim(item.fact.entryId, item.turnRecordId);\n\tfor (const entry of input.tree?.entries ?? []) {\n\t\tif (entry.type !== \"custom_message\" && entry.type !== \"compaction\") continue;\n\t\tconst details = entry.details as Record<string, unknown> | undefined;\n\t\tif (\n\t\t\tdetails &&\n\t\t\t(details.kind === \"turn_prompt\" || details.kind === \"turn_compaction\") &&\n\t\t\ttypeof details.startRecordId === \"string\"\n\t\t) {\n\t\t\tconst owner = starts.get(details.startRecordId);\n\t\t\tif (owner) claim(entry.id, owner);\n\t\t}\n\t}\n\tconst explicit = new Set(candidates.keys());\n\t// Bound legacy ownership by recorded start/result entries. Extending the owner\n\t// of an earlier result to arbitrary later descendants would invent lineage.\n\tfor (const record of input.records) {\n\t\tif (!record.resultPiEntryId || !input.tree?.getEntry(record.resultPiEntryId)) continue;\n\t\tconst branch = input.tree.getBranch(record.resultPiEntryId);\n\t\tconst prepared = preparedStart(input, record);\n\t\tconst boundary = prepared?.forkPiEntryId ?? record.forkPiEntryId;\n\t\tconst boundaryIndex = boundary ? branch.findIndex((entry) => entry.id === boundary) : -1;\n\t\tconst promptIndex = branch.findIndex((entry) => {\n\t\t\tif (entry.type !== \"custom_message\") return false;\n\t\t\tconst details = entry.details as Record<string, unknown> | undefined;\n\t\t\treturn details?.kind === \"turn_prompt\" && details.startRecordId === record.turnStartRecordId;\n\t\t});\n\t\tconst first =\n\t\t\tpromptIndex >= 0\n\t\t\t\t? promptIndex\n\t\t\t\t: boundaryIndex >= 0\n\t\t\t\t\t? boundaryIndex + 1\n\t\t\t\t\t: prepared?.startTarget.kind === \"root\"\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: -1;\n\t\tif (first < 0) continue;\n\t\tfor (const entry of branch.slice(first))\n\t\t\tif (!explicit.has(entry.id)) claim(entry.id, record.id);\n\t}\n\tconst inheritedOwner = (entryId: string): string | null => {\n\t\tconst owners = candidates.get(entryId);\n\t\treturn owners?.size === 1 ? [...owners][0] : null;\n\t};\n\tconst origin = (record: ProcessTurnRecord): ExecutionContextOrigin => {\n\t\tconst unknown = {\n\t\t\tstate: \"not_recorded\",\n\t\t\treason: \"Historical context origin was not recorded\",\n\t\t} as const;\n\t\tif (record.turnType !== \"llm\") {\n\t\t\tconst none = {\n\t\t\t\tstate: \"not_applicable\",\n\t\t\t\treason: `This ${record.turnType} execution does not invoke a model`,\n\t\t\t} as const;\n\t\t\treturn {\n\t\t\t\tauthoredMode: none,\n\t\t\t\tstartTarget: none,\n\t\t\t\tconversation: none,\n\t\t\t\tstructuralPath: record.pathType,\n\t\t\t\tsummary: none.reason,\n\t\t\t};\n\t\t}\n\t\tconst prepared = preparedStart(input, record);\n\t\tconst boundaryId = boundaryFor(record);\n\t\tlet conversation: InspectionEvidence<InspectionBoundary | null> = unknown;\n\t\tif (boundaryId)\n\t\t\tconversation = {\n\t\t\t\tstate: \"recorded\",\n\t\t\t\tvalue: { entryId: boundaryId, turnRecordId: inheritedOwner(boundaryId) },\n\t\t\t};\n\t\telse if (\n\t\t\tprepared &&\n\t\t\t(prepared.startTarget.kind === \"root\" || prepared.startTarget.kind === \"current_leaf\")\n\t\t)\n\t\t\tconversation = { state: \"recorded\", value: null };\n\t\tconst source = conversation.state === \"recorded\" ? conversation.value : undefined;\n\t\tconst summary =\n\t\t\tsource === null\n\t\t\t\t? \"No inherited conversation · supplied inputs may still apply\"\n\t\t\t\t: source\n\t\t\t\t\t? `${prepared?.contextMode === \"compacted\" ? \"Compacted conversation\" : \"Conversation inherited\"} through ${source.entryId}${source.turnRecordId ? \"\" : \" · source execution unknown\"}`\n\t\t\t\t\t: \"Conversation origin not recorded\";\n\t\treturn {\n\t\t\tauthoredMode: prepared ? { state: \"recorded\", value: prepared.contextMode } : unknown,\n\t\t\tstartTarget: prepared ? { state: \"recorded\", value: prepared.startTarget } : unknown,\n\t\t\tconversation,\n\t\t\tstructuralPath: record.pathType,\n\t\t\tsummary,\n\t\t};\n\t};\n\tconst ancestry = (record: ProcessTurnRecord) => {\n\t\tconst result: Array<{ turnRecordId: string; turnId: string; boundaryEntryId: string }> = [];\n\t\tconst visited = new Set([record.id]);\n\t\tlet current = record;\n\t\twhile (true) {\n\t\t\tconst context = origin(current).conversation;\n\t\t\tconst source = context.state === \"recorded\" ? context.value : null;\n\t\t\tif (!source?.turnRecordId || visited.has(source.turnRecordId)) break;\n\t\t\tconst parent = records.get(source.turnRecordId);\n\t\t\tif (!parent) break;\n\t\t\tvisited.add(parent.id);\n\t\t\tresult.push({\n\t\t\t\tturnRecordId: parent.id,\n\t\t\t\tturnId: parent.turnId,\n\t\t\t\tboundaryEntryId: source.entryId,\n\t\t\t});\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn result;\n\t};\n\treturn { owner: inheritedOwner, origin, ancestry, boundaryFor };\n}\n","import type {\n\tInspectionContextObservation,\n\tProcessInstance,\n\tProcessTurnRecord,\n\tWorkerLease,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tInstanceTreeEdgeSummary,\n\tInstanceTreeNodeSummary,\n\tProcessInstanceTreeResponseBody,\n\tProcessRunTurnView,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport { createInspectionLineage } from \"./process-inspection.js\";\n\nfunction titleCase(value: string): string {\n\treturn value\n\t\t.replaceAll(/[-_]+/g, \" \")\n\t\t.replaceAll(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\n/** Compact recorded context relationships. Current definitions supply labels only. @internal */\nexport function presentProcessInstanceTree(input: {\n\tprocess: ProcessInstance;\n\tturnRecords: readonly ProcessTurnRecord[];\n\tleases?: readonly WorkerLease[];\n\tobservations?: readonly InspectionContextObservation[];\n\tturnDetails?: readonly ProcessRunTurnView[];\n\tcurrentPiEntryId?: string | null;\n}): ProcessInstanceTreeResponseBody {\n\tconst records = [...input.turnRecords].sort(\n\t\t(a, b) => a.startedAt.localeCompare(b.startedAt) || a.id.localeCompare(b.id),\n\t);\n\tconst observations = input.observations ?? [];\n\tconst lineage = createInspectionLineage({ records, observations, leases: input.leases ?? [] });\n\tconst labels = new Map(input.turnDetails?.map((turn) => [turn.turnId, turn.description]));\n\tconst nodes: InstanceTreeNodeSummary[] = records.map((record) => {\n\t\tconst origin = lineage.origin(record);\n\t\tconst source = origin.conversation.state === \"recorded\" ? origin.conversation.value : null;\n\t\treturn {\n\t\t\tid: record.id,\n\t\t\tturnId: record.turnId,\n\t\t\tturnType: record.turnType,\n\t\t\torigin,\n\t\t\tparentId: source?.turnRecordId === record.id ? null : (source?.turnRecordId ?? null),\n\t\t\tlabel: labels.get(record.turnId) ?? titleCase(record.turnId),\n\t\t\tpathType: record.pathType,\n\t\t\tresultState:\n\t\t\t\trecord.status === \"succeeded\"\n\t\t\t\t\t? \"succeeded\"\n\t\t\t\t\t: record.status === \"failed\"\n\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t: record.status === \"superseded\"\n\t\t\t\t\t\t\t? \"aborted\"\n\t\t\t\t\t\t\t: \"pending\",\n\t\t\ttimestamp: record.startedAt,\n\t\t};\n\t});\n\tconst edges: InstanceTreeEdgeSummary[] = nodes.flatMap((node) =>\n\t\tnode.parentId\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `conversation:${node.id}`,\n\t\t\t\t\t\tsourceNodeId: node.parentId,\n\t\t\t\t\t\ttargetNodeId: node.id,\n\t\t\t\t\t\thasContext: true,\n\t\t\t\t\t\tproductLabels: [],\n\t\t\t\t\t\tactionLabel: null,\n\t\t\t\t\t\tendState: null,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [],\n\t);\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tfor (const observation of observations) {\n\t\tif (observation.fact.kind !== \"supplied_context\" || !byId.has(observation.turnRecordId))\n\t\t\tcontinue;\n\t\tfor (const product of observation.fact.products) {\n\t\t\tconst producer = byId.get(product.producerTurnRecordId);\n\t\t\tif (!producer || producer.resultPiEntryId !== product.entryId) continue;\n\t\t\tedges.push({\n\t\t\t\tid: `product:${observation.id}:${product.name}`,\n\t\t\t\tsourceNodeId: producer.id,\n\t\t\t\ttargetNodeId: observation.turnRecordId,\n\t\t\t\thasContext: false,\n\t\t\t\tproductLabels: [product.name],\n\t\t\t\tactionLabel: null,\n\t\t\t\tendState: null,\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tcurrentLeafId:\n\t\t\tinput.process.lifecycleStatus === \"completed\" || input.process.lifecycleStatus === \"aborted\"\n\t\t\t\t? null\n\t\t\t\t: (records.find((record) => record.turnStartRecordId === input.process.currentExecution?.id)\n\t\t\t\t\t\t?.id ??\n\t\t\t\t\trecords.find((record) => record.status === \"running\")?.id ??\n\t\t\t\t\t(input.currentPiEntryId ? lineage.owner(input.currentPiEntryId) : null)),\n\t\tnodes,\n\t\tedges,\n\t};\n}\n","import type {\n\tMappedItem,\n\tMappedRun,\n\tProcessLifecycleStatus,\n\tProcessTurnRecord,\n} from \"@leitwerk-dev/domain\";\nimport type { ProcessGraphView } from \"@leitwerk-dev/process-sdk\";\nimport type { ProcessTimelineIteration, ProcessTimelineTurnSummary } from \"@leitwerk-dev/protocol\";\n\n/** Mapped runs and items of one process, joined for presentation. @internal */\nexport interface MappedRunPresentation {\n\t/** @internal */\n\truns: readonly MappedRun[];\n\t/** @internal */\n\titems: readonly MappedItem[];\n}\n\nfunction iterationFor(\n\trun: MappedRun,\n\titem: MappedItem | undefined,\n\tindex: number,\n\titemKey: string,\n): ProcessTimelineIteration {\n\treturn {\n\t\trunId: run.id,\n\t\titemKey,\n\t\tindex,\n\t\tcount: run.itemCount,\n\t\tlabel: item?.label ?? itemKey,\n\t};\n}\n\nfunction withItemLabel(description: string, iteration: ProcessTimelineIteration): string {\n\treturn `${description}: ${iteration.label}`;\n}\n\n/** Navigation retains human decisions omitted by the business-flow diagram. */\nexport function presentProcessTurnNavigation(input: {\n\tgraph: ProcessGraphView;\n\tturns: readonly ProcessTimelineTurnSummary[];\n\tselectedTurnId: string | null;\n\tlifecycleStatus: ProcessLifecycleStatus;\n\tturnRecords?: readonly Pick<ProcessTurnRecord, \"id\" | \"iteration\">[];\n\tmapped?: MappedRunPresentation;\n}): {\n\tturns: ProcessTimelineTurnSummary[];\n\tplannedNextTurn: {\n\t\tturnId: string;\n\t\tdescription: string;\n\t\titeration?: ProcessTimelineIteration;\n\t} | null;\n} {\n\tconst runs = new Map(input.mapped?.runs.map((run) => [run.id, run]) ?? []);\n\tconst items = new Map(\n\t\tinput.mapped?.items.map((item) => [`${item.runId}:${item.itemIndex}`, item]) ?? [],\n\t);\n\tconst iterationsByRecordId = new Map<string, ProcessTimelineIteration>();\n\tfor (const record of input.turnRecords ?? []) {\n\t\tconst ref = record.iteration;\n\t\tconst run = ref ? runs.get(ref.runId) : undefined;\n\t\tif (!ref || !run) continue;\n\t\titerationsByRecordId.set(\n\t\t\trecord.id,\n\t\t\titerationFor(run, items.get(`${ref.runId}:${ref.itemIndex}`), ref.itemIndex, ref.itemKey),\n\t\t);\n\t}\n\tconst describe = (turnId: string) => input.graph.turns.get(turnId)?.description.trim();\n\n\tconst activeRun = input.mapped?.runs.find(\n\t\t(run) => run.status === \"active\" && run.turnId === input.selectedTurnId,\n\t);\n\tconst nextItem =\n\t\tinput.lifecycleStatus === \"active\" && activeRun\n\t\t\t? items.get(`${activeRun.id}:${activeRun.nextIndex + 1}`)\n\t\t\t: undefined;\n\tconst path = input.graph.happyPath ?? [];\n\tconst currentIndex = path.indexOf(input.selectedTurnId ?? \"\");\n\tconst nextId =\n\t\tinput.lifecycleStatus === \"active\" && currentIndex >= 0 ? path[currentIndex + 1] : undefined;\n\tconst next = nextId ? input.graph.turns.get(nextId) : undefined;\n\tlet plannedNextTurn: {\n\t\tturnId: string;\n\t\tdescription: string;\n\t\titeration?: ProcessTimelineIteration;\n\t} | null = next && nextId ? { turnId: nextId, description: next.description } : null;\n\tif (activeRun && nextItem) {\n\t\tconst iteration = iterationFor(activeRun, nextItem, nextItem.itemIndex, nextItem.itemKey);\n\t\tplannedNextTurn = {\n\t\t\tturnId: activeRun.turnId,\n\t\t\tdescription: withItemLabel(describe(activeRun.turnId) || activeRun.turnId, iteration),\n\t\t\titeration,\n\t\t};\n\t}\n\n\treturn {\n\t\tturns: input.turns.map((turn) => {\n\t\t\tconst displayTurn = describe(turn.turnId) || turn.displayTurn;\n\t\t\tconst iteration = iterationsByRecordId.get(turn.id);\n\t\t\treturn iteration\n\t\t\t\t? { ...turn, displayTurn: withItemLabel(displayTurn, iteration), iteration }\n\t\t\t\t: { ...turn, displayTurn };\n\t\t}),\n\t\tplannedNextTurn,\n\t};\n}\n","import {\n\tisUnknownRecord,\n\tnormalizeLaunchModelConfigInput,\n\ttype ProcessEvent,\n\ttype ProcessInstance,\n\ttype ProcessProject,\n\tredactCredentialBearingAbsoluteUrl,\n\tcopiedUnknownRecordSchema as unknownRecordSchema,\n} from \"@leitwerk-dev/domain\";\nimport type { ProcessModelSelectionServiceLike } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tfindUiLauncherById,\n\ttype OutcomeToolParameterSpec,\n\ttype ProcessLauncherService,\n\ttype ProcessLaunchPlanServiceLike,\n\ttype ProcessToolOutcomeSpec,\n} from \"@leitwerk-dev/process-sdk\";\nimport {\n\tcreateTemplateContext,\n\tresolveProcessPiConfig,\n\tresolveTurnActiveToolNames,\n} from \"@leitwerk-dev/process-sdk/pi-config\";\nimport { parseLauncherInputJson, parseLauncherRequestBody } from \"@leitwerk-dev/protocol\";\nimport type {\n\tLauncherModelConfigSchema,\n\tLauncherMutationResponseBody,\n\tProcessLaunchConfigurationView,\n\tProcessRunDetailsView,\n\tProcessRunTurnView,\n\tScheduledActionMutationResponseBody,\n} from \"@leitwerk-dev/protocol/http-contracts\";\nimport type { ToolCallRendererDefinition } from \"@leitwerk-dev/protocol/tool-renderer-contract\";\nimport type { FastifyReply } from \"fastify\";\nimport * as v from \"valibot\";\nimport { getDefaultConfig } from \"../config/config-loader.js\";\nimport type { LeitwerkConfig } from \"../config/config-types.js\";\nimport type { RepositoryBundle } from \"../db/repositories.js\";\nimport type { ExtensionHost } from \"../extensions/extension-host.js\";\nimport type {\n\tActionMutationOutcome,\n\tFutureExecutionLifecycle,\n\tLaunchMutationOutcome,\n\tNormalizedScheduledLaunchInput,\n} from \"../future-execution/index.js\";\nimport {\n\tbuildFutureExecutionListView,\n\tgetScheduledActionDetailForProcess,\n} from \"../future-execution-presenter.js\";\nimport type { LaunchCoordinator } from \"../launch-coordinator.js\";\nimport { normalizeSubmittedProcessTitle } from \"../launch-title.js\";\nimport type { LauncherRecentValuesService } from \"../launcher-recent-values-service.js\";\nimport type {\n\tModelProviderCredentialStatusResolver,\n\tModelProviderRegistry,\n\tModelStatusCache,\n} from \"../model-providers/index.js\";\nimport type { ProcessActionRegistry } from \"../process-action-registry.js\";\nimport type { ProcessDeletionService } from \"../process-deletion-service.js\";\nimport {\n\tisInternalEngineFailureCode,\n\tpublicInternalEngineFailureMessage,\n} from \"../process-engine/internal-failures.js\";\nimport type { ProcessEngine } from \"../process-engine/types.js\";\nimport { getProcessGraph, type ProcessGraphRegistry } from \"../process-graph.js\";\nimport type { ServerProcessModelPolicy } from \"../process-model-policy/index.js\";\nimport { presentLauncherModelConfigSchema } from \"../process-model-policy-presenter.js\";\nimport type { ProcessOperationCoordinator } from \"../process-operation-coordinator.js\";\nimport { getSelectedTurnSummaryForProcess } from \"../process-operator-attention.js\";\nimport type { ProcessQuestionService } from \"../process-question-service.js\";\nimport type { ProcessSessionReader } from \"../process-session-store.js\";\nimport type { ProcessTitleGenerator } from \"../process-title-generator.js\";\nimport type { ProcessUiRegistry } from \"../process-ui-registry.js\";\nimport type { SessionTransferService } from \"../session-transfer-service.js\";\nimport type { SkillCatalogService } from \"../skills/catalog-service.js\";\nimport type { WorkerSupervisor } from \"../supervisor/worker-supervisor.js\";\nimport type { ToolApprovalGate } from \"../tool-approval-gate.js\";\nimport type { Broadcaster } from \"../ws/broadcast.js\";\n\nexport const PRIMARY_PATH_ACTIVE_TURN_EVENT_LIMIT = 500;\n\n/** @public */\nexport interface RouteDeps\n\textends Pick<\n\t\tRepositoryBundle,\n\t\t| \"processes\"\n\t\t| \"launchRuns\"\n\t\t| \"projects\"\n\t\t| \"inputs\"\n\t\t| \"events\"\n\t\t| \"turnSummaries\"\n\t\t| \"executionInspections\"\n\t\t| \"futureExecutions\"\n\t\t| \"skills\"\n\t\t| \"processSkills\"\n\t\t| \"handoffDedupKeys\"\n\t\t| \"leafOutcomeSnapshots\"\n\t\t| \"questionRequests\"\n\t\t| \"processRelations\"\n\t\t| \"toolApprovalRequests\"\n\t\t| \"turnRecords\"\n\t\t| \"turnStarts\"\n\t\t| \"turnAnnotations\"\n\t\t| \"leases\"\n\t\t| \"externalWrites\"\n\t\t| \"transaction\"\n\t> {\n\t/** @internal */\n\tscopedSettingsService?: import(\"../scoped-settings-service.js\").ScopedSettingsService;\n\t/** @internal */\n\ttopicWiki?: RepositoryBundle[\"topicWiki\"];\n\t/** @internal */\n\tonSettingsChanged?: () => Promise<void>;\n\t/** @internal */\n\tmappedRuns?: RepositoryBundle[\"mappedRuns\"];\n\t/** @internal */\n\tstartupObservations?: RepositoryBundle[\"startupObservations\"];\n\t/** @public */\n\texternalSourceService?: Pick<\n\t\timport(\"../external-source-service.js\").ExternalSourceService,\n\t\t\"currentGenerations\"\n\t>;\n\t/** @internal */\n\tbroadcaster: Broadcaster;\n\t/** @internal */\n\tprocessOperations: ProcessOperationCoordinator;\n\t/** @internal */\n\tprocessQuestions: ProcessQuestionService;\n\t/** @internal */\n\ttoolApprovalGate: ToolApprovalGate;\n\t/** @internal */\n\tprocessGraphs: ProcessGraphRegistry;\n\t/** @internal */\n\tsupervisor?: WorkerSupervisor;\n\t/** @internal */\n\tprocessEngine: ProcessEngine;\n\t/** @internal */\n\tprocessDeletion: ProcessDeletionService;\n\t/** @internal */\n\tprocessActionRegistry?: ProcessActionRegistry;\n\t/** @internal */\n\tprocessUiRegistry?: ProcessUiRegistry;\n\t/** @internal */\n\textensionHost?: ExtensionHost;\n\t/** @internal */\n\tlauncherService: ProcessLauncherService;\n\t/** @internal */\n\tlaunchCoordinator: LaunchCoordinator;\n\t/** @internal */\n\tlauncherRecentValues: LauncherRecentValuesService;\n\t/** @internal */\n\tlaunchPlans: ProcessLaunchPlanServiceLike;\n\t/** @internal */\n\tprocessTitles?: ProcessTitleGenerator;\n\t/** @internal */\n\ttoolRenderers?: ReadonlyMap<string, ToolCallRendererDefinition>;\n\t/** @internal */\n\tconfig?: LeitwerkConfig;\n\t/** @internal */\n\tsessionReader: ProcessSessionReader;\n\t/** @internal */\n\tfutureExecutionLifecycle: FutureExecutionLifecycle;\n\t/** @internal */\n\tmodelProviderRegistry?: ModelProviderRegistry;\n\t/** @internal */\n\tmodelProviderCredentialStatus?: ModelProviderCredentialStatusResolver;\n\t/** @internal */\n\tmodelStatusCache: ModelStatusCache;\n\t/** @internal */\n\tprocessModelPolicy: ServerProcessModelPolicy;\n\t/** @internal */\n\tprocessModelSelection: ProcessModelSelectionServiceLike;\n\t/** @internal */\n\tskillCatalog?: SkillCatalogService;\n\t/** @internal */\n\tsessionTransferService?: SessionTransferService;\n}\n\nexport function routeConfig(deps: Pick<RouteDeps, \"config\">): LeitwerkConfig {\n\treturn deps.config ?? getDefaultConfig();\n}\n\nfunction safeLaunchValue(value: unknown): unknown {\n\tif (typeof value === \"string\") return redactCredentialBearingAbsoluteUrl(value);\n\tif (Array.isArray(value)) return value.map(safeLaunchValue);\n\tif (value && typeof value === \"object\")\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, item]) => [key, safeLaunchValue(item)]),\n\t\t);\n\treturn value;\n}\n\nfunction formatLaunchParameterValue(value: unknown): string | null {\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = redactCredentialBearingAbsoluteUrl(value.trim());\n\t\treturn normalized === \"\" ? null : normalized;\n\t}\n\treturn typeof value === \"object\"\n\t\t? JSON.stringify(safeLaunchValue(value), null, 2)\n\t\t: String(value);\n}\n\nfunction buildLaunchParameterRows(\n\tparams: Record<string, unknown>,\n\tlauncher: ReturnType<ProcessLauncherService[\"listUiLaunchers\"]>[number] | null,\n): ProcessLaunchConfigurationView[\"parameters\"] {\n\tconst fields = (launcher?.launchConfigSchema.fields ?? []).filter((field) =>\n\t\tObject.hasOwn(params, field.id),\n\t);\n\tconst declared = new Set(fields.map((field) => field.id));\n\treturn [\n\t\t...fields,\n\t\t...Object.keys(params)\n\t\t\t.sort((left, right) => left.localeCompare(right))\n\t\t\t.filter((id) => !declared.has(id))\n\t\t\t.map((id) => ({ id, label: id })),\n\t].map(({ id, label }) => ({\n\t\tfieldId: id,\n\t\tlabel: label || id,\n\t\tvalue: formatLaunchParameterValue(params[id]),\n\t\trawValue: safeLaunchValue(params[id]),\n\t}));\n}\n\nexport function buildProcessLaunchConfigurationView(\n\tdeps: Pick<RouteDeps, \"launcherService\">,\n\tprocess: ProcessInstance,\n\tprojects: readonly ProcessProject[],\n): ProcessLaunchConfigurationView {\n\tconst rawLauncherId = process.metadata?.launcherId;\n\tconst launcherId =\n\t\ttypeof rawLauncherId === \"string\" && rawLauncherId.trim() !== \"\" ? rawLauncherId.trim() : null;\n\tconst launcher = launcherId ? findUiLauncherById(deps.launcherService, launcherId) : null;\n\tconst parsedParams = parseLauncherInputJson(process.paramsJson, \"paramsJson\");\n\treturn {\n\t\tlauncherId,\n\t\tlauncherLabel: launcher?.label ?? null,\n\t\tlauncherSchemaTitle: launcher?.launchConfigSchema.title ?? null,\n\t\tparamsParseError: parsedParams.ok ? null : parsedParams.error,\n\t\tparameters: parsedParams.ok ? buildLaunchParameterRows(parsedParams.value, launcher) : [],\n\t\tprojects: projects.map((project) => ({\n\t\t\tkey: project.key,\n\t\t\trepoLocator: redactCredentialBearingAbsoluteUrl(project.repoLocator),\n\t\t\trepoLocatorKind: project.repoLocatorKind,\n\t\t\tbaseBranch: project.baseBranch,\n\t\t\tworkBranch: project.workBranch,\n\t\t\texternalId: project.externalId,\n\t\t\texternalUrl: project.externalUrl\n\t\t\t\t? redactCredentialBearingAbsoluteUrl(project.externalUrl)\n\t\t\t\t: null,\n\t\t\tpipelineStatus: project.pipelineStatus,\n\t\t})),\n\t};\n}\n\nexport function buildProcessRunDetailsView(\n\tdeps: Pick<RouteDeps, \"config\" | \"processActionRegistry\" | \"processGraphs\">,\n\tprocess: ProcessInstance,\n\tprojects: readonly ProcessProject[],\n): ProcessRunDetailsView {\n\tconst config = routeConfig(deps);\n\tconst processDef = deps.processActionRegistry?.getProcessGraph(process.processId);\n\tconst contextData = deps.processActionRegistry?.resolveContextData(\n\t\tprocess.processId,\n\t\tprocess,\n\t) ?? {\n\t\tparams: {},\n\t\tstate: {},\n\t};\n\tconst templateContext = createTemplateContext({\n\t\tparams: contextData.params,\n\t\tprocess,\n\t\tprojects,\n\t});\n\tconst resolvedPiConfig = resolveProcessPiConfig({\n\t\tprocessId: process.processId,\n\t\tprocessPiConfig: processDef?.piConfig,\n\t\tturns: processDef?.turns.values(),\n\t\tconfigSnapshot: config,\n\t\ttemplateContext,\n\t});\n\tconst contract = getProcessGraph(deps.processGraphs, process.processId);\n\tconst turns: ProcessRunTurnView[] = [];\n\n\tfor (const [turnId, turnContract] of contract.turns) {\n\t\tconst turnDef = deps.processActionRegistry?.getTurnDefinition(process.processId, turnId);\n\t\tif (!turnDef) continue;\n\t\tconst common = {\n\t\t\tturnId,\n\t\t\tdescription: turnDef.description,\n\t\t\tconsumedProducts: [...(turnContract.consumedProducts ?? [])],\n\t\t};\n\t\tif (turnDef.kind !== \"llm\") {\n\t\t\tconst actions =\n\t\t\t\tturnDef.kind === \"human\"\n\t\t\t\t\t? Object.entries(turnDef.actions).map(([name, action]) => ({\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tlabel: action.label,\n\t\t\t\t\t\t\tdescription: action.description,\n\t\t\t\t\t\t\tform: action.form,\n\t\t\t\t\t\t}))\n\t\t\t\t\t: [];\n\t\t\tconst outcomes =\n\t\t\t\tturnDef.kind === \"automatic\"\n\t\t\t\t\t? Object.entries(turnDef.outcomes ?? {}).map(([name, outcome]) => ({\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tdescription: outcome?.description,\n\t\t\t\t\t\t\tparameters: outcome?.parameters,\n\t\t\t\t\t\t}))\n\t\t\t\t\t: [];\n\t\t\tturns.push({\n\t\t\t\t...common,\n\t\t\t\tpathType: \"not_applicable\",\n\t\t\t\tpublishedProducts: [...(turnContract.publishedProducts ?? [])],\n\t\t\t\tactivePiToolNames: [],\n\t\t\t\toutcomeActions: [],\n\t\t\t\tintegrationToolNames: turnDef.kind === \"automatic\" ? (turnDef.integrationTools ?? []) : [],\n\t\t\t\tdefinitionContract: {\n\t\t\t\t\tkind: turnDef.kind,\n\t\t\t\t\tactions,\n\t\t\t\t\toutcomes,\n\t\t\t\t\treviewProduct: turnDef.kind === \"human\" ? turnDef.reviewProduct : undefined,\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tturns.push({\n\t\t\t...common,\n\t\t\tpathType: turnDef.branchType,\n\t\t\tdefinitionContract: {\n\t\t\t\tkind: turnDef.kind,\n\t\t\t\tcontext: turnDef.context,\n\t\t\t\tmodelPurpose: turnDef.modelPurpose ?? null,\n\t\t\t\taskQuestions: turnDef.askQuestions ?? false,\n\t\t\t},\n\t\t\tintegrationToolNames: turnDef.integrationTools ?? [],\n\t\t\tpublishedProducts: [\n\t\t\t\t...new Set(\n\t\t\t\t\t[turnContract.publishedProduct, ...(turnContract.publishedProducts ?? [])].filter(\n\t\t\t\t\t\t(product): product is string => Boolean(product),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t],\n\t\t\tactivePiToolNames: resolveTurnActiveToolNames({\n\t\t\t\tturnId,\n\t\t\t\tturnDef,\n\t\t\t}),\n\t\t\toutcomeActions: (\n\t\t\t\tObject.entries(turnDef.outcomes ?? {}) as [\n\t\t\t\t\tstring,\n\t\t\t\t\tProcessToolOutcomeSpec<unknown, unknown> | undefined,\n\t\t\t\t][]\n\t\t\t)\n\t\t\t\t.filter((entry): entry is [string, ProcessToolOutcomeSpec<unknown, unknown>] =>\n\t\t\t\t\tBoolean(entry[1]),\n\t\t\t\t)\n\t\t\t\t.map(([toolName, toolSpec]) => ({\n\t\t\t\t\tname: toolName,\n\t\t\t\t\tdescription: toolSpec.description,\n\t\t\t\t\tparameters: (\n\t\t\t\t\t\tObject.entries(toolSpec.parameters) as [string, OutcomeToolParameterSpec][]\n\t\t\t\t\t).map(([parameterName, parameterSpec]) => ({\n\t\t\t\t\t\tname: parameterName,\n\t\t\t\t\t\ttype: parameterSpec.type ?? \"union\",\n\t\t\t\t\t\tdescription: parameterSpec.description,\n\t\t\t\t\t\trequired: parameterSpec.required === true,\n\t\t\t\t\t})),\n\t\t\t\t})),\n\t\t});\n\t}\n\n\treturn {\n\t\tsystemPrompt: resolvedPiConfig.systemPrompt ?? null,\n\t\tappendSystemPrompt: resolvedPiConfig.appendSystemPrompt ?? null,\n\t\tavailablePiToolNames: [...resolvedPiConfig.availableToolNames],\n\t\tturns,\n\t};\n}\n\nexport function processDefinesLeafOutcome(\n\tdeps: Pick<RouteDeps, \"processUiRegistry\">,\n\tprocess: ProcessInstance,\n): boolean {\n\treturn deps.processUiRegistry?.getLeafOutcomeDefinition(process.processId) != null;\n}\n\nexport function getProcessOrReply(\n\tdeps: RouteDeps,\n\tinstanceId: string,\n\treply: FastifyReply,\n): ProcessInstance | null {\n\tconst process = deps.processes.getById(instanceId);\n\tif (!process) {\n\t\treply.code(404).send({ error: \"Process not found\" });\n\t\treturn null;\n\t}\n\treturn process;\n}\n\n/**\n * Resolves the acting principal for an HTTP request. When SSO is enabled,\n * the actor is extracted from the session cookie; when auth is disabled,\n * every web action is attributed to the `admin` actor.\n */\nexport { actorForRequest as resolveActor } from \"../auth/fastify-auth.js\";\n\nexport interface NormalizedContinueRequest extends NormalizedRecoveryModelRequest {\n\tprompt?: string | null;\n}\n\nexport interface NormalizedRecoveryModelRequest {\n\tnextTurnModelProfileId?: string | null;\n\tproviderOptions?: Record<string, string>;\n}\n\nconst modelRequestEntries = {\n\tnextTurnModelProfileId: v.exactOptional(\n\t\tv.pipe(\n\t\t\tv.nullish(v.string(\"nextTurnModelProfileId must be a string or null\")),\n\t\t\tv.transform((value) => value?.trim() || null),\n\t\t),\n\t),\n\tproviderOptions: v.exactOptional(\n\t\tv.pipe(\n\t\t\tv.custom<Record<string, unknown>>(\n\t\t\t\tisUnknownRecord,\n\t\t\t\t\"providerOptions must be an object of string values\",\n\t\t\t),\n\t\t\tv.maxEntries(64, \"providerOptions has too many fields\"),\n\t\t\tv.guard(\n\t\t\t\t(options): options is Record<string, string> =>\n\t\t\t\t\tObject.entries(options).every(\n\t\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t\tkey.length > 0 &&\n\t\t\t\t\t\t\tkey.length <= 128 &&\n\t\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\t\tvalue.length <= 4096,\n\t\t\t\t\t),\n\t\t\t\t\"providerOptions contains an invalid field\",\n\t\t\t),\n\t\t\tv.transform((options) => Object.assign({}, options)),\n\t\t),\n\t),\n};\nconst promptSchema = v.exactOptional(\n\tv.pipe(\n\t\tv.nullish(v.string(\"prompt must be a string or null\")),\n\t\tv.transform((value) => value ?? null),\n\t),\n);\n\nfunction parseModelRequest(\n\tvalue: unknown,\n\trequestName: \"continue\" | \"recovery\",\n): { ok: true; request: NormalizedContinueRequest } | { ok: false; error: string } {\n\tconst schema =\n\t\trequestName === \"continue\"\n\t\t\t? v.object({ ...modelRequestEntries, prompt: promptSchema })\n\t\t\t: v.object(modelRequestEntries);\n\tconst shape =\n\t\trequestName === \"continue\"\n\t\t\t? \"{ prompt, nextTurnModelProfileId, providerOptions }\"\n\t\t\t: \"{ nextTurnModelProfileId, providerOptions }\";\n\tconst parsed = v.safeParse(\n\t\tv.pipe(\n\t\t\tv.unknown(),\n\t\t\tv.check(isUnknownRecord, `${requestName} request body must be an object`),\n\t\t\tunknownRecordSchema,\n\t\t\tv.check(\n\t\t\t\t(body) => Object.keys(body).every((key) => Object.hasOwn(schema.entries, key)),\n\t\t\t\t`${requestName} request body must use ${shape}`,\n\t\t\t),\n\t\t\tschema,\n\t\t),\n\t\tvalue ?? {},\n\t\t{ abortEarly: true },\n\t);\n\treturn parsed.success\n\t\t? { ok: true, request: parsed.output }\n\t\t: { ok: false, error: parsed.issues[0].message };\n}\n\nexport function normalizeLauncherRequest(value: unknown):\n\t| { ok: true; request: NormalizedScheduledLaunchInput }\n\t| {\n\t\t\tok: false;\n\t\t\terror: string;\n\t } {\n\tconst parsed = parseLauncherRequestBody(value);\n\tif (!parsed.ok) {\n\t\treturn { ok: false, error: parsed.error };\n\t}\n\treturn {\n\t\tok: true,\n\t\trequest: {\n\t\t\ttitle: normalizeSubmittedProcessTitle(parsed.value.title),\n\t\t\ttitleProvided: parsed.value.titleProvided,\n\t\t\tlauncherInput: parsed.value.launcherInput,\n\t\t\tlauncherInputProvided: parsed.value.launcherInputProvided,\n\t\t\t...(parsed.value.skillIds ? { skillIds: parsed.value.skillIds } : {}),\n\t\t\tmodelConfig: normalizeLaunchModelConfigInput(parsed.value.modelConfig),\n\t\t\tmodelConfigProvided: parsed.value.modelConfigProvided,\n\t\t\tschedule: parsed.value.schedule,\n\t\t\tscheduleProvided: parsed.value.scheduleProvided,\n\t\t},\n\t};\n}\n\nfunction isScheduleRequestError(error: string): boolean {\n\treturn (\n\t\terror === \"schedule must be an object\" ||\n\t\terror === \"runAt must be a valid ISO datetime\" ||\n\t\terror === \"cronExpression is required for cron schedules\" ||\n\t\terror.startsWith(\"schedule.\")\n\t);\n}\n\nexport function sendLauncherRequestNormalizationError(reply: FastifyReply, error: string) {\n\treturn isScheduleRequestError(error)\n\t\t? reply.code(400).send({\n\t\t\t\terrors: [{ code: \"invalid_schedule\", message: error }],\n\t\t\t})\n\t\t: reply.code(400).send({ error });\n}\n\nexport function sendActionRequestNormalizationError(reply: FastifyReply, error: string) {\n\treturn isScheduleRequestError(error)\n\t\t? reply.code(400).send({ error, code: \"invalid_schedule\" })\n\t\t: reply.code(400).send({ error });\n}\n\nexport function normalizeContinueRequest(\n\tvalue: unknown,\n): { ok: true; request: NormalizedContinueRequest } | { ok: false; error: string } {\n\treturn parseModelRequest(value, \"continue\");\n}\n\nexport function normalizeRecoveryModelRequest(\n\tvalue: unknown,\n): { ok: true; request: NormalizedRecoveryModelRequest } | { ok: false; error: string } {\n\treturn parseModelRequest(value, \"recovery\");\n}\n\nexport function buildLauncherModelConfigSchema(\n\tdeps: RouteDeps,\n\tprocessId: string,\n): LauncherModelConfigSchema {\n\treturn presentLauncherModelConfigSchema(\n\t\tdeps.processModelPolicy.project({\n\t\t\tkind: \"launcher_schema\",\n\t\t\tprocessId,\n\t\t\tavailability: deps.modelStatusCache.snapshot(),\n\t\t}),\n\t);\n}\n\nexport function sendLauncherLookupFailure(reply: FastifyReply, error: unknown): boolean {\n\tif (!(error instanceof Error)) {\n\t\treturn false;\n\t}\n\tif (\n\t\terror.message.startsWith(\"Unknown launcher '\") ||\n\t\terror.message.includes(\"is not UI-visible\")\n\t) {\n\t\treply.code(404).send({ error: \"Launcher not found\" });\n\t\treturn true;\n\t}\n\treturn false;\n}\n\ntype SharedMutationFailure = Extract<\n\tLaunchMutationOutcome | ActionMutationOutcome,\n\t{ kind: \"conflict\" | \"unavailable\" | \"failed\" }\n>;\n\nfunction sendSharedMutationFailure(reply: FastifyReply, outcome: SharedMutationFailure) {\n\tswitch (outcome.kind) {\n\t\tcase \"conflict\":\n\t\t\treturn reply.code(409).send({ error: outcome.issue.message, code: outcome.issue.code });\n\t\tcase \"unavailable\":\n\t\t\treturn reply.code(503).send({ error: outcome.reason });\n\t\tcase \"failed\":\n\t\t\treturn reply.code(500).send({\n\t\t\t\terror: isInternalEngineFailureCode(outcome.issue.code)\n\t\t\t\t\t? publicInternalEngineFailureMessage(outcome.issue.code)\n\t\t\t\t\t: outcome.issue.message,\n\t\t\t\tcode: outcome.issue.code,\n\t\t\t});\n\t}\n}\n\nexport function sendLauncherMutationResponse(\n\treply: FastifyReply,\n\tdeps: RouteDeps,\n\toutcome: LaunchMutationOutcome,\n) {\n\tif (\"execution\" in outcome) {\n\t\tconst summary = buildFutureExecutionListView(deps, outcome.execution);\n\t\tconst body = {\n\t\t\tkind: \"scheduled\",\n\t\t\tfutureExecution: summary?.kind === \"launch\" ? summary : null,\n\t\t\t...(outcome.kind === \"committed_with_reaction_error\"\n\t\t\t\t? { error: outcome.error, code: outcome.code }\n\t\t\t\t: {}),\n\t\t} satisfies LauncherMutationResponseBody;\n\t\treturn reply\n\t\t\t.code(outcome.kind === \"scheduled\" && outcome.operation === \"created\" ? 201 : 200)\n\t\t\t.send(body);\n\t}\n\tswitch (outcome.kind) {\n\t\tcase \"launched\":\n\t\t\treturn reply\n\t\t\t\t.code(outcome.operation === \"created\" ? 201 : 200)\n\t\t\t\t.send({ process: outcome.process, projects: outcome.projects });\n\t\tcase \"committed_with_reaction_error\":\n\t\t\treturn reply.code(200).send({\n\t\t\t\tprocess: outcome.process,\n\t\t\t\tprojects: outcome.projects,\n\t\t\t\terror: outcome.error,\n\t\t\t\t...(outcome.code ? { code: outcome.code } : {}),\n\t\t\t});\n\t\tcase \"invalid\":\n\t\t\treturn reply.code(400).send({ errors: outcome.issues });\n\t\tcase \"not_found\":\n\t\t\treturn reply.code(404).send({ error: \"Scheduled launch not found\" });\n\t\tcase \"conflict\":\n\t\tcase \"unavailable\":\n\t\tcase \"failed\":\n\t\t\treturn sendSharedMutationFailure(reply, outcome);\n\t}\n}\n\nexport function sendScheduledActionMutationResponse(\n\treply: FastifyReply,\n\tdeps: RouteDeps,\n\toutcome: ActionMutationOutcome,\n) {\n\tif (\"execution\" in outcome) {\n\t\tconst lockedProcess = deps.processes.getById(outcome.instanceId);\n\t\tconst body = {\n\t\t\tkind: \"scheduled\",\n\t\t\tscheduledAction: lockedProcess\n\t\t\t\t? getScheduledActionDetailForProcess(deps, lockedProcess)\n\t\t\t\t: null,\n\t\t\t...(outcome.kind === \"committed_with_reaction_error\"\n\t\t\t\t? { error: outcome.error, code: outcome.code }\n\t\t\t\t: {}),\n\t\t} satisfies ScheduledActionMutationResponseBody;\n\t\treturn reply\n\t\t\t.code(outcome.kind === \"scheduled\" && outcome.operation === \"created\" ? 201 : 200)\n\t\t\t.send(body);\n\t}\n\tswitch (outcome.kind) {\n\t\tcase \"executed\":\n\t\t\treturn reply\n\t\t\t\t.code(200)\n\t\t\t\t.send({ process: outcome.process, ...(outcome.data ? { data: outcome.data } : {}) });\n\t\tcase \"committed_with_reaction_error\":\n\t\t\treturn reply.code(200).send({\n\t\t\t\tprocess: outcome.process,\n\t\t\t\terror: outcome.error,\n\t\t\t\t...(outcome.code ? { code: outcome.code } : {}),\n\t\t\t});\n\t\tcase \"invalid\": {\n\t\t\tconst issue = outcome.issues[0] ?? {\n\t\t\t\tcode: \"invalid_request\",\n\t\t\t\tmessage: \"Invalid action request\",\n\t\t\t};\n\t\t\treturn reply.code(400).send({ error: issue.message, code: issue.code });\n\t\t}\n\t\tcase \"not_found\":\n\t\t\treturn reply.code(404).send({\n\t\t\t\terror: outcome.target === \"process\" ? \"Process not found\" : \"Scheduled action not found\",\n\t\t\t});\n\t\tcase \"conflict\":\n\t\tcase \"unavailable\":\n\t\tcase \"failed\":\n\t\t\treturn sendSharedMutationFailure(reply, outcome);\n\t}\n}\n\nexport function mergeProcessEventWindowsAscending(\n\twindows: readonly (readonly ProcessEvent[])[],\n): ProcessEvent[] {\n\treturn [...new Map(windows.flat().map((event) => [event.id, event])).values()].sort(\n\t\t(left, right) =>\n\t\t\tleft.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n\t);\n}\n\nexport { getSelectedTurnSummaryForProcess };\n","import type { EngineErrorCode, EngineFailureStage, ProcessEngineLogger } from \"./types.js\";\n\nexport type InternalEngineFailureCode = \"operation_failed\" | \"record_failed\" | \"post_commit_failed\";\n\nexport function isInternalEngineFailureCode(\n\tcode: string | null | undefined,\n): code is InternalEngineFailureCode {\n\treturn code === \"operation_failed\" || code === \"record_failed\" || code === \"post_commit_failed\";\n}\n\nexport function publicInternalEngineFailureMessage(\n\tcode: string,\n\tstage?: EngineFailureStage,\n): string {\n\tswitch (code) {\n\t\tcase \"operation_failed\":\n\t\t\treturn \"Process operation failed before commit\";\n\t\tcase \"record_failed\":\n\t\t\treturn \"Process operation failed during durable recording\";\n\t\tcase \"post_commit_failed\":\n\t\t\treturn stage === \"pre_commit\"\n\t\t\t\t? \"Process operation failed before commit\"\n\t\t\t\t: \"Process operation failed after commit\";\n\t\tdefault:\n\t\t\treturn \"Process operation failed\";\n\t}\n}\n\nexport function publicEngineFailureMessage(input: {\n\tcode: string;\n\tmessage: string;\n\tstage?: EngineFailureStage;\n}): string {\n\treturn isInternalEngineFailureCode(input.code)\n\t\t? publicInternalEngineFailureMessage(input.code, input.stage)\n\t\t: input.message;\n}\n\nexport function logProcessEngineError(\n\tlogger: ProcessEngineLogger | undefined,\n\tinput: {\n\t\terr: unknown;\n\t\toperationKind: string;\n\t\tinstanceId: string;\n\t\tstage: EngineFailureStage;\n\t\tcode: EngineErrorCode;\n\t},\n): void {\n\tlogger?.error(\n\t\t{\n\t\t\terr: input.err,\n\t\t\toperationKind: input.operationKind,\n\t\t\tinstanceId: input.instanceId,\n\t\t\tstage: input.stage,\n\t\t\tcode: input.code,\n\t\t},\n\t\t\"ProcessEngine operation failed\",\n\t);\n}\n","import { type Actor, ADMIN_ACTOR } from \"@leitwerk-dev/domain\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport type { AuthService } from \"./auth-service.js\";\n\n/** @internal */\nexport interface TokenAuditContext {\n\t/** @internal */\n\toperation: string;\n\t/** @internal */\n\ttokenId?: string;\n\t/** @internal */\n\tactor?: Actor;\n\t/** @internal */\n\townerKind?: \"user\" | \"anonymous\";\n\t/** @internal */\n\tcount?: number;\n}\ndeclare module \"fastify\" {\n\t/** @internal */\n\tinterface FastifyRequest {\n\t\t/** @internal */\n\t\tactor?: Actor;\n\t\t/** @internal */\n\t\ttokenAudit?: TokenAuditContext;\n\t}\n}\nexport function actorForRequest(request: FastifyRequest): Actor {\n\treturn request.actor ?? ADMIN_ACTOR;\n}\nexport function hasAuthorization(request: FastifyRequest): boolean {\n\treturn (\n\t\trequest.headers.authorization !== undefined ||\n\t\trequest.raw.rawHeaders.some(\n\t\t\t(value, i) => i % 2 === 0 && value.toLowerCase() === \"authorization\",\n\t\t)\n\t);\n}\nfunction resolved(request: FastifyRequest, actor: Actor): Actor {\n\trequest.actor = actor;\n\treturn actor;\n}\nexport function authenticateBrowserRequest(\n\tauth: AuthService,\n\trequest: FastifyRequest,\n): Actor | null {\n\tif (hasAuthorization(request)) return null;\n\tif (!auth.config.enabled) return resolved(request, ADMIN_ACTOR);\n\tconst actor = auth.resolveSession(request.cookies?.[auth.config.sessionCookieName]);\n\treturn actor ? resolved(request, actor) : null;\n}\nexport function authenticateRequest(auth: AuthService, request: FastifyRequest): Actor | null {\n\tif (!hasAuthorization(request)) return authenticateBrowserRequest(auth, request);\n\trequest.tokenAudit = { operation: \"bearer_request\" };\n\tconst headerCount = request.raw.rawHeaders.filter(\n\t\t(v, i) => i % 2 === 0 && v.toLowerCase() === \"authorization\",\n\t).length;\n\tconst header = request.headers.authorization;\n\tif (\n\t\theaderCount > 1 ||\n\t\ttypeof header !== \"string\" ||\n\t\tObject.hasOwn(request.cookies ?? {}, auth.config.sessionCookieName)\n\t)\n\t\treturn null;\n\tconst match = /^Bearer ([A-Za-z0-9_-]+)$/i.exec(header);\n\tif (!match) return null;\n\tconst result = auth.apiTokens.resolve(match[1]);\n\tif (result.token) {\n\t\trequest.tokenAudit = {\n\t\t\t/** @internal */\n\t\t\toperation: \"bearer_request\",\n\t\t\t/** @internal */\n\t\t\ttokenId: result.token.id,\n\t\t\t/** @internal */\n\t\t\tactor: result.token.owner.actor,\n\t\t\t/** @internal */\n\t\t\townerKind: result.token.owner.kind,\n\t\t};\n\t}\n\treturn result.actor && result.token ? resolved(request, result.actor) : null;\n}\nexport function requireApiActor(\n\tauth: AuthService,\n\trequest: FastifyRequest,\n\treply: FastifyReply,\n): void {\n\tif (!authenticateRequest(auth, request))\n\t\treply.code(401).send({ error: \"Authentication required\" });\n}\n","import type {\n\tAutomaticStartupRecoverySummary,\n\tProcessEvent,\n\tStartupRetryState,\n\tTurnStartRecord,\n} from \"@leitwerk-dev/domain\";\n\n/** @internal */\nexport const MAX_STARTUP_STARTS = 3;\n\n/** Read retained history only for starts written before retry metadata existed. @internal */\nexport function startupRetryState(\n\tstart: TurnStartRecord,\n\tstarts: readonly TurnStartRecord[],\n\tevents: readonly ProcessEvent[] = [],\n): StartupRetryState {\n\tif (start.state.automaticRetry) return start.state.automaticRetry;\n\tconst byId = new Map(starts.map((entry) => [entry.id, entry]));\n\tconst predecessors = new Map(\n\t\tevents\n\t\t\t.filter((event) => event.eventType === \"startup_retry_scheduled\")\n\t\t\t.map((event) => [String(event.data.startRecordId), event]),\n\t);\n\tlet current = start;\n\tlet count = 1;\n\tconst seen = new Set([start.id]);\n\twhile (current.startKind === \"startup_retry\") {\n\t\tconst event = predecessors.get(current.id);\n\t\tconst actor = event?.data.actor as { kind?: string } | undefined;\n\t\tif (event?.data.retrySource === \"manual\" || (actor && actor.kind !== \"system\")) break;\n\t\tconst previous = byId.get(String(event?.data.previousStartRecordId));\n\t\tif (!previous || seen.has(previous.id) || previous.turnId !== start.turnId) {\n\t\t\t// Missing legacy history must not grant a new allowance after an upgrade.\n\t\t\tcount = Math.max(count, MAX_STARTUP_STARTS);\n\t\t\tbreak;\n\t\t}\n\t\tseen.add(previous.id);\n\t\tcount += 1;\n\t\tcurrent = previous;\n\t\tif (current.state.automaticRetry) {\n\t\t\treturn {\n\t\t\t\t...current.state.automaticRetry,\n\t\t\t\tstarts: current.state.automaticRetry.starts + count - 1,\n\t\t\t\tnextRetryAt: null,\n\t\t\t};\n\t\t}\n\t}\n\treturn { episodeStartRecordId: current.id, starts: count, nextRetryAt: null };\n}\n\n/** Configuration, unknown errors and OOMs require attention rather than blind retries. @internal */\nexport function automaticStartupRecovery(\n\tstart: TurnStartRecord,\n\tretry: StartupRetryState,\n\tnow = Date.now(),\n\tmodelRestored = false,\n): AutomaticStartupRecoverySummary {\n\tconst summary = (\n\t\tstatus: AutomaticStartupRecoverySummary[\"status\"],\n\t\treason: string,\n\t\tnextRetryAt: string | null = null,\n\t): AutomaticStartupRecoverySummary => ({\n\t\tstarts: retry.starts,\n\t\tmaxStarts: MAX_STARTUP_STARTS,\n\t\tstatus,\n\t\treason,\n\t\tnextRetryAt,\n\t});\n\tif (start.state.kind !== \"preparation_failed\" && start.state.kind !== \"bootstrap_failed\")\n\t\treturn summary(\"blocked\", \"This start is no longer eligible for automatic recovery.\");\n\tconst code = start.state.code;\n\tconst modelFailure = code === \"model_unavailable\" || code === \"model_stale\";\n\tconst transient =\n\t\tstart.state.kind === \"bootstrap_failed\" &&\n\t\t[\n\t\t\t\"startup_timeout\",\n\t\t\t\"spawn_error\",\n\t\t\t\"worker_spawn_failed\",\n\t\t\t\"worker_adoption_failed\",\n\t\t\t\"process_exited\",\n\t\t].includes(code);\n\tif (!modelFailure && !transient)\n\t\treturn summary(\"blocked\", \"Automatic retry stopped. Correct the failure and retry manually.\");\n\tif (retry.starts >= MAX_STARTUP_STARTS)\n\t\treturn summary(\n\t\t\t\"exhausted\",\n\t\t\t\"Automatic startup retries exhausted. Retry manually after correcting the failure.\",\n\t\t);\n\tif (modelFailure)\n\t\treturn summary(\n\t\t\tmodelRestored ? \"ready\" : \"waiting_for_model\",\n\t\t\tmodelRestored\n\t\t\t\t? \"Model availability restored.\"\n\t\t\t\t: \"Waiting for model availability to be restored.\",\n\t\t);\n\tconst failureAt = Date.parse(start.updatedAt);\n\tif (!Number.isFinite(failureAt))\n\t\treturn summary(\"blocked\", \"Startup failure timing is unavailable. Retry manually.\");\n\tconst nextRetryAt =\n\t\tretry.nextRetryAt ?? new Date(failureAt + 30_000 * 2 ** (retry.starts - 1)).toISOString();\n\treturn summary(\n\t\tDate.parse(nextRetryAt) > now ? \"waiting\" : \"ready\",\n\t\t\"A transient worker startup failure is eligible for automatic recovery.\",\n\t\tnextRetryAt,\n\t);\n}\n","import type {\n\tLaunchRun,\n\tProcessEvent,\n\tProcessInstance,\n\tProcessTurnRecord,\n\tTurnStartRecord,\n\tWorkerLease,\n} from \"@leitwerk-dev/domain\";\nimport type {\n\tProcessStartupSummary,\n\tStartupAttemptStepSummary,\n\tStartupAttemptSummary,\n\tStartupRecoverySummary,\n} from \"@leitwerk-dev/protocol\";\nimport { completeLaunchWhenReady, failLaunchRun } from \"./launch-pipeline.js\";\nimport { pendingTurnWait } from \"./process-engine/turn-wait-state.js\";\nimport { automaticStartupRecovery, startupRetryState } from \"./startup-retry-policy.js\";\n\nexport interface StartupEvidenceInput {\n\tprocess: ProcessInstance;\n\tturnStarts: readonly TurnStartRecord[];\n\tleases: readonly WorkerLease[];\n\tturnRecords: readonly ProcessTurnRecord[];\n\tevents?: readonly ProcessEvent[];\n}\n\nexport interface StartupEvidence {\n\treadiness?: { message: string | null };\n\tattempts: readonly StartupAttemptSummary[];\n\tcurrentAttempt: StartupAttemptSummary | null;\n\tauthoritativeAttemptId: string | null;\n\trecovery: StartupRecoverySummary | null;\n}\n\nexport type LaunchTitleState =\n\t| { status: \"pending\" }\n\t| { status: \"completed\" | \"skipped\" }\n\t| { status: \"failed\"; safeSummary?: string };\n\nconst STARTUP_STEP_LABELS = {\n\tstart_worker: \"Request worker\",\n\tconnect_worker: \"Start worker\",\n\tprepare_workspace: \"Prepare runtime\",\n\tstart_first_turn: \"Start first turn\",\n} as const;\n\nfunction validObservedAt(value: string | null | undefined, notBefore: string): string | null {\n\tif (!value) return null;\n\tconst time = Date.parse(value);\n\treturn Number.isFinite(time) && time >= Date.parse(notBefore) ? value : null;\n}\n\nexport function buildStartupRecovery(\n\tprocess: ProcessInstance,\n\tturnStartsById: ReadonlyMap<string, TurnStartRecord>,\n\tevents: readonly ProcessEvent[] = [],\n): StartupRecoverySummary | null {\n\tif (process.lifecycleStatus !== \"error\" || process.currentExecution?.kind !== \"worker_start\")\n\t\treturn null;\n\tconst start = turnStartsById.get(process.currentExecution.id);\n\tif (\n\t\t!start ||\n\t\t(start.state.kind !== \"preparation_failed\" && start.state.kind !== \"bootstrap_failed\")\n\t)\n\t\treturn null;\n\tconst resolvedStart = \"start\" in start.state ? start.state.start : null;\n\treturn {\n\t\tautomaticRetry: automaticStartupRecovery(\n\t\t\tstart,\n\t\t\tstartupRetryState(start, [...turnStartsById.values()], events),\n\t\t),\n\t\tstartRecordId: start.id,\n\t\tkind: start.state.kind,\n\t\taction: start.state.kind === \"bootstrap_failed\" ? \"retry_startup\" : \"choose_model\",\n\t\tdefaultModelProfileId:\n\t\t\tstart.state.kind === \"preparation_failed\"\n\t\t\t\t? start.state.requestedModelProfileId\n\t\t\t\t: resolvedStart?.kind === \"llm\"\n\t\t\t\t\t? resolvedStart.model.profileId\n\t\t\t\t\t: null,\n\t\tproviderOptions:\n\t\t\tstart.state.kind === \"preparation_failed\"\n\t\t\t\t? { ...start.state.providerOptions }\n\t\t\t\t: resolvedStart?.kind === \"llm\"\n\t\t\t\t\t? { ...resolvedStart.providerOptions }\n\t\t\t\t\t: {},\n\t\ttitle:\n\t\t\tstart.state.kind === \"bootstrap_failed\"\n\t\t\t\t? \"Worker startup failed\"\n\t\t\t\t: \"Model preparation failed\",\n\t\tsummary: start.state.safeSummary,\n\t};\n}\n\n/** Interprets startup exclusively from durable process, start, lease, and turn evidence. */\nexport function buildStartupEvidence(input: StartupEvidenceInput): StartupEvidence {\n\tconst orderedStarts = [...input.turnStarts].sort(\n\t\t(left, right) =>\n\t\t\tleft.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n\t);\n\tconst turnStartsById = new Map(orderedStarts.map((start) => [start.id, start]));\n\tconst leasesByStartRecordId = new Map(\n\t\tinput.leases\n\t\t\t.filter((lease) => lease.turnStartRecordId)\n\t\t\t.map((lease) => [lease.turnStartRecordId as string, lease]),\n\t);\n\tconst leasesById = new Map(input.leases.map((lease) => [lease.id, lease]));\n\tconst turnRecordsById = new Map(input.turnRecords.map((record) => [record.id, record]));\n\tconst firstAcceptedIndex = orderedStarts.findIndex((start) => start.state.kind === \"accepted\");\n\tconst currentStartId =\n\t\tinput.process.currentExecution?.kind === \"worker_start\"\n\t\t\t? input.process.currentExecution.id\n\t\t\t: null;\n\tconst startupStarts = orderedStarts.filter(\n\t\t(_start, index) => firstAcceptedIndex < 0 || index <= firstAcceptedIndex,\n\t);\n\tconst attempts: StartupAttemptSummary[] = startupStarts.map((start, index) => {\n\t\tconst stateLeaseId =\n\t\t\tstart.state.kind === \"accepted\"\n\t\t\t\t? start.state.acceptedWorkerLeaseId\n\t\t\t\t: start.state.kind === \"bootstrap_failed\"\n\t\t\t\t\t? start.state.failedWorkerLeaseId\n\t\t\t\t\t: null;\n\t\tconst lease =\n\t\t\t(stateLeaseId ? leasesById.get(stateLeaseId) : null) ??\n\t\t\tleasesByStartRecordId.get(start.id) ??\n\t\t\tnull;\n\t\tconst connectedAt = lease\n\t\t\t? validObservedAt(lease.connectedAt ?? lease.bootstrapReceipt?.readyAt, lease.startedAt)\n\t\t\t: null;\n\t\tconst workspaceAt = lease\n\t\t\t? validObservedAt(\n\t\t\t\t\tlease.workspacePreparationStartedAt ?? lease.bootstrapReceipt?.readyAt,\n\t\t\t\t\tconnectedAt ?? lease.startedAt,\n\t\t\t\t)\n\t\t\t: null;\n\t\tconst readyAt = lease\n\t\t\t? validObservedAt(\n\t\t\t\t\tlease.readyAt ?? lease.bootstrapReceipt?.readyAt,\n\t\t\t\t\tworkspaceAt ?? lease.startedAt,\n\t\t\t\t)\n\t\t\t: null;\n\t\tconst acceptedState = start.state.kind === \"accepted\" ? start.state : null;\n\t\tconst acceptedTurnCandidate = acceptedState\n\t\t\t? turnRecordsById.get(acceptedState.turnRecordId)\n\t\t\t: undefined;\n\t\tconst acceptedTurn =\n\t\t\tacceptedTurnCandidate &&\n\t\t\tacceptedTurnCandidate.turnStartRecordId === start.id &&\n\t\t\tacceptedTurnCandidate.acceptedWorkerLeaseId === acceptedState?.acceptedWorkerLeaseId\n\t\t\t\t? acceptedTurnCandidate\n\t\t\t\t: null;\n\t\tconst firstTurnAt =\n\t\t\tacceptedTurn && readyAt ? validObservedAt(acceptedTurn.startedAt, readyAt) : null;\n\t\tconst succeeded = Boolean(lease && readyAt && firstTurnAt && start.state.kind === \"accepted\");\n\t\tconst failed =\n\t\t\tstart.state.kind === \"preparation_failed\" || start.state.kind === \"bootstrap_failed\";\n\t\tconst status: StartupAttemptSummary[\"status\"] = succeeded\n\t\t\t? \"succeeded\"\n\t\t\t: failed\n\t\t\t\t? \"failed\"\n\t\t\t\t: start.state.kind === \"superseded\" ||\n\t\t\t\t\t\tinput.process.lifecycleStatus === \"aborted\" ||\n\t\t\t\t\t\tinput.process.lifecycleStatus === \"completed\" ||\n\t\t\t\t\t\t(start.id !== currentStartId && index < startupStarts.length - 1)\n\t\t\t\t\t? \"superseded\"\n\t\t\t\t\t: \"starting\";\n\t\tconst queued =\n\t\t\tstatus === \"starting\" &&\n\t\t\t!lease &&\n\t\t\tinput.events?.some(\n\t\t\t\t(event) =>\n\t\t\t\t\tevent.eventType === \"worker_capacity_queued\" && event.data.startRecordId === start.id,\n\t\t\t);\n\t\tconst queueSummary =\n\t\t\t\"Waiting for worker capacity; starts automatically when a slot is available.\";\n\t\tconst failedStepId: StartupAttemptStepSummary[\"id\"] = !lease\n\t\t\t? \"start_worker\"\n\t\t\t: !connectedAt\n\t\t\t\t? \"connect_worker\"\n\t\t\t\t: !readyAt\n\t\t\t\t\t? \"prepare_workspace\"\n\t\t\t\t\t: \"start_first_turn\";\n\t\tconst phases = [\n\t\t\t[\"start_worker\", queued ? queueSummary : \"Resolve the turn and request its worker.\"],\n\t\t\t[\"connect_worker\", \"Allocate storage, schedule and start the worker, then connect.\"],\n\t\t\t[\"prepare_workspace\", \"Prepare the workspace, tools and model provider.\"],\n\t\t\t[\"start_first_turn\", \"Accept the turn and hand it to the worker.\"],\n\t\t] as const;\n\t\tconst allocatedAt = lease?.startedAt ?? null;\n\t\tconst boundaries = [\n\t\t\tstart.createdAt,\n\t\t\tallocatedAt,\n\t\t\tlease?.connectedAt ?? null,\n\t\t\treadyAt,\n\t\t\tfirstTurnAt,\n\t\t];\n\t\tconst observations = [allocatedAt, connectedAt, readyAt, firstTurnAt];\n\t\tconst stoppedAt =\n\t\t\tfailed || start.state.kind === \"superseded\"\n\t\t\t\t? start.updatedAt\n\t\t\t\t: status === \"superseded\"\n\t\t\t\t\t? (startupStarts[index + 1]?.createdAt ??\n\t\t\t\t\t\tinput.process.closedAt ??\n\t\t\t\t\t\tinput.process.updatedAt ??\n\t\t\t\t\t\tstart.updatedAt)\n\t\t\t\t\t: null;\n\t\tconst steps = phases.map(\n\t\t\t([id, detail], phase): StartupAttemptStepSummary => ({\n\t\t\t\tid,\n\t\t\t\tlabel:\n\t\t\t\t\tqueued && id === \"start_worker\" ? \"Waiting for worker capacity\" : STARTUP_STEP_LABELS[id],\n\t\t\t\tstatus: (phase === 0 ? Boolean(lease) : Boolean(observations[phase]))\n\t\t\t\t\t? \"completed\"\n\t\t\t\t\t: status === \"superseded\"\n\t\t\t\t\t\t? \"superseded\"\n\t\t\t\t\t\t: failed && id === failedStepId\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: id === failedStepId && status === \"starting\"\n\t\t\t\t\t\t\t\t? \"in_progress\"\n\t\t\t\t\t\t\t\t: \"pending\",\n\t\t\t\toccurredAt: observations[phase] ?? null,\n\t\t\t\tstartedAt: boundaries[phase] ?? null,\n\t\t\t\tendedAt: boundaries[phase + 1] ?? (id === failedStepId ? stoppedAt : null),\n\t\t\t\tdetail,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\tstartRecordId: start.id,\n\t\t\tworkerLeaseId: lease?.id ?? null,\n\t\t\tstatus,\n\t\t\tstartedAt: start.createdAt,\n\t\t\treadyAt,\n\t\t\tdurationMs:\n\t\t\t\tlease && readyAt ? Math.max(0, Date.parse(readyAt) - Date.parse(start.createdAt)) : null,\n\t\t\tsummary:\n\t\t\t\tstart.state.kind === \"preparation_failed\" || start.state.kind === \"bootstrap_failed\"\n\t\t\t\t\t? start.state.safeSummary\n\t\t\t\t\t: queued\n\t\t\t\t\t\t? queueSummary\n\t\t\t\t\t\t: null,\n\t\t\trecoveredByStartRecordId: null,\n\t\t\tsteps,\n\t\t};\n\t});\n\t// Startup history ends at the first accepted start, so any success is the final attempt.\n\tconst authoritative = attempts.find((attempt) => attempt.status === \"succeeded\");\n\tconst recoveredAttempts = attempts.map((attempt) =>\n\t\tattempt.status === \"failed\" && authoritative\n\t\t\t? {\n\t\t\t\t\t...attempt,\n\t\t\t\t\tstatus: \"recovered\" as const,\n\t\t\t\t\trecoveredByStartRecordId: authoritative.startRecordId,\n\t\t\t\t}\n\t\t\t: attempt,\n\t);\n\tconst currentAttempt =\n\t\t(currentStartId\n\t\t\t? recoveredAttempts.find((attempt) => attempt.startRecordId === currentStartId)\n\t\t\t: undefined) ??\n\t\trecoveredAttempts.at(-1) ??\n\t\tnull;\n\treturn {\n\t\tattempts: recoveredAttempts,\n\t\t...(pendingTurnWait(input.process)?.initialSelection\n\t\t\t? { readiness: { message: pendingTurnWait(input.process)?.message ?? null } }\n\t\t\t: {}),\n\t\tcurrentAttempt,\n\t\tauthoritativeAttemptId: authoritative?.startRecordId ?? null,\n\t\trecovery: buildStartupRecovery(input.process, turnStartsById, input.events),\n\t};\n}\n\nexport function presentProcessStartupSummary(evidence: StartupEvidence): ProcessStartupSummary {\n\treturn {\n\t\tauthoritativeAttemptId: evidence.authoritativeAttemptId,\n\t\tattempts: [...evidence.attempts],\n\t\trecovery: evidence.recovery,\n\t};\n}\n\nfunction projectStep(\n\trun: LaunchRun,\n\tid: string,\n\tstatus: \"pending\" | \"in_progress\" | \"completed\" | \"failed\" | \"skipped\",\n\toccurredAt: string | null,\n\tsafeSummary?: string,\n): LaunchRun {\n\treturn {\n\t\t...run,\n\t\tsteps: run.steps.map((step) => {\n\t\t\tif (step.id !== id) return step;\n\t\t\tconst {\n\t\t\t\tstartedAt: previousStartedAt,\n\t\t\t\tcompletedAt: previousCompletedAt,\n\t\t\t\tsafeSummary: _previousSafeSummary,\n\t\t\t\t...base\n\t\t\t} = step;\n\t\t\tconst terminal = status === \"completed\" || status === \"failed\" || status === \"skipped\";\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tstatus,\n\t\t\t\t...(status !== \"pending\"\n\t\t\t\t\t? { startedAt: occurredAt ?? previousStartedAt ?? run.updatedAt ?? run.createdAt }\n\t\t\t\t\t: {}),\n\t\t\t\t...(terminal\n\t\t\t\t\t? { completedAt: occurredAt ?? previousCompletedAt ?? run.updatedAt ?? run.createdAt }\n\t\t\t\t\t: {}),\n\t\t\t\t...(safeSummary ? { safeSummary } : {}),\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/** Projects a launch checklist from canonical durable evidence, never from an incoming worker event. */\nexport function projectLaunchRunStartup(\n\trun: LaunchRun,\n\tevidence: StartupEvidence,\n\ttitleState: LaunchTitleState,\n): LaunchRun {\n\tif (run.status === \"cancelled\") return run;\n\tconst wasFailed = run.status === \"failed\";\n\tlet next = run;\n\tconst attempt = evidence.currentAttempt;\n\tif (!wasFailed) {\n\t\tnext = {\n\t\t\t...next,\n\t\t\tsteps: next.steps.map((item) => {\n\t\t\t\tif (!Object.hasOwn(STARTUP_STEP_LABELS, item.id)) return item;\n\t\t\t\tconst phase = attempt?.steps.find((candidate) => candidate.id === item.id);\n\t\t\t\tif (!phase && item.status === \"skipped\") return item;\n\t\t\t\tconst { startedAt: _start, completedAt: _end, safeSummary: _summary, ...rest } = item;\n\t\t\t\tconst status = !phase || phase.status === \"superseded\" ? \"pending\" : phase.status;\n\t\t\t\tconst safeSummary =\n\t\t\t\t\tstatus === \"failed\"\n\t\t\t\t\t\t? (attempt?.summary ??\n\t\t\t\t\t\t\t\"Worker startup stopped before completion. Retry startup from the process page.\")\n\t\t\t\t\t\t: item.id === \"start_worker\"\n\t\t\t\t\t\t\t? attempt?.summary\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\treturn {\n\t\t\t\t\t...rest,\n\t\t\t\t\tstatus,\n\t\t\t\t\tlabel: phase?.label ?? item.label,\n\t\t\t\t\t...(phase?.startedAt ? { startedAt: phase.startedAt } : {}),\n\t\t\t\t\t...(phase?.endedAt ? { completedAt: phase.endedAt } : {}),\n\t\t\t\t\t...(phase && safeSummary ? { safeSummary } : {}),\n\t\t\t\t};\n\t\t\t}),\n\t\t};\n\t\tconst failedStep = attempt?.steps.find((step) => step.status === \"failed\");\n\t\tif (!attempt && evidence.readiness) {\n\t\t\tnext = {\n\t\t\t\t...next,\n\t\t\t\tsteps: next.steps.map((step) =>\n\t\t\t\t\tstep.id === \"start_worker\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...step,\n\t\t\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\t\t\tlabel: \"Waiting for startup prerequisites\",\n\t\t\t\t\t\t\t\tsafeSummary: evidence.readiness?.message ?? \"Checking startup prerequisites…\",\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: step,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tif (failedStep) {\n\t\t\tnext = failLaunchRun(\n\t\t\t\tnext,\n\t\t\t\tfailedStep.id,\n\t\t\t\tattempt?.summary ??\n\t\t\t\t\t\"Worker startup stopped before completion. Retry startup from the process page.\",\n\t\t\t);\n\t\t}\n\t}\n\tconst projectedTitleStatus = titleState.status === \"pending\" ? \"in_progress\" : titleState.status;\n\tnext = projectStep(\n\t\tnext,\n\t\t\"choose_title\",\n\t\tprojectedTitleStatus,\n\t\tnull,\n\t\ttitleState.status === \"failed\" ? titleState.safeSummary : undefined,\n\t);\n\tif (wasFailed || next.status === \"failed\") {\n\t\treturn { ...next, status: \"failed\", completedAt: run.completedAt ?? next.completedAt };\n\t}\n\treturn completeLaunchWhenReady({\n\t\t...next,\n\t\tstatus: attempt ? \"starting\" : \"process_created\",\n\t});\n}\n","import {\n\tapplyEventToCompactTurnSummary,\n\temptyCompactTurnSummary,\n\textractFirstUserPromptOnBranch,\n\thasTurnContinuationProgress,\n\ttype PiSessionEntry,\n\ttype ReadonlyEntryTree,\n\tresolveTurnContinuationUserPrompt,\n} from \"@leitwerk-dev/protocol\";\nimport type { RepositoryBundle } from \"./db/repositories.js\";\nimport { buildPrimaryPathSnapshotFromTree } from \"./primary-path-snapshot.js\";\nimport { createProcessOperationCoordinator } from \"./process-operation-coordinator.js\";\nimport { ProcessSessionReader, type ProcessSessionSnapshotStore } from \"./process-session-store.js\";\nimport { buildTurnTracePreviewsFromSession } from \"./process-turn-trace.js\";\n\n/** Project on snapshot acceptance, never on a page read. The SQLite projection survives cold starts. */\nexport function createProjectedSessionSnapshotStore(\n\tsource: ProcessSessionSnapshotStore,\n\trepos: RepositoryBundle,\n) {\n\tconst reader = new ProcessSessionReader(source);\n\tconst { runExclusive: serial } = createProcessOperationCoordinator();\n\tasync function project(instanceId: string) {\n\t\tconst session = await reader.readSessionTree(instanceId);\n\t\tconst process = repos.processes.getById(instanceId);\n\t\tif (!process) return;\n\t\tconst turnRecords = repos.turnRecords.listByInstance(instanceId);\n\t\tconst primaryPath = buildPrimaryPathSnapshotFromTree({\n\t\t\tprocess,\n\t\t\tturnRecords,\n\t\t\tturnAnnotations: repos.turnAnnotations.listByInstance(instanceId),\n\t\t\tworkerLease: null,\n\t\t\tevents: [],\n\t\t\ttree: session.parsedTree,\n\t\t});\n\t\tconst entries = session.piTree.entries as unknown as PiSessionEntry[];\n\t\trepos.turnSummaries.putSession(instanceId, {\n\t\t\tsignature: session.signature,\n\t\t\tleafId: session.piTree.leafId,\n\t\t\tprimaryPath: {\n\t\t\t\tcurrentLeaf: primaryPath.currentLeaf,\n\t\t\t\tsemanticEntryRefs: primaryPath.semanticEntryRefs,\n\t\t\t\tentryCount: primaryPath.primaryPathEntries.length,\n\t\t\t\tturnAnnotations: primaryPath.turnAnnotations,\n\t\t\t},\n\t\t\tprompt: extractFirstUserPromptOnBranch(\n\t\t\t\tsession.piTree as unknown as ReadonlyEntryTree<PiSessionEntry>,\n\t\t\t\tprimaryPath.currentLeaf?.entryId ?? null,\n\t\t\t),\n\t\t\ttracePreviewsByTurnRecordId: buildTurnTracePreviewsFromSession({\n\t\t\t\ttree: session.piTree,\n\t\t\t\tturnRecords,\n\t\t\t}),\n\t\t\tcontinuationByTurnRecordId: Object.fromEntries(\n\t\t\t\tturnRecords\n\t\t\t\t\t.filter((turn) => turn.turnType === \"llm\")\n\t\t\t\t\t.map((turn) => [\n\t\t\t\t\t\tturn.id,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thasProgress: hasTurnContinuationProgress(entries, turn, { endedAt: turn.endedAt }),\n\t\t\t\t\t\t\tuserPrompt: resolveTurnContinuationUserPrompt(entries, turn, {\n\t\t\t\t\t\t\t\tendedAt: turn.endedAt,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t\t),\n\t\t});\n\t}\n\treturn {\n\t\t...source,\n\t\twriteSnapshot(instanceId, content) {\n\t\t\treturn serial(instanceId, async () => {\n\t\t\t\tconst result = await source.writeSnapshot(instanceId, content);\n\t\t\t\tawait project(instanceId);\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\t\twriteSnapshotFile(instanceId, contentPath) {\n\t\t\treturn serial(instanceId, async () => {\n\t\t\t\tconst result = await source.writeSnapshotFile(instanceId, contentPath);\n\t\t\t\tawait project(instanceId);\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\t\tdeleteSnapshot(instanceId) {\n\t\t\treturn serial(instanceId, async () => {\n\t\t\t\tawait source.deleteSnapshot(instanceId);\n\t\t\t\trepos.turnSummaries.deleteSession(instanceId);\n\t\t\t});\n\t\t},\n\t\tbackfill(instanceId: string) {\n\t\t\treturn serial(instanceId, async () => {\n\t\t\t\tfor (const turn of repos.turnRecords.listMissingSummaries(instanceId)) {\n\t\t\t\t\tlet summary = emptyCompactTurnSummary();\n\t\t\t\t\tfor (const event of repos.events.listByTurnRecord(instanceId, turn.id)) {\n\t\t\t\t\t\tsummary = applyEventToCompactTurnSummary(summary, {\n\t\t\t\t\t\t\t...event,\n\t\t\t\t\t\t\teventSequence: event.eventSequence ?? 0,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\trepos.turnSummaries.put(instanceId, turn.id, summary);\n\t\t\t\t}\n\t\t\t\tconst handle = await source.readSnapshotHandle(instanceId);\n\t\t\t\tif (repos.turnSummaries.getSession(instanceId)?.signature !== (handle?.signature ?? null))\n\t\t\t\t\tawait project(instanceId);\n\t\t\t});\n\t\t},\n\t} satisfies ProcessSessionSnapshotStore & { backfill(instanceId: string): Promise<void> };\n}\n","import type {\n\tProcessEvent,\n\tProcessInstance,\n\tProcessSemanticEntryRefKey,\n\tProcessSemanticEntryRefs,\n\tProcessTurnAnnotation,\n\tProcessTurnRecord,\n\tSemanticEntryRef,\n\tWorkerLease,\n} from \"@leitwerk-dev/domain\";\nimport { parseProcessStateJsonLenient } from \"@leitwerk-dev/domain\";\nimport { parseStructuralProcessState } from \"@leitwerk-dev/process-sdk\";\nimport {\n\tasWsEventPayloadRecord,\n\tcreateLiveTurnProjection,\n\ttype PrimaryPathActiveTurnSnapshot,\n\ttype PrimaryPathEntrySnapshot,\n\ttype PrimaryPathSnapshot,\n\treadWsEventTurnRecordId,\n} from \"@leitwerk-dev/protocol\";\nimport type { ParsedInstanceTree } from \"./instance-tree.js\";\n\nfunction buildPrimaryPathEntries(input: {\n\tentriesById: ReadonlyMap<string, PrimaryPathEntrySnapshot>;\n\trootEntryId: string | null;\n\tcurrentLeafEntryId: string | null;\n}): PrimaryPathEntrySnapshot[] {\n\tconst startEntryId = input.currentLeafEntryId ?? input.rootEntryId;\n\tif (!startEntryId) {\n\t\treturn [];\n\t}\n\n\tconst reversedEntries: PrimaryPathEntrySnapshot[] = [];\n\tconst visited = new Set<string>();\n\tlet currentEntryId: string | null = startEntryId;\n\twhile (currentEntryId) {\n\t\tif (visited.has(currentEntryId)) {\n\t\t\tbreak;\n\t\t}\n\t\tvisited.add(currentEntryId);\n\t\tconst entry = input.entriesById.get(currentEntryId);\n\t\tif (!entry) {\n\t\t\tbreak;\n\t\t}\n\t\treversedEntries.push(entry);\n\t\tcurrentEntryId = entry.parentId;\n\t}\n\n\tconst primaryPathEntries = reversedEntries.reverse();\n\tif (!input.rootEntryId) {\n\t\treturn primaryPathEntries;\n\t}\n\n\tconst rootIndex = primaryPathEntries.findIndex((entry) => entry.id === input.rootEntryId);\n\tif (rootIndex >= 0) {\n\t\treturn primaryPathEntries.slice(rootIndex);\n\t}\n\n\tconst rootEntry = input.entriesById.get(input.rootEntryId);\n\treturn rootEntry ? [rootEntry] : primaryPathEntries;\n}\n\nfunction getLatestSucceededPrimaryTurnRecord(\n\tturnRecords: readonly ProcessTurnRecord[],\n): ProcessTurnRecord | null {\n\treturn (\n\t\tturnRecords.findLast(\n\t\t\t(turnRecord) =>\n\t\t\t\tturnRecord?.status === \"succeeded\" &&\n\t\t\t\tturnRecord.pathType === \"primary\" &&\n\t\t\t\ttypeof turnRecord.resultPiEntryId === \"string\" &&\n\t\t\t\tturnRecord.resultPiEntryId.trim() !== \"\",\n\t\t) ?? null\n\t);\n}\n\nfunction resolveEntryRefIfPresent(\n\tentryRef: SemanticEntryRef | null,\n\tentriesById: ReadonlyMap<string, PrimaryPathEntrySnapshot>,\n): SemanticEntryRef | null {\n\tif (!entryRef) {\n\t\treturn null;\n\t}\n\treturn entriesById.has(entryRef.entryId) ? entryRef : null;\n}\n\nfunction deriveRootEntryRef(input: {\n\tentriesById: ReadonlyMap<string, PrimaryPathEntrySnapshot>;\n\tcurrentLeaf: SemanticEntryRef | null;\n}): SemanticEntryRef | null {\n\tif (input.currentLeaf) {\n\t\tlet currentEntry = input.entriesById.get(input.currentLeaf.entryId);\n\t\tconst visited = new Set<string>();\n\t\twhile (currentEntry) {\n\t\t\tif (visited.has(currentEntry.id)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvisited.add(currentEntry.id);\n\t\t\tif (currentEntry.parentId === null) {\n\t\t\t\treturn { entryId: currentEntry.id, turnRecordId: null };\n\t\t\t}\n\t\t\tcurrentEntry = input.entriesById.get(currentEntry.parentId);\n\t\t}\n\t}\n\n\tfor (const entry of input.entriesById.values()) {\n\t\tif (entry.parentId === null) {\n\t\t\treturn { entryId: entry.id, turnRecordId: null };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction deriveCurrentLeafRef(input: {\n\tturnRecords: readonly ProcessTurnRecord[];\n\tentriesById: ReadonlyMap<string, PrimaryPathEntrySnapshot>;\n\trootEntry: SemanticEntryRef | null;\n}): SemanticEntryRef | null {\n\tconst latestSucceededPrimaryTurnRecord = getLatestSucceededPrimaryTurnRecord(input.turnRecords);\n\tif (\n\t\tlatestSucceededPrimaryTurnRecord?.resultPiEntryId &&\n\t\tinput.entriesById.has(latestSucceededPrimaryTurnRecord.resultPiEntryId)\n\t) {\n\t\treturn {\n\t\t\tentryId: latestSucceededPrimaryTurnRecord.resultPiEntryId,\n\t\t\tturnRecordId: latestSucceededPrimaryTurnRecord.id,\n\t\t};\n\t}\n\n\treturn input.rootEntry;\n}\n\nfunction resolveSemanticEntryRefs(input: {\n\tsemanticEntryRefs: ProcessSemanticEntryRefs;\n\tturnRecords: readonly ProcessTurnRecord[];\n\tentriesById: ReadonlyMap<string, PrimaryPathEntrySnapshot>;\n}): ProcessSemanticEntryRefs {\n\tconst currentPrimaryPathLeaf =\n\t\tresolveEntryRefIfPresent(input.semanticEntryRefs.currentPrimaryPathLeaf, input.entriesById) ??\n\t\tnull;\n\tconst provisionalRootEntry =\n\t\tresolveEntryRefIfPresent(input.semanticEntryRefs.rootEntry, input.entriesById) ?? null;\n\tconst rootEntry =\n\t\tprovisionalRootEntry ??\n\t\tderiveRootEntryRef({\n\t\t\tentriesById: input.entriesById,\n\t\t\tcurrentLeaf: currentPrimaryPathLeaf,\n\t\t});\n\tconst resolvedCurrentPrimaryPathLeaf =\n\t\tcurrentPrimaryPathLeaf ??\n\t\tderiveCurrentLeafRef({\n\t\t\tturnRecords: input.turnRecords,\n\t\t\tentriesById: input.entriesById,\n\t\t\trootEntry,\n\t\t});\n\n\treturn {\n\t\t...input.semanticEntryRefs,\n\t\trootEntry,\n\t\tcurrentPrimaryPathLeaf: resolvedCurrentPrimaryPathLeaf,\n\t};\n}\n\nfunction collectDisplayedSemanticEntryRefKeys(\n\tsemanticEntryRefs: ProcessSemanticEntryRefs,\n\tdisplayedEntryIds: ReadonlySet<string>,\n): ProcessSemanticEntryRefKey[] {\n\treturn (\n\t\tObject.entries(semanticEntryRefs) as Array<\n\t\t\t[ProcessSemanticEntryRefKey, SemanticEntryRef | null]\n\t\t>\n\t)\n\t\t.filter(([, ref]) => Boolean(ref?.entryId) && displayedEntryIds.has(ref?.entryId ?? \"\"))\n\t\t.map(([key]) => key as ProcessSemanticEntryRefKey);\n}\n\nfunction collectRelevantTurnRecordIds(input: {\n\tturnRecords: readonly ProcessTurnRecord[];\n\tdisplayedEntryIds: ReadonlySet<string>;\n\tsemanticEntryRefs: ProcessSemanticEntryRefs;\n\tcurrentTurnRecordId: string | null;\n}): Set<string> {\n\tconst ids = new Set<string>();\n\tfor (const turnRecord of input.turnRecords) {\n\t\tif (\n\t\t\t(turnRecord.resultPiEntryId && input.displayedEntryIds.has(turnRecord.resultPiEntryId)) ||\n\t\t\t(turnRecord.forkPiEntryId && input.displayedEntryIds.has(turnRecord.forkPiEntryId))\n\t\t) {\n\t\t\tids.add(turnRecord.id);\n\t\t}\n\t}\n\n\tfor (const ref of Object.values(input.semanticEntryRefs) as Array<SemanticEntryRef | null>) {\n\t\tif (ref?.turnRecordId && input.displayedEntryIds.has(ref.entryId)) {\n\t\t\tids.add(ref.turnRecordId);\n\t\t}\n\t}\n\n\tif (input.currentTurnRecordId) {\n\t\tids.add(input.currentTurnRecordId);\n\t}\n\n\treturn ids;\n}\n\nfunction eventPayload(event: ProcessEvent) {\n\treturn asWsEventPayloadRecord(event.data);\n}\n\nfunction eventTurnRecordId(event: ProcessEvent): string | null {\n\treturn readWsEventTurnRecordId(eventPayload(event));\n}\n\nfunction buildActiveTurnSnapshot(input: {\n\tcurrentTurnRecordId: string | null;\n\tturnRecords: readonly ProcessTurnRecord[];\n\tevents: readonly ProcessEvent[];\n\teventWindowTruncated: boolean;\n}): PrimaryPathActiveTurnSnapshot | null {\n\tif (!input.currentTurnRecordId) {\n\t\treturn null;\n\t}\n\tconst currentTurnRecord = input.turnRecords.find(\n\t\t(turnRecord) => turnRecord.id === input.currentTurnRecordId,\n\t);\n\tif (!currentTurnRecord || currentTurnRecord.status !== \"running\") {\n\t\treturn null;\n\t}\n\n\tconst activeTurnEvents = input.events.filter((event) => {\n\t\tif (!event.eventType.startsWith(\"pi.\")) {\n\t\t\treturn false;\n\t\t}\n\t\tconst correlatedTurnRecordId = eventTurnRecordId(event);\n\t\tif (correlatedTurnRecordId) {\n\t\t\treturn correlatedTurnRecordId === currentTurnRecord.id;\n\t\t}\n\t\treturn event.createdAt >= currentTurnRecord.startedAt;\n\t});\n\tconst { assistant, toolCalls, traceItems, usage } =\n\t\tcreateLiveTurnProjection(activeTurnEvents).rawSnapshot();\n\n\treturn {\n\t\tturnRecordId: currentTurnRecord.id,\n\t\tturnId: currentTurnRecord.turnId,\n\t\tturnType: currentTurnRecord.turnType,\n\t\tpathType: currentTurnRecord.pathType,\n\t\tstartedAt: currentTurnRecord.startedAt,\n\t\tassistant,\n\t\ttoolCalls,\n\t\ttraceItems,\n\t\tusage,\n\t\teventWindowTruncated: input.eventWindowTruncated,\n\t};\n}\n\nexport interface PrimaryPathSnapshotProjectionInput {\n\tprocess: ProcessInstance;\n\tcurrentExecutionTurnRecordId?: string | null;\n\tworkerLease: WorkerLease | null;\n\tturnRecords: readonly ProcessTurnRecord[];\n\tturnAnnotations: readonly ProcessTurnAnnotation[];\n\tevents: readonly ProcessEvent[];\n\teventWindowTruncated?: boolean;\n}\n\nexport function buildPrimaryPathSnapshotFromTree(\n\tinput: PrimaryPathSnapshotProjectionInput & { tree: ParsedInstanceTree },\n): PrimaryPathSnapshot {\n\tconst structuralState = parseStructuralProcessState(\n\t\tparseProcessStateJsonLenient(input.process.stateJson),\n\t);\n\tconst tree = input.tree;\n\tconst semanticEntryRefs = resolveSemanticEntryRefs({\n\t\tsemanticEntryRefs: structuralState.semanticEntryRefs,\n\t\tturnRecords: input.turnRecords,\n\t\tentriesById: tree.entriesById,\n\t});\n\tconst currentLeaf = semanticEntryRefs.currentPrimaryPathLeaf;\n\tconst rootEntry = semanticEntryRefs.rootEntry;\n\tconst primaryPathEntries = buildPrimaryPathEntries({\n\t\tentriesById: tree.entriesById,\n\t\trootEntryId: rootEntry?.entryId ?? null,\n\t\tcurrentLeafEntryId: currentLeaf?.entryId ?? null,\n\t});\n\tconst displayedEntryIds = new Set(primaryPathEntries.map((entry) => entry.id));\n\tconst displayedSemanticEntryRefs = collectDisplayedSemanticEntryRefKeys(\n\t\tsemanticEntryRefs,\n\t\tdisplayedEntryIds,\n\t);\n\tconst currentTurnRecordId = input.currentExecutionTurnRecordId ?? null;\n\tconst relevantTurnRecordIds = collectRelevantTurnRecordIds({\n\t\tturnRecords: input.turnRecords,\n\t\tdisplayedEntryIds,\n\t\tsemanticEntryRefs,\n\t\tcurrentTurnRecordId,\n\t});\n\tconst displayedSemanticEntryRefSet = new Set(displayedSemanticEntryRefs);\n\tconst turnAnnotations =\n\t\tdisplayedEntryIds.size === 0 &&\n\t\tdisplayedSemanticEntryRefs.length === 0 &&\n\t\trelevantTurnRecordIds.size === 0\n\t\t\t? []\n\t\t\t: input.turnAnnotations.filter((annotation) =>\n\t\t\t\t\tannotation.references.some((reference: ProcessTurnAnnotation[\"references\"][number]) => {\n\t\t\t\t\t\tswitch (reference.kind) {\n\t\t\t\t\t\t\tcase \"entry\":\n\t\t\t\t\t\t\t\treturn displayedEntryIds.has(reference.entryId);\n\t\t\t\t\t\t\tcase \"turn_record\":\n\t\t\t\t\t\t\t\treturn relevantTurnRecordIds.has(reference.turnRecordId);\n\t\t\t\t\t\t\tcase \"semantic_entry_ref\":\n\t\t\t\t\t\t\t\treturn displayedSemanticEntryRefSet.has(reference.ref);\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\tconst labels = Object.fromEntries(\n\t\t[...tree.labelsByEntryId.entries()].filter(([entryId]) => displayedEntryIds.has(entryId)),\n\t);\n\n\tconst activeTurn = buildActiveTurnSnapshot({\n\t\tcurrentTurnRecordId,\n\t\tturnRecords: input.turnRecords,\n\t\tevents: input.events,\n\t\teventWindowTruncated: input.eventWindowTruncated === true,\n\t});\n\n\treturn {\n\t\tinstanceId: input.process.id,\n\t\trebuiltAt: new Date().toISOString(),\n\t\tprimaryPathEntries,\n\t\tcurrentLeaf,\n\t\tsemanticEntryRefs,\n\t\tlabels,\n\t\tturnAnnotations,\n\t\tdetailRail: {\n\t\t\tkeyPoints: [],\n\t\t\tfutureTurns: [],\n\t\t\tcurrentPosition: null,\n\t\t},\n\t\tturnState: {\n\t\t\tcurrentTurnRecordId,\n\t\t\tworkerState: input.workerLease?.state ?? null,\n\t\t\tisStreaming: currentTurnRecordId !== null && input.workerLease?.state === \"busy\",\n\t\t\tactiveTurn,\n\t\t},\n\t};\n}\n","import {\n\tcreateDurableWsFrame,\n\tcreateEphemeralWsFrame,\n\ttype DurableWsFrameInput,\n\ttype EphemeralWsFrameInput,\n\ttype KnownDurableWsFrameType,\n\ttype KnownEphemeralWsFrameType,\n\ttype WsDurability,\n\ttype WsFrame,\n\ttype WsPayloadByType,\n} from \"@leitwerk-dev/protocol\";\n\n/** @internal */\nexport interface WsClientLike {\n\t/** @internal */\n\treadyState: number;\n\t/** @internal */\n\tsend(data: string): void;\n\t/** @internal */\n\ton(event: string, handler: () => void): void;\n}\n\nexport type { WsDurability, WsFrame };\n\n/** @internal */\nexport function createBroadcaster() {\n\tconst clients = new Set<WsClientLike>();\n\n\t/** @internal */\n\tfunction addClient(ws: WsClientLike) {\n\t\tclients.add(ws);\n\t\tws.on(\"close\", () => clients.delete(ws));\n\t}\n\n\t/** @internal */\n\tfunction broadcast(frame: WsFrame) {\n\t\tconst data = JSON.stringify(frame);\n\t\tfor (const client of clients) {\n\t\t\tif (client.readyState === 1) {\n\t\t\t\tclient.send(data);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** @internal */\n\tfunction sendDurable<T extends KnownDurableWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t) {\n\t\tconst frame = createDurableWsFrame({\n\t\t\ttype,\n\t\t\tpayload,\n\t\t\tinstanceId,\n\t\t} as Extract<DurableWsFrameInput, { type: T }>);\n\t\tbroadcast(frame);\n\t}\n\n\t/** @internal */\n\tfunction sendEphemeral<T extends KnownEphemeralWsFrameType>(\n\t\ttype: T,\n\t\tpayload: WsPayloadByType[T],\n\t\tinstanceId?: string,\n\t) {\n\t\tconst frame = createEphemeralWsFrame({\n\t\t\ttype,\n\t\t\tpayload,\n\t\t\tinstanceId,\n\t\t} as Extract<EphemeralWsFrameInput, { type: T }>);\n\t\tbroadcast(frame);\n\t}\n\n\treturn {\n\t\t/** @internal */\n\t\taddClient,\n\t\t/** @internal */\n\t\tbroadcast,\n\t\t/** @internal */\n\t\tsendDurable,\n\t\t/** @internal */\n\t\tsendEphemeral,\n\t};\n}\n\n/** @internal */\nexport type Broadcaster = ReturnType<typeof createBroadcaster>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,6BAA6B,2BAA2B;AACjE,SAAS,8BAA8B,+BAA+B;AACtE,SAAS,uCAAuC;AAChD,SAAS,mBAAAA,wBAAuB;AAChC;AAAA,EACC;AAAA,EACA;AAAA,EACA,mBAAmB;AAAA,OACb;AACP,SAAS,kBAAkB;AAC3B,YAAY,OAAO;AACnB,SAAS,SAAS,iBAAiB;;;ACTnC,SAAS,uBAAuB;AAGzB,SAAS,sBAAsB,QAA0C;AAC/E,QAAM,WAAW,CAAC,OAAe,QAAwB;AACxD,UAAM,KAAK,gBAAgB,OAAO,IAAI,EAAE,YAAY,KAAK,CAAC;AAC1D,QAAI,CAAC,OAAO,cAAc,EAAE,KAAK,MAAM;AACtC,YAAM,IAAI,MAAM,mBAAmB,GAAG,8BAA8B;AACrE,WAAO;AAAA,EACR;AACA,QAAM,eAAe,SAAS,QAAQ,eAAe,MAAM,aAAa;AACxE,QAAM,WAAW,SAAS,QAAQ,WAAW,OAAO,SAAS;AAC7D,MAAI,eAAe;AAClB,UAAM,IAAI,MAAM,qDAAqD;AACtE,SAAO;AAAA,IACN,SAAS,QAAQ,WAAW;AAAA,IAC5B;AAAA,IACA;AAAA,IACA,eAAe,QAAQ,mBAAmB;AAAA,EAC3C;AACD;AACO,IAAM,0BAAN,cAAsC,MAAM;AAAC;AAE7C,SAAS,YACf,QACA,WACAC,MACgB;AAChB,MAAI,cAAc,MAAM;AACvB,QAAI,CAAC,OAAO,cAAe,OAAM,IAAI,wBAAwB,8BAA8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EACD;AACD;;;AE5GA;AAAA,EACC,wBAAAC;AAAA,EACA,0BAAAC;AAAA,OAQM;AAeA,SAAS,oBAAoB;AACnC,QAAM,UAAU,oBAAI,IAAkB;AAGtC,WAAS,UAAU,IAAkB;AACpC,YAAQ,IAAI,EAAE;AACd,OAAG,GAAG,SAAS,MAAM,QAAQ,OAAO,EAAE,CAAC;AAAA,EACxC;AAGA,WAAS,UAAU,OAAgB;AAClC,UAAM,OAAO,KAAK,UAAU,KAAK;AACjC,eAAW,UAAU,SAAS;AAC7B,UAAI,OAAO,eAAe,GAAG;AAC5B,eAAO,KAAK,IAAI;AAAA,MACjB;AAAA,IACD;AAAA,EACD;AAGA,WAAS,YACR,MACA,SACA,YACC;AACD,UAAM,QAAQD,sBAAqB;AAAA,MAClC;AAAA,MACA;AAAA,MACA;AAAA,IACD,CAA8C;AAC9C,cAAU,KAAK;AAAA,EAChB;AAGA,WAAS,cACR,MACA,SACA,YACC;AACD,UAAM,QAAQC,wBAAuB;AAAA,MACpC;AAAA,MACA;AAAA,MACA;AAAA,IACD,CAAgD;AAChD,cAAU,KAAK;AAAA,EAChB;AAEA,SAAO;AAAA;AAAA,IAEN;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA,EACD;AACD;","names":["parseDurationMs","now","override","process","object","candidate","index","issue","path","parseDurationMs","existsSync","wikiTopics","check","integer","wikiTopics","index","sql","existsSync","record","and","eq","sql","record","eq","sql","and","eq","eq","and","eq","eq","and","row","target","eq","eq","and","eq","inArray","sql","sql","eq","and","inArray","and","eq","and","eq","desc","eq","eq","desc","and","asc","desc","eq","inArray","sql","eq","sql","index","inArray","and","asc","title","desc","and","asc","eq","inArray","asc","eq","and","inArray","and","desc","eq","eq","desc","and","and","asc","eq","eq","and","asc","and","asc","eq","eq","asc","and","and","asc","desc","eq","inArray","sql","desc","and","eq","sql","inArray","asc","eq","eq","SYSTEM_ACTOR","and","asc","eq","isNull","and","eq","isNull","asc","SYSTEM_ACTOR","and","asc","count","desc","eq","inArray","notInArray","or","sql","maxLength","overviewPredicates","eq","inArray","sql","or","overviewWhere","and","desc","notInArray","asc","count","and","asc","desc","eq","sql","and","gte","lte","and","eq","asc","desc","sql","and","eq","inArray","eq","inArray","and","and","asc","eq","eq","and","asc","asc","eq","map","eq","asc","asc","eq","candidate","eq","asc","and","asc","eq","inArray","lte","sql","and","eq","inArray","target","asc","lte","sql","and","asc","eq","map","eq","and","asc","and","asc","eq","getTableColumns","sql","getTableColumns","sql","and","eq","asc","and","asc","desc","eq","getTableColumns","isNull","sql","eq","asc","getTableColumns","and","isNull","sql","desc","and","count","eq","count","eq","and","and","eq","inArray","isNull","lt","or","createHash","randomBytes","now","eq","and","inArray","isNull","now","or","lt","verifyCanonicalPiResourceBundle","and","asc","count","desc","eq","isNotNull","max","notExists","notInArray","sql","parseYaml","text","and","eq","count","sql","max","desc","verifyCanonicalPiResourceBundle","candidate","notExists","notInArray","asc","isNotNull","ids","resolved","revisionId","and","desc","eq","map","and","eq","desc","and","eq","map","eq","and","and","asc","eq","isNull","and","eq","isNull","asc","text","max","candidate","value","process","getProcessGraph","getProcessGraph","trimToNull","compareModelProfileIds","candidate","trimToNull","override","createHash","trimToNull","issue","process","trimToNull","trimToNull","process","trimToNull","parseStrictInstanceTurnConfigsJson","override","issue","parseStrictInstanceTurnConfigsJson","trimToNull","compareModelProfileIds","modelCostRank","issue","trimToNull","modelCostRank","compareModelProfileIds","candidate","turns","resolved","process","process","check","sha256Digest","resolved","maxEntries","candidate","sha256Digest","process","turnRecords","lstat","realpath","path","sha256Digest","validateResourceRelativePath","PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION","index","sha256Digest","validateResourceRelativePath","path","lstat","realpath","trimToNull","process","process","trimToNull","override","issue","process","candidate","count","issue","open","path","path","open","asUnknownRecord","trimToNull","record","text","index","toolCallId","toolName","createHash","path","DEFAULT_SESSION_TRANSFER_LIMITS","existsSync","mkdirSync","path","path","now","DEFAULT_SESSION_TRANSFER_LIMITS","process","createHash","CONTINUE_PROMPT_METADATA_KEY","createLiveTurnProjection","emptyCompactTurnSummary","mergeUsageSnapshots","reasoningPreviewTail","isLlmTurnDefinition","process","isLlmTurnDefinition","listVisibleActionsForProcess","candidate","parsedPayload","payload","process","start","turn","SYSTEM_ACTOR","process","process","index","record","unknown","record","index","record","path","normalizeLaunchModelConfigInput","unknownRecordSchema","v","v","process","getProcessGraph","unknownRecordSchema","normalizeLaunchModelConfigInput","issue","count","now","nextRetryAt","process","record","index","candidate","emptyCompactTurnSummary","reasoningPreviewTail","process","issue","record","index","turnRecords","path","CONTINUE_PROMPT_METADATA_KEY","mergeUsageSnapshots","turnAnnotations","workerLeases","signal","annotation","getProcessGraph","listVisibleActionsForProcess","createLiveTurnProjection","applyEventToCompactTurnSummary","emptyCompactTurnSummary","extractFirstUserPromptOnBranch","hasTurnContinuationProgress","resolveTurnContinuationUserPrompt","parseProcessStateJsonLenient","parseStructuralProcessState","asWsEventPayloadRecord","createLiveTurnProjection","turnRecords","eventTurnRecordId","turnAnnotations","process","turnRecords","extractFirstUserPromptOnBranch","hasTurnContinuationProgress","resolveTurnContinuationUserPrompt","emptyCompactTurnSummary","applyEventToCompactTurnSummary","createDurableWsFrame","createEphemeralWsFrame"]}
|