import { expect, test } from 'bun:test'; import { mkdir, mkdtemp, readFile, readdir, rm, unlink, writeFile, } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { loadWorkflowDir } from '../src/discovery.js'; import { resolveWorkflowBundle } from '../src/workflowDependencies.js'; import { coerceInputs } from '../src/inputCoercion.js'; import { runWorkflowScript } from '../src/runner.js'; import { publishCheckpoint } from '../src/runtime/fs.js'; import type { RunContext } from '../src/types.js'; import { skillTool } from '../../../src/tools/skill/skill.js'; import { prepareMessagesForProvider } from '../../../src/llm/messageProvenance.js'; import { filterEphemeralMessages } from '../../../src/context/persistContext.js'; async function fixture(parent: string, child: string) { const cwd = await mkdtemp(join(tmpdir(), 'wf-child-')); async function put(name: string, source: string) { const dir = join(cwd, 'workflows', name); await mkdir(dir, { recursive: true }); await writeFile(join(dir, 'workflow.mjs'), source); } await put('parent', parent); await put('child', child); let calls = 0; let peak = 0; let active = 0; const ctx = { cwd, provider: { name: 'stub' }, history: [{ role: 'system', content: 'sys' }], tools: [], chat: async function* () { calls++; active++; peak = Math.max(peak, active); await new Promise((r) => setTimeout(r, 5)); active--; yield { type: 'text_delta', delta: 'child-value' }; yield { type: 'done', stopReason: 'stop', promptTokens: 10, outputTokens: 2, }; }, } as unknown as RunContext; async function run(name = 'parent') { const script = await loadWorkflowDir(join(cwd, 'workflows', name)); if (!script.ok) throw Error(script.errors.join(';')); const events = []; for await (const e of runWorkflowScript(script.workflow, { ctx, inputs: {}, sessionId: 'test', })) events.push(e); return events; } async function done() { const base = join(cwd, '.minimal-agent-workflow/parent/test'); return join(base, (await readdir(base)).find((n) => n.endsWith('.done'))!); } return { cwd, ctx, put, run, done, calls: () => calls, peak: () => peak }; } const parent = `export const meta={description:'parent',dependencies:['child']}; export default async function run(wf) { const r=await wf.flow.child('child', {}, {label:'child-label'}); wf.output.message(r.result); return r; }`.replace('{description:', '{apiVersion:2,description:'); const child = `export const meta={apiVersion:2,description:'child'}; export default async function run(wf) { return await wf.model.generate('child', {isolated:true}); }`; test('only successful root completion presents artifacts, including completed replay', async () => { const h = await fixture( `export const meta={apiVersion:2,description:'parent',dependencies:['child'],artifacts:['root.txt']}; export default async function run(wf) { await wf.flow.child('child',{}); await wf.fs.writeText('root.txt','root'); }`, `export const meta={apiVersion:2,description:'child',artifacts:['child.txt']}; export default async function run(wf) { await wf.fs.writeText('child.txt','child'); }`, ); const delivered: string[][] = []; h.ctx.presentArtifacts = async function* (paths) { delivered.push([...paths]); }; try { expect((await h.run()).some(e => e.type === 'error')).toBe(false); const rootArtifacts = [join(h.cwd, 'root.txt'), join(h.cwd, 'child.txt')]; expect(delivered).toEqual([rootArtifacts]); await h.run(); expect(delivered).toEqual([rootArtifacts, rootArtifacts]); await h.put('parent', `export const meta={apiVersion:2,description:'parent',artifacts:['root.txt']}; export default async function run(wf) { throw new Error('fixture failure'); }`); expect((await h.run()).some(e => e.type === 'error')).toBe(true); expect(delivered).toHaveLength(2); } finally { await rm(h.cwd, { recursive: true, force: true }); } }); test('root and child use strict typed input coercion', () => { const defs = [{ name: 'n', type: 'number' as const }]; expect(coerceInputs({ n: '900' }, defs)).toEqual({ n: 900 }); expect(coerceInputs({ n: 900 }, defs)).toEqual({ n: 900 }); for (const n of ['3abc', '', Number.POSITIVE_INFINITY, {}]) expect(() => coerceInputs({ n }, defs)).toThrow(); }); test('a diamond shares its bundle within one run without bypassing depth on a longer path', async () => { const program = (dependencies: string[] = []) => `export const meta={apiVersion:2,description:'x',dependencies:${JSON.stringify(dependencies)}}; export default async function run(wf) {}`; const cwd = await mkdtemp(join(tmpdir(), 'bundle-diamond-')); const put = async (name: string, deps: string[]) => { const dir = join(cwd, 'workflows', name); await mkdir(dir, { recursive:true }); await writeFile(join(dir, 'workflow.mjs'), program(deps)); }; const load = async () => { const root = await loadWorkflowDir(join(cwd, 'workflows', 'parent')); if (!root.ok) throw Error(root.errors.join('; ')); return resolveWorkflowBundle(root.workflow, cwd); }; try { await put('parent', ['left','right']); await put('left', ['shared']); await put('right', ['shared']); await put('shared', ['leaf']); await put('leaf', []); const bundle = await load(); expect(bundle.children.get('left')!.children.get('shared')).toBe(bundle.children.get('right')!.children.get('shared')); await put('right',['d1']); for (let i = 1; i <= 5; i++) await put('d'+i, [i === 5 ? 'shared' : 'd'+(i+1)]); await expect(load()).rejects.toThrow('超过8层'); } finally { await rm(cwd,{recursive:true,force:true}); } }); test('child JSON return persists; only root completes; completed replay; missing return restarts', async () => { const h = await fixture(parent, child); const events = await h.run(); expect(events.filter((e) => e.type === 'error')).toEqual([]); expect(events.filter((e) => e.type === 'turn_done')).toHaveLength(1); const stages = h.ctx.history.filter(message => message.role === 'system' && message.id?.includes(':stage:')); expect(stages.length).toBeGreaterThan(0); expect(new Set(stages.map(message => message.id)).size).toBe(stages.length); for (const stage of stages) { expect(events.some(event => event.type === 'injected_message' && event.message === stage)).toBe(true); expect(filterEphemeralMessages([stage])).toEqual([stage]); expect(prepareMessagesForProvider([stage])).toEqual([]); } const snapshot = h.ctx.history.find(message => message.role === 'system' && message.workflowPresentation); expect(snapshot?.role).toBe('system'); if (snapshot?.role === 'system') { expect(snapshot._ephemeral).toBe(true); expect(snapshot._uiProgress).toBe(true); expect(snapshot.workflowPresentation?.outcome).toBe('succeeded'); expect(Object.values(snapshot.workflowPresentation?.branches ?? {}).some(branch => branch.outcome === 'succeeded')).toBe(true); expect(filterEphemeralMessages([snapshot])).toHaveLength(1); expect(prepareMessagesForProvider([snapshot])).toEqual([]); } expect(h.ctx.resourceLedger?.inputTokens).toBe(10); const dir = await h.done(); expect( JSON.parse(await readFile(join(dir, 'return.json'), 'utf8')).result, ).toBe('child-value'); await h.run(); expect(h.calls()).toBe(1); await unlink(join(dir, 'return.json')); await h.run(); expect(h.calls()).toBe(2); }); test('parent resume reuses completed child and child bundle change invalidates parent', async () => { const h = await fixture( parent.replace( 'wf.output.message(r.result);', `if (!(await wf.fs.exists('continue'))) throw new Error('pause'); wf.output.message(r.result);`, ), child, ); expect((await h.run()).some((e) => e.type === 'error')).toBe(true); await writeFile(join(h.cwd, 'continue'), 'go'); expect((await h.run()).some((e) => e.type === 'error')).toBe(false); expect(h.calls()).toBe(1); await h.put('child', `${child}\n// changed contract`); await h.run(); expect(h.calls()).toBe(2); await h.run('child'); expect(h.calls()).toBe(3); // standalone identity differs }); test('caught child failure does not send top-level error, undeclared/managed/cyclic dependencies fail', async () => { const h = await fixture( parent.replace( "const r=await wf.flow.child('child', {}, {label:'child-label'}); wf.output.message(r.result); return r;", `try {await wf.flow.child('child');} catch(e) {wf.output.message('caught');} return null;`, ), `export const meta={apiVersion:2,description:'child'};export default async function run(wf){throw new Error('broken');}`, ); expect((await h.run()).some((e) => e.type === 'error')).toBe(false); await h.put( 'child', `export const meta={apiVersion:2,description:'child',dependencies:['parent']};export default async function run(wf){}`, ); expect( (await h.run()).some( (e) => e.type === 'error' && e.error.includes('依赖环'), ), ).toBe(true); await h.put( 'child', `export const meta={apiVersion:2,description:'child',managedRuntime:'goal'};export default async function run(wf){}`, ); expect( (await h.run()).some( (e) => e.type === 'error' && e.error.includes('managedRuntime'), ), ).toBe(true); await h.put( 'parent', `export const meta={apiVersion:2,description:'parent'};export default async function run(wf){await wf.flow.child('child');}`, ); const undeclaredEvents = await h.run(); expect( undeclaredEvents.some( (e) => e.type === 'error' && e.error.includes('未声明'), ), ).toBe(true); }); test('pipeline child instances are isolated, share gate and usage; missing child output invalidates tree', async () => { const h = await fixture( `export const meta={apiVersion:2,description:'parent',dependencies:['child']}; export default async function run(wf){const batch=await wf.flow.pipeline(Array.from({length:12},(_,i)=>i),{label:'children',concurrency:8,errorMode:'fail-fast',stages:[async(i)=>wf.flow.child('child',{i})]});return batch.results.map(r=>r.value);}`, child, ); const events = await h.run(); expect(events.filter((e) => e.type === 'error')).toEqual([]); expect(h.calls()).toBe(12); expect(h.peak()).toBeLessThanOrEqual(8); expect(h.ctx.resourceLedger?.inputTokens).toBe(120); const results = JSON.parse( await readFile(join(await h.done(), 'return.json'), 'utf8'), ); expect(new Set(results.map((r: { runId: string }) => r.runId)).size).toBe(12); await h.run(); expect(h.calls()).toBe(12); const childRoot = join(await h.done(), 'children/child'); await unlink(join(childRoot, (await readdir(childRoot))[0], 'return.json')); expect((await h.run()).filter(e => e.type === 'error')).toEqual([]); expect(h.calls()).toBe(24); // 36 次真实子工作流实例化(各自 mkdir/journal/progress.md/return.json)在较慢的 // 文件系统(尤其 Windows)上实测约 5s,超过 bun 默认 5000ms 测试超时——这是真实 // 磁盘 IO 耗时,不是卡死或回归,给足预算避免偶发超时。 }, 15000); test('checkpoint retry is bounded and limited to Windows rename contention', async () => { const denied = Object.assign(new Error('fixture'), { code: 'EPERM', syscall: 'rename' }); let attempts = 0; await publishCheckpoint(async () => { if (++attempts === 1) throw denied; }, 'win32'); expect(attempts).toBe(2); attempts = 0; await expect(publishCheckpoint(async () => { attempts++; throw denied; }, 'win32')).rejects.toBe(denied); expect(attempts).toBe(6); for (const [platform, syscall] of [['linux', 'rename'], ['win32', 'open']] as const) { attempts = 0; const err = Object.assign(new Error('fixture'), { code: 'EPERM', syscall }); await expect(publishCheckpoint(async () => { attempts++; throw err; }, platform)).rejects.toBe(err); expect(attempts).toBe(1); } }); test('parent cancellation remains interrupted even if child exception is caught', async () => { const h = await fixture(parent, child); const controller = new AbortController(); h.ctx.signal = controller.signal; h.ctx.chat = async function* () { controller.abort(); yield* []; throw Object.assign(new Error('stop'), { name: 'AbortError' }); }; const events = await h.run(); expect(events.some((e) => e.type === 'interrupted')).toBe(true); expect(events.some((e) => e.type === 'turn_done')).toBe(false); }); test('explicit child resources use workflow cwd and do not inherit parent attachments/history', async () => { const h = await fixture( parent.replace( "wf.flow.child('child', {}", "wf.flow.child('child', {source:'input.png'}", ), `export const meta={apiVersion:2,description:'child',inputs:[{name:'source',type:'resource',required:true,accepts:['image/*'],attachmentFallback:true}]}; export default async function run(wf){return {source:wf.input.values.source};}`, ); await writeFile( join(h.cwd, 'input.png'), Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a5lsAAAAASUVORK5CYII=', 'base64', ), ); h.ctx.history.push({ role: 'user', content: 'private-parent-context' }); const events = await h.run(); expect(events.filter((e) => e.type === 'error')).toEqual([]); const value = JSON.parse( await readFile(join(await h.done(), 'return.json'), 'utf8'), ); expect(value.result.source).toBe(join(h.cwd, 'input.png')); await h.put('parent', parent); // No explicit source: must not absorb any parent attachment. const missingResourceEvents = await h.run(); expect( missingResourceEvents.some( (e) => e.type === 'error' && /source|输入/.test(e.error), ), ).toBe(true); }); test('history isolation preserves system instructions and child uses the same tool authorization ceiling', async () => { const h = await fixture(parent, child); h.ctx.history.push({ role: 'user', content: 'private-parent-context' }); h.ctx.chat = async function* (options) { expect(JSON.stringify(options)).not.toContain('private-parent-context'); yield { type: 'text_delta', delta: 'ok' }; yield { type: 'done', stopReason: 'stop' }; } as RunContext['chat']; expect((await h.run()).filter((e) => e.type === 'error')).toEqual([]); await h.put( 'child', `export const meta={apiVersion:2,description:'child'}; export default async function run(wf){await wf.tools.call('NotAuthorized',{});}`, ); const unauthorizedEvents = await h.run(); expect(unauthorizedEvents.some((e) => e.type === 'error')).toBe(true); }); test('artifact ownership tree archives once without touching standalone child outputs', async () => { const h = await fixture( parent, `export const meta={apiVersion:2,description:'child'}; export default async function run(wf){const path='artifact-'+wf.runtime.taskId+'.txt';wf.output.artifact(path);await wf.tools.call('Write',{file_path:path,content:'owned'});return {path};}`, ); const toolCallIds: string[] = []; h.ctx.executeTool = (async ( _name: string, raw: string, _signal: unknown, context: { toolCallId: string }, ) => { toolCallIds.push(context.toolCallId); const input = JSON.parse(raw); await writeFile(join(h.cwd, input.file_path), input.content); return { ok: true, content: 'written' }; }) as unknown as RunContext['executeTool']; // Match the host's real Write dispatch shape; the tool is deliberately restricted to this fixture. h.ctx.tools = [ { name: 'Write', description: 'write fixture', parameters: { type: 'object', properties: {} }, }, ] as unknown as RunContext['tools']; const first = await h.run(); expect(first.filter((e) => e.type === 'error')).toEqual([]); const result = JSON.parse( await readFile(join(await h.done(), 'return.json'), 'utf8'), ); expect(result.artifacts).toContain(join(h.cwd, result.result.path)); await h.run('child'); const before = (await readdir(h.cwd)).filter((n) => n.startsWith('artifact-'), ); expect(before).toHaveLength(2); await unlink(join(h.cwd, result.result.path)); expect((await h.run()).some((e) => e.type === 'error')).toBe(false); expect( await readFile( join(h.cwd, before.find((n) => n !== result.result.path)!), 'utf8', ), ).toBe('owned'); expect(new Set(toolCallIds).size).toBe(toolCallIds.length); }); test('dependency depth is bounded and JSON-only return is enforced', async () => { const h = await fixture(parent, child); for (let i = 0; i < 8; i++) await h.put( i === 0 ? 'child' : `level${i}`, `export const meta={apiVersion:2,description:'level',dependencies:['level${i + 1}']};export default async function run(wf){return wf.flow.child('level${i + 1}',{});}`, ); await h.put('level8', `export const meta={apiVersion:2,description:'last'};export default async function run(wf){return null;}`); expect( (await h.run()).some((e) => e.type === 'error' && e.error.includes('8层')), ).toBe(true); await h.put( 'child', `export const meta={apiVersion:2,description:'child'};export default async function run(wf){return {bad:Infinity};}`, ); expect((await h.run()).some((e) => e.type === 'error')).toBe(true); }); test('nested isolated skill nodes load complete instructions and root emits one terminal', async () => { const h = await fixture( `export const meta={apiVersion:2,description:'parent',dependencies:['child']};export default async function run(wf){return wf.flow.pipeline([1,2],{concurrency:2,stages:[async(_,item)=>wf.flow.child('child',{item})]});}`, `export const meta={apiVersion:2,description:'child',inputs:[{name:'item',type:'number'}]};export default async function run(wf){return wf.model.skill('nested-fixture','use existing instructions',{isolated:true});}`, ); const skillDir = join(h.cwd, 'skills/nested-fixture'); await mkdir(skillDir, { recursive: true }); await writeFile(join(skillDir, 'SKILL.md'), '---\nname: nested-fixture\nmetadata:\n surfaces: [workflow]\n modes: [private]\n---\nFOLLOW_EXISTING_FIXTURE_STEPS'); h.ctx.runtimeContext = { surface: 'workflow', profile: 'main', cwd: h.cwd, conversationMode: 'private', owner: 'local-owner', memoryAccess: 'denied', interactiveAsk: false }; h.ctx.tools = [skillTool]; let seen = 0; h.ctx.chat = async function* ({ messages }) { expect(JSON.stringify(messages)).toContain('FOLLOW_EXISTING_FIXTURE_STEPS'); seen++; yield { type: 'text_delta', delta: 'done' }; }; const events = await h.run(); expect(events.filter(e => e.type === 'error')).toEqual([]); expect(events.filter(e => e.type === 'turn_done')).toHaveLength(1); expect(seen).toBe(2); await h.run(); expect(seen).toBe(2); // Completed children are replayed, not another model invocation. });