import { lookupWorkflow } from './discovery.js'; import { fingerprint } from './journal.js'; import type { WorkflowScript } from './types.js'; import { workflowFingerprint } from './workflowFingerprint.js'; export interface WorkflowBundle { script: WorkflowScript; hash: string; children: Map; } /** Resolve once per root execution using the same override precedence as /workflow. */ export async function resolveWorkflowBundle( root: WorkflowScript, cwd: string, ): Promise { // Never persist discoveries across invocations: user edits to helper // scripts, resources or overrides must affect the next run's fingerprint. const scripts = new Map([[root.name, root]]); const completed = new Map(); async function visit( script: WorkflowScript, ancestors: string[], ): Promise { if (ancestors.includes(script.name)) throw new Error( `工作流依赖环:${[...ancestors, script.name].join(' → ')}`, ); if (ancestors.length >= 8) throw new Error('子工作流嵌套超过8层'); if (ancestors.length && script.meta.managedRuntime) throw new Error( `不能把 managedRuntime 工作流 ${script.name} 作为子流程调用`, ); const cached = completed.get(script.name); if (cached) { if (ancestors.length + cached.height > 8) throw new Error('子工作流嵌套超过8层'); return cached.bundle; } const children = new Map(); let height = 1; for (const name of script.meta.dependencies ?? []) { let child = scripts.get(name); if (!child) { const found = await lookupWorkflow(name, cwd); if (!found.script) throw new Error(`依赖工作流 ${name} 不可用:${found.errors?.join('; ') ?? '未找到'}`); child = found.script; scripts.set(name, child); } children.set(name, await visit(child, [...ancestors, script.name])); height = Math.max(height, 1 + completed.get(name)!.height); } const own = await workflowFingerprint( script.source, script.dir, script.meta.packages ?? [], ); // Leaf workflows retain their direct module fingerprint. A workflow with // dependencies receives a separate tree namespace so child wiring cannot // collide with a standalone workflow fingerprint. const hash = children.size ? fingerprint('workflow-tree-v1', { own, children: [...children].map(([name, b]) => [name, b.hash]), }) : own; const bundle = { script, hash, children }; completed.set(script.name, { bundle, height }); return bundle; } return visit(root, []); }