/** * plugins/workflow-runner/test/taskIdentity.test.ts —— 任务身份与状态目录布局 * * 这组测试的核心是**四级布局的三个并存需求**(见 taskIdentity.ts 头注): * 同 session 同 goal → 同目录(能 resume) * 同 session 换主题 → 不同目录(不覆盖) * 不同 session → 不同目录(能并行) * * legacy 曾把这三条压进两级布局,反复顾此失彼:Phase 2 用 taskId 层解决了「不覆盖」, * Phase 3 把那一层**换成** sessionId 换来了「并行」,「不覆盖」就丢了;补偿方案 * (宿主没给 session 就自动生成带时间戳的)又让「能 resume」也丢了 —— 时间每次都变, * 于是每次运行都是新 session。下面「三者并存」那一组就是钉这段历史的。 */ import { afterEach, describe, expect, test } from 'bun:test'; import { buildGoalAnchor } from '../src/goalAnchor.js'; import { DEFAULT_SESSION_ID, WF_STATE_DIR_ENV, buildTaskArbitrator, computeTaskId, extractGoal, isContinuationPhrase, resolveStateRoot, sanitizeWorkflowDirName, sessionStateDir, taskInstanceDir, } from '../src/taskIdentity.js'; const WD = process.platform === 'win32' ? 'D:\\work' : '/work'; describe('状态目录布局', () => { const savedEnv = process.env[WF_STATE_DIR_ENV]; afterEach(() => { if (savedEnv === undefined) delete process.env[WF_STATE_DIR_ENV]; else process.env[WF_STATE_DIR_ENV] = savedEnv; }); test('默认落在 cwd 下的 .minimal-agent-workflow/', () => { delete process.env[WF_STATE_DIR_ENV]; expect(resolveStateRoot(WD)).toContain('.minimal-agent-workflow'); }); test('环境变量指定的全局目录优先', () => { process.env[WF_STATE_DIR_ENV] = WD; expect(resolveStateRoot('/somewhere/else')).toBe(WD); }); test('目录名清洗:非 [字母数字._-] 一律换成 -', () => { expect(sanitizeWorkflowDirName('my flow/v2:x')).toBe('my-flow-v2-x'); }); test('实例目录是四级:workflow / session / taskId', () => { const dir = taskInstanceDir(WD, 'ppt', 'sess-a', 'abc123'); expect(dir).toContain('ppt'); expect(dir).toContain('sess-a'); expect(dir.endsWith('abc123')).toBe(true); // taskId 目录必须在 session 目录之内,不是它的兄弟 expect(dir.startsWith(sessionStateDir(WD, 'ppt', 'sess-a'))).toBe(true); }); }); describe('★ 三个需求必须并存(四级布局的存在理由)', () => { const dirFor = (session: string, goal: string): string => taskInstanceDir( WD, 'research', session, computeTaskId('research', { goal }), ); test('同 session + 同 goal → 同一个目录(resume 才够得着)', () => { expect(dirFor('s1', '调研 A 主题')).toBe(dirFor('s1', '调研 A 主题')); }); test('★ 同 session + 换主题 → 不同目录(连续研究不同内容不互相覆盖)', () => { expect(dirFor('s1', '调研 A 主题')).not.toBe(dirFor('s1', '调研 B 主题')); }); test('不同 session + 同 goal → 不同目录(并行隔离)', () => { expect(dirFor('s1', '调研 A 主题')).not.toBe(dirFor('s2', '调研 A 主题')); }); test('★ default session 也照常工作,不被替换成带时间戳的名字', () => { // legacy 在这里自动生成 `YYYYMMDD-HHmmss-xxxxxx`,导致每次运行都是新 session、 // resume/completed 永远够不着。四级布局下没有这个必要,也绝不能加回来。 const a = dirFor(DEFAULT_SESSION_ID, '同一个目标'); const b = dirFor(DEFAULT_SESSION_ID, '同一个目标'); expect(a).toBe(b); expect(a).toContain(DEFAULT_SESSION_ID); }); }); describe('computeTaskId', () => { test('纯函数:同输入恒等,不读盘不看时间', () => { const a = computeTaskId('w', { goal: 'x' }); const b = computeTaskId('w', { goal: 'x' }); expect(a).toBe(b); expect(a).toHaveLength(16); }); test('工作流名参与哈希 —— 不同工作流的同一目标不是同一个任务', () => { expect(computeTaskId('a', { goal: 'x' })).not.toBe( computeTaskId('b', { goal: 'x' }), ); }); test.each([ ['大小写', '调研 Foo', '调研 foo'], ['尾部标点', '调研 foo!!!', '调研 foo'], ['连续空格', '调研 foo', '调研 foo'], ['首尾空白', ' 调研 foo ', '调研 foo'], ])('归一化消除无意义差异:%s', (_label, a, b) => { expect(computeTaskId('w', { goal: a })).toBe( computeTaskId('w', { goal: b }), ); }); test('标点是被【删除】而不是换成空格 —— 记录真实边界,别想当然', () => { // `调研:foo` 归一化成 `调研foo`(不含空格),因此它与 `调研 foo` **不**同任务。 // 对中日韩文本这样处理没问题(本就不用空格分词),但拉丁文本里 // `foo,bar` 会并成 `foobar`。这是自 legacy 原样移植的行为,不在本次改动范围内; // 真要改,得先想清楚它会让所有既有 taskId 全部变化。 expect(computeTaskId('w', { goal: '调研:foo' })).toBe( computeTaskId('w', { goal: '调研foo' }), ); expect(computeTaskId('w', { goal: '调研:foo' })).not.toBe( computeTaskId('w', { goal: '调研 foo' }), ); }); test('★ 语义不同就是不同任务 —— 时间窗口不得覆盖内容差异', () => { // legacy 早期「30 分钟内视为同一任务」是 bug:半小时内换个完全不同的目标 // 重跑,会 resume 旧任务并把旧变量混进新目标。已移除,别加回来。 expect(computeTaskId('w', { goal: '写一份 PPT' })).not.toBe( computeTaskId('w', { goal: '修一个 bug' }), ); }); test('★ 同一句请求配不同附件内容必须是不同任务', () => { const defs = [ { name: 'source', type: 'resource' as const, required: true }, ]; const base = { source: '/runtime/paper.jpg', requestText: '帮我整理成 Word', }; expect( computeTaskId( 'wrong-question-docx', { ...base, __resource_fingerprint: 'source:sha-a' }, defs, ), ).not.toBe( computeTaskId( 'wrong-question-docx', { ...base, __resource_fingerprint: 'source:sha-b' }, defs, ), ); expect( buildGoalAnchor( { ...base, __resource_fingerprint: 'source:sha-a' }, defs, ), ).toContain('帮我整理成 Word'); }); test('超长 goal 截断到 200 字 —— 靠后的细微差异不该分裂同一件事', () => { const base = '主'.repeat(200); expect(computeTaskId('w', { goal: `${base}甲` })).toBe( computeTaskId('w', { goal: `${base}乙` }), ); }); test('资源工作流相同输入不同处理参数不能命中旧completed', () => { const defs = [ { name: 'source', type: 'resource' as const, required: true }, { name: 'format', type: 'enum' as const, values: ['pdf', 'docx'], default: 'pdf', }, { name: 'range' }, ]; const base = { source: '/runtime/image.png', requestText: '转换文件', __resource_fingerprint: 'same-bytes', format: 'pdf', }; expect(computeTaskId('converter', { ...base, range: '1' }, defs)).not.toBe( computeTaskId('converter', { ...base, range: '2' }, defs), ); expect(computeTaskId('converter', base, defs)).not.toBe( computeTaskId('converter', { ...base, format: 'docx' }, defs), ); expect(computeTaskId('converter', base, defs)).toBe( computeTaskId( 'converter', { ...base, source: '/another/staged.png' }, [...defs].reverse(), ), ); }); }); describe('extractGoal', () => { test('显式 goal 优先', () => { expect(extractGoal({ topic: '别的', goal: '真目标' })).toBe('真目标'); }); test('无 goal 时优先取作者标了 required 的输入', () => { // 作者用 required 表达了「这是主要输入」,比「第一个碰到的字符串」可靠得多 expect( extractGoal({ lang: 'zh', topic: '调研主题' }, [ { name: 'lang' }, { name: 'topic', required: true }, ]), ).toBe('调研主题'); }); test('没有 required 声明时退到第一个非空字符串', () => { expect(extractGoal({ n: 5, topic: '主题' })).toBe('主题'); }); test('★ 两个字的中文目标必须取到 —— 曾被 >2 的长度阈值跳过', () => { // 那条阈值是照拉丁文本想的(跳过 ab、语言代码),对中文直接失效: // `世界`、`调研` 这种目标会被跳过去落到 JSON 兜底,于是 current.json 里 // 记的目标变成一坨 JSON、仲裁时喂给 LLM 的也是那坨 JSON。端到端实跑复现过。 expect(extractGoal({ name: '世界' })).toBe('世界'); expect(extractGoal({ name: '世界', times: 3 })).not.toContain('{'); }); test('全是非字符串 → 回退整体 JSON(保证恒有确定值)', () => { expect(extractGoal({ pages: 12 })).toBe('{"pages":12}'); }); test('★ 与 buildGoalAnchor 共用同一份规则(两处分家会让身份与锚指向不同目标)', () => { const inputs = { lang: 'zh', topic: '调研主题' }; const defs = [{ name: 'lang' }, { name: 'topic', required: true }]; expect(buildGoalAnchor(inputs, defs)).toContain(extractGoal(inputs, defs)); }); }); describe('isContinuationPhrase', () => { test.each(['继续', '继续吧', '接着做', 'continue', 'RESUME', '继续 执行'])( '「%s」是延续指令', (s) => { expect(isContinuationPhrase(s)).toBe(true); }, ); test.each(['写一份关于继续教育的报告', '调研 A 主题', ''])( '「%s」不是延续指令', (s) => { expect(isContinuationPhrase(s)).toBe(false); }, ); test('★ 长句里出现「继续」二字不算延续指令(否则会误 resume 掉真正的新任务)', () => { expect(isContinuationPhrase('继续教育政策的调研报告怎么写')).toBe(false); }); }); describe('任务仲裁链', () => { const actx = { workflowName: 'research', prevGoal: '调研 A 主题', newGoal: '继续', completedCalls: 7, artifacts: ['out/a.md'], }; const provider = { name: 'test' } as never; /** 造一个只吐固定文本的 chat stub(DI,不用 mock.module)。 */ const chatStub = (text: string) => async function* () { yield { type: 'text_delta' as const, delta: text }; }; test('a. 延续短语走快路径,不花 LLM', async () => { let llmCalled = false; const arb = buildTaskArbitrator({ provider, chat: (() => { llmCalled = true; return chatStub('{"verdict":"new"}')(); }) as never, }); expect(await arb(actx)).toBe('resume'); expect(llmCalled).toBe(false); }); test('b. LLM 给出明确判定就采纳', async () => { const arb = buildTaskArbitrator({ provider, chat: chatStub('{"verdict":"new","reason":"无关"}') as never, }); expect(await arb({ ...actx, newGoal: '换个完全不同的题目' })).toBe('new'); }); test('LLM 输出被 markdown 代码块包着也能解析', async () => { const arb = buildTaskArbitrator({ provider, chat: chatStub('```json\n{"verdict":"resume"}\n```') as never, }); expect(await arb({ ...actx, newGoal: '把它做完,另外改成 12 页' })).toBe( 'resume', ); }); test('c. LLM 说 unsure → 降级问用户', async () => { const arb = buildTaskArbitrator({ provider, chat: chatStub('{"verdict":"unsure"}') as never, executeTool: async (_name, raw) => { const q = JSON.parse(raw).questions[0]; return { ok: true, content: `用户已回答 AskUserQuestion:\n\nQ1 [${q.header}] ${q.question}\nA1: 继续上次任务` }; }, }); expect(await arb({ ...actx, newGoal: '别的' })).toBe('resume'); }); test('取消不会降级成问人或按全新任务收尾', async () => { const abort = new AbortController(); let asks = 0; const arb = buildTaskArbitrator({ provider, signal: abort.signal, chat: async function* () { abort.abort(new Error('用户取消')); throw abort.signal.reason; }, executeTool: async () => { asks++; return { ok: false, error: 'unused' }; }, }); await expect(arb({ ...actx, newGoal: '不同目标' })).rejects.toThrow('用户取消'); expect(asks).toBe(0); }); test('★ d. 全都不可用 → 兜底 new,绝不 halt 工作流', async () => { // 仲裁只是个辅助判断。让它有能力中断整条工作流是本末倒置。 const boom = () => { throw new Error('不可用'); }; const arb = buildTaskArbitrator({ provider, chat: boom as never, executeTool: boom as never, }); expect(await arb({ ...actx, newGoal: '别的' })).toBe('new'); }); test('仲裁过程留下人话记录(用户要看得见为什么这么判)', async () => { const notes: string[] = []; const arb = buildTaskArbitrator({ provider, notes }); await arb(actx); expect(notes.join('\n')).toContain('延续短语'); }); });