Files
SupplierSystem/server/tests/assistantPlan.test.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

302 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import {
ASSISTANT_PLAN_MAX_STEPS,
ASSISTANT_PLAN_RETRIES,
PLAN_TOOL_NAME,
buildPlanToolSchema,
isRetryablePlanFailure,
parsePlanSteps,
renderPlanResult,
runPlanSteps,
validatePlanSteps,
type PlanStep,
} from '../src/mcp/assistantPlan';
/**
* L1「计划执行」(P2b-6,2026-09-23):`plan_steps` 结构化计划 + 服务端按步执行 + 瞬时失败重试。
* 最重要的一条:**写能力绝不允许进计划**(写操作必须单独走待确认单 + 用户确认)。
* 设计:docs/design/20260923-assistant-p2b-summary-plan-sse.md §2
*/
const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8');
const step = (id: string, capability: string, args: Record<string, unknown> = {}): PlanStep => ({
id,
capability,
args,
});
describe('parsePlanSteps(归一化与上限)', () => {
it('缺 id 自动编号,args 缺省为空对象', () => {
const parsed = parsePlanSteps({ goal: '看订单', steps: [{ capability: 'list_orders' }] });
expect(parsed.ok).toBe(true);
if (!parsed.ok) return;
expect(parsed.steps).toEqual([{ id: 'step1', capability: 'list_orders', args: {}, why: undefined }]);
});
it('空计划 / 缺 capability / id 重复 / args 非对象 全部拒绝', () => {
expect(parsePlanSteps({ goal: 'x', steps: [] }).ok).toBe(false);
expect(parsePlanSteps({ goal: 'x', steps: [{ args: {} }] }).ok).toBe(false);
expect(
parsePlanSteps({
goal: 'x',
steps: [
{ id: 'a', capability: 'list_orders' },
{ id: 'a', capability: 'list_customers' },
],
}).ok
).toBe(false);
expect(parsePlanSteps({ goal: 'x', steps: [{ capability: 'list_orders', args: [1, 2] }] }).ok).toBe(false);
});
it('超过步数上限直接拒绝(不问模型、不执行)', () => {
const steps = Array.from({ length: ASSISTANT_PLAN_MAX_STEPS + 1 }, (_, i) => ({
capability: 'list_orders',
id: `s${i}`,
}));
const parsed = parsePlanSteps({ goal: 'x', steps });
expect(parsed.ok).toBe(false);
if (!parsed.ok) expect(parsed.message).toContain(`最多 ${ASSISTANT_PLAN_MAX_STEPS} 步`);
});
it('continue_on_error 默认 false', () => {
const parsed = parsePlanSteps({ goal: 'x', steps: [{ capability: 'list_orders' }] });
expect(parsed.ok && parsed.continueOnError).toBe(false);
});
});
describe('validatePlanSteps(安全边界)', () => {
const effectOf = (name: string) => (name.startsWith('list_') ? 'read' : name.startsWith('create_') ? 'write' : null);
it('【核心】写能力必须被拒绝(写操作只能单独让用户确认)', () => {
const result = validatePlanSteps([step('a', 'create_after_sale')], {
allowedCapabilities: ['create_after_sale'],
effectOf,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.message).toContain('只读');
expect(result.message).toContain('用户确认');
}
});
it('不在本轮工具白名单里的能力被拒绝(不做字符串拼接绕过)', () => {
const result = validatePlanSteps([step('a', 'list_orders')], {
allowedCapabilities: ['list_customers'],
effectOf,
});
expect(result.ok).toBe(false);
});
it('不允许嵌套 plan_steps', () => {
const result = validatePlanSteps([step('a', PLAN_TOOL_NAME)], {
allowedCapabilities: [PLAN_TOOL_NAME],
effectOf: () => 'read',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.message).toContain('嵌套');
});
it('全只读且在白名单内 → 通过', () => {
expect(
validatePlanSteps([step('a', 'list_orders'), step('b', 'list_customers')], {
allowedCapabilities: ['list_orders', 'list_customers'],
effectOf,
}).ok
).toBe(true);
});
});
describe('runPlanSteps(按序执行 + 重试)', () => {
it('按给定顺序串行执行,全部成功则 ok', async () => {
const seen: string[] = [];
const result = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders'), step('b', 'list_customers')],
execute: async (s) => {
seen.push(s.id);
return { ok: true, data: { id: s.id } };
},
});
expect(seen).toEqual(['a', 'b']);
expect(result.ok).toBe(true);
expect(result.steps.map((row) => row.ok)).toEqual([true, true]);
});
it('瞬时错误重试后成功(attempts=2),业务失败不重试', async () => {
let attempts = 0;
const retried = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders')],
execute: async () => {
attempts += 1;
return attempts === 1 ? { ok: false, code: 'server_error', message: 'db 抖动' } : { ok: true, data: {} };
},
});
expect(attempts).toBe(2);
expect(retried.steps[0]).toMatchObject({ ok: true, attempts: 2 });
let bizAttempts = 0;
const biz = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders')],
execute: async () => {
bizAttempts += 1;
return { ok: false, code: 'forbidden', message: '无权' };
},
});
expect(bizAttempts).toBe(1);
expect(biz.steps[0]).toMatchObject({ ok: false, attempts: 1, code: 'forbidden' });
});
it('重试次数受 retryLimit 限制(默认 1 次)', async () => {
let attempts = 0;
const result = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders')],
execute: async () => {
attempts += 1;
return { ok: false, code: 'timeout', message: '超时' };
},
});
expect(attempts).toBe(ASSISTANT_PLAN_RETRIES + 1);
expect(result.ok).toBe(false);
});
it('抛异常也算瞬时失败并可重试', async () => {
let attempts = 0;
const result = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders')],
execute: async () => {
attempts += 1;
if (attempts === 1) throw new Error('boom');
return { ok: true, data: { ok: 1 } };
},
});
expect(attempts).toBe(2);
expect(result.steps[0].ok).toBe(true);
});
it('默认首个失败即停止,剩余步骤标记 skipped;continue_on_error 时继续', async () => {
const stop = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders'), step('b', 'list_customers')],
execute: async (s) => (s.id === 'a' ? { ok: false, code: 'forbidden', message: '无权' } : { ok: true, data: {} }),
});
expect(stop.stoppedEarly).toBe(true);
expect(stop.steps[1]).toMatchObject({ skipped: true, attempts: 0 });
expect(stop.ok).toBe(false);
const cont = await runPlanSteps({
goal: 'g',
continueOnError: true,
steps: [step('a', 'list_orders'), step('b', 'list_customers')],
execute: async (s) => (s.id === 'a' ? { ok: false, code: 'forbidden', message: '无权' } : { ok: true, data: {} }),
});
expect(cont.steps[1]).toMatchObject({ ok: true });
expect(cont.stoppedEarly).toBe(false);
});
it('onStep 每步回调一次(含 skipped),便于落 trace/进度', async () => {
const onStep = vi.fn();
await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders'), step('b', 'list_customers')],
onStep,
execute: async (s) => (s.id === 'a' ? { ok: false, code: 'forbidden', message: '无权' } : { ok: true, data: {} }),
});
expect(onStep).toHaveBeenCalledTimes(2);
expect(onStep.mock.calls[1][0]).toMatchObject({ skipped: true });
});
it('retryable 判定集合:瞬时错误重试,业务错误不重试', () => {
expect(isRetryablePlanFailure('server_error')).toBe(true);
expect(isRetryablePlanFailure('timeout')).toBe(true);
expect(isRetryablePlanFailure('forbidden')).toBe(false);
expect(isRetryablePlanFailure('need_input')).toBe(false);
expect(isRetryablePlanFailure(undefined)).toBe(false);
});
});
describe('renderPlanResult(回灌话术)', () => {
it('成功:列出各步并提示直接作答;失败:要求如实说明、不要编造', async () => {
const okRun = await runPlanSteps({
goal: '订单+入库',
steps: [step('a', 'list_orders')],
execute: async () => ({ ok: true, data: {} }),
});
const okText = renderPlanResult(okRun);
expect(okText).toContain('计划「订单+入库」执行完成');
expect(okText).toContain('list_orders');
expect(okText).toContain('直接回答用户');
const failRun = await runPlanSteps({
goal: '订单+入库',
steps: [step('a', 'list_orders'), step('b', 'list_customers')],
execute: async () => ({ ok: false, code: 'forbidden', message: '无权' }),
});
const failText = renderPlanResult(failRun);
expect(failText).toContain('未全部完成');
expect(failText).toContain('不要编造');
expect(failText).toContain('未执行');
});
it('重试过的步骤会标注重试次数', async () => {
let n = 0;
const run = await runPlanSteps({
goal: 'g',
steps: [step('a', 'list_orders')],
execute: async () => {
n += 1;
return n === 1 ? { ok: false, code: 'server_error', message: 'x' } : { ok: true, data: {} };
},
});
expect(renderPlanResult(run)).toContain('重试 1 次');
});
});
describe('tool schema 与宿主接线棘轮', () => {
it('plan_steps schema:只读/步数上限写进描述,steps 必填', () => {
const schema = buildPlanToolSchema();
expect(schema.name).toBe(PLAN_TOOL_NAME);
expect(schema.description).toContain('只读');
expect(schema.description).toContain(`最多 ${ASSISTANT_PLAN_MAX_STEPS} 步`);
const required = (schema.inputSchema as { required?: string[] }).required || [];
expect(required).toContain('steps');
expect(required).toContain('goal');
});
it('宿主:plan_steps 是合成工具(不进能力目录),命中时不调 executeCapability(plan_steps)', () => {
const host = read('src/mcp/orderEntryAgentHost.ts');
expect(host).toContain('ASSISTANT_PLAN_ENABLED ? [buildPlanToolSchema()] : []');
// 白名单必须是"该账号在该端可用的全部能力"(跨模块计划才有意义),而不是本轮路由到的那两个模块
expect(host).toContain('listCapabilityToolSchemas({ ctx: input.ctx, surface }).map((row) => row.name)');
expect(host).toContain('allowedCapabilities: planCapabilityWhitelist,');
expect(host).toContain('if (task.name === PLAN_TOOL_NAME)');
expect(host).toContain('await runPlanTask(task.args)');
expect(host).not.toContain("executeCapability(PLAN_TOOL_NAME");
// 每步都进 tool_trace(前端/用量可见),并推进工作集
expect(host).toContain('name: `plan:${outcome.capability}`');
expect(host).toContain('budget.noteProgress(true)');
// 分层:宿主不认识落库/摘要服务
expect(host).not.toContain('assistantChatLogService');
expect(host).not.toContain('assistantSummaryService');
});
it('能力目录里没有 plan_steps(避免污染 listCapableModuleIds 与既有路由 pin)', () => {
const builtins = read('src/capabilities/registerBuiltins.ts');
expect(builtins).not.toContain('plan_steps');
const plan = read('src/mcp/assistantPlan.ts');
expect(plan).not.toContain('registerCapability');
});
it('系统提示在开启时告知模型"多步任务先给计划"(关闭时不多这一句)', () => {
const host = read('src/mcp/orderEntryAgentHost.ts');
expect(host).toContain('const planNote = ASSISTANT_PLAN_ENABLED');
expect(host).toContain('先调用 ${PLAN_TOOL_NAME} 给出计划');
});
});