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,OAAO,CAAC,oBAAoB,CAAC,CAiB7E;IAED,OAAO,CAAC,SAAS;IAwBX,gBAAgB,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAQrF;YAEa,wBAAwB;YAqFxB,eAAe;IAkD7B,OAAO,CAAC,SAAS;IAmBX,SAAS,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAE9E;IAEK,MAAM,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAElE;YAEa,kBAAkB;IA6D1B,IAAI,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CA2CpE;IAEK,MAAM,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAgBlE;YAEa,YAAY;YAIZ,YAAY;YAKZ,WAAW;YAKX,mBAAmB;CAIjC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { bindChildSession } from \"../durable-child-session/child-session-restore.js\";\nimport { defaultChildSessionDir } from \"../durable-child-session/index.js\";\nimport type { GovernanceService } from \"../governance/service.js\";\nimport {\n\tcreateDurableMissionRecord,\n\ttype DurableMissionRecord,\n\ttype DurableMissionStore,\n} from \"../mission-domain/durable-store.js\";\nimport { createMissionRequest, type MissionRequest } from \"../mission-domain/mission-request.js\";\nimport { isTerminalMissionState } from \"../mission-domain/mission-state.js\";\nimport { SessionManager } from \"../session-manager.js\";\nimport type { LocalSubagentRuntime } from \"../shared-inference/runtime.js\";\nimport {\n\tcreateParentOrchestrationExecution,\n\tDEFAULT_ORCHESTRATION_CHILD_AUTHORITY,\n\ttype ParentOrchestrationExecution,\n\ttype ParentOrchestrationExecutionOptions,\n} from \"./parent-execution.js\";\nimport { createQwenPlanner } from \"./qwen-planner.js\";\nimport type { OrchestrationStore } from \"./types.js\";\nimport {\n\ttype OrchestrationChildExecutionPort,\n\ttype OrchestrationJoinResult,\n\ttype OrchestrationNode,\n\ttype OrchestrationNodeStatus,\n\ttype OrchestrationPlan,\n\ttype OrchestrationPlanDocument,\n\ttype OrchestrationPlanner,\n\ttype OrchestrationPlanProposal,\n\ttype OrchestrationProposalInput,\n\ttype OrchestrationReason,\n\ttype OrchestrationStatus,\n\ttype OrchestrationValidationResult,\n\torchestrationMetadataForNode,\n} from \"./types.js\";\nimport { validateOrchestrationPlan, validatePlanProposal } from \"./validation.js\";\n\nexport interface OrchestratorOptions {\n\tstore: OrchestrationStore;\n\tmissions: DurableMissionStore;\n\tlogicalRuntime?: LocalSubagentRuntime;\n\tsessionDir?: string;\n\tnow?: () => number;\n\torchestrationIdFactory?: () => string;\n\tmaxDepth?: number;\n\tmaxChildrenPerNode?: number;\n\tmaxTotalLogicalAgents?: number;\n\tmaxReplans?: number;\n\t/**\n\t * Explicit operator agent names accepted by plan validation on top of the\n\t * canonical subagent registry. Takes precedence over any roster a planner\n\t * exposes through `allowedAgents()`.\n\t */\n\toperatorAgents?: readonly string[];\n\t/**\n\t * Planner for the automatic start/preview path. Default:\n\t * `createQwenPlanner()` (the local Qwen planner). Inject a mocked planner\n\t * or a planner with a deterministic stream seam in tests.\n\t */\n\tplanner?: OrchestrationPlanner;\n\t/**\n\t * Child execution authority port. It is exposed through the\n\t * `childExecutionPort` seam and reused by automatic execution when no\n\t * explicit execution port is supplied.\n\t */\n\tchildExecutionPort?: OrchestrationChildExecutionPort;\n\tgovernance?: GovernanceService;\n}\n\nexport interface CreateOrchestrationOptions {\n\tparentMissionId: string;\n\tproposal: OrchestrationPlanProposal;\n\tparentDepth?: number;\n\trationale?: string;\n\t/** Per-call operator agent set; overrides the service-level option. */\n\toperatorAgents?: readonly string[];\n}\n\nexport interface OrchestrationPreview {\n\tplan?: OrchestrationPlan;\n\tvalidation: OrchestrationValidationResult;\n\tissues: unknown[];\n}\n\nexport interface OrchestrationReconcileResult {\n\tstatus: OrchestrationStatus;\n\tmaterializedMissionIds: string[];\n\tunblockedNodeIds: string[];\n}\n\n/** Result of an automatic start: the created plan plus the materialization. */\nexport interface AutomaticStartResult extends OrchestrationReconcileResult {\n\tplan: OrchestrationPlan;\n}\n\n/**\n * Options for `startAutomatic`. `childExecutionAuthority` names the child\n * execution authority that will drive the created plan: when present, the\n * parent mission's durable request is updated (atomically) to carry the\n * `orchestrationExecution` contract BEFORE the result is returned. When\n * absent the status quo holds: children are materialized but no parent\n * execution contract is persisted.\n */\nexport interface StartAutomaticOptions {\n\t/**\n\t * Named child execution authority persisted on the parent's durable\n\t * request as `orchestrationExecution.childExecutionAuthority`. Verified,\n\t * never defaulted: an empty/whitespace name is rejected.\n\t */\n\tchildExecutionAuthority?: string;\n}\n\nexport interface AutomaticExecuteOptions extends StartAutomaticOptions {\n\t/** Existing parent execution stack. When omitted, `executionOptions` builds one. */\n\texecution?: ParentOrchestrationExecution;\n\t/** Production factory inputs used when `execution` is omitted. */\n\texecutionOptions?: Omit<ParentOrchestrationExecutionOptions, \"orchestrator\" | \"store\" | \"missions\">;\n\t/** Coordinator resume options, including an optional cancellation signal. */\n\tresumeOptions?: { signal?: AbortSignal };\n}\n\n/** Recognize planners that expose their allowed agent set (roster hook). */\nfunction plannerAllowedAgents(planner: OrchestrationPlanner): readonly string[] | undefined {\n\treturn planner.allowedAgents ? planner.allowedAgents() : undefined;\n}\n\n/** Planner input derived from the parent mission's durable work contract. */\nfunction proposalInputFor(parent: DurableMissionRecord, maxTotalLogicalAgents: number): OrchestrationProposalInput {\n\treturn {\n\t\tparentMissionId: parent.missionId,\n\t\tobjective: parent.request.objective,\n\t\tconstraints: parent.request.constraints ?? [],\n\t\tmaxTotalLogicalAgents,\n\t};\n}\n\nfunction terminalForDependency(record: DurableMissionRecord | undefined): boolean {\n\treturn record?.state === \"SUCCEEDED\" || record?.state === \"PARTIAL\";\n}\n\nfunction childMissionId(orchestrationId: string, nodeId: string): string {\n\treturn `mission_orch_${orchestrationId}_${nodeId}`.replace(/[^A-Za-z0-9._-]/gu, \"_\");\n}\n\nfunction childSessionId(orchestrationId: string, nodeId: string): string {\n\treturn `child_orch_${orchestrationId}_${nodeId}`.replace(/[^A-Za-z0-9._-]/gu, \"_\");\n}\n\nfunction nodeDependencies(plan: OrchestrationPlan, nodeId: string): string[] {\n\treturn plan.edges\n\t\t.filter((edge) => edge.to === nodeId && edge.kind === \"REQUIRED\")\n\t\t.map((edge) => edge.from)\n\t\t.sort();\n}\n\nfunction isRemote(node: OrchestrationNode): boolean {\n\treturn node.requirements?.executionMode === \"remote\" || node.requirements?.preferences?.executionMode === \"remote\";\n}\n\nfunction nodeStatusForRecord(\n\tnode: OrchestrationNode,\n\trecord: DurableMissionRecord | undefined,\n): OrchestrationNodeStatus {\n\tif (!record) return node.status;\n\tif (record.state === \"SUCCEEDED\" || record.state === \"PARTIAL\") return \"COMPLETED\";\n\tif (record.state === \"FAILED\" || record.state === \"CRASHED\" || record.state === \"TIMED_OUT\") return \"FAILED\";\n\tif (record.state === \"CANCELLED\") return \"CANCELLED\";\n\tif (record.state === \"BLOCKED\") return \"BLOCKED\";\n\tif (record.state === \"CREATED\") return \"MATERIALIZED\";\n\treturn \"RUNNING\";\n}\n\nfunction isActiveNodeStatus(status: OrchestrationNodeStatus): boolean {\n\treturn status === \"MATERIALIZED\" || status === \"RUNNING\" || status === \"READY\";\n}\n\nexport class OrchestratorService {\n\tprivate readonly _store: OrchestrationStore;\n\tprivate readonly _missions: DurableMissionStore;\n\tprivate readonly _runtime?: LocalSubagentRuntime;\n\tprivate readonly _sessionDir?: string;\n\tprivate readonly _now: () => number;\n\tprivate readonly _idFactory: () => string;\n\tprivate readonly _operatorAgents?: readonly string[];\n\tprivate readonly _planner?: OrchestrationPlanner;\n\tprivate readonly _childExecutionPort?: OrchestrationChildExecutionPort;\n\tprivate readonly _governance?: GovernanceService;\n\tprivate readonly _limits: Pick<\n\t\tOrchestrationPlan,\n\t\t\"maxDepth\" | \"maxChildrenPerNode\" | \"maxTotalLogicalAgents\" | \"maxReplans\"\n\t>;\n\n\tconstructor(options: OrchestratorOptions) {\n\t\tthis._store = options.store;\n\t\tthis._missions = options.missions;\n\t\tthis._runtime = options.logicalRuntime;\n\t\tthis._sessionDir = options.sessionDir;\n\t\tthis._now = options.now ?? (() => Date.now());\n\t\tthis._idFactory =\n\t\t\toptions.orchestrationIdFactory ??\n\t\t\t(() => `orch_${createHash(\"sha256\").update(`${Date.now()}_${randomUUID()}`).digest(\"hex\").slice(0, 24)}`);\n\t\tthis._operatorAgents = options.operatorAgents;\n\t\tthis._planner = options.planner;\n\t\tthis._childExecutionPort = options.childExecutionPort;\n\t\tthis._governance = options.governance;\n\t\tthis._limits = {\n\t\t\tmaxDepth: options.maxDepth ?? 2,\n\t\t\tmaxChildrenPerNode: options.maxChildrenPerNode ?? 20,\n\t\t\tmaxTotalLogicalAgents: options.maxTotalLogicalAgents ?? 20,\n\t\t\tmaxReplans: options.maxReplans ?? 2,\n\t\t};\n\t}\n\n\t/**\n\t * Access seam for the child execution authority port.\n\t *\n\t * Returns the port configured for this orchestrator, when present. The\n\t * parent lifecycle executor — never materialization — owns child launch.\n\t */\n\tget childExecutionPort(): OrchestrationChildExecutionPort | undefined {\n\t\treturn this._childExecutionPort;\n\t}\n\n\t/**\n\t * Resolve the effective operator agent set for plan validation: an\n\t * explicit per-call override, then the service-level option, then the\n\t * roster exposed by the planner (when any). The canonical subagent\n\t * registry remains the primary authority in all cases.\n\t */\n\tprivate effectiveOperatorAgents(\n\t\toverrideAgents: readonly string[] | undefined,\n\t\tplanner: OrchestrationPlanner | undefined,\n\t): readonly string[] | undefined {\n\t\tif (overrideAgents) return overrideAgents;\n\t\tif (this._operatorAgents) return this._operatorAgents;\n\t\treturn planner ? plannerAllowedAgents(planner) : undefined;\n\t}\n\n\tasync preview(input: CreateOrchestrationOptions): Promise<OrchestrationPreview> {\n\t\tconst plan = this.buildPlan(input);\n\t\tconst validation = validateOrchestrationPlan(plan, {\n\t\t\tparentDepth: input.parentDepth,\n\t\t\toperatorAgents: this.effectiveOperatorAgents(input.operatorAgents, undefined),\n\t\t});\n\t\treturn { plan: validation.valid ? plan : undefined, validation, issues: validation.issues };\n\t}\n\n\tasync create(input: CreateOrchestrationOptions): Promise<OrchestrationPlan> {\n\t\tconst parent = await this.loadMission(input.parentMissionId);\n\t\tconst plan = this.buildPlan({ ...input, parentDepth: input.parentDepth ?? parent.depth });\n\t\tconst validation = validateOrchestrationPlan(plan, {\n\t\t\tparentDepth: parent.depth,\n\t\t\toperatorAgents: this.effectiveOperatorAgents(input.operatorAgents, undefined),\n\t\t});\n\t\tif (!validation.valid)\n\t\t\tthrow new Error(`ORCHESTRATION_PLAN_INVALID: ${validation.issues.map((item) => item.message).join(\"; \")}`);\n\t\tconst criticality = validation.dependencyCriticality;\n\t\tfor (const node of plan.nodes) node.dependencyCriticality = criticality.get(node.nodeId) ?? 0;\n\t\tconst document: OrchestrationPlanDocument = { schemaVersion: 1, plan, revisions: [] };\n\t\tconst created = await this._store.create(document);\n\t\tif (created.status === \"conflict\") throw new Error(`ORCHESTRATION_PLAN_INVALID: ${created.error}`);\n\t\treturn created.status === \"idempotent\" ? created.document.plan : plan;\n\t}\n\n\tasync createFromPlanner(\n\t\tinput: OrchestrationProposalInput,\n\t\tplanner: OrchestrationPlanner,\n\t): Promise<OrchestrationPlan> {\n\t\tconst operatorAgents = this.effectiveOperatorAgents(undefined, planner);\n\t\tlet feedback = \"\";\n\t\tfor (let attempt = 0; attempt <= this._limits.maxReplans; attempt++) {\n\t\t\tif (attempt > 0 && this._governance)\n\t\t\t\tawait this._governance.recordRetry(\n\t\t\t\t\tinput.parentMissionId,\n\t\t\t\t\t`orchestration:${input.parentMissionId}:planner-repair:${attempt}`,\n\t\t\t\t\t\"planner\",\n\t\t\t\t\tthis._now(),\n\t\t\t\t\t{ parentMissionId: input.parentMissionId, phase: \"planner_repair\", attempt },\n\t\t\t\t);\n\t\t\tconst proposed = await planner.propose({\n\t\t\t\t...input,\n\t\t\t\tconstraints: [...input.constraints, feedback].filter(Boolean),\n\t\t\t});\n\t\t\tconst parsed = validatePlanProposal(proposed);\n\t\t\tif (parsed.valid) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.create({\n\t\t\t\t\t\tparentMissionId: input.parentMissionId,\n\t\t\t\t\t\tproposal: parsed.proposal,\n\t\t\t\t\t\toperatorAgents,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfeedback = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tif (this._governance)\n\t\t\t\t\t\tawait this._governance.recordRetry(\n\t\t\t\t\t\t\tinput.parentMissionId,\n\t\t\t\t\t\t\t`orchestration:${input.parentMissionId}:orchestration-replan:${attempt}`,\n\t\t\t\t\t\t\t\"replan\",\n\t\t\t\t\t\t\tthis._now(),\n\t\t\t\t\t\t\t{ parentMissionId: input.parentMissionId, phase: \"orchestration_replan\", attempt },\n\t\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfeedback = parsed.issues.map((item) => `${item.code}:${item.message}`).join(\"; \");\n\t\t}\n\t\tthrow new Error(\"ORCHESTRATION_REPLAN_EXHAUSTED: no valid plan after bounded retries\");\n\t}\n\n\t/**\n\t * Automatic orchestration start. Loads the parent mission's objective and\n\t * constraints, asks the planner (default: `createQwenPlanner()`) to\n\t * propose a plan with bounded replans, creates it, and materializes the\n\t * ready child nodes. Children are never launched here; execution remains\n\t * owned by Mission/Scheduler. The explicit proposal API (`preview` /\n\t * `create`) remains the operator's debug override.\n\t *\n\t * When `options.childExecutionAuthority` is provided, the parent mission's\n\t * durable request is atomically updated (DurableMissionStore `mutate`) to\n\t * carry the `orchestrationExecution` contract naming this plan and that\n\t * authority, BEFORE the result is returned. The returned plan is reloaded\n\t * after materialization so it reflects persisted node state.\n\t */\n\tasync startAutomatic(parentMissionId: string, options: StartAutomaticOptions = {}): Promise<AutomaticStartResult> {\n\t\tconst parent = await this.loadMission(parentMissionId);\n\t\tif (isTerminalMissionState(parent.state))\n\t\t\tthrow new Error(`PARENT_MISSION_TERMINAL: ${parentMissionId} is terminal and cannot own an orchestration`);\n\n\t\tconst existingExecution = parent.request.orchestrationExecution;\n\t\tif (existingExecution) {\n\t\t\tif (\n\t\t\t\toptions.childExecutionAuthority !== undefined &&\n\t\t\t\toptions.childExecutionAuthority.trim() !== existingExecution.childExecutionAuthority\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`AUTHORITY_MISMATCH: parent contract names '${existingExecution.childExecutionAuthority}', ` +\n\t\t\t\t\t\t`requested '${options.childExecutionAuthority}'`,\n\t\t\t\t);\n\t\t\tconst loaded = await this._store.load(existingExecution.orchestrationId);\n\t\t\tif (loaded.status === \"missing\")\n\t\t\t\tthrow new Error(`ORCHESTRATION_NOT_FOUND: ${existingExecution.orchestrationId}`);\n\t\t\tif (loaded.status === \"corrupt\") throw new Error(`ORCHESTRATION_PLAN_CORRUPT: ${loaded.diagnostic}`);\n\t\t\tif (loaded.document.plan.parentMissionId !== parentMissionId)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ORCHESTRATION_PARENT_MISMATCH: orchestration ${existingExecution.orchestrationId} belongs to ` +\n\t\t\t\t\t\t`${loaded.document.plan.parentMissionId}, not ${parentMissionId}`,\n\t\t\t\t);\n\t\t\tconst reconcile = await this.materializeReady(existingExecution.orchestrationId);\n\t\t\tconst updated = await this._store.load(existingExecution.orchestrationId);\n\t\t\tif (updated.status !== \"ok\") throw new Error(`ORCHESTRATION_NOT_FOUND: ${existingExecution.orchestrationId}`);\n\t\t\treturn { ...reconcile, plan: updated.document.plan };\n\t\t}\n\n\t\tconst planner = this._planner ?? createQwenPlanner();\n\t\tconst plan = await this.createFromPlanner(proposalInputFor(parent, this._limits.maxTotalLogicalAgents), planner);\n\t\tif (options.childExecutionAuthority !== undefined)\n\t\t\tawait this.attachOrchestrationExecution(\n\t\t\t\tparentMissionId,\n\t\t\t\tplan.orchestrationId,\n\t\t\t\toptions.childExecutionAuthority,\n\t\t\t);\n\t\tconst reconcile = await this.materializeReady(plan.orchestrationId);\n\t\tconst updated = await this._store.load(plan.orchestrationId);\n\t\tif (updated.status !== \"ok\") throw new Error(`ORCHESTRATION_NOT_FOUND: ${plan.orchestrationId}`);\n\t\treturn { ...reconcile, plan: updated.document.plan };\n\t}\n\n\t/**\n\t * Plan, materialize, and explicitly resume the durable parent mission through\n\t * the existing coordinator. The parent request contract is attached before\n\t * `resume`, and no execution stack is constructed unless requested.\n\t */\n\tasync startAutomaticAndExecute(\n\t\tparentMissionId: string,\n\t\toptions: AutomaticExecuteOptions,\n\t): Promise<DurableMissionRecord> {\n\t\tconst existingParent = await this.loadMission(parentMissionId);\n\t\tif (isTerminalMissionState(existingParent.state)) return existingParent;\n\t\tif (!options.execution && !options.executionOptions)\n\t\t\tthrow new Error(\"EXECUTION_OPTIONS_REQUIRED: executionOptions are required when execution is omitted\");\n\t\tconst execution =\n\t\t\toptions.execution ??\n\t\t\tcreateParentOrchestrationExecution({\n\t\t\t\t...(options.executionOptions ?? {}),\n\t\t\t\t...(options.executionOptions?.port || this._childExecutionPort\n\t\t\t\t\t? { port: options.executionOptions?.port ?? this._childExecutionPort }\n\t\t\t\t\t: {}),\n\t\t\t\tmissions: this._missions,\n\t\t\t\tstore: this._store,\n\t\t\t\torchestrator: this,\n\t\t\t});\n\t\tconst authority =\n\t\t\toptions.childExecutionAuthority ?? execution.port.authority ?? DEFAULT_ORCHESTRATION_CHILD_AUTHORITY;\n\t\tif (execution.port.authority !== authority)\n\t\t\tthrow new Error(\n\t\t\t\t`AUTHORITY_MISMATCH: parent contract names '${authority}', execution provides '${execution.port.authority}'`,\n\t\t\t);\n\t\tawait this.startAutomatic(parentMissionId, { childExecutionAuthority: authority });\n\t\tconst resume = (signal?: AbortSignal) => execution.coordinator.resume(parentMissionId, { signal });\n\t\tif (execution.driver)\n\t\t\treturn execution.driver.execute((signal) => resume(signal), {\n\t\t\t\tsignal: options.resumeOptions?.signal,\n\t\t\t\tparentMissionId,\n\t\t\t});\n\t\treturn resume(options.resumeOptions?.signal);\n\t}\n\n\t/**\n\t * Persist the parent orchestration execution contract on the parent\n\t * mission's durable request: atomically (DurableMissionStore `mutate`)\n\t * update `request.orchestrationExecution` to name `orchestrationId` and\n\t * `childExecutionAuthority`.\n\t *\n\t * Verified, never defaulted, never overwritten:\n\t *   - `CHILD_EXECUTION_AUTHORITY_REQUIRED` — empty/whitespace authority\n\t *   - `PARENT_MISSION_NOT_FOUND` / `PARENT_MISSION_CORRUPT`\n\t *   - `PARENT_ALREADY_OWNS_ORCHESTRATION` — the parent already carries a\n\t *     DIFFERENT contract (re-attaching the identical contract is\n\t *     idempotent and writes nothing)\n\t *   - `PARENT_MISSION_TERMINAL` — a terminal parent cannot own an\n\t *     executable orchestration\n\t *\n\t * The contract is declarative: this writes no plan state and never\n\t * launches anything. The parent lifecycle executor resolves the named\n\t * authority later, at execution time.\n\t */\n\tasync attachOrchestrationExecution(\n\t\tparentMissionId: string,\n\t\torchestrationId: string,\n\t\tchildExecutionAuthority: string,\n\t): Promise<DurableMissionRecord> {\n\t\tconst authority = childExecutionAuthority.trim();\n\t\tif (authority.length === 0)\n\t\t\tthrow new Error(\"CHILD_EXECUTION_AUTHORITY_REQUIRED: a named child execution authority is required\");\n\t\tconst now = this._now();\n\n\t\ttype AttachOutcome = { status: \"attached\" | \"already_attached\" | \"conflict\" | \"terminal\" };\n\t\tconst result = await this._missions.mutate<AttachOutcome>(parentMissionId, (current) => {\n\t\t\tconst existing = current.request.orchestrationExecution;\n\t\t\tif (existing) {\n\t\t\t\tif (existing.orchestrationId === orchestrationId && existing.childExecutionAuthority === authority)\n\t\t\t\t\treturn { kind: \"noop\", value: { status: \"already_attached\" as const } };\n\t\t\t\treturn { kind: \"noop\", value: { status: \"conflict\" as const } };\n\t\t\t}\n\t\t\tif (isTerminalMissionState(current.state)) return { kind: \"noop\", value: { status: \"terminal\" as const } };\n\t\t\tconst next: DurableMissionRecord = {\n\t\t\t\t...current,\n\t\t\t\trequest: Object.freeze({\n\t\t\t\t\t...current.request,\n\t\t\t\t\torchestrationExecution: Object.freeze({ orchestrationId, childExecutionAuthority: authority }),\n\t\t\t\t}),\n\t\t\t\tupdatedAtMs: now,\n\t\t\t\trevision: current.revision + 1,\n\t\t\t};\n\t\t\treturn { kind: \"write\", next, value: { status: \"attached\" as const } };\n\t\t});\n\n\t\tif (result.status === \"missing\") throw new Error(`PARENT_MISSION_NOT_FOUND: ${parentMissionId}`);\n\t\tif (result.status === \"corrupt\")\n\t\t\tthrow new Error(`PARENT_MISSION_CORRUPT: ${parentMissionId} is corrupt: ${result.diagnostic}`);\n\t\tswitch (result.value.status) {\n\t\t\tcase \"attached\":\n\t\t\tcase \"already_attached\": {\n\t\t\t\tconst loaded = await this.loadMission(parentMissionId);\n\t\t\t\treturn loaded;\n\t\t\t}\n\t\t\tcase \"conflict\":\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`PARENT_ALREADY_OWNS_ORCHESTRATION: ${parentMissionId} already carries a different ` +\n\t\t\t\t\t\t`orchestration execution contract`,\n\t\t\t\t);\n\t\t\tcase \"terminal\":\n\t\t\t\tthrow new Error(`PARENT_MISSION_TERMINAL: ${parentMissionId} is terminal and cannot own an orchestration`);\n\t\t}\n\t}\n\n\t/**\n\t * Automatic orchestration preview. A single bounded planner probe (no\n\t * replans, nothing persisted) reporting the plan `startAutomatic` would\n\t * create for the parent mission.\n\t */\n\tasync previewAutomatic(parentMissionId: string): Promise<OrchestrationPreview> {\n\t\tconst parent = await this.loadMission(parentMissionId);\n\t\tconst planner = this._planner ?? createQwenPlanner();\n\t\tconst proposed = await planner.propose(proposalInputFor(parent, this._limits.maxTotalLogicalAgents));\n\t\tconst parsed = validatePlanProposal(proposed);\n\t\tif (!parsed.valid)\n\t\t\treturn {\n\t\t\t\tplan: undefined,\n\t\t\t\tvalidation: { valid: false, issues: parsed.issues, dependencyCriticality: new Map() },\n\t\t\t\tissues: parsed.issues,\n\t\t\t};\n\t\tconst plan = this.buildPlan({ parentMissionId, proposal: parsed.proposal, parentDepth: parent.depth });\n\t\tconst validation = validateOrchestrationPlan(plan, {\n\t\t\tparentDepth: parent.depth,\n\t\t\toperatorAgents: this.effectiveOperatorAgents(undefined, planner),\n\t\t});\n\t\treturn { plan: validation.valid ? plan : undefined, validation, issues: validation.issues };\n\t}\n\n\tprivate buildPlan(input: CreateOrchestrationOptions): OrchestrationPlan {\n\t\tconst now = this._now();\n\t\tconst orchestrationId = this._idFactory();\n\t\treturn {\n\t\t\tschemaVersion: 1,\n\t\t\torchestrationId,\n\t\t\tparentMissionId: input.parentMissionId,\n\t\t\tdecision: input.proposal.decision,\n\t\t\trationale: input.rationale ?? input.proposal.rationale,\n\t\t\tnodes: input.proposal.nodes.map((node) => ({\n\t\t\t\t...node,\n\t\t\t\tacceptanceCriteria: [...node.acceptanceCriteria],\n\t\t\t\tstatus: input.proposal.decision === \"DIRECT\" ? \"PROPOSED\" : node.status,\n\t\t\t})),\n\t\t\tedges: input.proposal.edges.map((edge) => ({ ...edge })),\n\t\t\trevision: 1,\n\t\t\tstate: \"DRAFT\",\n\t\t\t...this._limits,\n\t\t\treplanCount: 0,\n\t\t\tcreatedAtMs: now,\n\t\t\tupdatedAtMs: now,\n\t\t};\n\t}\n\n\tasync materializeReady(orchestrationId: string): Promise<OrchestrationReconcileResult> {\n\t\tconst exclusive = this._store.withExclusive;\n\t\tif (exclusive)\n\t\t\treturn exclusive.call(this._store, orchestrationId, async (document, save) =>\n\t\t\t\tthis.materializeReadyDocument(document, save),\n\t\t\t) as Promise<OrchestrationReconcileResult>;\n\t\tconst document = await this.loadDocument(orchestrationId);\n\t\treturn this.materializeReadyDocument(document, async (next) => this.saveDocument(next, document.plan.revision));\n\t}\n\n\tprivate async materializeReadyDocument(\n\t\tdocument: OrchestrationPlanDocument,\n\t\tsave: (document: OrchestrationPlanDocument) => Promise<void>,\n\t): Promise<OrchestrationReconcileResult> {\n\t\tconst plan = document.plan;\n\t\tconst records = new Map<string, DurableMissionRecord | undefined>();\n\t\tfor (const node of plan.nodes)\n\t\t\tif (node.childMissionId) records.set(node.nodeId, await this.loadOptionalMission(node.childMissionId));\n\t\tconst materialized: string[] = [];\n\t\tconst unblocked: string[] = [];\n\t\tconst nextNodes = plan.nodes.map((node) => {\n\t\t\tconst deps = nodeDependencies(plan, node.nodeId);\n\t\t\tconst blocked = deps.some(\n\t\t\t\t(dependency) =>\n\t\t\t\t\t!terminalForDependency(records.get(dependency)) &&\n\t\t\t\t\tplan.nodes.find((candidate) => candidate.nodeId === dependency)?.status !== \"COMPLETED\",\n\t\t\t);\n\t\t\tif (node.status === \"PROPOSED\" || node.status === \"BLOCKED\" || node.status === \"READY\") {\n\t\t\t\tif (blocked) return { ...node, status: \"BLOCKED\" as const };\n\t\t\t\tif (node.status === \"BLOCKED\") unblocked.push(node.nodeId);\n\t\t\t\treturn { ...node, status: \"READY\" as const };\n\t\t\t}\n\t\t\treturn { ...node, status: nodeStatusForRecord(node, records.get(node.nodeId)) };\n\t\t});\n\t\tfor (const node of nextNodes.filter((candidate) => candidate.status === \"READY\")) {\n\t\t\tif (node.childMissionId) continue;\n\t\t\tif (this._governance) {\n\t\t\t\tconst admission = await this._governance.recordOrchestrationChild({\n\t\t\t\t\tmissionId: plan.parentMissionId,\n\t\t\t\t\teventId: `orchestration:${plan.orchestrationId}:child:${node.nodeId}`,\n\t\t\t\t\tchildId: childMissionId(plan.orchestrationId, node.nodeId),\n\t\t\t\t\torchestrationDepth: 1,\n\t\t\t\t\tatMs: this._now(),\n\t\t\t\t\tcorrelation: {\n\t\t\t\t\t\tparentMissionId: plan.parentMissionId,\n\t\t\t\t\t\torchestrationId: plan.orchestrationId,\n\t\t\t\t\t\tnodeId: node.nodeId,\n\t\t\t\t\t\tphase: \"child_materialization\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!admission.allowed) {\n\t\t\t\t\tconst deniedIndex = nextNodes.findIndex((candidate) => candidate.nodeId === node.nodeId);\n\t\t\t\t\tnextNodes[deniedIndex] = { ...node, status: \"UNSCHEDULABLE\", lastError: admission.reason };\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst materializingIndex = nextNodes.findIndex((candidate) => candidate.nodeId === node.nodeId);\n\t\t\tnextNodes[materializingIndex] = { ...node, status: \"MATERIALIZING\" };\n\t\t\tlet created: MissionRequest & { childSessionId: string };\n\t\t\ttry {\n\t\t\t\tcreated = await this.materializeNode(plan, node);\n\t\t\t} catch (error) {\n\t\t\t\tconst failedIndex = nextNodes.findIndex((candidate) => candidate.nodeId === node.nodeId);\n\t\t\t\tnextNodes[failedIndex] = {\n\t\t\t\t\t...node,\n\t\t\t\t\tstatus: \"UNSCHEDULABLE\",\n\t\t\t\t\tlastError: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmaterialized.push(created.missionId);\n\t\t\tconst index = nextNodes.findIndex((candidate) => candidate.nodeId === node.nodeId);\n\t\t\tnextNodes[index] = {\n\t\t\t\t...node,\n\t\t\t\tstatus: \"MATERIALIZED\",\n\t\t\t\tchildMissionId: created.missionId,\n\t\t\t\tchildSessionId: created.childSessionId,\n\t\t\t};\n\t\t}\n\t\tconst state = this.planState(plan.decision, nextNodes);\n\t\tconst updated: OrchestrationPlan = {\n\t\t\t...plan,\n\t\t\trevision: plan.revision + 1,\n\t\t\tnodes: nextNodes,\n\t\t\tstate,\n\t\t\tupdatedAtMs: this._now(),\n\t\t};\n\t\tawait save({ ...document, plan: updated });\n\t\treturn {\n\t\t\tstatus: await this.statusFromDocument({ ...document, plan: updated }),\n\t\t\tmaterializedMissionIds: materialized,\n\t\t\tunblockedNodeIds: unblocked,\n\t\t};\n\t}\n\n\tprivate async materializeNode(\n\t\tplan: OrchestrationPlan,\n\t\tnode: OrchestrationNode,\n\t): Promise<MissionRequest & { childSessionId: string }> {\n\t\tconst parent = await this.loadMission(plan.parentMissionId);\n\t\tconst missionId = childMissionId(plan.orchestrationId, node.nodeId);\n\t\tconst sessionId = childSessionId(plan.orchestrationId, node.nodeId);\n\t\tconst sessionDir = this._sessionDir ?? defaultChildSessionDir();\n\t\tconst request = createMissionRequest({\n\t\t\tmissionId,\n\t\t\tparent: { missionId: parent.missionId, depth: parent.depth },\n\t\t\tobjective: node.objective,\n\t\t\tagent: node.agent,\n\t\t\texecutionMode: node.executionMode,\n\t\t\tacceptanceCriteria: node.acceptanceCriteria,\n\t\t\tworkspaceScope: parent.request.workspaceScope,\n\t\t\tbudget: parent.request.budget,\n\t\t\tcapabilities: node.capabilities,\n\t\t\tmodelPolicy: parent.request.modelPolicy,\n\t\t\tchildSessionId: sessionId,\n\t\t\tconstraints: node.constraints ?? parent.request.constraints,\n\t\t\tcontext: { parentMissionId: parent.missionId, nodeId: node.nodeId, role: node.role },\n\t\t\torchestration: orchestrationMetadataForNode(plan, node),\n\t\t\tnow: this._now(),\n\t\t});\n\t\tmkdirSync(sessionDir, { recursive: true });\n\t\tconst manager = SessionManager.createWithId(\n\t\t\tparent.request.workspaceScope?.cwd ?? process.cwd(),\n\t\t\tsessionDir,\n\t\t\tsessionId,\n\t\t);\n\t\tbindChildSession(manager, missionId, parent.missionId);\n\t\tconst existing = await this._missions.load(missionId);\n\t\tif (existing.status === \"missing\")\n\t\t\tawait this._missions.create(createDurableMissionRecord({ request, now: this._now() }));\n\t\telse if (existing.status === \"corrupt\") throw new Error(`ORCHESTRATION_CHILD_CORRUPT: ${missionId}`);\n\t\tif (this._runtime)\n\t\t\tawait this._runtime.register({\n\t\t\t\tlogicalAgentId: sessionId,\n\t\t\t\tparentAgentId: parent.request.childSessionId,\n\t\t\t\tmissionId,\n\t\t\t\tsessionId,\n\t\t\t\tsessionDir,\n\t\t\t\tmodelPolicy: request.modelPolicy,\n\t\t\t\tactivity: nodeDependencies(plan, node.nodeId).length > 0 ? \"BLOCKED_DEPENDENCY\" : \"RUNNABLE\",\n\t\t\t\tpriority: node.priority ?? 0,\n\t\t\t});\n\t\treturn { ...request, childSessionId: sessionId };\n\t}\n\n\tprivate planState(\n\t\tdecision: OrchestrationPlan[\"decision\"],\n\t\tnodes: readonly OrchestrationNode[],\n\t): OrchestrationPlan[\"state\"] {\n\t\tif (decision === \"DIRECT\" && nodes.length === 0) return \"COMPLETED\";\n\t\tif (nodes.some((node) => node.status === \"FAILED\" && node.requirement !== \"OPTIONAL\")) return \"FAILED\";\n\t\tif (\n\t\t\tnodes.length > 0 &&\n\t\t\tnodes.every(\n\t\t\t\t(node) =>\n\t\t\t\t\tnode.status === \"COMPLETED\" ||\n\t\t\t\t\t(node.status === \"FAILED\" && node.requirement === \"OPTIONAL\") ||\n\t\t\t\t\tnode.status === \"CANCELLED\",\n\t\t\t)\n\t\t)\n\t\t\treturn \"COMPLETED\";\n\t\treturn nodes.some((node) => isActiveNodeStatus(node.status)) ? \"ACTIVE\" : \"WAITING\";\n\t}\n\n\tasync reconcile(orchestrationId: string): Promise<OrchestrationReconcileResult> {\n\t\treturn this.materializeReady(orchestrationId);\n\t}\n\n\tasync status(orchestrationId: string): Promise<OrchestrationStatus> {\n\t\treturn this.statusFromDocument(await this.loadDocument(orchestrationId));\n\t}\n\n\tprivate async statusFromDocument(document: OrchestrationPlanDocument): Promise<OrchestrationStatus> {\n\t\tconst plan = document.plan;\n\t\tconst records = new Map<string, DurableMissionRecord | undefined>();\n\t\tfor (const node of plan.nodes)\n\t\t\tif (node.childMissionId) records.set(node.nodeId, await this.loadOptionalMission(node.childMissionId));\n\t\tconst graph = plan.nodes.map((node) => ({\n\t\t\tnodeId: node.nodeId,\n\t\t\tstatus: nodeStatusForRecord(node, records.get(node.nodeId)),\n\t\t\trole: node.role,\n\t\t\tobjective: node.objective,\n\t\t\treason: node.independenceReason,\n\t\t\tchildMissionId: node.childMissionId,\n\t\t\tdependencies: nodeDependencies(plan, node.nodeId),\n\t\t\twaitingFor: nodeDependencies(plan, node.nodeId).filter((id) => !terminalForDependency(records.get(id))),\n\t\t\tworkspaceAccess: node.workspaceAccess,\n\t\t}));\n\t\tconst counts = {\n\t\t\tchildrenMaterialized: 0,\n\t\t\tchildrenActive: 0,\n\t\t\tchildrenBlocked: 0,\n\t\t\tchildrenCompleted: 0,\n\t\t\tchildrenFailed: 0,\n\t\t\tchildrenCancelled: 0,\n\t\t\tlocalChildren: 0,\n\t\t\tremoteChildren: 0,\n\t\t\trunnableAgents: 0,\n\t\t\twaitingInferenceAgents: 0,\n\t\t\ttoolingAgents: 0,\n\t\t\tparkedAgents: 0,\n\t\t};\n\t\tfor (const node of graph) {\n\t\t\tif (node.childMissionId) counts.childrenMaterialized++;\n\t\t\tif (node.status === \"BLOCKED\") counts.childrenBlocked++;\n\t\t\tif (node.status === \"COMPLETED\") counts.childrenCompleted++;\n\t\t\tif (node.status === \"FAILED\") counts.childrenFailed++;\n\t\t\tif (node.status === \"CANCELLED\") counts.childrenCancelled++;\n\t\t\tif (isActiveNodeStatus(node.status)) counts.childrenActive++;\n\t\t\tif (node.childMissionId) {\n\t\t\t\tif (isRemote(plan.nodes.find((candidate) => candidate.nodeId === node.nodeId)!)) counts.remoteChildren++;\n\t\t\t\telse counts.localChildren++;\n\t\t\t}\n\t\t}\n\t\tif (this._runtime) Object.assign(counts, await this._runtime.activityCounts());\n\t\tconst fanoutReasonCounts: Partial<Record<OrchestrationReason, number>> = {};\n\t\tfor (const node of plan.nodes)\n\t\t\tif (node.independenceReason)\n\t\t\t\tfanoutReasonCounts[node.independenceReason] = (fanoutReasonCounts[node.independenceReason] ?? 0) + 1;\n\t\treturn {\n\t\t\torchestrationId: plan.orchestrationId,\n\t\t\tparentMissionId: plan.parentMissionId,\n\t\t\tdecision: plan.decision,\n\t\t\tstate: plan.state,\n\t\t\tplanRevision: plan.revision,\n\t\t\treplanCount: plan.replanCount,\n\t\t\tnodesTotal: plan.nodes.length,\n\t\t\t...counts,\n\t\t\tfanoutReasonCounts,\n\t\t\tgraph,\n\t\t};\n\t}\n\n\tasync join(orchestrationId: string): Promise<OrchestrationJoinResult> {\n\t\tconst document = await this.loadDocument(orchestrationId);\n\t\tconst plan = document.plan;\n\t\tconst results: OrchestrationJoinResult[\"results\"] = [];\n\t\tconst requiredFailures: string[] = [];\n\t\tconst optionalFailures: string[] = [];\n\t\tconst pendingNodeIds: string[] = [];\n\t\tconst completedNodeIds: string[] = [];\n\t\tfor (const node of plan.nodes) {\n\t\t\tif (!node.childMissionId) {\n\t\t\t\tif (node.status !== \"COMPLETED\") pendingNodeIds.push(node.nodeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = await this.loadOptionalMission(node.childMissionId);\n\t\t\tif (!record?.result) {\n\t\t\t\tpendingNodeIds.push(node.nodeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.result.state === \"SUCCEEDED\" || record.result.state === \"PARTIAL\")\n\t\t\t\tcompletedNodeIds.push(node.nodeId);\n\t\t\telse if (node.requirement === \"OPTIONAL\") optionalFailures.push(node.nodeId);\n\t\t\telse requiredFailures.push(node.nodeId);\n\t\t\tresults.push({\n\t\t\t\tnodeId: node.nodeId,\n\t\t\t\tmissionId: node.childMissionId,\n\t\t\t\tstate: record.result.state,\n\t\t\t\tsuccess: record.result.success,\n\t\t\t\tsummary: record.result.verification.summary,\n\t\t\t});\n\t\t}\n\t\tconst terminal = pendingNodeIds.length === 0 && requiredFailures.length === 0;\n\t\treturn {\n\t\t\torchestrationId,\n\t\t\tparentMissionId: plan.parentMissionId,\n\t\t\tstate: requiredFailures.length > 0 ? \"FAILED\" : terminal ? \"COMPLETED\" : \"WAITING\",\n\t\t\tdecision: plan.decision,\n\t\t\tterminal,\n\t\t\trequiredFailures,\n\t\t\toptionalFailures,\n\t\t\tcompletedNodeIds,\n\t\t\tpendingNodeIds,\n\t\t\tresults,\n\t\t};\n\t}\n\n\tasync cancel(orchestrationId: string): Promise<OrchestrationStatus> {\n\t\tconst document = await this.loadDocument(orchestrationId);\n\t\tconst plan = document.plan;\n\t\tconst next: OrchestrationPlan = {\n\t\t\t...plan,\n\t\t\trevision: plan.revision + 1,\n\t\t\tstate: \"CANCELLED\",\n\t\t\tnodes: plan.nodes.map((node) =>\n\t\t\t\tnode.status === \"PROPOSED\" || node.status === \"BLOCKED\" || node.status === \"READY\"\n\t\t\t\t\t? { ...node, status: \"CANCELLED\" as const }\n\t\t\t\t\t: node,\n\t\t\t),\n\t\t\tupdatedAtMs: this._now(),\n\t\t};\n\t\tawait this.saveDocument({ ...document, plan: next }, plan.revision);\n\t\treturn this.statusFromDocument({ ...document, plan: next });\n\t}\n\n\tprivate async saveDocument(document: OrchestrationPlanDocument, expectedRevision: number): Promise<void> {\n\t\tconst saved = await this._store.save(document, { expectedRevision });\n\t\tif (saved.status !== \"saved\") throw new Error(\"ORCHESTRATION_STALE_REVISION\");\n\t}\n\tprivate async loadDocument(id: string): Promise<OrchestrationPlanDocument> {\n\t\tconst loaded = await this._store.load(id);\n\t\tif (loaded.status !== \"ok\") throw new Error(`ORCHESTRATION_NOT_FOUND: ${id}`);\n\t\treturn loaded.document;\n\t}\n\tprivate async loadMission(id: string): Promise<DurableMissionRecord> {\n\t\tconst loaded = await this._missions.load(id);\n\t\tif (loaded.status !== \"ok\") throw new Error(`PARENT_MISSION_NOT_FOUND: ${id}`);\n\t\treturn loaded.record;\n\t}\n\tprivate async loadOptionalMission(id: string): Promise<DurableMissionRecord | undefined> {\n\t\tconst loaded = await this._missions.load(id);\n\t\treturn loaded.status === \"ok\" ? loaded.record : undefined;\n\t}\n}\n"]}