/** * plugins/workflow-runner/test/api.test.ts —— WorkflowContext V2 能力 * * 重点守「零工具调用」这条 announce-not-do 信号。 * * 背景:legacy 靠 yaml 里声明 `done_when:` 让引擎兜底「宣告要干活却不调工具就 * end_turn」这类烂尾。代码形态把守卫交给了作者(`if (!await exists(...))`), * 作者忘了写时就没有任何网 —— 这条记录是那种情况下唯一的线索,而且必须落进 * **progress.md**(TUI 的 scrollback 会被刷掉,排障总发生在跑完之后)。 * * 用 DI 注入 chat stub,不用 mock.module(后者全局泄漏、污染同批其它测试文件)。 */ import { afterEach, describe, expect, test } from 'bun:test'; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { getToolByName, type LoopEvent } from '../../../src/plugin-sdk.js'; import { createWorkflowContext } from '../src/runtime/context.js'; import { WORKFLOW_CONTEXT_CAPABILITIES, assertWorkflowContextShape, } from '../src/workflowContext.js'; import { Journal } from '../src/journal.js'; import type { RunContext } from '../src/types.js'; import { WorkflowState } from '../src/workflowState.js'; const dirs: string[] = []; afterEach(() => { for (const d of dirs.splice(0)) { try { rmSync(d, { recursive: true, force: true, maxRetries: 3 }); } catch { /* Windows 偶发 EBUSY;清理失败不影响断言 */ } } }); /** 只吐文本、不发任何 tool_call 的 chat stub —— 模拟「只宣告不动手」。 */ function textOnlyChat(text: string) { return async function* () { yield { type: 'text_delta' as const, delta: text }; yield { type: 'done' as const, stopReason: 'stop' as const }; }; } /** 造一套最小可跑的注入环境,返回 globals + 落盘位置 + 收到的事件。 */ async function harness(chat: RunContext['chat']) { const wd = mkdtempSync(join(tmpdir(), 'wf-api-')); dirs.push(wd); const state = new WorkflowState(wd, 'demo', 's1'); await state.init({ goal: '测试目标' }, 'hash-v1', []); const journal = new Journal(state.journalPath, { bundleHash: 'test', rootRunId: 'test-root' }); await journal.load(); const events: LoopEvent[] = []; const ctx = { provider: { name: 'test' }, history: [{ role: 'system', content: 'sys' }], cwd: wd, tools: [getToolByName('Write')!], chat, } as unknown as RunContext; const globals = createWorkflowContext({ ctx, state, journal, emit: (ev) => events.push(ev), args: {}, workflowName: 'demo', session: 's1', task: state.taskId, }); return { globals, events, progress: () => { const p = join(state.dir, 'progress.md'); return existsSync(p) ? readFileSync(p, 'utf8') : ''; }, // journaled() 里的 ▶/✓/✗ 行是 fire-and-forget(生产路径的落盘保证来自 // runner.ts 终止路径上对同一条 progressWrites 链的 await——这个测试 // harness 绕开了 runner.ts,直接调能力对象,没有那条终态保证)。 // 读 progress() 前如果要断言这几行,先 await flush()。 flush: () => state.flush(), }; } describe('零工具调用信号(announce-not-do)', () => { test('★ agent 产出文本但一次工具都没调 → progress.md 留下可搜索的标记', async () => { const h = await harness(textOnlyChat('好的,接下来我将创建那个文件。')); await h.globals.model.agent('把结果写进 out/x.md'); expect(h.progress()).toContain('零工具调用'); }); test('★ 同时 emit 一条 warning,并指向正确的补救动作', async () => { const h = await harness(textOnlyChat('接下来我会处理。')); await h.globals.model.agent('干点什么'); const warns = h.events.filter((e) => e.type === 'warning'); expect(warns.length).toBe(1); // 提示必须说清「该怎么办」——只说「零工具调用」等于让作者自己猜 expect(JSON.stringify(warns[0])).toContain('exists()/verify()'); }); test('★ 只记录不抛 —— 有些 agent 调用本就该纯思考(分类/判断/总结)', async () => { const h = await harness(textOnlyChat('minor')); const out = await h.globals.model.agent('判断这条反馈是 minor 还是 fundamental'); expect(out).toBe('minor'); // 正常返回,没有因为零工具调用而失败 }); test('空答明确失败,但不误报为 announce-not-do', async () => { const h = await harness(textOnlyChat(' ')); await expect(h.globals.model.agent('干点什么')).rejects.toMatchObject({ name: 'WorkflowModelError', code: 'no_answer', recovery: { partialText: '' }, }); expect(h.progress()).not.toContain('零工具调用'); }); test('log 阶段旁白同时持久化到 progress.md,便于事后定位卡点', async () => { const h = await harness(textOnlyChat('ok')); h.globals.output.progress({ phase: 'test', status: 'update', message: '开始页面结构识别' }); await h.flush(); expect(h.progress()).toContain('开始页面结构识别'); }); test('★ 账本重放命中时不重复报警(上次已经报过了)', async () => { // 第一次真跑:记账 + 报警 const first = await harness(textOnlyChat('我将要做这件事。')); await first.globals.model.agent('固定的提示词'); expect(first.events.filter((e) => e.type === 'warning').length).toBe(1); // 同一个工作目录、同一份提示词再来一次 → 命中重放,run 回调根本不执行 const wd = dirs[dirs.length - 1]; const state = new WorkflowState(wd, 'demo', 's1'); await state.init({ goal: '测试目标' }, 'hash-v1', []); const journal = new Journal(state.journalPath, { bundleHash: 'test', rootRunId: 'test-root' }); await journal.load(); const events: LoopEvent[] = []; const globals = createWorkflowContext({ ctx: { provider: { name: 'test' }, history: [{ role: 'system', content: 'sys' }], cwd: wd, tools: [], // 故意不给 chat:命中重放就不该真调模型;真调了这里会炸,等于反向验证 chat: undefined, } as unknown as RunContext, state, journal, emit: (ev) => events.push(ev), args: {}, workflowName: 'demo', session: 's1', task: state.taskId, }); const replayed = await globals.model.agent('固定的提示词'); expect(replayed).toBe('我将要做这件事。'); // 确实走了重放 expect(journal.replayedCount).toBe(1); expect(events.filter((e) => e.type === 'warning').length).toBe(0); }); }); describe('WorkflowContext 能力注册表(唯一真值)', () => { test('★ createWorkflowContext 实际形状与注册表完全一致', async () => { const h = await harness(textOnlyChat('x')); expect(() => assertWorkflowContextShape(h.globals)).not.toThrow(); expect(Object.keys(h.globals).sort()).toEqual( Object.keys(WORKFLOW_CONTEXT_CAPABILITIES).sort(), ); }); test('★ 组内能力多出会响亮失败', () => { const valid = Object.fromEntries( Object.entries(WORKFLOW_CONTEXT_CAPABILITIES).map(([group, names]) => [ group, Object.fromEntries(names.map((name) => [name, () => undefined])), ]), ); expect(() => assertWorkflowContextShape({ ...valid, model: { ...(valid.model as object), unexpected: () => undefined }, }), ).toThrow(/不同步/); }); }); describe('progress.md 逐调用记账', () => { test('★ 每次调用都留下开始与完成两行 —— 跑完之后唯一能回看的现场', async () => { const h = await harness(textOnlyChat('产出内容')); await h.globals.model.generate('生成一段文字'); await h.flush(); const log = h.progress(); expect(log).toContain('▶ #1 llm'); expect(log).toContain('✓ #1 llm'); expect(log).toContain('产出内容'); // 结果预览也在,排障时不用再去翻账本 }); }); describe('wf.tools.call(Write) 覆盖已存在文件不受"未在本会话 Read 过"闸门误伤', () => { test('★ 真实端到端跑 goal 工作流暴露过的场景:断点续跑是全新进程,目标路径是上次尝试留下的旧文件', async () => { // 该闸门(src/tools/write/write.ts::assertFresh)是为 agent 长对话里可能 // 凭过时印象盲写设计的;工作流脚本的 tool('Write', …) 是作者写死的、无条件 // 覆盖自己声明产物路径的确定性调用,不该被同一把闸拦住——尤其是 goal/ // ralph-loop 这类跨进程恢复的 managedRuntime 工作流:resume 是全新进程, // sessionState 从空白起步,而 CONTRACT.md/STATUS.json 这类文件是上一次 // (失败的)尝试留下的,本进程从未读过。 const path = mkdtempSync(join(tmpdir(), 'wf-write-guard-')) + '/CONTRACT.md'; writeFileSync(path, '上一次尝试留下的旧内容'); const h = await harness(textOnlyChat('x')); const result = await h.globals.tools.call('Write', { file_path: path, content: '这次重新计算出的最新内容', }); expect(result).not.toContain('已存在但未在本会话 Read 过'); expect(readFileSync(path, 'utf8')).toBe('这次重新计算出的最新内容'); }); });