import { mkdtemp } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { describe, expect, test } from 'bun:test'; import { GoalRuntime, GoalStore } from '../../../src/goal/index.js'; import { prepareGoalCommand } from '../../../src/goal/workflowController.js'; async function harness() { const root = await mkdtemp(join(tmpdir(), 'goal-controller-')); const runtime = new GoalRuntime({ store: new GoalStore({ stateRoot: root }) }); const options = { cwd: root, runtime, runtimeContext: { workspaceId: 'workspace-1', sessionId: 'session-1', cwd: root, surface: 'workflow' as const, profile: 'main' as const, owner: 'local-owner' as const, memoryAccess: 'read-only' as const, interactiveAsk: false, }, }; return { runtime, options }; } describe('/workflow goal controller', () => { test('group controls bind the trusted actor, group and task; retain the human contract', async () => { const { runtime, options } = await harness(); const groupOptions = { ...options, runtimeContext: { ...options.runtimeContext, conversationMode: 'group' as const }, provenance: { mode: 'group' as const, visibility: 'group-public' as const, groupId: 'group-a', senderId: 'user:alice' }, }; const contract = { objective: '交付完整功能', acceptanceCriteria: ['逗号,不拆分', '中文"引用"与换行\n保留'], deliverables: ['成品.zip'], sourceRefs: ['message:original'], scope: '限定项目目录' }; const prepared = await prepareGoalCommand({ action: 'start', group_id: 'group-a', task_id: 'task-a', contract_json: JSON.stringify(contract) }, groupOptions); expect(prepared.handled).toBe(false); await prepared.bridge!.updateContract({ objective: '模型自行缩减', acceptanceCriteria: ['随便通过'] }); const scope = { workspaceId: 'workspace-1', sessionId: 'session-1' }; let goal = (await runtime.get(scope))!; expect(runtime.currentContract(goal)).toMatchObject(contract); const before = goal.revision; for (const [group, task, sender] of [['group-b', 'task-a', 'user:alice'], ['group-a', 'task-b', 'user:alice'], ['group-a', 'task-a', 'user:bob']]) { const rejected = await prepareGoalCommand({ action: 'cancel', group_id: group, task_id: task }, { ...groupOptions, provenance: { ...groupOptions.provenance, senderId: sender! } }); expect(rejected.events[0]?.type).toBe('error'); expect((await runtime.get(scope))?.revision).toBe(before); } await prepared.bridge!.finish({ status: 'verified' }); await prepareGoalCommand({ action: 'accept', group_id: 'group-a', task_id: 'task-a' }, groupOptions); goal = (await runtime.get(scope))!; expect(goal.status).toBe('accepted'); expect(goal.acceptorHumanIds).toEqual(['user:alice']); }); test('creates stable Goal/Attempt and rejects an implicit objective replacement', async () => { const { options } = await harness(); const first = await prepareGoalCommand({ objective: '实现功能', checks: 'shell:bun test', group_id: 'group-1', task_id: 'task-1', }, options); expect(first.handled).toBe(false); expect(first.execution?.correlations?.taskId).toBe('task-1'); const conflict = await prepareGoalCommand({ objective: '换一个目标' }, options); expect(conflict.handled).toBe(true); expect(conflict.events[0]).toMatchObject({ type: 'error' }); }); test('confirmed workflow contract is versioned and verification stops at human acceptance', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand({ objective: '交付功能' }, options); await prepared.bridge?.updateContract({ objective: '交付功能', deliverables: ['代码', '说明'], acceptanceCriteria: ['测试通过'], }); const ready = await prepared.bridge?.finish({ status: 'verified', artifacts: ['out/result.md'], evidence: ['tests pass'], }) as import('../../../src/goal/types.js').Goal | undefined; expect(ready?.status).toBe('ready_for_acceptance'); expect(ready?.currentContractVersion).toBe(2); const status = await prepareGoalCommand({ action: 'status' }, options); expect(status.events[0]).toMatchObject({ type: 'text' }); const accepted = await prepareGoalCommand({ action: 'accept' }, options); expect(accepted.events[0]).toMatchObject({ type: 'text' }); expect((await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }))?.status) .toBe('accepted'); }); test('pause/resume reuses the stopped Attempt journal identity', async () => { const { options } = await harness(); const first = await prepareGoalCommand({ objective: '长任务' }, options); await first.bridge?.finish({ status: 'stopped', blocker: '用户暂停' }); const resumed = await prepareGoalCommand({ action: 'resume' }, options); expect(resumed.handled).toBe(false); expect(resumed.execution?.runId).toBe(first.execution?.runId); }); }); /** * ── 资源记账(A2)───────────────────────────────────────────────────── * * `recordUsage` 此前**全仓零调用点**:方法定义在 GoalRuntime 上, * `GoalResourceUsage` / `budget_limited` / `usage_limited` 全是有形状无执行器, * 连桌面端 App.tsx 都已经在渲染两个永远不会发生的状态。这里把通路锁死。 */ describe('goal bridge —— 资源记账', () => { test('★ recordUsage 累计进 goal.usage,并回报最新契约的上限', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '记账测试', checks: 'shell:exit 0' }, options, ); expect(prepared.bridge?.recordUsage).toBeDefined(); const first = await prepared.bridge!.recordUsage!({ inputTokens: 100, outputTokens: 20 }); expect(first.inputTokens).toBe(100); expect(first.outputTokens).toBe(20); // 没设预算时上限是 null(不是 0 —— 0 会被判成「一开始就超了」)。 expect(first.limit).toBeNull(); const second = await prepared.bridge!.recordUsage!({ inputTokens: 50, outputTokens: 5 }); expect(second.inputTokens).toBe(150); expect(second.outputTokens).toBe(25); }); test('★ 用量落进事件流,跨进程读回来还在(不是进程内计数)', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '持久化测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.recordUsage!({ inputTokens: 777, outputTokens: 88 }); // 重新从 store 读(模拟 resume:账本重放不会重新执行 agent 调用, // 已花掉的钱必须从持久层拿回来,否则预算闸永远不触发)。 const scope = { workspaceId: 'workspace-1', sessionId: 'session-1' }; const reloaded = await runtime.get(scope); expect(reloaded?.usage.inputTokens).toBe(777); expect(reloaded?.usage.outputTokens).toBe(88); }); test('★ 改预算 = 新契约版本,已消耗量不重置', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '预算改版测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.recordUsage!({ inputTokens: 1_000, outputTokens: 100 }); const before = await prepared.bridge!.updateContract({ objective: '预算改版测试', tokenBudget: 5_000, }); const after = await prepared.bridge!.recordUsage!({ inputTokens: 1, outputTokens: 1 }); expect(before.version).toBeGreaterThan(1); expect(after.limit).toBe(5_000); // 「加预算继续跑」是自然操作 —— 已花的 1000 不该被偷偷清零。 expect(after.inputTokens).toBe(1_001); }); test('★ update 显式改预算时保留其它契约字段', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '保留契约字段', checks: '测试通过', token_budget: 1_000 }, options, ); await prepared.bridge!.updateContract({ objective: '保留契约字段', deliverables: ['交付代码'], scope: '当前工作区', sourceRefs: ['issue-42'], tokenBudget: 1_000, }); await prepared.bridge!.finish({ status: 'stopped', blocker: '暂停' }); const updated = await prepareGoalCommand( { action: 'update', objective: '保留契约字段(修订)', token_budget: 2_000 }, options, ); expect(updated.handled).toBe(false); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); const contract = goal ? runtime.currentContract(goal) : null; expect(contract).toMatchObject({ objective: '保留契约字段(修订)', deliverables: ['交付代码'], scope: '当前工作区', sourceRefs: ['issue-42'], tokenBudget: 2_000, }); }); }); /** * ── usage_limited(A5)──────────────────────────────────────────────── * * 这个状态此前只在 TRANSITIONS 与 types 里声明,**没有任何代码能推到它**, * 而 minimal-desktop/src/App.tsx 已经在渲染它 —— 一个永远不会发生的 UI 分支。 */ describe('goal bridge —— 服务端配额耗尽落 usage_limited', () => { test('★ 配额类失败 → usage_limited(不是笼统的 failed)', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '配额测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.finish({ status: 'failed', blocker: '在线模型请求失败:TOKEN_QUOTA_EXHAUSTED Token 额度已用尽', }); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); expect(goal?.status).toBe('usage_limited'); // 可恢复:解决授权后能回到 active(TRANSITIONS 允许)。 expect(goal?.statusReason).toContain('TOKEN_QUOTA_EXHAUSTED'); }); test('★ 普通失败不该被误判成配额问题', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '普通失败测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.finish({ status: 'failed', blocker: '脚本第 12 行抛错:文件不存在', }); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); // 普通失败让 Goal 留在 active(可以再起一次 attempt),不是 usage_limited。 expect(goal?.status).not.toBe('usage_limited'); }); }); /** * ── budget_limited 真的可达(A3 收口)────────────────────────────────── * * 复核发现的真实缺口:`budget_limited` 在 TRANSITIONS 和类型里都声明了, * `workflows/goal/workflow.mjs` 也确实会把 `status='budget_limited'` 写进 STATUS.json, * 但脚本随后统一 `throw new Error(...)`,runner 的通用 catch 一律记 `status:'failed'`, * `finishAttempt` 把 failed 派生成 `blocked`——而 TRANSITIONS 里根本没有 * `blocked → budget_limited` 这条边。整条链路走一遍,Goal 永远停在 blocked, * `budget_limited` 从声明到落地之间没有任何代码路径。 * * 修法:工作流在 Error 上挂 `workflowOutcome` 属性传结构化信息 → runner 原样 * 转发成 `finish({..., outcome})` → 这里按 * `statusMapping.ts::OUTCOME_TO_ATTEMPT` 精化成 `'stopped'` → `finishAttempt` 派生成 * `paused` → 再精化成 `budget_limited`(新增的 `paused → budget_limited` 边)。 */ describe('goal bridge —— 预算耗尽落 budget_limited(不是 blocked,也不是普通 paused)', () => { test('★ 带 outcome:budget_limited 的 stopped → Goal 落 budget_limited', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '预算耗尽测试', checks: 'shell:exit 0' }, options, ); // 模拟 workflow.mjs 的真实调用形状:runner 把脚本 Error 上的 workflowOutcome // 原样转发给 bridge.finish,status 恒是 runner 自己的通用默认值 'failed'。 await prepared.bridge!.finish({ status: 'failed', blocker: '💰 token 预算用尽,已停在轮次边界', outcome: 'budget_limited', }); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); expect(goal?.status).toBe('budget_limited'); expect(goal?.status).not.toBe('blocked'); // 可恢复:TRANSITIONS 允许 budget_limited → active,加预算后能续跑。 const resumed = await prepareGoalCommand({ action: 'resume' }, options); expect(resumed.handled).toBe(false); }); test('用户主动暂停(无 outcome)仍然落 paused,不会被误判成 budget_limited', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '普通暂停测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.finish({ status: 'stopped', blocker: '用户停止,现场已保留' }); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); expect(goal?.status).toBe('paused'); expect(goal?.status).not.toBe('budget_limited'); }); test('未知 outcome 值不精化,退回 runner 传入的 status(防御未来新增结局忘了同步)', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '未知结局测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.finish({ status: 'failed', blocker: '未知原因', outcome: 'some_future_outcome', }); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); expect(goal?.status).toBe('blocked'); }); }); /** * ── resume 不再静默清空预算(A4 收口)────────────────────────────────── * * 复核发现的真实缺口:workflow.mjs 每次都无条件把 * `Number(args.token_budget) > 0 ? Number(args.token_budget) : null` 写进新契约版本。 * resume/rework 时如果调用方没有重新传 token_budget(文档说的就是不需要重传), * `args.token_budget` 是 undefined → 新契约的预算被静默写成 null(不限), * 「用尽后加预算续跑」的断点续跑设计对用户完全不可见地失效了。 */ describe('goal 控制器 —— resume 沿用已有预算,不静默清零', () => { test('★ resume 不显式传 token_budget 时,沿用上一版契约的预算', async () => { const { runtime, options } = await harness(); const prepared = await prepareGoalCommand( { objective: '预算续跑测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.updateContract({ objective: '预算续跑测试', tokenBudget: 42_000 }); await prepared.bridge!.finish({ status: 'failed', blocker: '预算耗尽', outcome: 'budget_limited', }); // resume 时不传 token_budget —— 这正是文档描述的用户操作: // 「加预算后用同一目标重跑即可从这里继续」,不改预算就不用重复传参。 const resumed = await prepareGoalCommand({ action: 'resume' }, options); expect(resumed.inputs.token_budget).toBe(42_000); const goal = await runtime.get({ workspaceId: 'workspace-1', sessionId: 'session-1' }); expect(goal?.status).toBe('active'); }); test('resume 显式传新预算时,新值优先于旧契约的预算', async () => { const { options } = await harness(); const prepared = await prepareGoalCommand( { objective: '预算改值测试', checks: 'shell:exit 0' }, options, ); await prepared.bridge!.updateContract({ objective: '预算改值测试', tokenBudget: 1_000 }); await prepared.bridge!.finish({ status: 'failed', blocker: '预算耗尽', outcome: 'budget_limited', }); const resumed = await prepareGoalCommand( { action: 'resume', token_budget: 99_000 }, options, ); expect(resumed.inputs.token_budget).toBe(99_000); }); });