@ai-agent-forge/plugin-workflow 0.88.14 → 0.88.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AA+EH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AACrC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AACtC,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAC3C,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACjC,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,MAAM,UAAU,eAAe,CAAC,QAAwB,EAAU;IACjE,OAAO,IAAI,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAAA,CACnE;AAED,8EAA8E;AAC9E,gBAAgB;AAChB,8EAA8E;AAE9E,SAAS,SAAS,CAAC,QAAwB,EAAE,OAAe,EAA4B;IACvF,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,KAAK,OAAO,CAAC,CAAC;AAAA,CACjE;AAED,SAAS,MAAM,CAAC,QAAwB,EAAE,OAAe,EAAyB;IACjF,OAAO,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC;AAAA,CAC3D;AAED,SAAS,YAAY,CAAC,IAAe,EAAU;IAC9C,OAAO,IAAI,CAAC,UAAU,IAAI,mBAAmB,CAAC;AAAA,CAC9C;AAED,MAAM,UAAU,aAAa,CAAC,QAAwB,EAAU;IAC/D,OAAO,QAAQ,CAAC,WAAW,IAAI,oBAAoB,CAA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AAC;gBACpG,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;oBACnD,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ;yBAC/B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,CAAC,EAAE,CAAC;yBACjD,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;oBAC5B,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC;gBAAA,CAClF,CAAC;aACF,CAAC;QAAA,CACF,CAAC;KACF,CAAC;AAAA,CACF","sourcesContent":["/**\n * Workflow advance engine: pure state-machine derivation over WorkflowState\n * (§5 of docs/design/工作流编排插件设计.md).\n *\n * Everything here is deterministic and derived from the persisted snapshot\n * plus a plan-lookup callback: no clocks, no CapabilityAPI access — index.ts\n * owns persistence (§5 总则 1 snapshot-driven reevaluation; events are only\n * trigger signals, the truth always comes from the current branch entries).\n * Every conversion appends exactly one transition; held/rejected activation\n * attempts are audited too, deduplicated when the previous transition for the\n * stage already carries the same held code and unchanged wait condition\n * (§5 总则 5).\n *\n * Budget note (§5 总则 4): the per-workflow cascade limit\n * (max(32, 2 x stageCount), recomputed per run from the workflow's current\n * stage count — see cascadeLimitFor) covers every transition of one run —\n * the explicit action's own conversions plus the derived reevaluation chain.\n * Logical operations reserve their maximum\n * bump count up front (canBump) so a mid-chain stop never leaves a mutated\n * status without its audit entry; hitting the cap is not terminal — any\n * workflow_advance action resumes the chain.\n */\n\nimport type {\n\tStageRuntime,\n\tStageSpec,\n\tTransitionReason,\n\tTransitionReasonCode,\n\tWorkflowRecord,\n\tWorkflowState,\n\tWorkflowTransitionEntry,\n\tWorkflowTransitionTrigger,\n} from \"./types.ts\";\nimport type { ParsedWorkflowSet, WorkflowSetDiff } from \"./validate.ts\";\n\n/** Minimal plan projection read from the current branch's latest plan.state entry. */\nexport interface PlanFacts {\n\treadonly id: string;\n\treadonly status: \"draft\" | \"active\" | \"completed\" | \"cancelled\";\n\treadonly evidence: readonly string[];\n}\n\nexport interface EngineDeps {\n\t/** Plan lookup against the current branch entries (latest plan.state snapshot). */\n\tgetPlan(planId: string): PlanFacts | undefined;\n\t/**\n\t * Last transition per stage (`${workflowId}::${stageId}`), seeded from the\n\t * branch audit stream at load and maintained by the engine — the input to\n\t * the held-dedup rule (§5 总则 5).\n\t */\n\tlastStageTransition: Map<string, { code: TransitionReasonCode; detail?: string }>;\n}\n\n/** Evidence item accepted by workflow_advance (acceptanceId is required in acceptance mode). */\nexport interface EvidenceItem {\n\tacceptanceId?: string;\n\tref: string;\n}\n\nexport type AdvanceAction =\n\t| \"start\"\n\t| \"record-evidence\"\n\t| \"inspect\"\n\t| \"approve\"\n\t| \"reject\"\n\t| \"retreat\"\n\t| \"complete\"\n\t| \"skip\"\n\t| \"cancel\";\n\nexport interface AdvanceInput {\n\tworkflowId: string;\n\taction: AdvanceAction;\n\tstageId?: string;\n\tevidence?: EvidenceItem[];\n\tnote?: string;\n\t/** Advisory executor id for record-evidence; written to StageRuntime.executor last-write-wins (§4). */\n\texecutor?: string;\n}\n\nexport interface ClosureEvidenceItem {\n\tstageId: string;\n\tacceptanceId: string;\n\tref: string;\n}\n\n/** Rule 7 closure summary: per-acceptance evidence of completed stages, as goal-achievement candidates. */\nexport interface WorkflowClosure {\n\tworkflowId: string;\n\tgoalId?: string;\n\tevidence: ClosureEvidenceItem[];\n}\n\nexport interface EngineRun {\n\tstate: WorkflowState;\n\ttransitions: WorkflowTransitionEntry[];\n\tcascadeLimitReached: boolean;\n\tclosures: WorkflowClosure[];\n}\n\nexport const DEFAULT_RETRY_LIMIT = 2;\nexport const DEFAULT_MAX_RETREATS = 3;\nexport const DEFAULT_MAX_ACTIVE_STAGES = 4;\nconst DEFAULT_CASCADE_LIMIT = 32;\nconst DIAGNOSTICS_CAP = 50;\n\nexport function cascadeLimitFor(workflow: WorkflowRecord): number {\n\treturn Math.max(DEFAULT_CASCADE_LIMIT, 2 * workflow.stages.length);\n}\n\n// ---------------------------------------------------------------------------\n// Small lookups\n// ---------------------------------------------------------------------------\n\nfunction runtimeOf(workflow: WorkflowRecord, stageId: string): StageRuntime | undefined {\n\treturn workflow.runtime.find((item) => item.stageId === stageId);\n}\n\nfunction specOf(workflow: WorkflowRecord, stageId: string): StageSpec | undefined {\n\treturn workflow.stages.find((item) => item.id === stageId);\n}\n\nfunction retryLimitOf(spec: StageSpec): number {\n\treturn spec.retryLimit ?? DEFAULT_RETRY_LIMIT;\n}\n\nexport function maxRetreatsOf(workflow: WorkflowRecord): number {\n\treturn workflow.maxRetreats ?? DEFAULT_MAX_RETREATS;\n}\n\nexport function maxActiveOf(workflow: WorkflowRecord): number {\n\treturn workflow.maxActiveStages ?? DEFAULT_MAX_ACTIVE_STAGES;\n}\n\nfunction activeCount(workflow: WorkflowRecord): number {\n\treturn workflow.runtime.filter((item) => item.status === \"active\").length;\n}\n\nfunction uncoveredAcceptanceIds(spec: StageSpec, runtime: StageRuntime): string[] {\n\tconst covered = new Set(runtime.evidence.map((item) => item.acceptanceId));\n\treturn spec.objective.acceptance.map((item) => item.id).filter((id) => !covered.has(id));\n}\n\nfunction pushDiagnostic(workflow: WorkflowRecord, text: string): void {\n\tif (workflow.diagnostics.length >= DIAGNOSTICS_CAP) workflow.diagnostics.shift();\n\tworkflow.diagnostics.push(text);\n}\n\nconst stageKey = (workflowId: string, stageId: string): string => `${workflowId}::${stageId}`;\n\n// ---------------------------------------------------------------------------\n// Run context and transition emission\n// ---------------------------------------------------------------------------\n\ninterface WorkflowRun {\n\tworkflow: WorkflowRecord; // mutable working copy\n\tdeps: EngineDeps;\n\tlimit: number;\n\tused: number;\n\ttransitions: WorkflowTransitionEntry[];\n\tclosures: WorkflowClosure[];\n\thitLimit: boolean;\n}\n\nfunction newWorkflowRun(workflow: WorkflowRecord, deps: EngineDeps, closures: WorkflowClosure[]): WorkflowRun {\n\treturn { workflow, deps, limit: cascadeLimitFor(workflow), used: 0, transitions: [], closures, hitLimit: false };\n}\n\n/** Reserves `needed` transition slots so an operation never mutates without its audit entry. */\nfunction canBump(run: WorkflowRun, needed: number): boolean {\n\tif (run.used + needed <= run.limit) return true;\n\trun.hitLimit = true;\n\treturn false;\n}\n\nfunction appendTransition(\n\trun: WorkflowRun,\n\tstageId: string | undefined,\n\tfrom: string,\n\tto: string,\n\ttrigger: WorkflowTransitionTrigger,\n\treason: TransitionReason,\n): boolean {\n\tif (run.used >= run.limit) {\n\t\trun.hitLimit = true;\n\t\treturn false;\n\t}\n\trun.workflow.revision += 1;\n\trun.transitions.push({\n\t\tworkflowId: run.workflow.id,\n\t\t...(stageId !== undefined ? { stageId } : {}),\n\t\tfrom,\n\t\tto,\n\t\ttrigger,\n\t\treason,\n\t\trevision: run.workflow.revision,\n\t});\n\trun.used += 1;\n\tif (stageId !== undefined) {\n\t\trun.deps.lastStageTransition.set(stageKey(run.workflow.id, stageId), {\n\t\t\tcode: reason.code,\n\t\t\tdetail: reason.detail,\n\t\t});\n\t}\n\treturn true;\n}\n\n/**\n * A held (not activated) pending stage: appends the held transition unless\n * the stage's previous transition already carries the same held code and\n * unchanged wait condition (§5 总则 5 dedup — reevaluation becomes a no-op).\n * plan-dangling and write-scope-conflict additionally raise a diagnostic\n * (§5 总则 2 conditions b/d); deps-incomplete and active-limit are normal\n * graph waiting and stay transition-only.\n */\nfunction holdStage(\n\trun: WorkflowRun,\n\tstageId: string,\n\ttrigger: WorkflowTransitionTrigger,\n\tcode: TransitionReasonCode,\n\tmessage: string,\n\tdetail: string,\n): boolean {\n\tconst key = stageKey(run.workflow.id, stageId);\n\tconst last = run.deps.lastStageTransition.get(key);\n\tif (last !== undefined && last.code === code && last.detail === detail) return false;\n\tconst runtime = runtimeOf(run.workflow, stageId);\n\tconst from = runtime?.status ?? \"pending\";\n\tif (!appendTransition(run, stageId, from, from, trigger, { code, message, detail })) return false;\n\tif (code === \"stage.activated.held-plan-dangling\" || code === \"stage.held.write-scope-conflict\") {\n\t\tpushDiagnostic(run.workflow, message);\n\t}\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// Scope guards (§5 总则 2 condition d)\n// ---------------------------------------------------------------------------\n\n/**\n * An undeclared (or empty) scope on a write stage is global: it intersects\n * every other write stage. Read stages are never scope-checked.\n */\nfunction scopesIntersect(a: string[] | undefined, b: string[] | undefined): boolean {\n\tif (a === undefined || a.length === 0 || b === undefined || b.length === 0) return true;\n\treturn a.some((tag) => b.includes(tag));\n}\n\nfunction findWriteConflict(workflow: WorkflowRecord, spec: StageSpec): StageSpec | undefined {\n\treturn workflow.stages.find((other) => {\n\t\tif (other.id === spec.id || other.kind !== \"write\") return false;\n\t\treturn runtimeOf(workflow, other.id)?.status === \"active\" && scopesIntersect(spec.scope, other.scope);\n\t});\n}\n\n/** Every stage that transitively depends on `stageId` (reverse dependsOn reachability). */\nfunction transitiveDependents(workflow: WorkflowRecord, stageId: string): string[] {\n\tconst dependents = new Set<string>();\n\tlet grew = true;\n\twhile (grew) {\n\t\tgrew = false;\n\t\tfor (const spec of workflow.stages) {\n\t\t\tif (dependents.has(spec.id)) continue;\n\t\t\tif (spec.dependsOn.some((dep) => dep === stageId || dependents.has(dep))) {\n\t\t\t\tdependents.add(spec.id);\n\t\t\t\tgrew = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn [...dependents];\n}\n\n// ---------------------------------------------------------------------------\n// Evaluation (§5 rule 3) and failure disposal (§5 rule 5)\n// ---------------------------------------------------------------------------\n\n/** Settlement of a passed evaluation: auto -> completed, review -> awaiting_review. */\nfunction settlePassedStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n): number {\n\tconst from = runtime.status;\n\tif (spec.advance === \"review\") {\n\t\truntime.status = \"awaiting_review\";\n\t\t// §5 rule 3: awaiting_review does not count as completed — dependents stay locked.\n\t\treturn appendTransition(run, spec.id, from, \"awaiting_review\", trigger, {\n\t\t\tcode: \"stage.awaiting-review\",\n\t\t\tmessage: `stage ${spec.id} passed evaluation and awaits review`,\n\t\t})\n\t\t\t? 1\n\t\t\t: 0;\n\t}\n\truntime.status = \"completed\";\n\tconst covered = spec.objective.acceptance.length > 0;\n\treturn appendTransition(run, spec.id, from, \"completed\", trigger, {\n\t\tcode: covered ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\tmessage: `stage ${spec.id} completed (${covered ? \"acceptance covered\" : \"plan lower bound\"})`,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n/**\n * §5 rule 3 objective evaluation of one ACTIVE stage against its plan: the\n * lower bound is the completed plan's own evidence; declared acceptance adds\n * per-item evidence coverage. Cancelled plan or unmet evaluation -> rule 5\n * failure disposal.\n */\nfunction evaluateActiveStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n): number {\n\tif (spec.planId === undefined) return 0; // checkpoint stages settle via the explicit complete action\n\tconst plan = run.deps.getPlan(spec.planId);\n\tif (plan === undefined) return 0; // unresolvable after activation (plans are append-only); nothing to evaluate\n\tif (plan.status === \"cancelled\") {\n\t\treturn failStage(run, spec, runtime, trigger, \"stage.failed.plan-cancelled\", `plan ${spec.planId} is cancelled`);\n\t}\n\tif (plan.status !== \"completed\") return 0; // waiting: plan-incomplete\n\tconst missing = uncoveredAcceptanceIds(spec, runtime);\n\tconst lowerBoundUnmet = spec.objective.acceptance.length === 0 && plan.evidence.length === 0;\n\tif (missing.length > 0 || lowerBoundUnmet) {\n\t\treturn failStage(\n\t\t\trun,\n\t\t\tspec,\n\t\t\truntime,\n\t\t\ttrigger,\n\t\t\t\"stage.failed.acceptance-missing\",\n\t\t\t`missing acceptance: [${missing.join(\", \")}]${lowerBoundUnmet ? \" (plan evidence empty)\" : \"\"}`,\n\t\t);\n\t}\n\treturn settlePassedStage(run, spec, runtime, trigger);\n}\n\n/**\n * §5 rule 5 failure disposal: the stage transition to failed is audited, then\n * either in-place retry (evidence retained, attempts + 1), cross-stage\n * retreat via the stage's onFail edge (when retries are exhausted and onFail\n * is declared), or workflow failure. A failed workflow keeps every stage in\n * its current state — no forced settlement (rule 5, contrast with cancel).\n */\nfunction failStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n\tcode: TransitionReasonCode,\n\tdetail: string,\n): number {\n\tif (!canBump(run, 2)) return 0; // failure transition + one disposal transition\n\tconst from = runtime.status;\n\truntime.status = \"failed\";\n\tconst appended = appendTransition(run, spec.id, from, \"failed\", trigger, {\n\t\tcode,\n\t\tmessage: `stage ${spec.id} failed`,\n\t\tdetail,\n\t})\n\t\t? 1\n\t\t: 0;\n\tpushDiagnostic(run.workflow, `stage ${spec.id} failed: ${detail}`);\n\truntime.attempts += 1;\n\tif (runtime.attempts > retryLimitOf(spec)) {\n\t\tif (spec.onFail !== undefined) {\n\t\t\tconst target = specOf(run.workflow, spec.onFail);\n\t\t\tif (target !== undefined)\n\t\t\t\treturn appended + crossStageRetreat(run, target, trigger, `stage ${spec.id} exhausted retries`, spec);\n\t\t}\n\t\tconst message = `workflow failed: stage ${spec.id} exhausted retry limit ${retryLimitOf(spec)}`;\n\t\tpushDiagnostic(run.workflow, message);\n\t\trun.workflow.status = \"failed\";\n\t\treturn appendTransition(run, undefined, \"running\", \"failed\", trigger, {\n\t\t\tcode: \"workflow.failed.stage-retries\",\n\t\t\tmessage,\n\t\t\tdetail: `stage:${spec.id}`,\n\t\t})\n\t\t\t? appended + 1\n\t\t\t: appended;\n\t}\n\truntime.status = \"pending\";\n\treturn appendTransition(run, spec.id, \"failed\", \"pending\", trigger, {\n\t\tcode: \"stage.retry.queued\",\n\t\tmessage: `stage ${spec.id} queued for in-place retry (attempt ${runtime.attempts}/${retryLimitOf(spec)}); evidence retained`,\n\t})\n\t\t? appended + 1\n\t\t: appended;\n}\n\n/**\n * §5 rule 5 cross-stage retreat (explicit onFail, retreat, or reject): the\n * retreat budget is checked first — over budget the workflow fails and the\n * scene is preserved as-is; otherwise the target resets to pending\n * unconditionally (a retry-waiting target loses its evidence too) and every\n * non-pending transitive dependent resets to pending with evidence cleared\n * (their inputs are invalidated — DAG propagation). The failing/rejected\n * `origin` stage itself always resets as well (rule 5 is unconditional): when\n * the onFail target sits on a parallel branch the origin is outside the\n * dependent closure and joins the reset set explicitly. attempts are\n * retained (§4); `skipped` dependents never reset (explicit scope ruling).\n */\nfunction crossStageRetreat(\n\trun: WorkflowRun,\n\ttarget: StageSpec,\n\ttrigger: WorkflowTransitionTrigger,\n\tnote: string,\n\torigin?: StageSpec,\n): number {\n\tconst dependents = transitiveDependents(run.workflow, target.id);\n\tconst originOutside = origin !== undefined && origin.id !== target.id && !dependents.includes(origin.id);\n\t// Retreat audit transition (+ at most one more disposal transition when the\n\t// origin sits outside the dependent closure and needs its own audit slot).\n\tif (!canBump(run, originOutside ? 2 : 1)) return 0;\n\trun.workflow.retreatCount += 1;\n\tif (run.workflow.retreatCount > maxRetreatsOf(run.workflow)) {\n\t\tconst message = `workflow failed: retreat budget exhausted (${run.workflow.retreatCount}/${maxRetreatsOf(run.workflow)})`;\n\t\tpushDiagnostic(run.workflow, `${message} — ${note}`);\n\t\trun.workflow.status = \"failed\";\n\t\treturn appendTransition(run, undefined, \"running\", \"failed\", trigger, {\n\t\t\tcode: \"workflow.failed.retreat-budget\",\n\t\t\tmessage,\n\t\t\tdetail: note,\n\t\t})\n\t\t\t? 1\n\t\t\t: 0;\n\t}\n\tconst targetFrom = runtimeOf(run.workflow, target.id)?.status ?? \"pending\";\n\tconst resetIds: string[] = [];\n\tfor (const stageId of [target.id, ...(originOutside ? [origin.id] : []), ...dependents]) {\n\t\tconst runtime = runtimeOf(run.workflow, stageId);\n\t\tif (runtime === undefined) continue;\n\t\tif (\n\t\t\tstageId === target.id ||\n\t\t\tstageId === origin?.id ||\n\t\t\truntime.status === \"completed\" ||\n\t\t\truntime.status === \"active\" ||\n\t\t\truntime.status === \"awaiting_review\" ||\n\t\t\truntime.status === \"failed\"\n\t\t) {\n\t\t\truntime.status = \"pending\";\n\t\t\truntime.evidence = [];\n\t\t\tresetIds.push(stageId);\n\t\t}\n\t}\n\tconst detail = `target:${target.id} reset:[${resetIds.join(\", \")}]${note !== \"\" ? ` — ${note}` : \"\"}`;\n\treturn appendTransition(run, target.id, targetFrom, \"pending\", trigger, {\n\t\tcode: \"stage.retreated\",\n\t\tmessage: `retreat to stage ${target.id}: reset [${resetIds.join(\", \")}]`,\n\t\tdetail,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n// ---------------------------------------------------------------------------\n// Activation scan (§5 总则 2) and the reevaluation loop (§5 总则 1)\n// ---------------------------------------------------------------------------\n\n/**\n * One activation pass over pending stages in declaration order. A pending\n * stage activates only when (a) dependsOn are all completed/skipped (skip\n * counts as completed for unlocking — §5 rule 6), (b) its planId resolves in\n * the current branch entries, (c) the active count is below the cap, (d) a\n * write stage's scope does not intersect an active write stage, and (e)\n * attempts === 0 — retry-waiting stages never auto-activate (anti\n * burnout-spiral, §5 总则 2 e). Each freshly activated stage is immediately\n * re-evaluated once (§5 rule 2), which covers \"plan already completed at\n * activation\" and pure-checkpoint restore flows.\n */\nfunction activationPass(run: WorkflowRun, trigger: WorkflowTransitionTrigger): number {\n\tlet appended = 0;\n\tfor (const spec of run.workflow.stages) {\n\t\tconst runtime = runtimeOf(run.workflow, spec.id);\n\t\tif (runtime === undefined || runtime.status !== \"pending\" || runtime.attempts !== 0) continue; // (e)\n\t\tconst incomplete = spec.dependsOn.filter((dep) => {\n\t\t\tconst dependency = runtimeOf(run.workflow, dep);\n\t\t\treturn !(dependency !== undefined && (dependency.status === \"completed\" || dependency.status === \"skipped\"));\n\t\t});\n\t\tif (incomplete.length > 0) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.held.deps-incomplete\",\n\t\t\t\t\t`stage ${spec.id} waiting: dependencies incomplete [${incomplete.join(\", \")}]`,\n\t\t\t\t\t`missing:[${incomplete.join(\", \")}]`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (spec.planId !== undefined && run.deps.getPlan(spec.planId) === undefined) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.activated.held-plan-dangling\",\n\t\t\t\t\t`stage ${spec.id} held: plan ${spec.planId} not found in the session branch`,\n\t\t\t\t\t`plan:${spec.planId}`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (activeCount(run.workflow) >= maxActiveOf(run.workflow)) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.held.active-limit\",\n\t\t\t\t\t`stage ${spec.id} waiting: active stage limit (${maxActiveOf(run.workflow)}) reached`,\n\t\t\t\t\t`limit:${maxActiveOf(run.workflow)}`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (spec.kind === \"write\") {\n\t\t\tconst conflict = findWriteConflict(run.workflow, spec);\n\t\t\tif (conflict !== undefined) {\n\t\t\t\tconst own = spec.scope === undefined || spec.scope.length === 0 ? \"global\" : spec.scope.join(\",\");\n\t\t\t\tconst other =\n\t\t\t\t\tconflict.scope === undefined || conflict.scope.length === 0 ? \"global\" : conflict.scope.join(\",\");\n\t\t\t\tif (\n\t\t\t\t\tholdStage(\n\t\t\t\t\t\trun,\n\t\t\t\t\t\tspec.id,\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\t\"stage.held.write-scope-conflict\",\n\t\t\t\t\t\t`stage ${spec.id} blocked: write scope [${own}] intersects active stage ${conflict.id} scope [${other}]`,\n\t\t\t\t\t\t`conflict:${conflict.id} scope:[${own}] vs [${other}]`,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tappended += 1;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!canBump(run, 3)) break; // activation + immediate evaluation chain (worst case 2 more)\n\t\truntime.status = \"active\";\n\t\tif (\n\t\t\tappendTransition(run, spec.id, \"pending\", \"active\", trigger, {\n\t\t\t\tcode: \"stage.activated\",\n\t\t\t\tmessage: `stage ${spec.id} activated`,\n\t\t\t})\n\t\t) {\n\t\t\tappended += 1;\n\t\t}\n\t\t// §5 rule 2: immediate single-stage snapshot reevaluation of the activated stage.\n\t\tappended += evaluateActiveStage(run, spec, runtime, \"activation-reeval\");\n\t}\n\treturn appended;\n}\n\n/** §5 rule 7 closure: all stages completed/skipped -> workflow completed, closure evidence recorded. */\nfunction checkClosure(run: WorkflowRun, trigger: WorkflowTransitionTrigger): number {\n\tif (run.workflow.status !== \"running\") return 0;\n\tif (!run.workflow.runtime.every((item) => item.status === \"completed\" || item.status === \"skipped\")) return 0;\n\tif (!canBump(run, 1)) return 0;\n\trun.workflow.status = \"completed\";\n\tconst evidence = run.workflow.runtime\n\t\t.filter((item) => item.status === \"completed\")\n\t\t.flatMap((item) =>\n\t\t\titem.evidence.map((entry) => ({ stageId: item.stageId, acceptanceId: entry.acceptanceId, ref: entry.ref })),\n\t\t);\n\trun.closures.push({\n\t\tworkflowId: run.workflow.id,\n\t\t...(run.workflow.goalId !== undefined ? { goalId: run.workflow.goalId } : {}),\n\t\tevidence,\n\t});\n\treturn appendTransition(run, undefined, \"running\", \"completed\", trigger, {\n\t\tcode: \"workflow.completed\",\n\t\tmessage: `workflow completed: all ${run.workflow.stages.length} stage(s) settled`,\n\t\tdetail: `evidence items: ${evidence.length}`,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n/** §5 总则 4: the cascade marker is appended beyond the budget by design (it is the stop record, not a chain step). */\nfunction markCascadeLimit(run: WorkflowRun, trigger: WorkflowTransitionTrigger): void {\n\tconst message = `cascade limit ${run.limit} reached; transitions stopped — resumable via any workflow_advance action`;\n\tpushDiagnostic(run.workflow, message);\n\trun.workflow.revision += 1;\n\trun.transitions.push({\n\t\tworkflowId: run.workflow.id,\n\t\tfrom: run.workflow.status,\n\t\tto: run.workflow.status,\n\t\ttrigger,\n\t\treason: { code: \"cascade.limit-reached\", message },\n\t\trevision: run.workflow.revision,\n\t});\n}\n\n/**\n * The reevaluation loop for one running workflow: evaluate active stages ->\n * scan activation -> check closure, repeating to a fixed point (no new\n * persisted transitions). Condition-not-met passes are idempotent no-ops;\n * the held dedup keeps repeat passes audit-silent (§5 总则 1 / 总则 5).\n */\nfunction reevaluateWorkflow(run: WorkflowRun, trigger: WorkflowTransitionTrigger): void {\n\twhile (run.workflow.status === \"running\") {\n\t\tif (run.used >= run.limit) {\n\t\t\trun.hitLimit = true;\n\t\t\tbreak;\n\t\t}\n\t\tlet appended = 0;\n\t\tfor (const spec of run.workflow.stages) {\n\t\t\tconst runtime = runtimeOf(run.workflow, spec.id);\n\t\t\tif (runtime === undefined || runtime.status !== \"active\") continue;\n\t\t\tif (!canBump(run, 2)) break;\n\t\t\tappended += evaluateActiveStage(run, spec, runtime, trigger);\n\t\t}\n\t\tif (run.hitLimit) break;\n\t\tappended += activationPass(run, trigger);\n\t\tif (run.hitLimit) break;\n\t\tappended += checkClosure(run, trigger);\n\t\tif (run.hitLimit) break;\n\t\tif (appended === 0) return; // fixed point\n\t}\n\tif (run.hitLimit) markCascadeLimit(run, trigger);\n}\n\n/** Snapshot reevaluation over every workflow in the state (one budget per workflow per run). */\nexport function reevaluateAll(state: WorkflowState, deps: EngineDeps, trigger: WorkflowTransitionTrigger): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tfor (const workflow of workflows) {\n\t\tif (workflow.status !== \"running\") continue;\n\t\tconst workflowRun = newWorkflowRun(workflow, deps, run.closures);\n\t\treevaluateWorkflow(workflowRun, trigger);\n\t\trun.transitions.push(...workflowRun.transitions);\n\t\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\t}\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// workflow_set application (§6)\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a graded full-submit update: workflow-level fields (v8 §6: omitted\n * optional fields keep their stored values), the new stage\n * sequence (runtime aligned by stageId — existing runtimes are preserved,\n * appended stages get fresh pending runtimes), evidence linkage pruning for\n * removed acceptance ids, one stage.spec-amended transition per amended\n * active/awaiting_review stage, then the post-change reevaluation chain\n * (§5 总则 1: conversions settle -> same-call reevaluation).\n */\nexport function applyWorkflowSet(\n\tstate: WorkflowState,\n\tnext: ParsedWorkflowSet,\n\tdiff: WorkflowSetDiff,\n\tdeps: EngineDeps,\n): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tif (diff.created) {\n\t\tif (next.title === undefined) {\n\t\t\t// v8 §6: the create path still requires a title (updates keep the\n\t\t\t// stored value instead, see below).\n\t\t\tthrow new Error(\"title is required to create a workflow (updates keep the stored value when omitted)\");\n\t\t}\n\t\tworkflows.push({\n\t\t\tid: next.id,\n\t\t\ttitle: next.title,\n\t\t\t...(next.goalId !== undefined ? { goalId: next.goalId } : {}),\n\t\t\tstatus: \"draft\",\n\t\t\trevision: next.revision,\n\t\t\tstages: next.stages.map((stage) => structuredClone(stage)),\n\t\t\truntime: next.stages.map((stage) => ({ stageId: stage.id, status: \"pending\", attempts: 0, evidence: [] })),\n\t\t\tretreatCount: 0,\n\t\t\t...(next.maxRetreats !== undefined ? { maxRetreats: next.maxRetreats } : {}),\n\t\t\t...(next.maxActiveStages !== undefined ? { maxActiveStages: next.maxActiveStages } : {}),\n\t\t\tdiagnostics: [],\n\t\t});\n\t\treturn run;\n\t}\n\tconst record = workflows.find((workflow) => workflow.id === next.id);\n\tif (record === undefined) throw new Error(`unknown workflow: ${next.id}`);\n\t// Workflow-level fields are modifiable while running (§6), revision is the\n\t// caller's monotonic value; engine conversions below increment past it.\n\t// v8 keep-stored-value semantics (§6): an omitted optional field (title/\n\t// goalId/maxRetreats/maxActiveStages) keeps the stored value — the model\n\t// full-resends from memory and a dropped field would silently sever the\n\t// closure evidence chain (2026-10-01 dogfood). Explicit clearing is not\n\t// supported; rebinding goes through an explicit set.\n\tif (next.title !== undefined) record.title = next.title;\n\tif (next.goalId !== undefined) record.goalId = next.goalId;\n\tif (next.maxRetreats !== undefined) record.maxRetreats = next.maxRetreats;\n\tif (next.maxActiveStages !== undefined) record.maxActiveStages = next.maxActiveStages;\n\trecord.revision = next.revision;\n\trecord.stages = next.stages.map((stage) => structuredClone(stage));\n\tconst previousRuntime = new Map(record.runtime.map((item) => [item.stageId, item]));\n\trecord.runtime = record.stages.map(\n\t\t(spec) => previousRuntime.get(spec.id) ?? { stageId: spec.id, status: \"pending\", attempts: 0, evidence: [] },\n\t);\n\t// Evidence linkage (§6): an evidence item is dropped when its acceptanceId\n\t// is non-empty and no longer references the amended acceptance set — this\n\t// holds even when the amend emptied acceptance entirely, so no dead linkage\n\t// survives a switch to lower-bound mode. Ref-only items (empty\n\t// acceptanceId, checkpoint completion records) survive regardless of the\n\t// spec shape.\n\tfor (const spec of record.stages) {\n\t\tconst runtime = runtimeOf(record, spec.id);\n\t\tif (runtime === undefined || runtime.evidence.length === 0) continue;\n\t\tconst ids = new Set(spec.objective.acceptance.map((item) => item.id));\n\t\truntime.evidence = runtime.evidence.filter((entry) => entry.acceptanceId === \"\" || ids.has(entry.acceptanceId));\n\t}\n\tconst workflowRun = newWorkflowRun(record, deps, run.closures);\n\tfor (const change of diff.amendChanges) {\n\t\tconst runtime = runtimeOf(record, change.stageId);\n\t\tconst from = runtime?.status ?? \"pending\";\n\t\tconst detail =\n\t\t\t`fields:[${change.fields.join(\", \")}] note:${change.amendNote}` +\n\t\t\t(change.prunedEvidence.length > 0 ? ` pruned evidence for [${change.prunedEvidence.join(\", \")}]` : \"\");\n\t\tif (canBump(workflowRun, 1)) {\n\t\t\tappendTransition(workflowRun, change.stageId, from, from, \"tool\", {\n\t\t\t\tcode: \"stage.spec-amended\",\n\t\t\t\tmessage: `stage ${change.stageId} spec amended`,\n\t\t\t\tdetail,\n\t\t\t});\n\t\t}\n\t}\n\tif (record.status === \"running\") reevaluateWorkflow(workflowRun, \"tool\");\n\trun.transitions.push(...workflowRun.transitions);\n\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// workflow_advance application (§5 rule 6)\n// ---------------------------------------------------------------------------\n\nfunction requireStage(workflow: WorkflowRecord, stageId: string | undefined): StageSpec {\n\tif (stageId === undefined) throw new Error(\"stageId is required for this action\");\n\tconst spec = specOf(workflow, stageId);\n\tif (spec === undefined) throw new Error(`unknown stage: ${stageId} (workflow ${workflow.id})`);\n\treturn spec;\n}\n\nfunction normalizeEvidence(items: EvidenceItem[]): { acceptanceId: string; ref: string }[] {\n\treturn items.map((item) => ({ acceptanceId: item.acceptanceId ?? \"\", ref: item.ref }));\n}\n\n/**\n * Applies one explicit workflow_advance action, then runs the post-action\n * reevaluation chain (§5 总则 1). Illegal conversions throw structured\n * errors (§5 rule 6) — index.ts surfaces them as tool errors unchanged.\n */\nexport function applyAdvance(state: WorkflowState, input: AdvanceInput, deps: EngineDeps): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tif (input.action === \"inspect\") {\n\t\t// Read-only and allowed on every workflow status (§5 rule 6), but still\n\t\t// scoped to one workflow: an unknown id is a structured error.\n\t\tif (!workflows.some((workflow) => workflow.id === input.workflowId)) {\n\t\t\tthrow new Error(`unknown workflow: ${input.workflowId}`);\n\t\t}\n\t\treturn run; // response decorations are added by the caller\n\t}\n\tconst record = workflows.find((workflow) => workflow.id === input.workflowId);\n\tif (record === undefined) throw new Error(`unknown workflow: ${input.workflowId}`);\n\tif (record.status === \"completed\" || record.status === \"failed\" || record.status === \"cancelled\") {\n\t\tthrow new Error(`workflow is ${record.status} and accepts no further actions: ${input.workflowId}`);\n\t}\n\tconst workflowRun = newWorkflowRun(record, deps, run.closures);\n\tconst requireRunning = (): void => {\n\t\tif (record.status !== \"running\") {\n\t\t\tthrow new Error(`workflow is ${record.status}; this action requires a running workflow`);\n\t\t}\n\t};\n\tconst noteSuffix = input.note !== undefined && input.note !== \"\" ? `: ${input.note}` : \"\";\n\n\tswitch (input.action) {\n\t\tcase \"start\": {\n\t\t\tif (record.status !== \"draft\") throw new Error(`workflow is already ${record.status}; start requires draft`);\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\tconst roots = record.stages.filter((spec) => spec.dependsOn.length === 0).length;\n\t\t\trecord.status = \"running\";\n\t\t\tappendTransition(workflowRun, undefined, \"draft\", \"running\", \"tool\", {\n\t\t\t\tcode: \"workflow.started\",\n\t\t\t\tmessage: `workflow started with ${roots} root stage(s)`,\n\t\t\t\tdetail: `roots:${roots}`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"record-evidence\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status === \"completed\" || runtime.status === \"skipped\" || runtime.status === \"failed\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} is ${runtime.status}; record-evidence accepts pending (retry wait), active, and awaiting_review stages`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (spec.objective.acceptance.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} declares no acceptance (lower-bound mode); record-evidence does not apply — the plan's completion evidence is the lower bound`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (items.length === 0) throw new Error(\"record-evidence requires at least one evidence item\");\n\t\t\tfor (const item of items) {\n\t\t\t\tif (item.acceptanceId === undefined || item.acceptanceId.trim() === \"\") {\n\t\t\t\t\tthrow new Error(`stage ${spec.id}: evidence items must carry acceptanceId in acceptance mode`);\n\t\t\t\t}\n\t\t\t\tif (!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`stage ${spec.id}: acceptanceId ${item.acceptanceId} does not reference the current spec's acceptance`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 2)) break; // evidence.recorded + possible single-stage wake settlement\n\t\t\tconst from = runtime.status;\n\t\t\truntime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\tif (input.executor !== undefined && input.executor.trim() !== \"\") {\n\t\t\t\truntime.executor = input.executor.trim();\n\t\t\t}\n\t\t\tappendTransition(workflowRun, spec.id, from, from, \"tool\", {\n\t\t\t\tcode: \"evidence.recorded\",\n\t\t\t\tmessage: `stage ${spec.id}: recorded ${items.length} evidence item(s)`,\n\t\t\t\tdetail: `${items.map((item) => `${item.acceptanceId} <- ${item.ref}`).join(\"; \")}${runtime.executor === undefined ? \"\" : ` | executor: ${runtime.executor}`}`,\n\t\t\t});\n\t\t\tif (runtime.status === \"pending\" && runtime.attempts > 0) {\n\t\t\t\t// §5 rule 4 exception — the only automatic wake channel for\n\t\t\t\t// retry-waiting stages: a single-stage evaluation by the current\n\t\t\t\t// spec and latest evidence. Pass -> settle (completion propagates\n\t\t\t\t// through the reevaluation below); still missing -> keep waiting,\n\t\t\t\t// no attempts consumed.\n\t\t\t\tconst plan = spec.planId !== undefined ? workflowRun.deps.getPlan(spec.planId) : undefined;\n\t\t\t\tconst passed =\n\t\t\t\t\tplan !== undefined &&\n\t\t\t\t\tplan.status === \"completed\" &&\n\t\t\t\t\tplan.evidence.length > 0 &&\n\t\t\t\t\tuncoveredAcceptanceIds(spec, runtime).length === 0;\n\t\t\t\tif (passed) settlePassedStage(workflowRun, spec, runtime, \"tool\");\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"approve\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"awaiting_review\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; approve only settles awaiting_review stages`);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (spec.objective.acceptance.length > 0) {\n\t\t\t\t// Same strong validation as record-evidence/complete: in acceptance\n\t\t\t\t// mode every carried evidence item must reference the current spec.\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tif (item.acceptanceId === undefined || item.acceptanceId.trim() === \"\") {\n\t\t\t\t\t\tthrow new Error(`stage ${spec.id}: evidence items must carry acceptanceId in acceptance mode`);\n\t\t\t\t\t}\n\t\t\t\t\tif (!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`stage ${spec.id}: acceptanceId ${item.acceptanceId} does not reference the current spec's acceptance`,\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\tif (!canBump(workflowRun, 1)) break;\n\t\t\tif (items.length > 0) runtime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\truntime.status = \"completed\";\n\t\t\tappendTransition(workflowRun, spec.id, \"awaiting_review\", \"completed\", \"tool\", {\n\t\t\t\tcode: spec.objective.acceptance.length > 0 ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\t\t\tmessage: `stage ${spec.id} approved in review`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reject\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"awaiting_review\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; reject only applies to awaiting_review stages`);\n\t\t\t}\n\t\t\tif (spec.onFail !== undefined) {\n\t\t\t\t// §5 rule 6: reject walks the stage's onFail edge; the rejected\n\t\t\t\t// stage itself is the retreat origin and always resets (rule 5).\n\t\t\t\tconst target = requireStage(record, spec.onFail);\n\t\t\t\tcrossStageRetreat(workflowRun, target, \"tool\", `review rejection of stage ${spec.id}${noteSuffix}`, spec);\n\t\t\t} else {\n\t\t\t\t// No onFail edge: in-place retry semantics (rule 6 / rule 5).\n\t\t\t\truntime.attempts += 1;\n\t\t\t\tif (runtime.attempts > retryLimitOf(spec)) {\n\t\t\t\t\tconst message = `workflow failed: stage ${spec.id} exhausted retry limit ${retryLimitOf(spec)} (rejected in review)`;\n\t\t\t\t\tif (canBump(workflowRun, 1)) {\n\t\t\t\t\t\tpushDiagnostic(record, message);\n\t\t\t\t\t\trecord.status = \"failed\";\n\t\t\t\t\t\tappendTransition(workflowRun, undefined, \"running\", \"failed\", \"tool\", {\n\t\t\t\t\t\t\tcode: \"workflow.failed.stage-retries\",\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\tdetail: `stage:${spec.id}${noteSuffix}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (canBump(workflowRun, 1)) {\n\t\t\t\t\truntime.status = \"pending\";\n\t\t\t\t\tappendTransition(workflowRun, spec.id, \"awaiting_review\", \"pending\", \"tool\", {\n\t\t\t\t\t\tcode: \"stage.retry.queued\",\n\t\t\t\t\t\tmessage: `stage ${spec.id} rejected in review; queued for in-place retry (attempt ${runtime.attempts}/${retryLimitOf(spec)})`,\n\t\t\t\t\t\tdetail: input.note,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"retreat\": {\n\t\t\trequireRunning();\n\t\t\tconst target = requireStage(record, input.stageId);\n\t\t\tconst targetRuntime = runtimeOf(record, target.id);\n\t\t\tif (targetRuntime === undefined) throw new Error(`unknown stage: ${target.id}`);\n\t\t\tconst wasActivated =\n\t\t\t\ttargetRuntime.status === \"active\" ||\n\t\t\t\ttargetRuntime.status === \"awaiting_review\" ||\n\t\t\t\ttargetRuntime.status === \"completed\" ||\n\t\t\t\ttargetRuntime.attempts > 0;\n\t\t\tif (!wasActivated) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`retreat target ${target.id} has never been activated; retreat targets a previously activated earlier stage`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcrossStageRetreat(workflowRun, target, \"tool\", input.note ?? \"explicit retreat\");\n\t\t\tbreak;\n\t\t}\n\t\tcase \"complete\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (spec.planId !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} references plan ${spec.planId}; complete only applies to checkpoint stages without planId — plan-backed stages settle via plan completion and evaluation`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (runtime.status !== \"active\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; complete requires an active checkpoint stage`);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (items.length === 0) throw new Error(`stage ${spec.id}: complete requires evidence`);\n\t\t\tconst covered = new Set<string>();\n\t\t\tfor (const item of items) {\n\t\t\t\tif (spec.objective.acceptance.length > 0) {\n\t\t\t\t\tif (\n\t\t\t\t\t\titem.acceptanceId === undefined ||\n\t\t\t\t\t\t!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`stage ${spec.id}: evidence acceptanceId must reference the declared acceptance items`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcovered.add(item.acceptanceId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst missing = spec.objective.acceptance.filter((item) => !covered.has(item.id)).map((item) => item.id);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tthrow new Error(`stage ${spec.id}: evidence does not cover acceptance [${missing.join(\", \")}]`);\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\truntime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\truntime.status = \"completed\";\n\t\t\tappendTransition(workflowRun, spec.id, \"active\", \"completed\", \"tool\", {\n\t\t\t\tcode: spec.objective.acceptance.length > 0 ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\t\t\tmessage: `stage ${spec.id} completed at checkpoint`,\n\t\t\t\tdetail: items.map((item) => item.ref).join(\"; \"),\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"skip\": {\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"pending\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; only pending stages can be skipped`);\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\t// §5 rule 6: skipped counts as completed for dependency unlocking —\n\t\t\t// an explicit scope ruling, applied uniformly in closure checks.\n\t\t\truntime.status = \"skipped\";\n\t\t\tappendTransition(workflowRun, spec.id, \"pending\", \"skipped\", \"tool\", {\n\t\t\t\tcode: \"stage.skipped\",\n\t\t\t\tmessage: `stage ${spec.id} skipped (explicit scope ruling)`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"cancel\": {\n\t\t\tconst from = record.status;\n\t\t\t// §5 rule 6: every non-terminal stage becomes skipped; referenced\n\t\t\t// active plans are left untouched (soft reference — the plan domain\n\t\t\t// keeps its own sovereignty).\n\t\t\tfor (const spec of record.stages) {\n\t\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\t\tif (runtime === undefined || runtime.status === \"completed\" || runtime.status === \"skipped\") continue;\n\t\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\t\tconst stageFrom = runtime.status;\n\t\t\t\truntime.status = \"skipped\";\n\t\t\t\tappendTransition(workflowRun, spec.id, stageFrom, \"skipped\", \"tool\", {\n\t\t\t\t\tcode: \"stage.skipped\",\n\t\t\t\t\tmessage: `stage ${spec.id} skipped by workflow cancellation`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\trecord.status = \"cancelled\";\n\t\t\tappendTransition(workflowRun, undefined, from, \"cancelled\", \"tool\", {\n\t\t\t\tcode: \"workflow.cancelled\",\n\t\t\t\tmessage: `workflow cancelled (non-terminal stages skipped)`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (record.status === \"running\") reevaluateWorkflow(workflowRun, \"tool\");\n\trun.transitions.push(...workflowRun.transitions);\n\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// Inspection (§8.1 waiting conditions + acceptance coverage)\n// ---------------------------------------------------------------------------\n\n/**\n * The §8.1 waiting-condition label for one stage, or null when nothing is\n * blocking it. Label ownership: `acceptance-missing` is exclusively the\n * acceptance-mode retry wait (pending with attempts > 0); `retry-wait` is the\n * lower-bound retry wait (pending with attempts > 0 and no acceptance\n * declared — the plan completed but its evidence is empty); an active stage\n * whose plan is not completed yet is `plan-incomplete`. The check order\n * mirrors activationPass (§8.1: active-limit precedes write-scope conflict),\n * so the inspect label always names the same condition the audit recorded.\n */\nexport function computeWaitingOn(\n\tworkflow: WorkflowRecord,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\tdeps: EngineDeps,\n): string | null {\n\tif (runtime.status === \"awaiting_review\") return \"review\";\n\tif (runtime.status === \"pending\") {\n\t\tif (workflow.status === \"draft\") return \"not-yet-active\";\n\t\tif (runtime.attempts > 0) {\n\t\t\tif (spec.objective.acceptance.length === 0) return \"retry-wait\"; // lower-bound retry wait\n\t\t\treturn `acceptance-missing:[${uncoveredAcceptanceIds(spec, runtime).join(\", \")}]`;\n\t\t}\n\t\tconst incomplete = spec.dependsOn.filter((dep) => {\n\t\t\tconst dependency = runtimeOf(workflow, dep);\n\t\t\treturn !(dependency !== undefined && (dependency.status === \"completed\" || dependency.status === \"skipped\"));\n\t\t});\n\t\tif (incomplete.length > 0) return `deps-incomplete:[${incomplete.join(\", \")}]`;\n\t\tif (spec.planId !== undefined && deps.getPlan(spec.planId) === undefined) return \"plan-dangling\";\n\t\tif (activeCount(workflow) >= maxActiveOf(workflow)) return \"active-limit\";\n\t\tif (spec.kind === \"write\") {\n\t\t\tconst conflict = findWriteConflict(workflow, spec);\n\t\t\tif (conflict !== undefined) return `write-scope-conflict:[${conflict.id}]`;\n\t\t}\n\t\treturn \"not-yet-active\";\n\t}\n\tif (runtime.status === \"active\") {\n\t\tif (spec.planId === undefined) return null; // checkpoint waiting for the explicit complete action\n\t\tconst plan = deps.getPlan(spec.planId);\n\t\tif (plan === undefined) return \"plan-dangling\";\n\t\tif (plan.status !== \"completed\") return \"plan-incomplete\";\n\t\treturn null; // completed plan, evaluation pending the next reevaluation trigger\n\t}\n\treturn null;\n}\n\nexport interface AcceptanceCoverage {\n\tid: string;\n\tstatement: string;\n\tcovered: boolean;\n\trefs: string[];\n}\n\nexport interface StageInspection {\n\tstageId: string;\n\tstatus: StageRuntime[\"status\"];\n\tattempts: number;\n\twaitingOn: string | null;\n\tplanId?: string;\n\tplanStatus?: string;\n\tacceptance: AcceptanceCoverage[];\n}\n\nexport interface WorkflowInspection {\n\tworkflowId: string;\n\tstatus: WorkflowRecord[\"status\"];\n\tstages: StageInspection[];\n}\n\n/** §5 rule 6 inspect payload: full snapshot plus per-stage waiting conditions and acceptance coverage (§8.1). */\nexport function inspectWorkflow(workflow: WorkflowRecord, deps: EngineDeps): WorkflowInspection {\n\treturn {\n\t\tworkflowId: workflow.id,\n\t\tstatus: workflow.status,\n\t\tstages: workflow.stages.map((spec) => {\n\t\t\tconst runtime = runtimeOf(workflow, spec.id);\n\t\t\tconst safeRuntime: StageRuntime = runtime ?? {\n\t\t\t\tstageId: spec.id,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattempts: 0,\n\t\t\t\tevidence: [],\n\t\t\t};\n\t\t\tconst plan = spec.planId !== undefined ? deps.getPlan(spec.planId) : undefined;\n\t\t\treturn {\n\t\t\t\tstageId: spec.id,\n\t\t\t\tstatus: safeRuntime.status,\n\t\t\t\tattempts: safeRuntime.attempts,\n\t\t\t\twaitingOn: computeWaitingOn(workflow, spec, safeRuntime, deps),\n\t\t\t\t...(spec.planId !== undefined ? { planId: spec.planId, planStatus: plan?.status ?? \"missing\" } : {}),\n\t\t\t\tacceptance: spec.objective.acceptance.map((item) => {\n\t\t\t\t\tconst refs = safeRuntime.evidence\n\t\t\t\t\t\t.filter((entry) => entry.acceptanceId === item.id)\n\t\t\t\t\t\t.map((entry) => entry.ref);\n\t\t\t\t\treturn { id: item.id, statement: item.statement, covered: refs.length > 0, refs };\n\t\t\t\t}),\n\t\t\t};\n\t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,EAAE,EAAE,CAAC;oBACnD,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ;yBAC/B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,CAAC,EAAE,CAAC;yBACjD,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;oBAC5B,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC;gBAAA,CAClF,CAAC;aACF,CAAC;QAAA,CACF,CAAC;KACF,CAAC;AAAA,CACF","sourcesContent":["/**\n * Workflow advance engine: pure state-machine derivation over WorkflowState\n * (§5 of docs/design/工作流编排插件设计.md).\n *\n * Everything here is deterministic and derived from the persisted snapshot\n * plus a plan-lookup callback: no clocks, no CapabilityAPI access — index.ts\n * owns persistence (§5 总则 1 snapshot-driven reevaluation; events are only\n * trigger signals, the truth always comes from the current branch entries).\n * Every conversion appends exactly one transition; held/rejected activation\n * attempts are audited too, deduplicated when the previous transition for the\n * stage already carries the same held code and unchanged wait condition\n * (§5 总则 5).\n *\n * Budget note (§5 总则 4): the per-workflow cascade limit\n * (max(32, 2 x stageCount), recomputed per run from the workflow's current\n * stage count — see cascadeLimitFor) covers every transition of one run —\n * the explicit action's own conversions plus the derived reevaluation chain.\n * Logical operations reserve their maximum\n * bump count up front (canBump) so a mid-chain stop never leaves a mutated\n * status without its audit entry; hitting the cap is not terminal — any\n * workflow_advance action resumes the chain.\n */\n\nimport type {\n\tStageRuntime,\n\tStageSpec,\n\tTransitionReason,\n\tTransitionReasonCode,\n\tWorkflowRecord,\n\tWorkflowState,\n\tWorkflowTransitionEntry,\n\tWorkflowTransitionTrigger,\n} from \"./types.ts\";\nimport type { ParsedWorkflowSet, WorkflowSetDiff } from \"./validate.ts\";\n\n/** Minimal plan projection read from the current branch's latest plan.state entry. */\nexport interface PlanFacts {\n\treadonly id: string;\n\treadonly status: \"draft\" | \"active\" | \"completed\" | \"cancelled\";\n\treadonly evidence: readonly string[];\n}\n\nexport interface EngineDeps {\n\t/** Plan lookup against the current branch entries (latest plan.state snapshot). */\n\tgetPlan(planId: string): PlanFacts | undefined;\n\t/**\n\t * Last transition per stage (`${workflowId}::${stageId}`), seeded from the\n\t * branch audit stream at load and maintained by the engine — the input to\n\t * the held-dedup rule (§5 总则 5).\n\t */\n\tlastStageTransition: Map<string, { code: TransitionReasonCode; detail?: string }>;\n}\n\n/** Evidence item accepted by workflow_advance (acceptanceId is required in acceptance mode). */\nexport interface EvidenceItem {\n\tacceptanceId?: string;\n\tref: string;\n}\n\nexport type AdvanceAction =\n\t| \"start\"\n\t| \"record-evidence\"\n\t| \"inspect\"\n\t| \"approve\"\n\t| \"reject\"\n\t| \"retreat\"\n\t| \"complete\"\n\t| \"skip\"\n\t| \"cancel\";\n\nexport interface AdvanceInput {\n\tworkflowId: string;\n\taction: AdvanceAction;\n\tstageId?: string;\n\tevidence?: EvidenceItem[];\n\tnote?: string;\n\t/** Advisory executor id for record-evidence; written to StageRuntime.executor last-write-wins (§4). */\n\texecutor?: string;\n}\n\nexport interface ClosureEvidenceItem {\n\tstageId: string;\n\tacceptanceId: string;\n\tref: string;\n}\n\n/** Rule 7 closure summary: per-acceptance evidence of completed stages, as goal-achievement candidates. */\nexport interface WorkflowClosure {\n\tworkflowId: string;\n\tgoalId?: string;\n\tevidence: ClosureEvidenceItem[];\n}\n\nexport interface EngineRun {\n\tstate: WorkflowState;\n\ttransitions: WorkflowTransitionEntry[];\n\tcascadeLimitReached: boolean;\n\tclosures: WorkflowClosure[];\n}\n\nexport const DEFAULT_RETRY_LIMIT = 2;\nexport const DEFAULT_MAX_RETREATS = 3;\n// 并行激活上限出厂默认(2026-10-19 由 4 调定为 8):重度并行画像下 4 个并行阶段\n// 容易成为吞吐瓶颈;scope 冲突检测仍是写入安全的第一道闸,上限只防扇出失控。\nexport const DEFAULT_MAX_ACTIVE_STAGES = 8;\nconst DEFAULT_CASCADE_LIMIT = 32;\nconst DIAGNOSTICS_CAP = 50;\n\nexport function cascadeLimitFor(workflow: WorkflowRecord): number {\n\treturn Math.max(DEFAULT_CASCADE_LIMIT, 2 * workflow.stages.length);\n}\n\n// ---------------------------------------------------------------------------\n// Small lookups\n// ---------------------------------------------------------------------------\n\nfunction runtimeOf(workflow: WorkflowRecord, stageId: string): StageRuntime | undefined {\n\treturn workflow.runtime.find((item) => item.stageId === stageId);\n}\n\nfunction specOf(workflow: WorkflowRecord, stageId: string): StageSpec | undefined {\n\treturn workflow.stages.find((item) => item.id === stageId);\n}\n\nfunction retryLimitOf(spec: StageSpec): number {\n\treturn spec.retryLimit ?? DEFAULT_RETRY_LIMIT;\n}\n\nexport function maxRetreatsOf(workflow: WorkflowRecord): number {\n\treturn workflow.maxRetreats ?? DEFAULT_MAX_RETREATS;\n}\n\nexport function maxActiveOf(workflow: WorkflowRecord): number {\n\treturn workflow.maxActiveStages ?? DEFAULT_MAX_ACTIVE_STAGES;\n}\n\nfunction activeCount(workflow: WorkflowRecord): number {\n\treturn workflow.runtime.filter((item) => item.status === \"active\").length;\n}\n\nfunction uncoveredAcceptanceIds(spec: StageSpec, runtime: StageRuntime): string[] {\n\tconst covered = new Set(runtime.evidence.map((item) => item.acceptanceId));\n\treturn spec.objective.acceptance.map((item) => item.id).filter((id) => !covered.has(id));\n}\n\nfunction pushDiagnostic(workflow: WorkflowRecord, text: string): void {\n\tif (workflow.diagnostics.length >= DIAGNOSTICS_CAP) workflow.diagnostics.shift();\n\tworkflow.diagnostics.push(text);\n}\n\nconst stageKey = (workflowId: string, stageId: string): string => `${workflowId}::${stageId}`;\n\n// ---------------------------------------------------------------------------\n// Run context and transition emission\n// ---------------------------------------------------------------------------\n\ninterface WorkflowRun {\n\tworkflow: WorkflowRecord; // mutable working copy\n\tdeps: EngineDeps;\n\tlimit: number;\n\tused: number;\n\ttransitions: WorkflowTransitionEntry[];\n\tclosures: WorkflowClosure[];\n\thitLimit: boolean;\n}\n\nfunction newWorkflowRun(workflow: WorkflowRecord, deps: EngineDeps, closures: WorkflowClosure[]): WorkflowRun {\n\treturn { workflow, deps, limit: cascadeLimitFor(workflow), used: 0, transitions: [], closures, hitLimit: false };\n}\n\n/** Reserves `needed` transition slots so an operation never mutates without its audit entry. */\nfunction canBump(run: WorkflowRun, needed: number): boolean {\n\tif (run.used + needed <= run.limit) return true;\n\trun.hitLimit = true;\n\treturn false;\n}\n\nfunction appendTransition(\n\trun: WorkflowRun,\n\tstageId: string | undefined,\n\tfrom: string,\n\tto: string,\n\ttrigger: WorkflowTransitionTrigger,\n\treason: TransitionReason,\n): boolean {\n\tif (run.used >= run.limit) {\n\t\trun.hitLimit = true;\n\t\treturn false;\n\t}\n\trun.workflow.revision += 1;\n\trun.transitions.push({\n\t\tworkflowId: run.workflow.id,\n\t\t...(stageId !== undefined ? { stageId } : {}),\n\t\tfrom,\n\t\tto,\n\t\ttrigger,\n\t\treason,\n\t\trevision: run.workflow.revision,\n\t});\n\trun.used += 1;\n\tif (stageId !== undefined) {\n\t\trun.deps.lastStageTransition.set(stageKey(run.workflow.id, stageId), {\n\t\t\tcode: reason.code,\n\t\t\tdetail: reason.detail,\n\t\t});\n\t}\n\treturn true;\n}\n\n/**\n * A held (not activated) pending stage: appends the held transition unless\n * the stage's previous transition already carries the same held code and\n * unchanged wait condition (§5 总则 5 dedup — reevaluation becomes a no-op).\n * plan-dangling and write-scope-conflict additionally raise a diagnostic\n * (§5 总则 2 conditions b/d); deps-incomplete and active-limit are normal\n * graph waiting and stay transition-only.\n */\nfunction holdStage(\n\trun: WorkflowRun,\n\tstageId: string,\n\ttrigger: WorkflowTransitionTrigger,\n\tcode: TransitionReasonCode,\n\tmessage: string,\n\tdetail: string,\n): boolean {\n\tconst key = stageKey(run.workflow.id, stageId);\n\tconst last = run.deps.lastStageTransition.get(key);\n\tif (last !== undefined && last.code === code && last.detail === detail) return false;\n\tconst runtime = runtimeOf(run.workflow, stageId);\n\tconst from = runtime?.status ?? \"pending\";\n\tif (!appendTransition(run, stageId, from, from, trigger, { code, message, detail })) return false;\n\tif (code === \"stage.activated.held-plan-dangling\" || code === \"stage.held.write-scope-conflict\") {\n\t\tpushDiagnostic(run.workflow, message);\n\t}\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// Scope guards (§5 总则 2 condition d)\n// ---------------------------------------------------------------------------\n\n/**\n * An undeclared (or empty) scope on a write stage is global: it intersects\n * every other write stage. Read stages are never scope-checked.\n */\nfunction scopesIntersect(a: string[] | undefined, b: string[] | undefined): boolean {\n\tif (a === undefined || a.length === 0 || b === undefined || b.length === 0) return true;\n\treturn a.some((tag) => b.includes(tag));\n}\n\nfunction findWriteConflict(workflow: WorkflowRecord, spec: StageSpec): StageSpec | undefined {\n\treturn workflow.stages.find((other) => {\n\t\tif (other.id === spec.id || other.kind !== \"write\") return false;\n\t\treturn runtimeOf(workflow, other.id)?.status === \"active\" && scopesIntersect(spec.scope, other.scope);\n\t});\n}\n\n/** Every stage that transitively depends on `stageId` (reverse dependsOn reachability). */\nfunction transitiveDependents(workflow: WorkflowRecord, stageId: string): string[] {\n\tconst dependents = new Set<string>();\n\tlet grew = true;\n\twhile (grew) {\n\t\tgrew = false;\n\t\tfor (const spec of workflow.stages) {\n\t\t\tif (dependents.has(spec.id)) continue;\n\t\t\tif (spec.dependsOn.some((dep) => dep === stageId || dependents.has(dep))) {\n\t\t\t\tdependents.add(spec.id);\n\t\t\t\tgrew = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn [...dependents];\n}\n\n// ---------------------------------------------------------------------------\n// Evaluation (§5 rule 3) and failure disposal (§5 rule 5)\n// ---------------------------------------------------------------------------\n\n/** Settlement of a passed evaluation: auto -> completed, review -> awaiting_review. */\nfunction settlePassedStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n): number {\n\tconst from = runtime.status;\n\tif (spec.advance === \"review\") {\n\t\truntime.status = \"awaiting_review\";\n\t\t// §5 rule 3: awaiting_review does not count as completed — dependents stay locked.\n\t\treturn appendTransition(run, spec.id, from, \"awaiting_review\", trigger, {\n\t\t\tcode: \"stage.awaiting-review\",\n\t\t\tmessage: `stage ${spec.id} passed evaluation and awaits review`,\n\t\t})\n\t\t\t? 1\n\t\t\t: 0;\n\t}\n\truntime.status = \"completed\";\n\tconst covered = spec.objective.acceptance.length > 0;\n\treturn appendTransition(run, spec.id, from, \"completed\", trigger, {\n\t\tcode: covered ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\tmessage: `stage ${spec.id} completed (${covered ? \"acceptance covered\" : \"plan lower bound\"})`,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n/**\n * §5 rule 3 objective evaluation of one ACTIVE stage against its plan: the\n * lower bound is the completed plan's own evidence; declared acceptance adds\n * per-item evidence coverage. Cancelled plan or unmet evaluation -> rule 5\n * failure disposal.\n */\nfunction evaluateActiveStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n): number {\n\tif (spec.planId === undefined) return 0; // checkpoint stages settle via the explicit complete action\n\tconst plan = run.deps.getPlan(spec.planId);\n\tif (plan === undefined) return 0; // unresolvable after activation (plans are append-only); nothing to evaluate\n\tif (plan.status === \"cancelled\") {\n\t\treturn failStage(run, spec, runtime, trigger, \"stage.failed.plan-cancelled\", `plan ${spec.planId} is cancelled`);\n\t}\n\tif (plan.status !== \"completed\") return 0; // waiting: plan-incomplete\n\tconst missing = uncoveredAcceptanceIds(spec, runtime);\n\tconst lowerBoundUnmet = spec.objective.acceptance.length === 0 && plan.evidence.length === 0;\n\tif (missing.length > 0 || lowerBoundUnmet) {\n\t\treturn failStage(\n\t\t\trun,\n\t\t\tspec,\n\t\t\truntime,\n\t\t\ttrigger,\n\t\t\t\"stage.failed.acceptance-missing\",\n\t\t\t`missing acceptance: [${missing.join(\", \")}]${lowerBoundUnmet ? \" (plan evidence empty)\" : \"\"}`,\n\t\t);\n\t}\n\treturn settlePassedStage(run, spec, runtime, trigger);\n}\n\n/**\n * §5 rule 5 failure disposal: the stage transition to failed is audited, then\n * either in-place retry (evidence retained, attempts + 1), cross-stage\n * retreat via the stage's onFail edge (when retries are exhausted and onFail\n * is declared), or workflow failure. A failed workflow keeps every stage in\n * its current state — no forced settlement (rule 5, contrast with cancel).\n */\nfunction failStage(\n\trun: WorkflowRun,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\ttrigger: WorkflowTransitionTrigger,\n\tcode: TransitionReasonCode,\n\tdetail: string,\n): number {\n\tif (!canBump(run, 2)) return 0; // failure transition + one disposal transition\n\tconst from = runtime.status;\n\truntime.status = \"failed\";\n\tconst appended = appendTransition(run, spec.id, from, \"failed\", trigger, {\n\t\tcode,\n\t\tmessage: `stage ${spec.id} failed`,\n\t\tdetail,\n\t})\n\t\t? 1\n\t\t: 0;\n\tpushDiagnostic(run.workflow, `stage ${spec.id} failed: ${detail}`);\n\truntime.attempts += 1;\n\tif (runtime.attempts > retryLimitOf(spec)) {\n\t\tif (spec.onFail !== undefined) {\n\t\t\tconst target = specOf(run.workflow, spec.onFail);\n\t\t\tif (target !== undefined)\n\t\t\t\treturn appended + crossStageRetreat(run, target, trigger, `stage ${spec.id} exhausted retries`, spec);\n\t\t}\n\t\tconst message = `workflow failed: stage ${spec.id} exhausted retry limit ${retryLimitOf(spec)}`;\n\t\tpushDiagnostic(run.workflow, message);\n\t\trun.workflow.status = \"failed\";\n\t\treturn appendTransition(run, undefined, \"running\", \"failed\", trigger, {\n\t\t\tcode: \"workflow.failed.stage-retries\",\n\t\t\tmessage,\n\t\t\tdetail: `stage:${spec.id}`,\n\t\t})\n\t\t\t? appended + 1\n\t\t\t: appended;\n\t}\n\truntime.status = \"pending\";\n\treturn appendTransition(run, spec.id, \"failed\", \"pending\", trigger, {\n\t\tcode: \"stage.retry.queued\",\n\t\tmessage: `stage ${spec.id} queued for in-place retry (attempt ${runtime.attempts}/${retryLimitOf(spec)}); evidence retained`,\n\t})\n\t\t? appended + 1\n\t\t: appended;\n}\n\n/**\n * §5 rule 5 cross-stage retreat (explicit onFail, retreat, or reject): the\n * retreat budget is checked first — over budget the workflow fails and the\n * scene is preserved as-is; otherwise the target resets to pending\n * unconditionally (a retry-waiting target loses its evidence too) and every\n * non-pending transitive dependent resets to pending with evidence cleared\n * (their inputs are invalidated — DAG propagation). The failing/rejected\n * `origin` stage itself always resets as well (rule 5 is unconditional): when\n * the onFail target sits on a parallel branch the origin is outside the\n * dependent closure and joins the reset set explicitly. attempts are\n * retained (§4); `skipped` dependents never reset (explicit scope ruling).\n */\nfunction crossStageRetreat(\n\trun: WorkflowRun,\n\ttarget: StageSpec,\n\ttrigger: WorkflowTransitionTrigger,\n\tnote: string,\n\torigin?: StageSpec,\n): number {\n\tconst dependents = transitiveDependents(run.workflow, target.id);\n\tconst originOutside = origin !== undefined && origin.id !== target.id && !dependents.includes(origin.id);\n\t// Retreat audit transition (+ at most one more disposal transition when the\n\t// origin sits outside the dependent closure and needs its own audit slot).\n\tif (!canBump(run, originOutside ? 2 : 1)) return 0;\n\trun.workflow.retreatCount += 1;\n\tif (run.workflow.retreatCount > maxRetreatsOf(run.workflow)) {\n\t\tconst message = `workflow failed: retreat budget exhausted (${run.workflow.retreatCount}/${maxRetreatsOf(run.workflow)})`;\n\t\tpushDiagnostic(run.workflow, `${message} — ${note}`);\n\t\trun.workflow.status = \"failed\";\n\t\treturn appendTransition(run, undefined, \"running\", \"failed\", trigger, {\n\t\t\tcode: \"workflow.failed.retreat-budget\",\n\t\t\tmessage,\n\t\t\tdetail: note,\n\t\t})\n\t\t\t? 1\n\t\t\t: 0;\n\t}\n\tconst targetFrom = runtimeOf(run.workflow, target.id)?.status ?? \"pending\";\n\tconst resetIds: string[] = [];\n\tfor (const stageId of [target.id, ...(originOutside ? [origin.id] : []), ...dependents]) {\n\t\tconst runtime = runtimeOf(run.workflow, stageId);\n\t\tif (runtime === undefined) continue;\n\t\tif (\n\t\t\tstageId === target.id ||\n\t\t\tstageId === origin?.id ||\n\t\t\truntime.status === \"completed\" ||\n\t\t\truntime.status === \"active\" ||\n\t\t\truntime.status === \"awaiting_review\" ||\n\t\t\truntime.status === \"failed\"\n\t\t) {\n\t\t\truntime.status = \"pending\";\n\t\t\truntime.evidence = [];\n\t\t\tresetIds.push(stageId);\n\t\t}\n\t}\n\tconst detail = `target:${target.id} reset:[${resetIds.join(\", \")}]${note !== \"\" ? ` — ${note}` : \"\"}`;\n\treturn appendTransition(run, target.id, targetFrom, \"pending\", trigger, {\n\t\tcode: \"stage.retreated\",\n\t\tmessage: `retreat to stage ${target.id}: reset [${resetIds.join(\", \")}]`,\n\t\tdetail,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n// ---------------------------------------------------------------------------\n// Activation scan (§5 总则 2) and the reevaluation loop (§5 总则 1)\n// ---------------------------------------------------------------------------\n\n/**\n * One activation pass over pending stages in declaration order. A pending\n * stage activates only when (a) dependsOn are all completed/skipped (skip\n * counts as completed for unlocking — §5 rule 6), (b) its planId resolves in\n * the current branch entries, (c) the active count is below the cap, (d) a\n * write stage's scope does not intersect an active write stage, and (e)\n * attempts === 0 — retry-waiting stages never auto-activate (anti\n * burnout-spiral, §5 总则 2 e). Each freshly activated stage is immediately\n * re-evaluated once (§5 rule 2), which covers \"plan already completed at\n * activation\" and pure-checkpoint restore flows.\n */\nfunction activationPass(run: WorkflowRun, trigger: WorkflowTransitionTrigger): number {\n\tlet appended = 0;\n\tfor (const spec of run.workflow.stages) {\n\t\tconst runtime = runtimeOf(run.workflow, spec.id);\n\t\tif (runtime === undefined || runtime.status !== \"pending\" || runtime.attempts !== 0) continue; // (e)\n\t\tconst incomplete = spec.dependsOn.filter((dep) => {\n\t\t\tconst dependency = runtimeOf(run.workflow, dep);\n\t\t\treturn !(dependency !== undefined && (dependency.status === \"completed\" || dependency.status === \"skipped\"));\n\t\t});\n\t\tif (incomplete.length > 0) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.held.deps-incomplete\",\n\t\t\t\t\t`stage ${spec.id} waiting: dependencies incomplete [${incomplete.join(\", \")}]`,\n\t\t\t\t\t`missing:[${incomplete.join(\", \")}]`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (spec.planId !== undefined && run.deps.getPlan(spec.planId) === undefined) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.activated.held-plan-dangling\",\n\t\t\t\t\t`stage ${spec.id} held: plan ${spec.planId} not found in the session branch`,\n\t\t\t\t\t`plan:${spec.planId}`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (activeCount(run.workflow) >= maxActiveOf(run.workflow)) {\n\t\t\tif (\n\t\t\t\tholdStage(\n\t\t\t\t\trun,\n\t\t\t\t\tspec.id,\n\t\t\t\t\ttrigger,\n\t\t\t\t\t\"stage.held.active-limit\",\n\t\t\t\t\t`stage ${spec.id} waiting: active stage limit (${maxActiveOf(run.workflow)}) reached`,\n\t\t\t\t\t`limit:${maxActiveOf(run.workflow)}`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tappended += 1;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (spec.kind === \"write\") {\n\t\t\tconst conflict = findWriteConflict(run.workflow, spec);\n\t\t\tif (conflict !== undefined) {\n\t\t\t\tconst own = spec.scope === undefined || spec.scope.length === 0 ? \"global\" : spec.scope.join(\",\");\n\t\t\t\tconst other =\n\t\t\t\t\tconflict.scope === undefined || conflict.scope.length === 0 ? \"global\" : conflict.scope.join(\",\");\n\t\t\t\tif (\n\t\t\t\t\tholdStage(\n\t\t\t\t\t\trun,\n\t\t\t\t\t\tspec.id,\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\t\"stage.held.write-scope-conflict\",\n\t\t\t\t\t\t`stage ${spec.id} blocked: write scope [${own}] intersects active stage ${conflict.id} scope [${other}]`,\n\t\t\t\t\t\t`conflict:${conflict.id} scope:[${own}] vs [${other}]`,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tappended += 1;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!canBump(run, 3)) break; // activation + immediate evaluation chain (worst case 2 more)\n\t\truntime.status = \"active\";\n\t\tif (\n\t\t\tappendTransition(run, spec.id, \"pending\", \"active\", trigger, {\n\t\t\t\tcode: \"stage.activated\",\n\t\t\t\tmessage: `stage ${spec.id} activated`,\n\t\t\t})\n\t\t) {\n\t\t\tappended += 1;\n\t\t}\n\t\t// §5 rule 2: immediate single-stage snapshot reevaluation of the activated stage.\n\t\tappended += evaluateActiveStage(run, spec, runtime, \"activation-reeval\");\n\t}\n\treturn appended;\n}\n\n/** §5 rule 7 closure: all stages completed/skipped -> workflow completed, closure evidence recorded. */\nfunction checkClosure(run: WorkflowRun, trigger: WorkflowTransitionTrigger): number {\n\tif (run.workflow.status !== \"running\") return 0;\n\tif (!run.workflow.runtime.every((item) => item.status === \"completed\" || item.status === \"skipped\")) return 0;\n\tif (!canBump(run, 1)) return 0;\n\trun.workflow.status = \"completed\";\n\tconst evidence = run.workflow.runtime\n\t\t.filter((item) => item.status === \"completed\")\n\t\t.flatMap((item) =>\n\t\t\titem.evidence.map((entry) => ({ stageId: item.stageId, acceptanceId: entry.acceptanceId, ref: entry.ref })),\n\t\t);\n\trun.closures.push({\n\t\tworkflowId: run.workflow.id,\n\t\t...(run.workflow.goalId !== undefined ? { goalId: run.workflow.goalId } : {}),\n\t\tevidence,\n\t});\n\treturn appendTransition(run, undefined, \"running\", \"completed\", trigger, {\n\t\tcode: \"workflow.completed\",\n\t\tmessage: `workflow completed: all ${run.workflow.stages.length} stage(s) settled`,\n\t\tdetail: `evidence items: ${evidence.length}`,\n\t})\n\t\t? 1\n\t\t: 0;\n}\n\n/** §5 总则 4: the cascade marker is appended beyond the budget by design (it is the stop record, not a chain step). */\nfunction markCascadeLimit(run: WorkflowRun, trigger: WorkflowTransitionTrigger): void {\n\tconst message = `cascade limit ${run.limit} reached; transitions stopped — resumable via any workflow_advance action`;\n\tpushDiagnostic(run.workflow, message);\n\trun.workflow.revision += 1;\n\trun.transitions.push({\n\t\tworkflowId: run.workflow.id,\n\t\tfrom: run.workflow.status,\n\t\tto: run.workflow.status,\n\t\ttrigger,\n\t\treason: { code: \"cascade.limit-reached\", message },\n\t\trevision: run.workflow.revision,\n\t});\n}\n\n/**\n * The reevaluation loop for one running workflow: evaluate active stages ->\n * scan activation -> check closure, repeating to a fixed point (no new\n * persisted transitions). Condition-not-met passes are idempotent no-ops;\n * the held dedup keeps repeat passes audit-silent (§5 总则 1 / 总则 5).\n */\nfunction reevaluateWorkflow(run: WorkflowRun, trigger: WorkflowTransitionTrigger): void {\n\twhile (run.workflow.status === \"running\") {\n\t\tif (run.used >= run.limit) {\n\t\t\trun.hitLimit = true;\n\t\t\tbreak;\n\t\t}\n\t\tlet appended = 0;\n\t\tfor (const spec of run.workflow.stages) {\n\t\t\tconst runtime = runtimeOf(run.workflow, spec.id);\n\t\t\tif (runtime === undefined || runtime.status !== \"active\") continue;\n\t\t\tif (!canBump(run, 2)) break;\n\t\t\tappended += evaluateActiveStage(run, spec, runtime, trigger);\n\t\t}\n\t\tif (run.hitLimit) break;\n\t\tappended += activationPass(run, trigger);\n\t\tif (run.hitLimit) break;\n\t\tappended += checkClosure(run, trigger);\n\t\tif (run.hitLimit) break;\n\t\tif (appended === 0) return; // fixed point\n\t}\n\tif (run.hitLimit) markCascadeLimit(run, trigger);\n}\n\n/** Snapshot reevaluation over every workflow in the state (one budget per workflow per run). */\nexport function reevaluateAll(state: WorkflowState, deps: EngineDeps, trigger: WorkflowTransitionTrigger): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tfor (const workflow of workflows) {\n\t\tif (workflow.status !== \"running\") continue;\n\t\tconst workflowRun = newWorkflowRun(workflow, deps, run.closures);\n\t\treevaluateWorkflow(workflowRun, trigger);\n\t\trun.transitions.push(...workflowRun.transitions);\n\t\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\t}\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// workflow_set application (§6)\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a graded full-submit update: workflow-level fields (v8 §6: omitted\n * optional fields keep their stored values), the new stage\n * sequence (runtime aligned by stageId — existing runtimes are preserved,\n * appended stages get fresh pending runtimes), evidence linkage pruning for\n * removed acceptance ids, one stage.spec-amended transition per amended\n * active/awaiting_review stage, then the post-change reevaluation chain\n * (§5 总则 1: conversions settle -> same-call reevaluation).\n */\nexport function applyWorkflowSet(\n\tstate: WorkflowState,\n\tnext: ParsedWorkflowSet,\n\tdiff: WorkflowSetDiff,\n\tdeps: EngineDeps,\n): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tif (diff.created) {\n\t\tif (next.title === undefined) {\n\t\t\t// v8 §6: the create path still requires a title (updates keep the\n\t\t\t// stored value instead, see below).\n\t\t\tthrow new Error(\"title is required to create a workflow (updates keep the stored value when omitted)\");\n\t\t}\n\t\tworkflows.push({\n\t\t\tid: next.id,\n\t\t\ttitle: next.title,\n\t\t\t...(next.goalId !== undefined ? { goalId: next.goalId } : {}),\n\t\t\tstatus: \"draft\",\n\t\t\trevision: next.revision,\n\t\t\tstages: next.stages.map((stage) => structuredClone(stage)),\n\t\t\truntime: next.stages.map((stage) => ({ stageId: stage.id, status: \"pending\", attempts: 0, evidence: [] })),\n\t\t\tretreatCount: 0,\n\t\t\t...(next.maxRetreats !== undefined ? { maxRetreats: next.maxRetreats } : {}),\n\t\t\t...(next.maxActiveStages !== undefined ? { maxActiveStages: next.maxActiveStages } : {}),\n\t\t\tdiagnostics: [],\n\t\t});\n\t\treturn run;\n\t}\n\tconst record = workflows.find((workflow) => workflow.id === next.id);\n\tif (record === undefined) throw new Error(`unknown workflow: ${next.id}`);\n\t// Workflow-level fields are modifiable while running (§6), revision is the\n\t// caller's monotonic value; engine conversions below increment past it.\n\t// v8 keep-stored-value semantics (§6): an omitted optional field (title/\n\t// goalId/maxRetreats/maxActiveStages) keeps the stored value — the model\n\t// full-resends from memory and a dropped field would silently sever the\n\t// closure evidence chain (2026-10-01 dogfood). Explicit clearing is not\n\t// supported; rebinding goes through an explicit set.\n\tif (next.title !== undefined) record.title = next.title;\n\tif (next.goalId !== undefined) record.goalId = next.goalId;\n\tif (next.maxRetreats !== undefined) record.maxRetreats = next.maxRetreats;\n\tif (next.maxActiveStages !== undefined) record.maxActiveStages = next.maxActiveStages;\n\trecord.revision = next.revision;\n\trecord.stages = next.stages.map((stage) => structuredClone(stage));\n\tconst previousRuntime = new Map(record.runtime.map((item) => [item.stageId, item]));\n\trecord.runtime = record.stages.map(\n\t\t(spec) => previousRuntime.get(spec.id) ?? { stageId: spec.id, status: \"pending\", attempts: 0, evidence: [] },\n\t);\n\t// Evidence linkage (§6): an evidence item is dropped when its acceptanceId\n\t// is non-empty and no longer references the amended acceptance set — this\n\t// holds even when the amend emptied acceptance entirely, so no dead linkage\n\t// survives a switch to lower-bound mode. Ref-only items (empty\n\t// acceptanceId, checkpoint completion records) survive regardless of the\n\t// spec shape.\n\tfor (const spec of record.stages) {\n\t\tconst runtime = runtimeOf(record, spec.id);\n\t\tif (runtime === undefined || runtime.evidence.length === 0) continue;\n\t\tconst ids = new Set(spec.objective.acceptance.map((item) => item.id));\n\t\truntime.evidence = runtime.evidence.filter((entry) => entry.acceptanceId === \"\" || ids.has(entry.acceptanceId));\n\t}\n\tconst workflowRun = newWorkflowRun(record, deps, run.closures);\n\tfor (const change of diff.amendChanges) {\n\t\tconst runtime = runtimeOf(record, change.stageId);\n\t\tconst from = runtime?.status ?? \"pending\";\n\t\tconst detail =\n\t\t\t`fields:[${change.fields.join(\", \")}] note:${change.amendNote}` +\n\t\t\t(change.prunedEvidence.length > 0 ? ` pruned evidence for [${change.prunedEvidence.join(\", \")}]` : \"\");\n\t\tif (canBump(workflowRun, 1)) {\n\t\t\tappendTransition(workflowRun, change.stageId, from, from, \"tool\", {\n\t\t\t\tcode: \"stage.spec-amended\",\n\t\t\t\tmessage: `stage ${change.stageId} spec amended`,\n\t\t\t\tdetail,\n\t\t\t});\n\t\t}\n\t}\n\tif (record.status === \"running\") reevaluateWorkflow(workflowRun, \"tool\");\n\trun.transitions.push(...workflowRun.transitions);\n\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// workflow_advance application (§5 rule 6)\n// ---------------------------------------------------------------------------\n\nfunction requireStage(workflow: WorkflowRecord, stageId: string | undefined): StageSpec {\n\tif (stageId === undefined) throw new Error(\"stageId is required for this action\");\n\tconst spec = specOf(workflow, stageId);\n\tif (spec === undefined) throw new Error(`unknown stage: ${stageId} (workflow ${workflow.id})`);\n\treturn spec;\n}\n\nfunction normalizeEvidence(items: EvidenceItem[]): { acceptanceId: string; ref: string }[] {\n\treturn items.map((item) => ({ acceptanceId: item.acceptanceId ?? \"\", ref: item.ref }));\n}\n\n/**\n * Applies one explicit workflow_advance action, then runs the post-action\n * reevaluation chain (§5 总则 1). Illegal conversions throw structured\n * errors (§5 rule 6) — index.ts surfaces them as tool errors unchanged.\n */\nexport function applyAdvance(state: WorkflowState, input: AdvanceInput, deps: EngineDeps): EngineRun {\n\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\tconst run: EngineRun = { state: { workflows }, transitions: [], cascadeLimitReached: false, closures: [] };\n\tif (input.action === \"inspect\") {\n\t\t// Read-only and allowed on every workflow status (§5 rule 6), but still\n\t\t// scoped to one workflow: an unknown id is a structured error.\n\t\tif (!workflows.some((workflow) => workflow.id === input.workflowId)) {\n\t\t\tthrow new Error(`unknown workflow: ${input.workflowId}`);\n\t\t}\n\t\treturn run; // response decorations are added by the caller\n\t}\n\tconst record = workflows.find((workflow) => workflow.id === input.workflowId);\n\tif (record === undefined) throw new Error(`unknown workflow: ${input.workflowId}`);\n\tif (record.status === \"completed\" || record.status === \"failed\" || record.status === \"cancelled\") {\n\t\tthrow new Error(`workflow is ${record.status} and accepts no further actions: ${input.workflowId}`);\n\t}\n\tconst workflowRun = newWorkflowRun(record, deps, run.closures);\n\tconst requireRunning = (): void => {\n\t\tif (record.status !== \"running\") {\n\t\t\tthrow new Error(`workflow is ${record.status}; this action requires a running workflow`);\n\t\t}\n\t};\n\tconst noteSuffix = input.note !== undefined && input.note !== \"\" ? `: ${input.note}` : \"\";\n\n\tswitch (input.action) {\n\t\tcase \"start\": {\n\t\t\tif (record.status !== \"draft\") throw new Error(`workflow is already ${record.status}; start requires draft`);\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\tconst roots = record.stages.filter((spec) => spec.dependsOn.length === 0).length;\n\t\t\trecord.status = \"running\";\n\t\t\tappendTransition(workflowRun, undefined, \"draft\", \"running\", \"tool\", {\n\t\t\t\tcode: \"workflow.started\",\n\t\t\t\tmessage: `workflow started with ${roots} root stage(s)`,\n\t\t\t\tdetail: `roots:${roots}`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"record-evidence\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status === \"completed\" || runtime.status === \"skipped\" || runtime.status === \"failed\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} is ${runtime.status}; record-evidence accepts pending (retry wait), active, and awaiting_review stages`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (spec.objective.acceptance.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} declares no acceptance (lower-bound mode); record-evidence does not apply — the plan's completion evidence is the lower bound`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (items.length === 0) throw new Error(\"record-evidence requires at least one evidence item\");\n\t\t\tfor (const item of items) {\n\t\t\t\tif (item.acceptanceId === undefined || item.acceptanceId.trim() === \"\") {\n\t\t\t\t\tthrow new Error(`stage ${spec.id}: evidence items must carry acceptanceId in acceptance mode`);\n\t\t\t\t}\n\t\t\t\tif (!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`stage ${spec.id}: acceptanceId ${item.acceptanceId} does not reference the current spec's acceptance`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 2)) break; // evidence.recorded + possible single-stage wake settlement\n\t\t\tconst from = runtime.status;\n\t\t\truntime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\tif (input.executor !== undefined && input.executor.trim() !== \"\") {\n\t\t\t\truntime.executor = input.executor.trim();\n\t\t\t}\n\t\t\tappendTransition(workflowRun, spec.id, from, from, \"tool\", {\n\t\t\t\tcode: \"evidence.recorded\",\n\t\t\t\tmessage: `stage ${spec.id}: recorded ${items.length} evidence item(s)`,\n\t\t\t\tdetail: `${items.map((item) => `${item.acceptanceId} <- ${item.ref}`).join(\"; \")}${runtime.executor === undefined ? \"\" : ` | executor: ${runtime.executor}`}`,\n\t\t\t});\n\t\t\tif (runtime.status === \"pending\" && runtime.attempts > 0) {\n\t\t\t\t// §5 rule 4 exception — the only automatic wake channel for\n\t\t\t\t// retry-waiting stages: a single-stage evaluation by the current\n\t\t\t\t// spec and latest evidence. Pass -> settle (completion propagates\n\t\t\t\t// through the reevaluation below); still missing -> keep waiting,\n\t\t\t\t// no attempts consumed.\n\t\t\t\tconst plan = spec.planId !== undefined ? workflowRun.deps.getPlan(spec.planId) : undefined;\n\t\t\t\tconst passed =\n\t\t\t\t\tplan !== undefined &&\n\t\t\t\t\tplan.status === \"completed\" &&\n\t\t\t\t\tplan.evidence.length > 0 &&\n\t\t\t\t\tuncoveredAcceptanceIds(spec, runtime).length === 0;\n\t\t\t\tif (passed) settlePassedStage(workflowRun, spec, runtime, \"tool\");\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"approve\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"awaiting_review\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; approve only settles awaiting_review stages`);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (spec.objective.acceptance.length > 0) {\n\t\t\t\t// Same strong validation as record-evidence/complete: in acceptance\n\t\t\t\t// mode every carried evidence item must reference the current spec.\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tif (item.acceptanceId === undefined || item.acceptanceId.trim() === \"\") {\n\t\t\t\t\t\tthrow new Error(`stage ${spec.id}: evidence items must carry acceptanceId in acceptance mode`);\n\t\t\t\t\t}\n\t\t\t\t\tif (!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`stage ${spec.id}: acceptanceId ${item.acceptanceId} does not reference the current spec's acceptance`,\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\tif (!canBump(workflowRun, 1)) break;\n\t\t\tif (items.length > 0) runtime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\truntime.status = \"completed\";\n\t\t\tappendTransition(workflowRun, spec.id, \"awaiting_review\", \"completed\", \"tool\", {\n\t\t\t\tcode: spec.objective.acceptance.length > 0 ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\t\t\tmessage: `stage ${spec.id} approved in review`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"reject\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"awaiting_review\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; reject only applies to awaiting_review stages`);\n\t\t\t}\n\t\t\tif (spec.onFail !== undefined) {\n\t\t\t\t// §5 rule 6: reject walks the stage's onFail edge; the rejected\n\t\t\t\t// stage itself is the retreat origin and always resets (rule 5).\n\t\t\t\tconst target = requireStage(record, spec.onFail);\n\t\t\t\tcrossStageRetreat(workflowRun, target, \"tool\", `review rejection of stage ${spec.id}${noteSuffix}`, spec);\n\t\t\t} else {\n\t\t\t\t// No onFail edge: in-place retry semantics (rule 6 / rule 5).\n\t\t\t\truntime.attempts += 1;\n\t\t\t\tif (runtime.attempts > retryLimitOf(spec)) {\n\t\t\t\t\tconst message = `workflow failed: stage ${spec.id} exhausted retry limit ${retryLimitOf(spec)} (rejected in review)`;\n\t\t\t\t\tif (canBump(workflowRun, 1)) {\n\t\t\t\t\t\tpushDiagnostic(record, message);\n\t\t\t\t\t\trecord.status = \"failed\";\n\t\t\t\t\t\tappendTransition(workflowRun, undefined, \"running\", \"failed\", \"tool\", {\n\t\t\t\t\t\t\tcode: \"workflow.failed.stage-retries\",\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\tdetail: `stage:${spec.id}${noteSuffix}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (canBump(workflowRun, 1)) {\n\t\t\t\t\truntime.status = \"pending\";\n\t\t\t\t\tappendTransition(workflowRun, spec.id, \"awaiting_review\", \"pending\", \"tool\", {\n\t\t\t\t\t\tcode: \"stage.retry.queued\",\n\t\t\t\t\t\tmessage: `stage ${spec.id} rejected in review; queued for in-place retry (attempt ${runtime.attempts}/${retryLimitOf(spec)})`,\n\t\t\t\t\t\tdetail: input.note,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase \"retreat\": {\n\t\t\trequireRunning();\n\t\t\tconst target = requireStage(record, input.stageId);\n\t\t\tconst targetRuntime = runtimeOf(record, target.id);\n\t\t\tif (targetRuntime === undefined) throw new Error(`unknown stage: ${target.id}`);\n\t\t\tconst wasActivated =\n\t\t\t\ttargetRuntime.status === \"active\" ||\n\t\t\t\ttargetRuntime.status === \"awaiting_review\" ||\n\t\t\t\ttargetRuntime.status === \"completed\" ||\n\t\t\t\ttargetRuntime.attempts > 0;\n\t\t\tif (!wasActivated) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`retreat target ${target.id} has never been activated; retreat targets a previously activated earlier stage`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcrossStageRetreat(workflowRun, target, \"tool\", input.note ?? \"explicit retreat\");\n\t\t\tbreak;\n\t\t}\n\t\tcase \"complete\": {\n\t\t\trequireRunning();\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (spec.planId !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`stage ${spec.id} references plan ${spec.planId}; complete only applies to checkpoint stages without planId — plan-backed stages settle via plan completion and evaluation`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (runtime.status !== \"active\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; complete requires an active checkpoint stage`);\n\t\t\t}\n\t\t\tconst items = input.evidence ?? [];\n\t\t\tif (items.length === 0) throw new Error(`stage ${spec.id}: complete requires evidence`);\n\t\t\tconst covered = new Set<string>();\n\t\t\tfor (const item of items) {\n\t\t\t\tif (spec.objective.acceptance.length > 0) {\n\t\t\t\t\tif (\n\t\t\t\t\t\titem.acceptanceId === undefined ||\n\t\t\t\t\t\t!spec.objective.acceptance.some((entry) => entry.id === item.acceptanceId)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`stage ${spec.id}: evidence acceptanceId must reference the declared acceptance items`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcovered.add(item.acceptanceId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst missing = spec.objective.acceptance.filter((item) => !covered.has(item.id)).map((item) => item.id);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tthrow new Error(`stage ${spec.id}: evidence does not cover acceptance [${missing.join(\", \")}]`);\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\truntime.evidence = [...runtime.evidence, ...normalizeEvidence(items)];\n\t\t\truntime.status = \"completed\";\n\t\t\tappendTransition(workflowRun, spec.id, \"active\", \"completed\", \"tool\", {\n\t\t\t\tcode: spec.objective.acceptance.length > 0 ? \"stage.completed.acceptance-covered\" : \"stage.completed\",\n\t\t\t\tmessage: `stage ${spec.id} completed at checkpoint`,\n\t\t\t\tdetail: items.map((item) => item.ref).join(\"; \"),\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"skip\": {\n\t\t\tconst spec = requireStage(record, input.stageId);\n\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\tif (runtime === undefined) throw new Error(`unknown stage: ${spec.id}`);\n\t\t\tif (runtime.status !== \"pending\") {\n\t\t\t\tthrow new Error(`stage ${spec.id} is ${runtime.status}; only pending stages can be skipped`);\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\t// §5 rule 6: skipped counts as completed for dependency unlocking —\n\t\t\t// an explicit scope ruling, applied uniformly in closure checks.\n\t\t\truntime.status = \"skipped\";\n\t\t\tappendTransition(workflowRun, spec.id, \"pending\", \"skipped\", \"tool\", {\n\t\t\t\tcode: \"stage.skipped\",\n\t\t\t\tmessage: `stage ${spec.id} skipped (explicit scope ruling)`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"cancel\": {\n\t\t\tconst from = record.status;\n\t\t\t// §5 rule 6: every non-terminal stage becomes skipped; referenced\n\t\t\t// active plans are left untouched (soft reference — the plan domain\n\t\t\t// keeps its own sovereignty).\n\t\t\tfor (const spec of record.stages) {\n\t\t\t\tconst runtime = runtimeOf(record, spec.id);\n\t\t\t\tif (runtime === undefined || runtime.status === \"completed\" || runtime.status === \"skipped\") continue;\n\t\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\t\tconst stageFrom = runtime.status;\n\t\t\t\truntime.status = \"skipped\";\n\t\t\t\tappendTransition(workflowRun, spec.id, stageFrom, \"skipped\", \"tool\", {\n\t\t\t\t\tcode: \"stage.skipped\",\n\t\t\t\t\tmessage: `stage ${spec.id} skipped by workflow cancellation`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!canBump(workflowRun, 1)) break;\n\t\t\trecord.status = \"cancelled\";\n\t\t\tappendTransition(workflowRun, undefined, from, \"cancelled\", \"tool\", {\n\t\t\t\tcode: \"workflow.cancelled\",\n\t\t\t\tmessage: `workflow cancelled (non-terminal stages skipped)`,\n\t\t\t\tdetail: input.note,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (record.status === \"running\") reevaluateWorkflow(workflowRun, \"tool\");\n\trun.transitions.push(...workflowRun.transitions);\n\tif (workflowRun.hitLimit) run.cascadeLimitReached = true;\n\treturn run;\n}\n\n// ---------------------------------------------------------------------------\n// Inspection (§8.1 waiting conditions + acceptance coverage)\n// ---------------------------------------------------------------------------\n\n/**\n * The §8.1 waiting-condition label for one stage, or null when nothing is\n * blocking it. Label ownership: `acceptance-missing` is exclusively the\n * acceptance-mode retry wait (pending with attempts > 0); `retry-wait` is the\n * lower-bound retry wait (pending with attempts > 0 and no acceptance\n * declared — the plan completed but its evidence is empty); an active stage\n * whose plan is not completed yet is `plan-incomplete`. The check order\n * mirrors activationPass (§8.1: active-limit precedes write-scope conflict),\n * so the inspect label always names the same condition the audit recorded.\n */\nexport function computeWaitingOn(\n\tworkflow: WorkflowRecord,\n\tspec: StageSpec,\n\truntime: StageRuntime,\n\tdeps: EngineDeps,\n): string | null {\n\tif (runtime.status === \"awaiting_review\") return \"review\";\n\tif (runtime.status === \"pending\") {\n\t\tif (workflow.status === \"draft\") return \"not-yet-active\";\n\t\tif (runtime.attempts > 0) {\n\t\t\tif (spec.objective.acceptance.length === 0) return \"retry-wait\"; // lower-bound retry wait\n\t\t\treturn `acceptance-missing:[${uncoveredAcceptanceIds(spec, runtime).join(\", \")}]`;\n\t\t}\n\t\tconst incomplete = spec.dependsOn.filter((dep) => {\n\t\t\tconst dependency = runtimeOf(workflow, dep);\n\t\t\treturn !(dependency !== undefined && (dependency.status === \"completed\" || dependency.status === \"skipped\"));\n\t\t});\n\t\tif (incomplete.length > 0) return `deps-incomplete:[${incomplete.join(\", \")}]`;\n\t\tif (spec.planId !== undefined && deps.getPlan(spec.planId) === undefined) return \"plan-dangling\";\n\t\tif (activeCount(workflow) >= maxActiveOf(workflow)) return \"active-limit\";\n\t\tif (spec.kind === \"write\") {\n\t\t\tconst conflict = findWriteConflict(workflow, spec);\n\t\t\tif (conflict !== undefined) return `write-scope-conflict:[${conflict.id}]`;\n\t\t}\n\t\treturn \"not-yet-active\";\n\t}\n\tif (runtime.status === \"active\") {\n\t\tif (spec.planId === undefined) return null; // checkpoint waiting for the explicit complete action\n\t\tconst plan = deps.getPlan(spec.planId);\n\t\tif (plan === undefined) return \"plan-dangling\";\n\t\tif (plan.status !== \"completed\") return \"plan-incomplete\";\n\t\treturn null; // completed plan, evaluation pending the next reevaluation trigger\n\t}\n\treturn null;\n}\n\nexport interface AcceptanceCoverage {\n\tid: string;\n\tstatement: string;\n\tcovered: boolean;\n\trefs: string[];\n}\n\nexport interface StageInspection {\n\tstageId: string;\n\tstatus: StageRuntime[\"status\"];\n\tattempts: number;\n\twaitingOn: string | null;\n\tplanId?: string;\n\tplanStatus?: string;\n\tacceptance: AcceptanceCoverage[];\n}\n\nexport interface WorkflowInspection {\n\tworkflowId: string;\n\tstatus: WorkflowRecord[\"status\"];\n\tstages: StageInspection[];\n}\n\n/** §5 rule 6 inspect payload: full snapshot plus per-stage waiting conditions and acceptance coverage (§8.1). */\nexport function inspectWorkflow(workflow: WorkflowRecord, deps: EngineDeps): WorkflowInspection {\n\treturn {\n\t\tworkflowId: workflow.id,\n\t\tstatus: workflow.status,\n\t\tstages: workflow.stages.map((spec) => {\n\t\t\tconst runtime = runtimeOf(workflow, spec.id);\n\t\t\tconst safeRuntime: StageRuntime = runtime ?? {\n\t\t\t\tstageId: spec.id,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattempts: 0,\n\t\t\t\tevidence: [],\n\t\t\t};\n\t\t\tconst plan = spec.planId !== undefined ? deps.getPlan(spec.planId) : undefined;\n\t\t\treturn {\n\t\t\t\tstageId: spec.id,\n\t\t\t\tstatus: safeRuntime.status,\n\t\t\t\tattempts: safeRuntime.attempts,\n\t\t\t\twaitingOn: computeWaitingOn(workflow, spec, safeRuntime, deps),\n\t\t\t\t...(spec.planId !== undefined ? { planId: spec.planId, planStatus: plan?.status ?? \"missing\" } : {}),\n\t\t\t\tacceptance: spec.objective.acceptance.map((item) => {\n\t\t\t\t\tconst refs = safeRuntime.evidence\n\t\t\t\t\t\t.filter((entry) => entry.acceptanceId === item.id)\n\t\t\t\t\t\t.map((entry) => entry.ref);\n\t\t\t\t\treturn { id: item.id, statement: item.statement, covered: refs.length > 0, refs };\n\t\t\t\t}),\n\t\t\t};\n\t\t}),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AA2BrF,YAAY,EACX,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,UAAU,EACV,SAAS,EACT,YAAY,EACZ,SAAS,EACT,eAAe,EACf,eAAe,EACf,kBAAkB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC/E,YAAY,EACX,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,EACd,aAAa,EACb,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAmZ7E,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,aAAa,GAChB,OAAO,CAAC,SAAS,sBAAsB,EAAE,CAAC,GAAG,SAAS,sBAAsB,EAAE,CA0MhF","sourcesContent":["/**\n * Workflow orchestration capability plugin (M1 of\n * `docs/design/工作流编排插件设计.md`): a fourth self-contained state machine\n * orchestrating a stage dependency graph on top of the goal/plan/todo layers.\n *\n * Persistence protocol, structurally identical to the goal/plan/todo plugins:\n * append-only `workflow.state` full snapshots (the single rebuild source) plus\n * one `workflow.transition` audit entry per conversion, announced as\n * `workflow.changed` (version 1, correlationId \"workflow.state\", data = the\n * complete WorkflowState snapshot).\n *\n * This plugin is the repository's FIRST event subscriber (§7): `plan.changed`\n * is used as a trigger signal only — its in-memory data may be misaligned\n * with the current branch, so every reevaluation reads the plan facts from\n * the current branch entries. The handler is fully isolated (§5 总则 3): any\n * failure lands in diagnostics + a `handler.error` transition and never\n * rethrows at the publisher (an unisolated throw would pierce plan_set's tool\n * return). Soft references (goalId / planId / role) never fail a write (#10):\n * they surface as response warnings; a dangling planId additionally holds the\n * stage's activation until a reevaluation finds the plan.\n */\n\nimport type { CapabilityAPI, DisposableRegistration } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport {\n\ttype AdvanceAction,\n\ttype AdvanceInput,\n\tapplyAdvance,\n\tapplyWorkflowSet,\n\ttype EngineDeps,\n\ttype EngineRun,\n\ttype EvidenceItem,\n\tinspectWorkflow,\n\ttype PlanFacts,\n\treevaluateAll,\n\ttype WorkflowClosure,\n\ttype WorkflowInspection,\n} from \"./engine.ts\";\nimport { createWorkflowToolResultRenderer, renderLog, renderPanorama, renderWhy } from \"./render.ts\";\nimport {\n\ttype TransitionReasonCode,\n\tWORKFLOW_STATE_ENTRY,\n\tWORKFLOW_TRANSITION_ENTRY,\n\ttype WorkflowState,\n\ttype WorkflowTransitionEntry,\n\ttype WorkflowTransitionTrigger,\n} from \"./types.ts\";\nimport { asObject, asText, parseWorkflowSetInput, planWorkflowSpecUpdate, validateStageGraph } from \"./validate.ts\";\n\nexport type {\n\tAcceptanceCoverage,\n\tAdvanceAction,\n\tAdvanceInput,\n\tClosureEvidenceItem,\n\tEngineDeps,\n\tEngineRun,\n\tEvidenceItem,\n\tPlanFacts,\n\tStageInspection,\n\tWorkflowClosure,\n\tWorkflowInspection,\n} from \"./engine.ts\";\nexport { cascadeLimitFor, computeWaitingOn, reevaluateAll } from \"./engine.ts\";\nexport type {\n\tStageRuntime,\n\tStageSpec,\n\tTransitionReason,\n\tTransitionReasonCode,\n\tWorkflowRecord,\n\tWorkflowState,\n\tWorkflowTransitionEntry,\n\tWorkflowTransitionTrigger,\n} from \"./types.ts\";\nexport { WORKFLOW_STATE_ENTRY, WORKFLOW_TRANSITION_ENTRY } from \"./types.ts\";\n\n/** Session protocol key of the plan plugin's snapshot entry (plugins/plan). */\nconst planStateEntry = \"plan.state\";\n/** Session protocol key of the goal plugin's snapshot entry (plugins/goal). */\nconst goalStateEntry = \"goal.state\";\n/**\n * Session protocol key of the subagent-delegate plugin's session role snapshot\n * (plugins/subagent-delegate, D-081 item 7: `{ version: 1, roles: [{ id, ... }] }`\n * append-only full snapshots). Same literal-coupling precedent as plan/goal\n * above: the workflow plugin never imports the owning plugin.\n */\nconst subagentRoleStateEntry = \"subagent.roles.state\";\n/**\n * Role id shape: the same expression as the authoritative reader's\n * ROLE_ID_PATTERN (plugins/subagent-delegate `readSessionRoles`). Same\n * cross-plugin literal-coupling precedent as the entry keys above — the\n * workflow plugin never imports the owning plugin. The residual difference is\n * field-level only: subagent-delegate validates the whole role record and drops\n * invalid entries, while this side reads the id alone — so the divergence can\n * only under-warn, never false-warn.\n */\nconst roleIdPattern = /^[a-z0-9][a-z0-9_-]{0,31}$/;\nconst DIAGNOSTICS_CAP = 50;\n\n/** §3.1 applicability, verbatim scope (when to use / not to use a workflow). */\nconst WORKFLOW_APPLICABILITY_GUIDE =\n\t\"Workflow applicability — use a workflow only when ALL of these hold: (1) the goal needs at least 3 stages that can be accepted independently (you can write each stage's objective/acceptance); (2) the stages have a real dependency structure (branching or joins), not a plain sequence; (3) independent branches can be pushed in parallel — parallelism is a core payoff, purely linear multi-stage work belongs to goal/plan/todo; (4) the task spans multiple turns/days and is valuable enough to justify process overhead (definition, evidence recording, stage gates). Counterexamples that keep goal/plan/todo or direct execution: single-step tasks; two- or three-step linear tasks; exploratory work with no presettable dependency graph; one-shot questions. A workflow does not exclude the three layers — each stage still uses plan/todo for its execution checklist. Never escalate a small task to a workflow by default. When the user explicitly asks for workflow orchestration, still run this weighing: if the task genuinely misses the bar, skipping is fine — but say so in one line why you stayed on goal/plan/todo (an unexplained skip reads as ignoring the request); conversely, do not build one just because it was asked when the task is small (over-orchestration costs more than it saves). (2026-10-04 user ruling after a dogfood where an explicitly requested orchestration was silently skipped.)\";\n\nconst WORKFLOW_AUTHORING_GUIDE =\n\t\"Define each stage by a verifiable end state, not by a work list or a role: objective.statement says what must be achieved; acceptance items list the evidence that proves it, referenced from real tool output. Stop splitting at the first verifiable boundary — finer handoffs lose more to interface drift than they gain in drift protection.\";\n\nconst WORKFLOW_EXECUTION_GUIDE =\n\t\"After plan_set marks a stage's plan completed, run workflow_advance inspect to see unlocked stages and acceptance coverage. Record evidence (workflow_advance record-evidence) before completion is evaluated; lower-bound stages (no acceptance declared) need no record-evidence. When multiple stages are active, delegate one subagent per stage following stage.role and push them in parallel.\";\n\nconst WORKFLOW_CORRECTION_GUIDE =\n\t\"On user corrections: run workflow_advance inspect first to confirm the current state, then route by what changed — amend the stage spec (active/awaiting_review stages, amendNote required), append a stage, skip, retreat, or cancel — and report the adjustment and its impact range back to the user.\";\n\nconst WORKFLOW_REVIEW_GUIDE =\n\t\"Stages declared advance: 'review' stop at awaiting_review. Before approve you must present the result and its evidence to the user and get explicit confirmation — never approve on your own (the engine does not authorize; the discipline lives here).\";\n\nconst WORKFLOW_CONCURRENCY_GUIDE =\n\t\"Do not send workflow_set in the same parallel batch as plan_set: amends and completion evaluation race (completed freezes first; if the amend loses, recover via retreat).\";\n\nconst WORKFLOW_INCREMENTAL_DEMAND_GUIDE =\n\t\"When a new batch of requirements arrives (incremental features on top of shipped work), default to creating a NEW workflow to carry it — reuse the same goalId and keep the completed workflow's history intact; never pull a completed workflow back into motion. Retreat or append a corrective stage only when the new requirements overturn already completed output.\";\n\nconst WORKFLOW_EXECUTOR_GUIDE =\n\t\"When delegating a stage to a subagent, pass that subagent's session/task id as the executor field of record-evidence — it is recorded on the stage (advisory) so /workflow log shows who drove it.\";\n\nconst acceptanceSchema = Type.Object({\n\tid: Type.String({ description: \"Acceptance item id; evidence references this id\" }),\n\tstatement: Type.String({ description: \"Verifiable completion criterion for this item\" }),\n});\n\nconst stageSchema = Type.Object({\n\tid: Type.String({ description: \"Stable stage id, unique within the workflow\" }),\n\ttitle: Type.String({ description: \"Human-readable stage title\" }),\n\tobjective: Type.Object({\n\t\tstatement: Type.String({\n\t\t\tdescription: \"Verifiable end state this stage must reach (required, non-empty)\",\n\t\t}),\n\t\tacceptance: Type.Optional(\n\t\t\tType.Array(acceptanceSchema, {\n\t\t\t\tdescription:\n\t\t\t\t\t\"Completion criteria items; when empty (or omitted) the lower bound is the referenced plan's completion evidence\",\n\t\t\t}),\n\t\t),\n\t}),\n\tdependsOn: Type.Optional(\n\t\tType.Array(Type.String(), { description: \"Hard prerequisite stage ids; empty array = root stage\" }),\n\t),\n\tplanId: Type.Optional(Type.String({ description: \"Soft reference to a plan id; missing = pure checkpoint stage\" })),\n\tkind: Type.Optional(\n\t\tType.Union([Type.Literal(\"read\"), Type.Literal(\"write\")], {\n\t\t\tdescription: 'Stage kind; write stages are scope-checked, default \"write\"',\n\t\t}),\n\t),\n\tscope: Type.Optional(\n\t\tType.Array(Type.String(), {\n\t\t\tdescription: \"Write scope tags (modules/dirs); missing = global (intersects every other write stage)\",\n\t\t}),\n\t),\n\trole: Type.Optional(\n\t\tType.String({ description: \"Delegation advice: role id for the subagent recommended to drive this stage\" }),\n\t),\n\tadvance: Type.Optional(\n\t\tType.Union([Type.Literal(\"auto\"), Type.Literal(\"review\")], {\n\t\t\tdescription:\n\t\t\t\t'\"auto\" completes on evaluation, \"review\" stops at awaiting_review (planId stages only), default \"auto\"',\n\t\t}),\n\t),\n\tretryLimit: Type.Optional(\n\t\tType.Integer({ description: \"In-place retry limit before onFail/workflow failure, default 2\", minimum: 0 }),\n\t),\n\tonFail: Type.Optional(\n\t\tType.String({ description: \"Explicit cross-stage retreat target (a topologically earlier stage id)\" }),\n\t),\n\tamendNote: Type.Optional(\n\t\tType.String({\n\t\t\tdescription: \"Correction reason; required when an active/awaiting_review stage's spec changes\",\n\t\t}),\n\t),\n});\n\nconst workflowSetSchema = Type.Object({\n\tid: Type.String({ description: \"Stable id of the workflow to create or update\" }),\n\ttitle: Type.Optional(\n\t\tType.String({\n\t\t\tdescription: \"Human-readable workflow title; required on create, omitting on update keeps the stored value\",\n\t\t}),\n\t),\n\trevision: Type.Integer({\n\t\tdescription: \"New revision counter; must be greater than the stored revision of an existing workflow\",\n\t\tminimum: 0,\n\t}),\n\tgoalId: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Soft reference to a goal id; the closure evidence summary is addressed to this goal. Omitting on update keeps the stored value\",\n\t\t}),\n\t),\n\tmaxRetreats: Type.Optional(\n\t\tType.Integer({\n\t\t\tdescription:\n\t\t\t\t\"Workflow lifetime retreat budget before failure, default 3. Omitting on update keeps the stored value\",\n\t\t\tminimum: 0,\n\t\t}),\n\t),\n\tmaxActiveStages: Type.Optional(\n\t\tType.Integer({\n\t\t\tdescription: \"Parallel activation cap, default 4. Omitting on update keeps the stored value\",\n\t\t\tminimum: 1,\n\t\t}),\n\t),\n\tstages: Type.Array(stageSchema, {\n\t\tdescription: \"Full stage list (whole submit, not a patch); the engine aligns runtime by stage id\",\n\t}),\n});\n\nconst workflowAdvanceSchema = Type.Object({\n\tworkflowId: Type.String({ description: \"Target workflow id\" }),\n\taction: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"start\"),\n\t\t\tType.Literal(\"record-evidence\"),\n\t\t\tType.Literal(\"inspect\"),\n\t\t\tType.Literal(\"approve\"),\n\t\t\tType.Literal(\"reject\"),\n\t\t\tType.Literal(\"retreat\"),\n\t\t\tType.Literal(\"complete\"),\n\t\t\tType.Literal(\"skip\"),\n\t\t\tType.Literal(\"cancel\"),\n\t\t],\n\t\t{ description: \"Explicit action to perform\" },\n\t),\n\tstageId: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Stage id: the evidence/approve/reject/complete/skip target, or the retreat target stage to roll back to\",\n\t\t}),\n\t),\n\texecutor: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Advisory executor id (e.g. subagent session/task id) driving the stage; record-only, last-write-wins, never affects evaluation\",\n\t\t}),\n\t),\n\tevidence: Type.Optional(\n\t\tType.Array(\n\t\t\tType.Object({\n\t\t\t\tacceptanceId: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Acceptance item id; required in acceptance mode\" }),\n\t\t\t\t),\n\t\t\t\tref: Type.String({ description: \"Evidence reference (tool output, file, artifact)\" }),\n\t\t\t}),\n\t\t\t{ description: \"Evidence items for record-evidence/approve/complete\" },\n\t\t),\n\t),\n\tnote: Type.Optional(\n\t\tType.String({ description: \"Optional note recorded in the transition detail (reject/retreat/skip/cancel)\" }),\n\t),\n});\n\nconst ADVANCE_ACTIONS: readonly string[] = [\n\t\"start\",\n\t\"record-evidence\",\n\t\"inspect\",\n\t\"approve\",\n\t\"reject\",\n\t\"retreat\",\n\t\"complete\",\n\t\"skip\",\n\t\"cancel\",\n];\n\nfunction objectInput(first: unknown, second: unknown): Record<string, unknown> {\n\tconst value = second === undefined ? first : second;\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new Error(\"Workflow input must be an object\");\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction parseAdvanceInput(value: Record<string, unknown>): AdvanceInput {\n\tconst workflowId = asText(value.workflowId, \"workflowId\");\n\tconst action = value.action;\n\tif (typeof action !== \"string\" || !ADVANCE_ACTIONS.includes(action)) {\n\t\tthrow new Error(`action must be one of ${ADVANCE_ACTIONS.join(\", \")}`);\n\t}\n\tconst stageId = value.stageId === undefined ? undefined : asText(value.stageId, \"stageId\");\n\tconst note = value.note === undefined ? undefined : asText(value.note, \"note\");\n\tconst executor = value.executor === undefined ? undefined : asText(value.executor, \"executor\");\n\tlet evidence: EvidenceItem[] | undefined;\n\tif (value.evidence !== undefined) {\n\t\tif (!Array.isArray(value.evidence)) throw new Error(\"evidence must be an array of {acceptanceId?, ref}\");\n\t\tevidence = value.evidence.map((item) => {\n\t\t\tconst entry = asObject(item, \"evidence item\");\n\t\t\tconst ref = asText(entry.ref, \"evidence item ref\");\n\t\t\tconst acceptanceId =\n\t\t\t\tentry.acceptanceId === undefined ? undefined : asText(entry.acceptanceId, \"evidence item acceptanceId\");\n\t\t\treturn acceptanceId === undefined ? { ref } : { acceptanceId, ref };\n\t\t});\n\t}\n\treturn {\n\t\tworkflowId,\n\t\taction: action as AdvanceAction,\n\t\t...(stageId !== undefined ? { stageId } : {}),\n\t\t...(evidence !== undefined ? { evidence } : {}),\n\t\t...(note !== undefined ? { note } : {}),\n\t\t...(executor !== undefined ? { executor } : {}),\n\t};\n}\n\nfunction loadState(api: CapabilityAPI): WorkflowState {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tconst entry = [...entries].reverse().find((item) => item.customType === WORKFLOW_STATE_ENTRY);\n\tif (!entry?.data || typeof entry.data !== \"object\") return { workflows: [] };\n\tconst data = entry.data as Partial<WorkflowState>;\n\treturn { workflows: Array.isArray(data.workflows) ? [...data.workflows] : [] };\n}\n\n/**\n * Plan facts read from the current branch's LATEST `plan.state` snapshot (the\n * same latest-snapshot semantics as the plan plugin's own loadState). The\n * plan.changed payload is never trusted for state — only as a trigger.\n *\n * Uncached by design: identity-keyed caching collided across test hosts and\n * hooking invalidation into appendEntry crosses the persistence boundary; the\n * O(stages x entries) rescan is the price of snapshot-driven truth. Revisit\n * only with a per-run cache channel if long-session profiling demands it.\n */\nfunction loadPlansSnapshot(api: CapabilityAPI): Map<string, PlanFacts> {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index] as { customType?: string; data?: unknown } | undefined;\n\t\tif (entry?.customType !== planStateEntry) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return new Map();\n\t\tconst plans = (data as { plans?: unknown }).plans;\n\t\tif (!Array.isArray(plans)) return new Map();\n\t\tconst facts = new Map<string, PlanFacts>();\n\t\tfor (const plan of plans) {\n\t\t\tif (!plan || typeof plan !== \"object\") continue;\n\t\t\tconst record = plan as { id?: unknown; status?: unknown; evidence?: unknown };\n\t\t\tif (typeof record.id !== \"string\") continue;\n\t\t\tconst status =\n\t\t\t\trecord.status === \"draft\" ||\n\t\t\t\trecord.status === \"active\" ||\n\t\t\t\trecord.status === \"completed\" ||\n\t\t\t\trecord.status === \"cancelled\"\n\t\t\t\t\t? record.status\n\t\t\t\t\t: \"draft\";\n\t\t\tconst evidence = Array.isArray(record.evidence)\n\t\t\t\t? record.evidence.filter((item): item is string => typeof item === \"string\")\n\t\t\t\t: [];\n\t\t\tfacts.set(record.id, { id: record.id, status, evidence });\n\t\t}\n\t\treturn facts;\n\t}\n\treturn new Map();\n}\n\n/** Whether the latest `<entryType>` snapshot on the branch knows `id` in its `idsField` array (advisory, #10). */\nfunction idKnownToSession(api: CapabilityAPI, entryType: string, idsField: string, id: string): boolean {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.customType !== entryType) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return false;\n\t\tconst records = (data as Record<string, unknown>)[idsField];\n\t\tif (!Array.isArray(records)) return false;\n\t\treturn records.some(\n\t\t\t(record) => record !== null && typeof record === \"object\" && (record as { id?: unknown }).id === id,\n\t\t);\n\t}\n\treturn false;\n}\n\n/**\n * Seeds the held-dedup view (§5 总则 5) from the branch audit stream: the\n * last transition per stage, whatever its code — a repeat held emission is\n * dropped only when it matches that last code and detail.\n */\nfunction buildLastStageTransition(api: CapabilityAPI): Map<string, { code: TransitionReasonCode; detail?: string }> {\n\tconst map = new Map<string, { code: TransitionReasonCode; detail?: string }>();\n\tfor (const entry of api.session?.getBranchEntries() ?? []) {\n\t\tif (entry.customType !== WORKFLOW_TRANSITION_ENTRY) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\tconst record = data as Partial<WorkflowTransitionEntry>;\n\t\tif (typeof record.workflowId !== \"string\" || typeof record.stageId !== \"string\") continue;\n\t\tconst reason = record.reason as { code?: unknown; detail?: unknown } | undefined;\n\t\tif (!reason || typeof reason !== \"object\" || typeof reason.code !== \"string\") continue;\n\t\tmap.set(`${record.workflowId}::${record.stageId}`, {\n\t\t\tcode: reason.code as TransitionReasonCode,\n\t\t\tdetail: typeof reason.detail === \"string\" ? reason.detail : undefined,\n\t\t});\n\t}\n\treturn map;\n}\n\n/**\n * Role ids from the current branch's latest READABLE `subagent.roles.state`\n * snapshot (D-081 item 7). Fallback is symmetric with the authoritative reader\n * (subagent-delegate `readSessionRoles`): a snapshot-level corruption (data not\n * an object / version mismatch / roles not an array) steps back to the previous\n * readable snapshot, and only a fully unreadable table degrades to the empty\n * set. Individual malformed role records are skipped — including ids that do\n * not match `roleIdPattern` — keeping the remaining ids of an otherwise\n * readable snapshot. Silent by contract: the\n * subagent-delegate plugin owns the degradation warning on its side, and a\n * second report here would double-warn for the same fact — this side only\n * tolerates.\n */\nfunction loadSessionRoleIds(api: CapabilityAPI): Set<string> {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.customType !== subagentRoleStateEntry) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\tconst snapshot = data as { version?: unknown; roles?: unknown };\n\t\tif (snapshot.version !== 1 || !Array.isArray(snapshot.roles)) continue;\n\t\tconst known = new Set<string>();\n\t\tfor (const role of snapshot.roles) {\n\t\t\tif (!role || typeof role !== \"object\" || Array.isArray(role)) continue;\n\t\t\tconst id = (role as { id?: unknown }).id;\n\t\t\tif (typeof id === \"string\" && roleIdPattern.test(id)) known.add(id);\n\t\t}\n\t\treturn known;\n\t}\n\treturn new Set();\n}\n\n/** Soft-reference warnings for the tool response only (never the persisted state, #10). */\nfunction collectSoftReferenceWarnings(\n\tapi: CapabilityAPI,\n\tgoalId: string | undefined,\n\tplanIds: { stageId: string; planId: string }[],\n\troles: { stageId: string; role: string }[],\n): string[] {\n\tconst warnings: string[] = [];\n\tif (goalId !== undefined && !idKnownToSession(api, goalStateEntry, \"goals\", goalId)) {\n\t\twarnings.push(\n\t\t\t`goalId \"${goalId}\" does not match any goal in this session's goal state; the workflow keeps the soft reference`,\n\t\t);\n\t}\n\tfor (const item of planIds) {\n\t\tif (!idKnownToSession(api, planStateEntry, \"plans\", item.planId)) {\n\t\t\twarnings.push(\n\t\t\t\t`stage ${item.stageId}: planId \"${item.planId}\" does not match any plan in this session's plan state; ` +\n\t\t\t\t\t\"the stage stays held until a reevaluation finds the plan\",\n\t\t\t);\n\t\t}\n\t}\n\t// Two verifiable role sources (D-081 item 7): the host's suite role\n\t// associations (disk roles) plus this branch's session role table. A host\n\t// without the listing AND an empty session table verifies nothing, so the\n\t// advice stays unverified — no warning (缺面不告警). An explicitly empty\n\t// association face ([]) still warns for every role.\n\tconst associated = api.host?.roleAssociations;\n\tconst sessionRoleIds = roles.length > 0 ? loadSessionRoleIds(api) : new Set<string>();\n\tconst merged = new Set([...(associated ?? []), ...sessionRoleIds]);\n\tfor (const item of roles) {\n\t\tif ((associated !== undefined || sessionRoleIds.size > 0) && !merged.has(item.role)) {\n\t\t\twarnings.push(\n\t\t\t\t`stage ${item.stageId}: role \"${item.role}\" is neither associated with the active suite nor ` +\n\t\t\t\t\t\"registered in this session; delegation advice treated as unspecified — register it with \" +\n\t\t\t\t\t\"subagent_role_set or add it to the suite's roles associations\",\n\t\t\t);\n\t\t}\n\t}\n\treturn warnings;\n}\n\ninterface WorkflowToolResponse extends WorkflowState {\n\tclosures?: WorkflowClosure[];\n\tinspections?: WorkflowInspection[];\n\twarning?: string;\n}\n\nexport function createCapability(\n\tapi: CapabilityAPI,\n): Promise<readonly DisposableRegistration[]> | readonly DisposableRegistration[] {\n\tlet state = loadState(api);\n\tconst deps: EngineDeps = {\n\t\tgetPlan: (planId) => loadPlansSnapshot(api).get(planId),\n\t\tlastStageTransition: buildLastStageTransition(api),\n\t};\n\t// Shared structural renderResult (render.ts): the host TUI gets the\n\t// panorama face for both tools' JSON-serialized responses.\n\tconst toolResultRenderer = createWorkflowToolResultRenderer(deps);\n\n\t// Persistence boundary (§4): audit entries first, then the full snapshot —\n\t// a crash mid-batch replays from the older snapshot while the audit stays\n\t// intact. appendEntry failures propagate unchanged (§5 总则 5: no swallow);\n\t// publish rejections surface to the tool caller (or are contained on the\n\t// load/subscriber paths below).\n\tconst persistRun = (run: EngineRun): void => {\n\t\tfor (const transition of run.transitions) {\n\t\t\tapi.session?.appendEntry(WORKFLOW_TRANSITION_ENTRY, transition);\n\t\t}\n\t\tapi.session?.appendEntry(WORKFLOW_STATE_ENTRY, run.state);\n\t};\n\tconst announce = (run: EngineRun): Promise<unknown> =>\n\t\tapi.publish({ type: \"workflow.changed\", version: 1, correlationId: WORKFLOW_STATE_ENTRY, data: run.state });\n\n\t/**\n\t * §5 总则 3 containment: land the failure in diagnostics + a handler.error\n\t * transition (detail = original error text) and never rethrow. Best-effort\n\t * — an already-failing boundary must not turn isolation into a second crash.\n\t */\n\tconst quarantineEngineError = (error: unknown, trigger: WorkflowTransitionTrigger): void => {\n\t\ttry {\n\t\t\tif (state.workflows.length === 0) return;\n\t\t\tconst original = error instanceof Error ? error.message : String(error);\n\t\t\tconst text = `${trigger} handler failed: ${original}`;\n\t\t\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\t\t\tconst transitions: WorkflowTransitionEntry[] = [];\n\t\t\tfor (const workflow of workflows) {\n\t\t\t\tif (workflow.diagnostics.length >= DIAGNOSTICS_CAP) workflow.diagnostics.shift();\n\t\t\t\tworkflow.diagnostics.push(text);\n\t\t\t\tworkflow.revision += 1;\n\t\t\t\ttransitions.push({\n\t\t\t\t\tworkflowId: workflow.id,\n\t\t\t\t\tfrom: workflow.status,\n\t\t\t\t\tto: workflow.status,\n\t\t\t\t\ttrigger,\n\t\t\t\t\treason: { code: \"handler.error\", message: text, detail: original },\n\t\t\t\t\trevision: workflow.revision,\n\t\t\t\t});\n\t\t\t}\n\t\t\tstate = { workflows };\n\t\t\tfor (const transition of transitions) {\n\t\t\t\tapi.session?.appendEntry(WORKFLOW_TRANSITION_ENTRY, transition);\n\t\t\t}\n\t\t\tapi.session?.appendEntry(WORKFLOW_STATE_ENTRY, state);\n\t\t\tvoid api\n\t\t\t\t.publish({ type: \"workflow.changed\", version: 1, correlationId: WORKFLOW_STATE_ENTRY, data: state })\n\t\t\t\t.catch(() => undefined);\n\t\t} catch {\n\t\t\t// Containment is best-effort by design.\n\t\t}\n\t};\n\n\t// §5 rule 8 recovery: state replayed from workflow.state, then the\n\t// load-time reevaluation (总则 1 fallback moment #1). Runs synchronously at\n\t// factory time; failures are contained, never blocking plugin load.\n\ttry {\n\t\tconst run = reevaluateAll(state, deps, \"load-reeval\");\n\t\tif (run.transitions.length > 0) {\n\t\t\tstate = run.state;\n\t\t\tpersistRun(run);\n\t\t\tvoid announce(run).catch(() => undefined);\n\t\t}\n\t} catch (error) {\n\t\tquarantineEngineError(error, \"load-reeval\");\n\t}\n\n\tconst setTool = api.registerTool({\n\t\tname: \"workflow_set\",\n\t\tlabel: \"Set workflow\",\n\t\tpromptGuidelines: [\n\t\t\tWORKFLOW_APPLICABILITY_GUIDE,\n\t\t\tWORKFLOW_AUTHORING_GUIDE,\n\t\t\tWORKFLOW_EXECUTION_GUIDE,\n\t\t\tWORKFLOW_CORRECTION_GUIDE,\n\t\t\tWORKFLOW_REVIEW_GUIDE,\n\t\t\tWORKFLOW_CONCURRENCY_GUIDE,\n\t\t\tWORKFLOW_INCREMENTAL_DEMAND_GUIDE,\n\t\t\tWORKFLOW_EXECUTOR_GUIDE,\n\t\t],\n\t\tdescription:\n\t\t\t\"Create or update a workflow: a stage dependency graph (DAG) with per-stage objectives, acceptance evidence, and soft goal/plan references. On update, an omitted workflow-level optional field (title/goalId/maxRetreats/maxActiveStages) keeps its stored value; stages are always submitted in full\",\n\t\tparameters: workflowSetSchema,\n\t\trenderResult: toolResultRenderer,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst parsed = parseWorkflowSetInput(objectInput(first, second));\n\t\t\tvalidateStageGraph(parsed.stages);\n\t\t\tconst current = state.workflows.find((workflow) => workflow.id === parsed.id);\n\t\t\tif (current !== undefined && parsed.revision <= current.revision) {\n\t\t\t\tthrow new Error(`stale workflow revision: ${parsed.id}`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcurrent !== undefined &&\n\t\t\t\t(current.status === \"completed\" || current.status === \"failed\" || current.status === \"cancelled\")\n\t\t\t) {\n\t\t\t\tthrow new Error(`workflow is terminal and cannot be updated: ${parsed.id}`);\n\t\t\t}\n\t\t\tconst diff = planWorkflowSpecUpdate(current, parsed);\n\t\t\tconst run = applyWorkflowSet(state, parsed, diff, deps);\n\t\t\tstate = run.state;\n\t\t\tif (run.transitions.length > 0 || diff.created) persistRun(run);\n\t\t\tif (run.transitions.length > 0 || diff.created) await announce(run);\n\t\t\tconst response: WorkflowToolResponse = { ...state };\n\t\t\tif (run.closures.length > 0) response.closures = run.closures;\n\t\t\tconst warnings = collectSoftReferenceWarnings(\n\t\t\t\tapi,\n\t\t\t\tparsed.goalId,\n\t\t\t\tparsed.stages.flatMap((stage) =>\n\t\t\t\t\tstage.planId !== undefined ? [{ stageId: stage.id, planId: stage.planId }] : [],\n\t\t\t\t),\n\t\t\t\tparsed.stages.flatMap((stage) =>\n\t\t\t\t\tstage.role !== undefined ? [{ stageId: stage.id, role: stage.role }] : [],\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (warnings.length > 0) response.warning = warnings.join(\"; \");\n\t\t\treturn response;\n\t\t},\n\t});\n\n\tconst advanceTool = api.registerTool({\n\t\tname: \"workflow_advance\",\n\t\tlabel: \"Advance workflow\",\n\t\tdescription:\n\t\t\t\"Drive a workflow: start it, record acceptance evidence, inspect waiting conditions and coverage, approve/reject reviews, retreat, complete checkpoints, skip stages, or cancel\",\n\t\tparameters: workflowAdvanceSchema,\n\t\trenderResult: toolResultRenderer,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst parsed = parseAdvanceInput(objectInput(first, second));\n\t\t\t// Illegal conversions throw structured errors (§5 rule 6) surfaced\n\t\t\t// as tool errors unchanged; legal ones return the full snapshot\n\t\t\t// (the goal_set full-state response pattern).\n\t\t\tconst run = applyAdvance(state, parsed, deps);\n\t\t\tstate = run.state;\n\t\t\tif (run.transitions.length > 0) {\n\t\t\t\tpersistRun(run);\n\t\t\t\tawait announce(run);\n\t\t\t}\n\t\t\tconst response: WorkflowToolResponse = { ...state };\n\t\t\tif (parsed.action === \"inspect\") {\n\t\t\t\t// §5 rule 6 single-workflow semantics: applyAdvance has already\n\t\t\t\t// rejected unknown ids, so the target always resolves here.\n\t\t\t\tconst target = state.workflows.find((workflow) => workflow.id === parsed.workflowId);\n\t\t\t\tif (target !== undefined) response.inspections = [inspectWorkflow(target, deps)];\n\t\t\t}\n\t\t\tif (run.closures.length > 0) response.closures = run.closures;\n\t\t\treturn response;\n\t\t},\n\t});\n\n\tconst workflowCommand = api.registerCommand({\n\t\tname: \"workflow\",\n\t\tdescription: \"Workflow overview: dependency tree and status (default), why it is stopped, or the transition log\",\n\t\targumentHint: \"[view | why | log [N]]\",\n\t\texecute: async (args: string) => {\n\t\t\ttry {\n\t\t\t\tconst trimmed = args.trim();\n\t\t\t\tif (trimmed === \"\" || trimmed === \"view\") {\n\t\t\t\t\treturn { status: \"success\" as const, message: renderPanorama(state, deps) };\n\t\t\t\t}\n\t\t\t\tif (trimmed === \"why\") {\n\t\t\t\t\treturn { status: \"success\" as const, message: renderWhy(state, deps) };\n\t\t\t\t}\n\t\t\t\tconst logMatch = /^log(?:\\s+(\\d+))?$/.exec(trimmed);\n\t\t\t\tif (logMatch !== null) {\n\t\t\t\t\tconst limit = logMatch[1] === undefined ? 20 : Math.max(1, Number.parseInt(logMatch[1], 10));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\t\tmessage: renderLog(api.session?.getBranchEntries() ?? [], limit),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { status: \"error\" as const, message: \"Usage: /workflow [view | why | log [N]]\" };\n\t\t\t} catch (error) {\n\t\t\t\t// A slash command must not crash the host (memory /promote precedent).\n\t\t\t\treturn { status: \"error\" as const, message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t},\n\t});\n\n\t// The repository's first event subscription (§7). The payload is ignored:\n\t// reevaluation always reads the current branch entries (§5 总则 1).\n\tconst planChanged = api.subscribe(\"plan.changed\", async () => {\n\t\ttry {\n\t\t\tconst run = reevaluateAll(state, deps, \"plan.changed\");\n\t\t\tif (run.transitions.length === 0) return;\n\t\t\tstate = run.state;\n\t\t\tpersistRun(run);\n\t\t\tawait announce(run);\n\t\t} catch (error) {\n\t\t\tquarantineEngineError(error, \"plan.changed\");\n\t\t}\n\t});\n\n\treturn [setTool, advanceTool, workflowCommand, planChanged];\n}\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AA2BrF,YAAY,EACX,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,UAAU,EACV,SAAS,EACT,YAAY,EACZ,SAAS,EACT,eAAe,EACf,eAAe,EACf,kBAAkB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC/E,YAAY,EACX,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,EACd,aAAa,EACb,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AA0Z7E,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,aAAa,GAChB,OAAO,CAAC,SAAS,sBAAsB,EAAE,CAAC,GAAG,SAAS,sBAAsB,EAAE,CA0MhF","sourcesContent":["/**\n * Workflow orchestration capability plugin (M1 of\n * `docs/design/工作流编排插件设计.md`): a fourth self-contained state machine\n * orchestrating a stage dependency graph on top of the goal/plan/todo layers.\n *\n * Persistence protocol, structurally identical to the goal/plan/todo plugins:\n * append-only `workflow.state` full snapshots (the single rebuild source) plus\n * one `workflow.transition` audit entry per conversion, announced as\n * `workflow.changed` (version 1, correlationId \"workflow.state\", data = the\n * complete WorkflowState snapshot).\n *\n * This plugin is the repository's FIRST event subscriber (§7): `plan.changed`\n * is used as a trigger signal only — its in-memory data may be misaligned\n * with the current branch, so every reevaluation reads the plan facts from\n * the current branch entries. The handler is fully isolated (§5 总则 3): any\n * failure lands in diagnostics + a `handler.error` transition and never\n * rethrows at the publisher (an unisolated throw would pierce plan_set's tool\n * return). Soft references (goalId / planId / role) never fail a write (#10):\n * they surface as response warnings; a dangling planId additionally holds the\n * stage's activation until a reevaluation finds the plan.\n */\n\nimport type { CapabilityAPI, DisposableRegistration } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport {\n\ttype AdvanceAction,\n\ttype AdvanceInput,\n\tapplyAdvance,\n\tapplyWorkflowSet,\n\ttype EngineDeps,\n\ttype EngineRun,\n\ttype EvidenceItem,\n\tinspectWorkflow,\n\ttype PlanFacts,\n\treevaluateAll,\n\ttype WorkflowClosure,\n\ttype WorkflowInspection,\n} from \"./engine.ts\";\nimport { createWorkflowToolResultRenderer, renderLog, renderPanorama, renderWhy } from \"./render.ts\";\nimport {\n\ttype TransitionReasonCode,\n\tWORKFLOW_STATE_ENTRY,\n\tWORKFLOW_TRANSITION_ENTRY,\n\ttype WorkflowState,\n\ttype WorkflowTransitionEntry,\n\ttype WorkflowTransitionTrigger,\n} from \"./types.ts\";\nimport { asObject, asText, parseWorkflowSetInput, planWorkflowSpecUpdate, validateStageGraph } from \"./validate.ts\";\n\nexport type {\n\tAcceptanceCoverage,\n\tAdvanceAction,\n\tAdvanceInput,\n\tClosureEvidenceItem,\n\tEngineDeps,\n\tEngineRun,\n\tEvidenceItem,\n\tPlanFacts,\n\tStageInspection,\n\tWorkflowClosure,\n\tWorkflowInspection,\n} from \"./engine.ts\";\nexport { cascadeLimitFor, computeWaitingOn, reevaluateAll } from \"./engine.ts\";\nexport type {\n\tStageRuntime,\n\tStageSpec,\n\tTransitionReason,\n\tTransitionReasonCode,\n\tWorkflowRecord,\n\tWorkflowState,\n\tWorkflowTransitionEntry,\n\tWorkflowTransitionTrigger,\n} from \"./types.ts\";\nexport { WORKFLOW_STATE_ENTRY, WORKFLOW_TRANSITION_ENTRY } from \"./types.ts\";\n\n/** Session protocol key of the plan plugin's snapshot entry (plugins/plan). */\nconst planStateEntry = \"plan.state\";\n/** Session protocol key of the goal plugin's snapshot entry (plugins/goal). */\nconst goalStateEntry = \"goal.state\";\n/**\n * Session protocol key of the subagent-delegate plugin's session role snapshot\n * (plugins/subagent-delegate, D-081 item 7: `{ version: 1, roles: [{ id, ... }] }`\n * append-only full snapshots). Same literal-coupling precedent as plan/goal\n * above: the workflow plugin never imports the owning plugin.\n */\nconst subagentRoleStateEntry = \"subagent.roles.state\";\n/**\n * Role id shape: the same expression as the authoritative reader's\n * ROLE_ID_PATTERN (plugins/subagent-delegate `readSessionRoles`). Same\n * cross-plugin literal-coupling precedent as the entry keys above — the\n * workflow plugin never imports the owning plugin. The residual difference is\n * field-level only: subagent-delegate validates the whole role record and drops\n * invalid entries, while this side reads the id alone — so the divergence can\n * only under-warn, never false-warn.\n */\nconst roleIdPattern = /^[a-z0-9][a-z0-9_-]{0,31}$/;\nconst DIAGNOSTICS_CAP = 50;\n\n/** §3.1 applicability, verbatim scope (when to use / not to use a workflow). */\nconst WORKFLOW_APPLICABILITY_GUIDE =\n\t\"Workflow applicability — use a workflow only when ALL of these hold: (1) the goal needs at least 3 stages that can be accepted independently (you can write each stage's objective/acceptance); (2) the stages have a real dependency structure (branching or joins), not a plain sequence; (3) independent branches can be pushed in parallel — parallelism is a core payoff, purely linear multi-stage work belongs to goal/plan/todo; (4) the task spans multiple turns/days and is valuable enough to justify process overhead (definition, evidence recording, stage gates). Counterexamples that keep goal/plan/todo or direct execution: single-step tasks; two- or three-step linear tasks; exploratory work with no presettable dependency graph; one-shot questions. A workflow does not exclude the three layers — each stage still uses plan/todo for its execution checklist. Never escalate a small task to a workflow by default. When the user explicitly asks for workflow orchestration, still run this weighing: if the task genuinely misses the bar, skipping is fine — but say so in one line why you stayed on goal/plan/todo (an unexplained skip reads as ignoring the request); conversely, do not build one just because it was asked when the task is small (over-orchestration costs more than it saves).\";\n\nconst WORKFLOW_AUTHORING_GUIDE =\n\t\"Define each stage by a verifiable end state, not by a work list or a role: objective.statement says what must be achieved; acceptance items list the evidence that proves it, referenced from real tool output. Stop splitting at the first verifiable boundary — finer handoffs lose more to interface drift than they gain in drift protection.\";\n\nconst WORKFLOW_EXECUTION_GUIDE =\n\t\"After plan_set marks a stage's plan completed, run workflow_advance inspect to see unlocked stages and acceptance coverage. Record evidence (workflow_advance record-evidence) before completion is evaluated; lower-bound stages (no acceptance declared) need no record-evidence. When multiple stages are active, delegate one subagent per stage following stage.role and push them in parallel.\";\n\nconst WORKFLOW_CORRECTION_GUIDE =\n\t\"On user corrections: run workflow_advance inspect first to confirm the current state, then route by what changed — amend the stage spec (active/awaiting_review stages, amendNote required), append a stage, skip, retreat, or cancel — and report the adjustment and its impact range back to the user.\";\n\nconst WORKFLOW_REVIEW_GUIDE =\n\t\"Stages declared advance: 'review' stop at awaiting_review. Before approve you must present the result and its evidence to the user and get explicit confirmation — never approve on your own (the engine does not authorize; the discipline lives here).\";\n\nconst WORKFLOW_CONCURRENCY_GUIDE =\n\t\"Do not send workflow_set in the same parallel batch as plan_set: amends and completion evaluation race (completed freezes first; if the amend loses, recover via retreat).\";\n\nconst WORKFLOW_INCREMENTAL_DEMAND_GUIDE =\n\t\"When a new batch of requirements arrives (incremental features on top of shipped work), default to creating a NEW workflow to carry it — reuse the same goalId and keep the completed workflow's history intact; never pull a completed workflow back into motion. Retreat or append a corrective stage only when the new requirements overturn already completed output.\";\n\nconst WORKFLOW_EXECUTOR_GUIDE =\n\t\"When delegating a stage to a subagent, pass that subagent's session/task id as the executor field of record-evidence — it is recorded on the stage (advisory) so /workflow log shows who drove it.\";\n\nconst acceptanceSchema = Type.Object({\n\tid: Type.String({ description: \"Acceptance item id; evidence references this id\" }),\n\tstatement: Type.String({ description: \"Verifiable completion criterion for this item\" }),\n});\n\nconst stageSchema = Type.Object({\n\tid: Type.String({ description: \"Stable stage id, unique within the workflow\" }),\n\ttitle: Type.String({ description: \"Human-readable stage title\" }),\n\tobjective: Type.Object({\n\t\tstatement: Type.String({\n\t\t\tdescription: \"Verifiable end state this stage must reach (required, non-empty)\",\n\t\t}),\n\t\tacceptance: Type.Optional(\n\t\t\tType.Array(acceptanceSchema, {\n\t\t\t\tdescription:\n\t\t\t\t\t\"Completion criteria items; when empty (or omitted) the lower bound is the referenced plan's completion evidence\",\n\t\t\t}),\n\t\t),\n\t}),\n\tdependsOn: Type.Optional(\n\t\tType.Array(Type.String(), { description: \"Hard prerequisite stage ids; empty array = root stage\" }),\n\t),\n\tplanId: Type.Optional(Type.String({ description: \"Soft reference to a plan id; missing = pure checkpoint stage\" })),\n\tkind: Type.Optional(\n\t\tType.Union([Type.Literal(\"read\"), Type.Literal(\"write\")], {\n\t\t\tdescription: 'Stage kind; write stages are scope-checked, default \"write\"',\n\t\t}),\n\t),\n\tscope: Type.Optional(\n\t\tType.Array(Type.String(), {\n\t\t\tdescription: \"Write scope tags (modules/dirs); missing = global (intersects every other write stage)\",\n\t\t}),\n\t),\n\trole: Type.Optional(\n\t\tType.String({ description: \"Delegation advice: role id for the subagent recommended to drive this stage\" }),\n\t),\n\tadvance: Type.Optional(\n\t\tType.Union([Type.Literal(\"auto\"), Type.Literal(\"review\")], {\n\t\t\tdescription:\n\t\t\t\t'\"auto\" completes on evaluation, \"review\" stops at awaiting_review (planId stages only), default \"auto\"',\n\t\t}),\n\t),\n\tretryLimit: Type.Optional(\n\t\tType.Integer({ description: \"In-place retry limit before onFail/workflow failure, default 2\", minimum: 0 }),\n\t),\n\tonFail: Type.Optional(\n\t\tType.String({ description: \"Explicit cross-stage retreat target (a topologically earlier stage id)\" }),\n\t),\n\tamendNote: Type.Optional(\n\t\tType.String({\n\t\t\tdescription: \"Correction reason; required when an active/awaiting_review stage's spec changes\",\n\t\t}),\n\t),\n});\n\nconst workflowSetSchema = Type.Object({\n\tid: Type.String({ description: \"Stable id of the workflow to create or update\" }),\n\ttitle: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Human-readable workflow title. Required when creating a new workflow; on update, omitting it keeps the stored value\",\n\t\t}),\n\t),\n\trevision: Type.Integer({\n\t\tdescription: \"New revision counter; must be greater than the stored revision of an existing workflow\",\n\t\tminimum: 0,\n\t}),\n\tgoalId: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Soft reference to a goal id; the closure evidence summary is addressed to this goal. Omitting on update keeps the stored value\",\n\t\t}),\n\t),\n\tmaxRetreats: Type.Optional(\n\t\tType.Integer({\n\t\t\tdescription:\n\t\t\t\t\"Workflow lifetime retreat budget before failure, default 3. Omitting on update keeps the stored value\",\n\t\t\tminimum: 0,\n\t\t}),\n\t),\n\tmaxActiveStages: Type.Optional(\n\t\tType.Integer({\n\t\t\tdescription: \"Parallel activation cap, default 8. Omitting on update keeps the stored value\",\n\t\t\tminimum: 1,\n\t\t}),\n\t),\n\tstages: Type.Array(stageSchema, {\n\t\tdescription: \"Full stage list (whole submit, not a patch); the engine aligns runtime by stage id\",\n\t}),\n});\n\nconst workflowAdvanceSchema = Type.Object({\n\tworkflowId: Type.String({ description: \"Target workflow id\" }),\n\taction: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"start\"),\n\t\t\tType.Literal(\"record-evidence\"),\n\t\t\tType.Literal(\"inspect\"),\n\t\t\tType.Literal(\"approve\"),\n\t\t\tType.Literal(\"reject\"),\n\t\t\tType.Literal(\"retreat\"),\n\t\t\tType.Literal(\"complete\"),\n\t\t\tType.Literal(\"skip\"),\n\t\t\tType.Literal(\"cancel\"),\n\t\t],\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"Explicit action to perform. Prerequisites: start requires a draft workflow; every other action requires a running one. record-evidence and complete require non-empty `evidence`; approve/reject require an awaiting_review stage; retreat requires a previously activated stage; complete applies only to checkpoint stages without planId\",\n\t\t},\n\t),\n\tstageId: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Stage id: the evidence/approve/reject/complete/skip target, or the retreat target stage to roll back to; required by every action except start and inspect\",\n\t\t}),\n\t),\n\texecutor: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Advisory executor id (e.g. subagent session/task id) driving the stage; record-only, last-write-wins, never affects evaluation\",\n\t\t}),\n\t),\n\tevidence: Type.Optional(\n\t\tType.Array(\n\t\t\tType.Object({\n\t\t\t\tacceptanceId: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Acceptance item id; required in acceptance mode\" }),\n\t\t\t\t),\n\t\t\t\tref: Type.String({ description: \"Evidence reference (tool output, file, artifact)\" }),\n\t\t\t}),\n\t\t\t{\n\t\t\t\tdescription:\n\t\t\t\t\t\"Evidence items for record-evidence/approve/complete. record-evidence and complete require at least one item; when the stage declares acceptance items, every item must carry an acceptanceId that exists in the current spec, and complete must cover all of them\",\n\t\t\t},\n\t\t),\n\t),\n\tnote: Type.Optional(\n\t\tType.String({ description: \"Optional note recorded in the transition detail (reject/retreat/skip/cancel)\" }),\n\t),\n});\n\nconst ADVANCE_ACTIONS: readonly string[] = [\n\t\"start\",\n\t\"record-evidence\",\n\t\"inspect\",\n\t\"approve\",\n\t\"reject\",\n\t\"retreat\",\n\t\"complete\",\n\t\"skip\",\n\t\"cancel\",\n];\n\nfunction objectInput(first: unknown, second: unknown): Record<string, unknown> {\n\tconst value = second === undefined ? first : second;\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new Error(\"Workflow input must be an object\");\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction parseAdvanceInput(value: Record<string, unknown>): AdvanceInput {\n\tconst workflowId = asText(value.workflowId, \"workflowId\");\n\tconst action = value.action;\n\tif (typeof action !== \"string\" || !ADVANCE_ACTIONS.includes(action)) {\n\t\tthrow new Error(`action must be one of ${ADVANCE_ACTIONS.join(\", \")}`);\n\t}\n\tconst stageId = value.stageId === undefined ? undefined : asText(value.stageId, \"stageId\");\n\tconst note = value.note === undefined ? undefined : asText(value.note, \"note\");\n\tconst executor = value.executor === undefined ? undefined : asText(value.executor, \"executor\");\n\tlet evidence: EvidenceItem[] | undefined;\n\tif (value.evidence !== undefined) {\n\t\tif (!Array.isArray(value.evidence)) throw new Error(\"evidence must be an array of {acceptanceId?, ref}\");\n\t\tevidence = value.evidence.map((item) => {\n\t\t\tconst entry = asObject(item, \"evidence item\");\n\t\t\tconst ref = asText(entry.ref, \"evidence item ref\");\n\t\t\tconst acceptanceId =\n\t\t\t\tentry.acceptanceId === undefined ? undefined : asText(entry.acceptanceId, \"evidence item acceptanceId\");\n\t\t\treturn acceptanceId === undefined ? { ref } : { acceptanceId, ref };\n\t\t});\n\t}\n\treturn {\n\t\tworkflowId,\n\t\taction: action as AdvanceAction,\n\t\t...(stageId !== undefined ? { stageId } : {}),\n\t\t...(evidence !== undefined ? { evidence } : {}),\n\t\t...(note !== undefined ? { note } : {}),\n\t\t...(executor !== undefined ? { executor } : {}),\n\t};\n}\n\nfunction loadState(api: CapabilityAPI): WorkflowState {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tconst entry = [...entries].reverse().find((item) => item.customType === WORKFLOW_STATE_ENTRY);\n\tif (!entry?.data || typeof entry.data !== \"object\") return { workflows: [] };\n\tconst data = entry.data as Partial<WorkflowState>;\n\treturn { workflows: Array.isArray(data.workflows) ? [...data.workflows] : [] };\n}\n\n/**\n * Plan facts read from the current branch's LATEST `plan.state` snapshot (the\n * same latest-snapshot semantics as the plan plugin's own loadState). The\n * plan.changed payload is never trusted for state — only as a trigger.\n *\n * Uncached by design: identity-keyed caching collided across test hosts and\n * hooking invalidation into appendEntry crosses the persistence boundary; the\n * O(stages x entries) rescan is the price of snapshot-driven truth. Revisit\n * only with a per-run cache channel if long-session profiling demands it.\n */\nfunction loadPlansSnapshot(api: CapabilityAPI): Map<string, PlanFacts> {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index] as { customType?: string; data?: unknown } | undefined;\n\t\tif (entry?.customType !== planStateEntry) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return new Map();\n\t\tconst plans = (data as { plans?: unknown }).plans;\n\t\tif (!Array.isArray(plans)) return new Map();\n\t\tconst facts = new Map<string, PlanFacts>();\n\t\tfor (const plan of plans) {\n\t\t\tif (!plan || typeof plan !== \"object\") continue;\n\t\t\tconst record = plan as { id?: unknown; status?: unknown; evidence?: unknown };\n\t\t\tif (typeof record.id !== \"string\") continue;\n\t\t\tconst status =\n\t\t\t\trecord.status === \"draft\" ||\n\t\t\t\trecord.status === \"active\" ||\n\t\t\t\trecord.status === \"completed\" ||\n\t\t\t\trecord.status === \"cancelled\"\n\t\t\t\t\t? record.status\n\t\t\t\t\t: \"draft\";\n\t\t\tconst evidence = Array.isArray(record.evidence)\n\t\t\t\t? record.evidence.filter((item): item is string => typeof item === \"string\")\n\t\t\t\t: [];\n\t\t\tfacts.set(record.id, { id: record.id, status, evidence });\n\t\t}\n\t\treturn facts;\n\t}\n\treturn new Map();\n}\n\n/** Whether the latest `<entryType>` snapshot on the branch knows `id` in its `idsField` array (advisory, #10). */\nfunction idKnownToSession(api: CapabilityAPI, entryType: string, idsField: string, id: string): boolean {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.customType !== entryType) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return false;\n\t\tconst records = (data as Record<string, unknown>)[idsField];\n\t\tif (!Array.isArray(records)) return false;\n\t\treturn records.some(\n\t\t\t(record) => record !== null && typeof record === \"object\" && (record as { id?: unknown }).id === id,\n\t\t);\n\t}\n\treturn false;\n}\n\n/**\n * Seeds the held-dedup view (§5 总则 5) from the branch audit stream: the\n * last transition per stage, whatever its code — a repeat held emission is\n * dropped only when it matches that last code and detail.\n */\nfunction buildLastStageTransition(api: CapabilityAPI): Map<string, { code: TransitionReasonCode; detail?: string }> {\n\tconst map = new Map<string, { code: TransitionReasonCode; detail?: string }>();\n\tfor (const entry of api.session?.getBranchEntries() ?? []) {\n\t\tif (entry.customType !== WORKFLOW_TRANSITION_ENTRY) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\tconst record = data as Partial<WorkflowTransitionEntry>;\n\t\tif (typeof record.workflowId !== \"string\" || typeof record.stageId !== \"string\") continue;\n\t\tconst reason = record.reason as { code?: unknown; detail?: unknown } | undefined;\n\t\tif (!reason || typeof reason !== \"object\" || typeof reason.code !== \"string\") continue;\n\t\tmap.set(`${record.workflowId}::${record.stageId}`, {\n\t\t\tcode: reason.code as TransitionReasonCode,\n\t\t\tdetail: typeof reason.detail === \"string\" ? reason.detail : undefined,\n\t\t});\n\t}\n\treturn map;\n}\n\n/**\n * Role ids from the current branch's latest READABLE `subagent.roles.state`\n * snapshot (D-081 item 7). Fallback is symmetric with the authoritative reader\n * (subagent-delegate `readSessionRoles`): a snapshot-level corruption (data not\n * an object / version mismatch / roles not an array) steps back to the previous\n * readable snapshot, and only a fully unreadable table degrades to the empty\n * set. Individual malformed role records are skipped — including ids that do\n * not match `roleIdPattern` — keeping the remaining ids of an otherwise\n * readable snapshot. Silent by contract: the\n * subagent-delegate plugin owns the degradation warning on its side, and a\n * second report here would double-warn for the same fact — this side only\n * tolerates.\n */\nfunction loadSessionRoleIds(api: CapabilityAPI): Set<string> {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.customType !== subagentRoleStateEntry) continue;\n\t\tconst data = entry.data;\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\tconst snapshot = data as { version?: unknown; roles?: unknown };\n\t\tif (snapshot.version !== 1 || !Array.isArray(snapshot.roles)) continue;\n\t\tconst known = new Set<string>();\n\t\tfor (const role of snapshot.roles) {\n\t\t\tif (!role || typeof role !== \"object\" || Array.isArray(role)) continue;\n\t\t\tconst id = (role as { id?: unknown }).id;\n\t\t\tif (typeof id === \"string\" && roleIdPattern.test(id)) known.add(id);\n\t\t}\n\t\treturn known;\n\t}\n\treturn new Set();\n}\n\n/** Soft-reference warnings for the tool response only (never the persisted state, #10). */\nfunction collectSoftReferenceWarnings(\n\tapi: CapabilityAPI,\n\tgoalId: string | undefined,\n\tplanIds: { stageId: string; planId: string }[],\n\troles: { stageId: string; role: string }[],\n): string[] {\n\tconst warnings: string[] = [];\n\tif (goalId !== undefined && !idKnownToSession(api, goalStateEntry, \"goals\", goalId)) {\n\t\twarnings.push(\n\t\t\t`goalId \"${goalId}\" does not match any goal in this session's goal state; the workflow keeps the soft reference`,\n\t\t);\n\t}\n\tfor (const item of planIds) {\n\t\tif (!idKnownToSession(api, planStateEntry, \"plans\", item.planId)) {\n\t\t\twarnings.push(\n\t\t\t\t`stage ${item.stageId}: planId \"${item.planId}\" does not match any plan in this session's plan state; ` +\n\t\t\t\t\t\"the stage stays held until a reevaluation finds the plan\",\n\t\t\t);\n\t\t}\n\t}\n\t// Two verifiable role sources (D-081 item 7): the host's suite role\n\t// associations (disk roles) plus this branch's session role table. A host\n\t// without the listing AND an empty session table verifies nothing, so the\n\t// advice stays unverified — no warning (缺面不告警). An explicitly empty\n\t// association face ([]) still warns for every role.\n\tconst associated = api.host?.roleAssociations;\n\tconst sessionRoleIds = roles.length > 0 ? loadSessionRoleIds(api) : new Set<string>();\n\tconst merged = new Set([...(associated ?? []), ...sessionRoleIds]);\n\tfor (const item of roles) {\n\t\tif ((associated !== undefined || sessionRoleIds.size > 0) && !merged.has(item.role)) {\n\t\t\twarnings.push(\n\t\t\t\t`stage ${item.stageId}: role \"${item.role}\" is neither associated with the active suite nor ` +\n\t\t\t\t\t\"registered in this session; delegation advice treated as unspecified — register it with \" +\n\t\t\t\t\t'subagent_role (type \"set\") or add it to the suite\\'s roles associations',\n\t\t\t);\n\t\t}\n\t}\n\treturn warnings;\n}\n\ninterface WorkflowToolResponse extends WorkflowState {\n\tclosures?: WorkflowClosure[];\n\tinspections?: WorkflowInspection[];\n\twarning?: string;\n}\n\nexport function createCapability(\n\tapi: CapabilityAPI,\n): Promise<readonly DisposableRegistration[]> | readonly DisposableRegistration[] {\n\tlet state = loadState(api);\n\tconst deps: EngineDeps = {\n\t\tgetPlan: (planId) => loadPlansSnapshot(api).get(planId),\n\t\tlastStageTransition: buildLastStageTransition(api),\n\t};\n\t// Shared structural renderResult (render.ts): the host TUI gets the\n\t// panorama face for both tools' JSON-serialized responses.\n\tconst toolResultRenderer = createWorkflowToolResultRenderer(deps);\n\n\t// Persistence boundary (§4): audit entries first, then the full snapshot —\n\t// a crash mid-batch replays from the older snapshot while the audit stays\n\t// intact. appendEntry failures propagate unchanged (§5 总则 5: no swallow);\n\t// publish rejections surface to the tool caller (or are contained on the\n\t// load/subscriber paths below).\n\tconst persistRun = (run: EngineRun): void => {\n\t\tfor (const transition of run.transitions) {\n\t\t\tapi.session?.appendEntry(WORKFLOW_TRANSITION_ENTRY, transition);\n\t\t}\n\t\tapi.session?.appendEntry(WORKFLOW_STATE_ENTRY, run.state);\n\t};\n\tconst announce = (run: EngineRun): Promise<unknown> =>\n\t\tapi.publish({ type: \"workflow.changed\", version: 1, correlationId: WORKFLOW_STATE_ENTRY, data: run.state });\n\n\t/**\n\t * §5 总则 3 containment: land the failure in diagnostics + a handler.error\n\t * transition (detail = original error text) and never rethrow. Best-effort\n\t * — an already-failing boundary must not turn isolation into a second crash.\n\t */\n\tconst quarantineEngineError = (error: unknown, trigger: WorkflowTransitionTrigger): void => {\n\t\ttry {\n\t\t\tif (state.workflows.length === 0) return;\n\t\t\tconst original = error instanceof Error ? error.message : String(error);\n\t\t\tconst text = `${trigger} handler failed: ${original}`;\n\t\t\tconst workflows = state.workflows.map((workflow) => structuredClone(workflow));\n\t\t\tconst transitions: WorkflowTransitionEntry[] = [];\n\t\t\tfor (const workflow of workflows) {\n\t\t\t\tif (workflow.diagnostics.length >= DIAGNOSTICS_CAP) workflow.diagnostics.shift();\n\t\t\t\tworkflow.diagnostics.push(text);\n\t\t\t\tworkflow.revision += 1;\n\t\t\t\ttransitions.push({\n\t\t\t\t\tworkflowId: workflow.id,\n\t\t\t\t\tfrom: workflow.status,\n\t\t\t\t\tto: workflow.status,\n\t\t\t\t\ttrigger,\n\t\t\t\t\treason: { code: \"handler.error\", message: text, detail: original },\n\t\t\t\t\trevision: workflow.revision,\n\t\t\t\t});\n\t\t\t}\n\t\t\tstate = { workflows };\n\t\t\tfor (const transition of transitions) {\n\t\t\t\tapi.session?.appendEntry(WORKFLOW_TRANSITION_ENTRY, transition);\n\t\t\t}\n\t\t\tapi.session?.appendEntry(WORKFLOW_STATE_ENTRY, state);\n\t\t\tvoid api\n\t\t\t\t.publish({ type: \"workflow.changed\", version: 1, correlationId: WORKFLOW_STATE_ENTRY, data: state })\n\t\t\t\t.catch(() => undefined);\n\t\t} catch {\n\t\t\t// Containment is best-effort by design.\n\t\t}\n\t};\n\n\t// §5 rule 8 recovery: state replayed from workflow.state, then the\n\t// load-time reevaluation (总则 1 fallback moment #1). Runs synchronously at\n\t// factory time; failures are contained, never blocking plugin load.\n\ttry {\n\t\tconst run = reevaluateAll(state, deps, \"load-reeval\");\n\t\tif (run.transitions.length > 0) {\n\t\t\tstate = run.state;\n\t\t\tpersistRun(run);\n\t\t\tvoid announce(run).catch(() => undefined);\n\t\t}\n\t} catch (error) {\n\t\tquarantineEngineError(error, \"load-reeval\");\n\t}\n\n\tconst setTool = api.registerTool({\n\t\tname: \"workflow_set\",\n\t\tlabel: \"Set workflow\",\n\t\tpromptGuidelines: [\n\t\t\tWORKFLOW_APPLICABILITY_GUIDE,\n\t\t\tWORKFLOW_AUTHORING_GUIDE,\n\t\t\tWORKFLOW_EXECUTION_GUIDE,\n\t\t\tWORKFLOW_CORRECTION_GUIDE,\n\t\t\tWORKFLOW_REVIEW_GUIDE,\n\t\t\tWORKFLOW_CONCURRENCY_GUIDE,\n\t\t\tWORKFLOW_INCREMENTAL_DEMAND_GUIDE,\n\t\t\tWORKFLOW_EXECUTOR_GUIDE,\n\t\t],\n\t\tdescription:\n\t\t\t\"Create or update a workflow: a stage dependency graph (DAG) with per-stage objectives, acceptance evidence, and soft goal/plan references. Creating a workflow requires `title`; on update, an omitted optional field (title/goalId/maxRetreats/maxActiveStages) keeps its stored value. Stages are always submitted in full\",\n\t\tparameters: workflowSetSchema,\n\t\trenderResult: toolResultRenderer,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst parsed = parseWorkflowSetInput(objectInput(first, second));\n\t\t\tvalidateStageGraph(parsed.stages);\n\t\t\tconst current = state.workflows.find((workflow) => workflow.id === parsed.id);\n\t\t\tif (current !== undefined && parsed.revision <= current.revision) {\n\t\t\t\tthrow new Error(`stale workflow revision: ${parsed.id}`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcurrent !== undefined &&\n\t\t\t\t(current.status === \"completed\" || current.status === \"failed\" || current.status === \"cancelled\")\n\t\t\t) {\n\t\t\t\tthrow new Error(`workflow is terminal and cannot be updated: ${parsed.id}`);\n\t\t\t}\n\t\t\tconst diff = planWorkflowSpecUpdate(current, parsed);\n\t\t\tconst run = applyWorkflowSet(state, parsed, diff, deps);\n\t\t\tstate = run.state;\n\t\t\tif (run.transitions.length > 0 || diff.created) persistRun(run);\n\t\t\tif (run.transitions.length > 0 || diff.created) await announce(run);\n\t\t\tconst response: WorkflowToolResponse = { ...state };\n\t\t\tif (run.closures.length > 0) response.closures = run.closures;\n\t\t\tconst warnings = collectSoftReferenceWarnings(\n\t\t\t\tapi,\n\t\t\t\tparsed.goalId,\n\t\t\t\tparsed.stages.flatMap((stage) =>\n\t\t\t\t\tstage.planId !== undefined ? [{ stageId: stage.id, planId: stage.planId }] : [],\n\t\t\t\t),\n\t\t\t\tparsed.stages.flatMap((stage) =>\n\t\t\t\t\tstage.role !== undefined ? [{ stageId: stage.id, role: stage.role }] : [],\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (warnings.length > 0) response.warning = warnings.join(\"; \");\n\t\t\treturn response;\n\t\t},\n\t});\n\n\tconst advanceTool = api.registerTool({\n\t\tname: \"workflow_advance\",\n\t\tlabel: \"Advance workflow\",\n\t\tdescription:\n\t\t\t\"Drive a workflow: start it, record acceptance evidence, inspect waiting conditions and coverage, approve/reject reviews, retreat, complete checkpoints, skip stages, or cancel. Every action except start and inspect needs stageId; record-evidence and complete need non-empty evidence, and complete requires an active checkpoint stage with no planId\",\n\t\tparameters: workflowAdvanceSchema,\n\t\trenderResult: toolResultRenderer,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst parsed = parseAdvanceInput(objectInput(first, second));\n\t\t\t// Illegal conversions throw structured errors (§5 rule 6) surfaced\n\t\t\t// as tool errors unchanged; legal ones return the full snapshot\n\t\t\t// (the goal_set full-state response pattern).\n\t\t\tconst run = applyAdvance(state, parsed, deps);\n\t\t\tstate = run.state;\n\t\t\tif (run.transitions.length > 0) {\n\t\t\t\tpersistRun(run);\n\t\t\t\tawait announce(run);\n\t\t\t}\n\t\t\tconst response: WorkflowToolResponse = { ...state };\n\t\t\tif (parsed.action === \"inspect\") {\n\t\t\t\t// §5 rule 6 single-workflow semantics: applyAdvance has already\n\t\t\t\t// rejected unknown ids, so the target always resolves here.\n\t\t\t\tconst target = state.workflows.find((workflow) => workflow.id === parsed.workflowId);\n\t\t\t\tif (target !== undefined) response.inspections = [inspectWorkflow(target, deps)];\n\t\t\t}\n\t\t\tif (run.closures.length > 0) response.closures = run.closures;\n\t\t\treturn response;\n\t\t},\n\t});\n\n\tconst workflowCommand = api.registerCommand({\n\t\tname: \"workflow\",\n\t\tdescription: \"Workflow overview: dependency tree and status (default), why it is stopped, or the transition log\",\n\t\targumentHint: \"[view | why | log [N]]\",\n\t\texecute: async (args: string) => {\n\t\t\ttry {\n\t\t\t\tconst trimmed = args.trim();\n\t\t\t\tif (trimmed === \"\" || trimmed === \"view\") {\n\t\t\t\t\treturn { status: \"success\" as const, message: renderPanorama(state, deps) };\n\t\t\t\t}\n\t\t\t\tif (trimmed === \"why\") {\n\t\t\t\t\treturn { status: \"success\" as const, message: renderWhy(state, deps) };\n\t\t\t\t}\n\t\t\t\tconst logMatch = /^log(?:\\s+(\\d+))?$/.exec(trimmed);\n\t\t\t\tif (logMatch !== null) {\n\t\t\t\t\tconst limit = logMatch[1] === undefined ? 20 : Math.max(1, Number.parseInt(logMatch[1], 10));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\t\tmessage: renderLog(api.session?.getBranchEntries() ?? [], limit),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { status: \"error\" as const, message: \"Usage: /workflow [view | why | log [N]]\" };\n\t\t\t} catch (error) {\n\t\t\t\t// A slash command must not crash the host (memory /promote precedent).\n\t\t\t\treturn { status: \"error\" as const, message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t},\n\t});\n\n\t// The repository's first event subscription (§7). The payload is ignored:\n\t// reevaluation always reads the current branch entries (§5 总则 1).\n\tconst planChanged = api.subscribe(\"plan.changed\", async () => {\n\t\ttry {\n\t\t\tconst run = reevaluateAll(state, deps, \"plan.changed\");\n\t\t\tif (run.transitions.length === 0) return;\n\t\t\tstate = run.state;\n\t\t\tpersistRun(run);\n\t\t\tawait announce(run);\n\t\t} catch (error) {\n\t\t\tquarantineEngineError(error, \"plan.changed\");\n\t\t}\n\t});\n\n\treturn [setTool, advanceTool, workflowCommand, planChanged];\n}\n"]}