agent-console-smoke-test.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. const assert = require('assert/strict');
  2. const fs = require('fs');
  3. const os = require('os');
  4. const path = require('path');
  5. const { DatabaseSync } = require('node:sqlite');
  6. const { AgentWorkbenchDb } = require('../mcp/src/core/agent-workbench-db');
  7. const { AgentWorkbenchService } = require('../mcp/src/core/agent-workbench-service');
  8. const { createCustomerTaskOfficialSync } = require('../mcp/src/core/customer-task-official-sync');
  9. const { evaluatePolledMessage, roomIdOf } = require('../mcp/src/core/agent-poller-policy');
  10. const {
  11. ClaudeCodeClient,
  12. ClaudeCodeSessionStore,
  13. buildClaudeSessionName,
  14. claudeSessionResetReason,
  15. enforceAuthoritativeGrounding,
  16. extractExplicitCustomerIntelligence,
  17. isNoReplyNeededMessage,
  18. parseClaudeProcessResult,
  19. resolveClaudeExecutable,
  20. selectAuthoritativeHistory,
  21. } = require('../mcp/src/core/agent-runtime');
  22. const { getCustomerSessionGuide } = require('../mcp/src/core/agent-session-guide');
  23. const { FmodeQiweiClient } = require('../mcp/src/providers/fmode-agent-transport');
  24. const { normalizeAllowlistIds, normalizeAllowlistContact } = require('../mcp/src/core/allowlist-config');
  25. const { GroupAgentService } = require('../mcp/src/dashboard/group-agent-service');
  26. const { friendlyAgentError } = require('../mcp/src/core/agent-error-message');
  27. const results = [];
  28. function setup({ paused = false, defaultMode = 'review', agentRun } = {}) {
  29. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-smoke-'));
  30. const db = new AgentWorkbenchDb(path.join(dir, 'test.db'), {
  31. globalPaused: paused,
  32. defaultMode,
  33. autoSendConfidence: 0.88,
  34. });
  35. const sent = [];
  36. const qiwei = {
  37. isConfigured: () => true,
  38. async sendText(toId, content) {
  39. sent.push({ toId, content });
  40. return { isSendSuccess: true };
  41. },
  42. };
  43. const agent = {
  44. async run(input) {
  45. if (agentRun) return agentRun(input);
  46. return {
  47. content: '这是 Agent 基于知识检索生成的草稿',
  48. confidence: 0.91,
  49. intent: '购房咨询',
  50. reason: '命中企业规则与 FAQ',
  51. requiresHuman: false,
  52. profileUpdates: { intent: '购房' },
  53. citations: [{ id: 'faq.md#1', source: 'faq.md', heading: 'Agent 能做什么' }],
  54. toolTrace: [{ tool: 'search_knowledge', args: { query: '购房咨询' }, result: [] }],
  55. };
  56. },
  57. };
  58. const config = {
  59. agent: { apiKey: 'smoke-only', model: 'stub-model', provider: 'stub' },
  60. qiwei: { allowedSenders: ['contact-1'] },
  61. };
  62. const service = new AgentWorkbenchService({ db, agent, qiwei, config });
  63. return {
  64. dir,
  65. db,
  66. sent,
  67. service,
  68. close() {
  69. db.close();
  70. fs.rmSync(dir, { recursive: true, force: true });
  71. },
  72. };
  73. }
  74. async function check(name, fn) {
  75. await fn();
  76. results.push({ name, status: 'passed' });
  77. }
  78. async function main() {
  79. await check('invalid contact names cannot overwrite a real customer name', async () => {
  80. const ctx = setup();
  81. try {
  82. const original = ctx.db.ensureConversation('contact-name-test', 'Valid Customer');
  83. const corrupted = ctx.db.ensureConversation('contact-name-test', '??????');
  84. assert.equal(corrupted.id, original.id);
  85. assert.equal(corrupted.contact_name, 'Valid Customer');
  86. const renamed = ctx.db.ensureConversation('contact-name-test', 'Renamed Customer');
  87. assert.equal(renamed.contact_name, 'Renamed Customer');
  88. const unnamed = ctx.db.ensureConversation('contact-unnamed-test', '????');
  89. assert.equal(unnamed.contact_name, '');
  90. } finally { ctx.close(); }
  91. });
  92. await check('Claude Code 原始错误会转换为可操作的用户提示', async () => {
  93. assert.equal(friendlyAgentError('403 reached your usage limit for this billing cycle').code, 'quota_exhausted');
  94. assert.match(friendlyAgentError('403 reached your usage limit for this billing cycle').message, /额度不足/);
  95. assert.equal(friendlyAgentError('Failed to authenticate: invalid API key').code, 'authentication_failed');
  96. assert.equal(friendlyAgentError('spawn claude ENOENT').code, 'cli_not_found');
  97. assert.equal(friendlyAgentError('request timed out').code, 'timeout');
  98. });
  99. await check('白名单选择会去重并拒绝不安全的联系人 ID', async () => {
  100. assert.deepEqual(normalizeAllowlistIds(['contact-1', ' contact-1 ', 'wm_test:2']), ['contact-1', 'wm_test:2']);
  101. assert.throws(() => normalizeAllowlistIds(['contact-1\nINJECTED=true']), /联系人 ID 格式无效/);
  102. assert.deepEqual(normalizeAllowlistContact({ userId: 'contact-1', remark: '刘总', corpName: '示例公司' }), {
  103. id: 'contact-1', displayName: '刘总', remark: '刘总', company: '示例公司'
  104. });
  105. });
  106. await check('Agent 企微传输统一走 Fmode 网关与登录专用端点', async () => {
  107. const calls = [];
  108. const originalFetch = global.fetch;
  109. global.fetch = async (url, options = {}) => {
  110. const parsedBody = options.body && typeof options.body === 'string' ? JSON.parse(options.body) : null;
  111. calls.push({ url: String(url), options, body: parsedBody });
  112. if (String(url).endsWith('/doFileApi')) {
  113. return { ok: true, status: 200, async text() { return JSON.stringify({ code: 0, data: { data: { fileId: 'file-voice', fileAesKey: 'aes-voice', fileSize: 128 } } }); } };
  114. }
  115. const loginStatus = String(url).includes('/login/status');
  116. let payload;
  117. if (loginStatus) {
  118. payload = { code: 0, data: { configured: true, online: true, statusCode: 2, detail: { nickname: '演示账号' } } };
  119. } else if (parsedBody?.method === '/contact/getWxContactList') {
  120. payload = { code: 0, data: { data: { currentSeq: 9, contactCount: 1, hasMore: false, contactList: [{ userId: 'contact-1' }] } } };
  121. } else if (parsedBody?.method === '/contact/batchGetUserinfo') {
  122. payload = { code: 0, data: { data: { contactList: [{ userId: 'contact-1', nickname: '测试客户' }] } } };
  123. } else {
  124. payload = { code: 0, data: { data: { isSendSuccess: true, syncMsgList: [], travelSyncKey: 9 } } };
  125. }
  126. return {
  127. ok: true,
  128. status: 200,
  129. async text() { return JSON.stringify(payload); },
  130. };
  131. };
  132. try {
  133. const client = new FmodeQiweiClient({
  134. authToken: 'test-fmode-token',
  135. uid: 'uid-smoke',
  136. guid: 'guid-smoke',
  137. apiBase: 'https://gateway.example/api/qiwei',
  138. });
  139. const account = await client.checkLogin();
  140. await client.syncMessages(8, 50);
  141. const contacts = await client.listExternalContacts();
  142. await client.sendText('external-contact-1', '测试回复');
  143. const voiceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-voice-transport-'));
  144. const voicePath = path.join(voiceDir, 'voice.silk');
  145. fs.writeFileSync(voicePath, Buffer.from('#!SILK_V3'));
  146. const uploaded = await client.uploadVoiceFile(voicePath);
  147. await client.sendVoice('external-contact-1', { ...uploaded, voiceTime: 2 });
  148. fs.rmSync(voiceDir, { recursive: true, force: true });
  149. assert.equal(account.online, true);
  150. assert.equal(account.nickname, '演示账号');
  151. assert.match(calls[0].url, /\/login\/status\?uid=uid-smoke$/);
  152. assert.equal(calls[0].options.method, 'GET');
  153. assert.equal(calls[1].body.uid, 'uid-smoke');
  154. assert.equal(calls[1].body.method, '/msg/syncMsg');
  155. assert.equal(calls[1].body.params.guid, 'guid-smoke');
  156. assert.equal(contacts.contacts[0].nickname, '测试客户');
  157. assert.equal(calls[2].body.method, '/contact/getWxContactList');
  158. assert.equal(calls[3].body.method, '/contact/batchGetUserinfo');
  159. assert.equal(calls[4].body.method, '/msg/sendText');
  160. assert.equal(calls[4].options.headers.Authorization, 'Bearer test-fmode-token');
  161. assert.match(calls[5].url, /\/doFileApi$/);
  162. assert.equal(calls[6].body.method, '/msg/sendVoice');
  163. assert.equal(calls[6].body.params.voiceTime, 2);
  164. let failedSendAttempts = 0;
  165. global.fetch = async () => {
  166. failedSendAttempts += 1;
  167. throw new Error('ambiguous network failure');
  168. };
  169. await assert.rejects(() => client.sendVoice('external-contact-1', { ...uploaded, voiceTime: 2 }), /网络请求失败/);
  170. assert.equal(failedSendAttempts, 1);
  171. } finally {
  172. global.fetch = originalFetch;
  173. }
  174. });
  175. await check('多企微账号使用独立工作台数据库和 Claude Session', async () => {
  176. const { __testing } = require('../mcp/src/dashboard/agent-service');
  177. const accountA = { uid: 'account-a', guid: 'guid-a', nickname: '账号 A' };
  178. const accountB = { uid: 'account-b', guid: 'guid-b', nickname: '账号 B' };
  179. const keyA = __testing.accountRuntimeKey(accountA);
  180. const keyB = __testing.accountRuntimeKey(accountB);
  181. const configA = __testing.accountWorkbenchOverrides(accountA);
  182. const configB = __testing.accountWorkbenchOverrides(accountB);
  183. assert.notEqual(keyA, keyB);
  184. assert.notEqual(configA.dbPath, configB.dbPath);
  185. assert.notEqual(configA.agent.claudeSessionFile, configB.agent.claudeSessionFile);
  186. assert.equal(configA.qiwei.uid, accountA.uid);
  187. assert.equal(configB.qiwei.guid, accountB.guid);
  188. });
  189. await check('发送语音后会结算当前待审核草稿并关联语音消息', async () => {
  190. const { __testing } = require('../mcp/src/dashboard/agent-service');
  191. const draft = {
  192. id: 'draft-voice-1',
  193. conversation_id: 'conversation-1',
  194. status: 'pending',
  195. content: '原草稿',
  196. };
  197. const updates = [];
  198. const db = {
  199. getDraft(id) { return id === draft.id ? draft : null; },
  200. listDrafts() { return [draft]; },
  201. updateDraft(id, fields) {
  202. updates.push({ id, fields });
  203. return { ...draft, ...fields };
  204. },
  205. };
  206. const selected = __testing.pendingVoiceDraft(db, 'conversation-1', draft.id);
  207. const resolved = __testing.markVoiceDraftSent(db, selected, {
  208. content: '实际发送的语音内容',
  209. messageId: 'message-voice-1',
  210. });
  211. assert.equal(resolved.status, 'sent');
  212. assert.equal(resolved.content, '实际发送的语音内容');
  213. assert.equal(resolved.sent_message_id, 'message-voice-1');
  214. assert.equal(resolved.reviewer, 'human:voice');
  215. assert.equal(updates.length, 1);
  216. assert.throws(() => __testing.pendingVoiceDraft(db, 'another-conversation', draft.id), /当前会话不匹配/);
  217. });
  218. await check('启动监听保留当前审核策略,不自动切换会话模式', async () => {
  219. const { __testing } = require('../mcp/src/dashboard/agent-service');
  220. const calls = [];
  221. const target = {
  222. poller: {
  223. async start() {
  224. calls.push('poller.start');
  225. return { running: true, syncKey: 7 };
  226. }
  227. }
  228. };
  229. const result = await __testing.startListenerForWorkbench(target, { online: true, nickname: '测试账号' });
  230. assert.deepEqual(calls, ['poller.start']);
  231. assert.equal(result.status, 'ok');
  232. assert.equal(result.data.running, true);
  233. });
  234. await check('Claude Code 可从 Fmode Studio npm-global PATH 中发现', async () => {
  235. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-claude-path-'));
  236. const executable = process.platform === 'win32'
  237. ? path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe')
  238. : path.join(dir, 'claude');
  239. fs.mkdirSync(path.dirname(executable), { recursive: true });
  240. fs.writeFileSync(executable, 'smoke');
  241. const previousPath = process.env.PATH;
  242. try {
  243. process.env.PATH = `${dir}${path.delimiter}${previousPath || ''}`;
  244. assert.equal(resolveClaudeExecutable({}), executable);
  245. } finally {
  246. process.env.PATH = previousPath;
  247. fs.rmSync(dir, { recursive: true, force: true });
  248. }
  249. });
  250. await check('不同消息 ID 的同内容在 60 秒内只入库一次', async () => {
  251. const ctx = setup();
  252. try {
  253. const first = await ctx.service.ingestInbound({ externalId: 'm1', contactId: 'contact-1', contactName: '王刚', content: '我想咨询房源' });
  254. const duplicate = await ctx.service.ingestInbound({ externalId: 'm1-copy', contactId: 'contact-1', contactName: '王刚', content: '我想咨询房源' });
  255. assert.equal(first.status, 'pending_review');
  256. assert.equal(duplicate.status, 'duplicate_content');
  257. assert.equal(ctx.db.listMessages(first.conversation.id).length, 1);
  258. } finally { ctx.close(); }
  259. });
  260. await check('审核模式生成草稿但不自动外发', async () => {
  261. const ctx = setup();
  262. try {
  263. const result = await ctx.service.ingestInbound({ externalId: 'm2', contactId: 'contact-1', contactName: '王刚', content: '预算 150 万,想买三室' });
  264. assert.equal(result.status, 'pending_review');
  265. assert.equal(ctx.sent.length, 0);
  266. assert.equal(ctx.db.getDraft(result.draft.id).status, 'pending');
  267. assert.equal(result.draft.citations[0].source, 'faq.md');
  268. assert.equal(result.draft.tool_trace[0].tool, 'search_knowledge');
  269. } finally { ctx.close(); }
  270. });
  271. await check('批准草稿只发送一次,重复批准被拒绝', async () => {
  272. const ctx = setup();
  273. try {
  274. const result = await ctx.service.ingestInbound({ externalId: 'm3', contactId: 'contact-1', contactName: '王刚', content: '请给我一个建议' });
  275. await ctx.service.approveDraft(result.draft.id, { content: '人工编辑后的回复', actor: 'human' });
  276. await assert.rejects(() => ctx.service.approveDraft(result.draft.id, { actor: 'human' }), /不能重复发送/);
  277. assert.deepEqual(ctx.sent, [{ toId: 'contact-1', content: '人工编辑后的回复' }]);
  278. assert.equal(ctx.db.getDraft(result.draft.id).status, 'sent');
  279. } finally { ctx.close(); }
  280. });
  281. await check('全局暂停与人工接管都抑制 Agent', async () => {
  282. const ctx = setup({ paused: true });
  283. try {
  284. const paused = await ctx.service.ingestInbound({ externalId: 'm4', contactId: 'contact-1', contactName: '王刚', content: '暂停时消息' });
  285. assert.equal(paused.status, 'paused');
  286. ctx.service.setGlobal({ paused: false });
  287. ctx.service.setConversationMode(paused.conversation.id, 'human');
  288. const human = await ctx.service.ingestInbound({ externalId: 'm5', contactId: 'contact-1', contactName: '王刚', content: '人工接管时消息' });
  289. assert.equal(human.status, 'human');
  290. assert.equal(ctx.db.listDrafts().length, 0);
  291. assert.equal(ctx.sent.length, 0);
  292. } finally { ctx.close(); }
  293. });
  294. await check('Agent 上游失败只留审计,不生成伪回复、不外发', async () => {
  295. const ctx = setup({ agentRun: async () => { throw new Error('Agent 上游暂时不可用(HTTP 522)'); } });
  296. try {
  297. const result = await ctx.service.ingestInbound({ externalId: 'm6', contactId: 'contact-1', contactName: '王刚', content: '请推荐房源' });
  298. assert.equal(result.status, 'agent_failed');
  299. assert.equal(ctx.db.listDrafts().length, 0);
  300. assert.equal(ctx.sent.length, 0);
  301. assert.equal(ctx.db.latestAgentState(result.conversation.id).action, 'agent_failed');
  302. assert.match(result.error, /暂时无法完成/);
  303. const audit = ctx.db.listAudit(20, result.conversation.id).find(item => item.action === 'agent_failed');
  304. assert.equal(audit.detail.message, result.error);
  305. assert.equal(audit.detail.rawMessage, 'Agent 上游暂时不可用(HTTP 522)');
  306. } finally { ctx.close(); }
  307. });
  308. await check('确认消息无需调用模型、无需回复且会清除旧错误状态', async () => {
  309. let agentCalls = 0;
  310. const ctx = setup({ agentRun: async () => { agentCalls += 1; throw new Error('不应调用模型'); } });
  311. try {
  312. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  313. ctx.db.audit({ actor: 'agent', action: 'agent_failed', conversationId: conversation.id, detail: { message: '历史上游失败' } });
  314. const result = await ctx.service.ingestInbound({ externalId: 'm-ack', contactId: 'contact-1', contactName: '王刚', content: '收到' });
  315. assert.equal(result.status, 'no_reply_needed');
  316. assert.equal(agentCalls, 0);
  317. assert.equal(ctx.sent.length, 0);
  318. assert.equal(ctx.db.latestAgentState(conversation.id), null);
  319. assert.equal(ctx.db.latestAgentOutcome(conversation.id).action, 'agent_no_reply_needed');
  320. assert.equal(ctx.db.latestAgentOutcome(conversation.id).entityId, result.message.id);
  321. assert.equal(isNoReplyNeededMessage('好的。'), true);
  322. assert.equal(isNoReplyNeededMessage('地址确认好了吗'), false);
  323. } finally { ctx.close(); }
  324. });
  325. await check('Claude Code 预算超限时轮换客户 Session 并只重试一次', async () => {
  326. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-budget-reset-'));
  327. try {
  328. const client = new ClaudeCodeClient({
  329. claudeWorkdir: dir,
  330. claudeSessionFile: path.join(dir, 'sessions.json'),
  331. claudeMaxBudgetUsd: 0.35,
  332. claudeRetryMaxBudgetUsd: 1,
  333. });
  334. const sessionIds = [];
  335. const invokeOptions = [];
  336. client.invoke = async (_messages, _context, session, options = {}) => {
  337. sessionIds.push(session.id);
  338. invokeOptions.push(options);
  339. if (sessionIds.length === 1) throw new Error('Claude Code 调用失败(退出码 1):error_max_budget_usd');
  340. return { content: '{}', claudeCode: { resumed: false } };
  341. };
  342. const result = await client.complete([{ role: 'user', content: '请推荐房源' }], [], { conversation: { id: 'conversation-budget', contact_name: '王刚' } });
  343. assert.equal(sessionIds.length, 2);
  344. assert.notEqual(sessionIds[0], sessionIds[1]);
  345. assert.equal(invokeOptions[1].maxBudgetUsd, 1);
  346. assert.equal(result.claudeCode.sessionResetReason, 'budget_exceeded');
  347. assert.equal(claudeSessionResetReason(new Error('error_max_budget_usd')), 'budget_exceeded');
  348. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  349. });
  350. await check('Claude Code 客服调用使用精简模式与低推理强度', async () => {
  351. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-claude-bare-'));
  352. try {
  353. let capturedArgs = [];
  354. const client = new ClaudeCodeClient({
  355. claudeWorkdir: dir,
  356. claudeSessionFile: path.join(dir, 'sessions.json'),
  357. claudeBare: true,
  358. claudeEffort: 'low',
  359. claudeTools: 'Read,Glob,Grep',
  360. model: 'deepseek-v4-pro',
  361. });
  362. client.runProcess = async args => {
  363. capturedArgs = args;
  364. return { structured_output: { reply: '测试草稿' }, duration_ms: 1, total_cost_usd: 0.01 };
  365. };
  366. await client.invoke([{ role: 'system', content: '测试' }, { role: 'user', content: '推荐房源' }], {}, { id: '33333333-3333-4333-8333-333333333333', initialized: false });
  367. assert(capturedArgs.includes('--bare'));
  368. assert.equal(capturedArgs[capturedArgs.indexOf('--effort') + 1], 'low');
  369. assert.equal(capturedArgs[capturedArgs.indexOf('--tools') + 1], 'Read,Glob,Grep');
  370. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  371. });
  372. await check('Claude Code 已完成结构化输出时不因末尾预算退出码丢弃草稿', async () => {
  373. const recovered = parseClaudeProcessResult(JSON.stringify({
  374. is_error: true,
  375. subtype: 'error_max_budget_usd',
  376. structured_output: {
  377. reply: '已经生成的客服草稿',
  378. confidence: 0.75,
  379. intent: '继续推荐',
  380. },
  381. }), '', 1);
  382. assert.equal(recovered.error, undefined);
  383. assert.equal(recovered.payload.is_error, false);
  384. assert.equal(recovered.payload.structured_output.reply, '已经生成的客服草稿');
  385. assert.equal(recovered.payload.process_warning.detail, 'error_max_budget_usd');
  386. const failed = parseClaudeProcessResult(JSON.stringify({ is_error: true, subtype: 'error_max_budget_usd' }), '', 1);
  387. assert.match(failed.error, /error_max_budget_usd/);
  388. });
  389. await check('非白名单联系人被忽略且不能人工发送', async () => {
  390. const ctx = setup();
  391. try {
  392. const ignored = await ctx.service.ingestInbound({ externalId: 'm7', contactId: 'contact-2', contactName: '其他人', content: '你好' });
  393. assert.equal(ignored.status, 'ignored_not_allowlisted');
  394. assert.equal(ctx.db.listConversations().length, 0);
  395. const allowed = ctx.db.ensureConversation('contact-1', '王刚');
  396. ctx.db.db.prepare('UPDATE conversations SET contact_id=? WHERE id=?').run('contact-2', allowed.id);
  397. await assert.rejects(() => ctx.service.manualSend(allowed.id, '测试'), /不在测试白名单/);
  398. assert.equal(ctx.sent.length, 0);
  399. } finally { ctx.close(); }
  400. });
  401. await check('项目主控关联下每个客户绑定独立 Claude Code Session', async () => {
  402. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-session-map-'));
  403. try {
  404. const filePath = path.join(dir, 'sessions.json');
  405. const store = new ClaudeCodeSessionStore(filePath, {
  406. projectId: 'project-smoke',
  407. projectRoot: dir,
  408. mainSessionId: '11111111-1111-4111-8111-111111111111',
  409. });
  410. const first = store.ensure('conversation-a', { customerName: '王刚', displayName: '企微客户-王刚-a001' });
  411. const second = store.ensure('conversation-b', { customerName: '李女士', displayName: '企微客户-李女士-b002' });
  412. assert.notEqual(first.id, second.id);
  413. assert.equal(first.parentControllerSessionId, second.parentControllerSessionId);
  414. assert.equal(first.projectId, 'project-smoke');
  415. assert.equal(first.customerName, '王刚');
  416. assert.equal(first.displayName, '企微客户-王刚-a001');
  417. const persisted = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  418. assert.equal(persisted.project.boundMainSessionId, '11111111-1111-4111-8111-111111111111');
  419. assert.equal(Object.keys(persisted.sessions).length, 2);
  420. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  421. });
  422. await check('Claude Code 只采用本轮权威上下文并使用客户可识别会话名', async () => {
  423. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-prompt-boundary-'));
  424. try {
  425. const messages = [
  426. { role: 'user', content: '我是两个两个买' },
  427. { role: 'user', content: '加进去这个api服务就不用管了' },
  428. { role: 'assistant', content: '新北区有4套三室房,请问预算是多少?' },
  429. { role: 'user', content: '200万吧' },
  430. ];
  431. const authoritative = selectAuthoritativeHistory(messages);
  432. assert.deepEqual(authoritative.map(item => item.content), [
  433. '新北区有4套三室房,请问预算是多少?',
  434. '200万吧',
  435. ]);
  436. const client = new ClaudeCodeClient({
  437. claudeSessionFile: path.join(dir, 'sessions.json'),
  438. claudeWorkdir: dir,
  439. });
  440. const prompt = client.buildPrompt(messages, { profile: { profile: {} } });
  441. assert.match(prompt, /本轮有效会话/);
  442. assert.match(prompt, /200万吧/);
  443. assert.doesNotMatch(prompt, /两个两个买/);
  444. assert.doesNotMatch(prompt, /api服务/);
  445. const sessionName = buildClaudeSessionName({ conversation: { contact_name: '王刚' } }, 'conversation-a');
  446. assert.match(sessionName, /^企微客户-王刚-[a-f0-9]{4}$/);
  447. assert.doesNotMatch(sessionName, /conversation-a/);
  448. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  449. });
  450. await check('Session 残留原话被证据闸门拦截并降级为人工确认', async () => {
  451. const history = [
  452. { role: 'assistant', content: '新北区有4套三室房,请问预算是多少?' },
  453. { role: 'user', content: '200万吧' },
  454. ];
  455. const guarded = enforceAuthoritativeGrounding({
  456. reply: '您之前提到“两个两个买”,是想一次买两套吗?',
  457. confidence: 0.9,
  458. intent: '预算确认',
  459. reason: '客户之前说“两个两个买”。',
  460. requiresHuman: false,
  461. }, history, { preferredRegion: '新北区', layout: '三室', budgetWan: 200, budgetType: '待确认' }, '200万吧');
  462. assert.equal(guarded.requiresHuman, true);
  463. assert(guarded.confidence <= 0.68);
  464. assert.doesNotMatch(guarded.reply, /两个两个买|两套/);
  465. assert.match(guarded.reply, /新北区/);
  466. const intelligence = extractExplicitCustomerIntelligence('200万吧', { preferredRegion: '新北区', layout: '三室' }, {
  467. profileUpdates: { purchaseQuantity: 2, budgetWan: 200 },
  468. tasks: [{ type: 'purchase', title: '准备两套方案', evidence: '两个两个买' }],
  469. alerts: [{ type: 'high_intent', severity: 'high', title: '两套购买', evidence: '两个两个买' }],
  470. });
  471. assert.equal(intelligence.profileUpdates.purchaseQuantity, undefined);
  472. assert.equal(intelligence.profileUpdates.budgetWan, 200);
  473. assert.doesNotMatch(JSON.stringify(intelligence), /两个两个买|两套购买|准备两套方案/);
  474. });
  475. await check('客户 Session 指引主动返回可识别名称和安全打开命令', async () => {
  476. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-session-guide-'));
  477. try {
  478. const sessionFile = path.join(dir, 'sessions.json');
  479. fs.writeFileSync(sessionFile, JSON.stringify({
  480. version: 1,
  481. project: {},
  482. sessions: {
  483. 'conversation-a': {
  484. id: '22222222-2222-4222-8222-222222222222',
  485. role: 'customer-agent',
  486. initialized: true,
  487. displayName: '企微客户-王刚-a001',
  488. },
  489. },
  490. }), 'utf8');
  491. const guide = getCustomerSessionGuide({ id: 'conversation-a', contact_name: '王刚' }, { sessionFile });
  492. assert.equal(guide.ready, true);
  493. assert.equal(guide.displayName, '企微客户-王刚-a001');
  494. assert.match(guide.openCommand, /agent:session/);
  495. assert.match(guide.openCommand, /王刚/);
  496. assert.doesNotMatch(JSON.stringify(guide), /22222222/);
  497. assert.equal(guide.productionSessionProtected, true);
  498. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  499. });
  500. await check('监听消息持续沉淀客户画像、内部待办和预警', async () => {
  501. const housing = extractExplicitCustomerIntelligence('我想咨询一下新北区的三室房', {}, {});
  502. assert.equal(housing.profileUpdates.preferredRegion, '新北区');
  503. assert.equal(housing.profileUpdates.layout, '三室');
  504. const explicit = extractExplicitCustomerIntelligence('200万吧', { preferredRegion: '新北区', layout: '三室' }, {});
  505. assert.equal(explicit.profileUpdates.budgetWan, 200);
  506. assert(explicit.tasks.some(item => item.type === 'recommendation'));
  507. assert(explicit.alerts.some(item => item.type === 'high_intent'));
  508. const purpose = extractExplicitCustomerIntelligence('自己住吧', { budgetWan: 200 }, {});
  509. assert.equal(purpose.profileUpdates.purpose, '自住');
  510. const ctx = setup({ agentRun: async () => ({
  511. content: '好的,我再确认一下您的用途和时间计划。',
  512. confidence: 0.82,
  513. intent: '预算确认',
  514. reason: '客户给出明确预算,需要补齐用途和时间。',
  515. requiresHuman: false,
  516. profileUpdates: { budgetWan: 200, budgetType: '待确认' },
  517. tasks: [{ type: 'qualification', title: '确认用途与时间计划', owner: '待分配', dueAt: '', priority: 'high', reason: '关键信息待补齐', evidence: '200万吧' }],
  518. alerts: [{ type: 'high_intent', severity: 'high', title: '预算已明确', detail: '可以进入需求收敛阶段', evidence: '200万吧', recommendedAction: '确认用途与时间' }],
  519. citations: [],
  520. toolTrace: [],
  521. }) });
  522. try {
  523. const result = await ctx.service.ingestInbound({ externalId: 'm-intel', contactId: 'contact-1', contactName: '王刚', content: '200万吧' });
  524. assert.equal(result.status, 'pending_review');
  525. const detail = ctx.service.conversationDetail(result.conversation.id);
  526. assert.equal(detail.profile.profile.budgetWan, 200);
  527. assert.equal(detail.tasks.length, 1);
  528. assert.equal(detail.alerts.length, 1);
  529. assert.equal(ctx.sent.length, 0);
  530. } finally { ctx.close(); }
  531. });
  532. await check('监听重启后仍接收停机期间的白名单积压消息', async () => {
  533. const candidate = evaluatePolledMessage({
  534. msgType: 1,
  535. senderId: 'contact-1',
  536. timestamp: Math.floor(Date.now() / 1000) - 600,
  537. msgData: { content: '自己住吧' },
  538. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  539. assert.equal(candidate.eligible, true);
  540. assert.equal(candidate.content, '自己住吧');
  541. });
  542. await check('群聊与本账号消息不会串入白名单客户私聊', async () => {
  543. const group = evaluatePolledMessage({
  544. msgType: 2,
  545. senderId: 'contact-1',
  546. receiverId: 'self',
  547. fromRoomId: 'room-123',
  548. timestamp: Math.floor(Date.now() / 1000),
  549. msgData: { content: '@同事 请发会议录屏' },
  550. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  551. assert.equal(group.eligible, false);
  552. assert.equal(group.reason, 'group_message');
  553. assert.equal(group.roomId, 'room-123');
  554. assert.equal(roomIdOf({ fromRoomId: 0, roomId: '' }), '');
  555. const self = evaluatePolledMessage({
  556. msgType: 1,
  557. senderId: 'self',
  558. receiverId: 'contact-1',
  559. timestamp: Math.floor(Date.now() / 1000),
  560. msgData: { content: '我发出的私聊' },
  561. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  562. assert.equal(self.eligible, false);
  563. assert.equal(self.reason, 'self_message');
  564. const ctx = setup();
  565. try {
  566. const ignored = await ctx.service.ingestInbound({
  567. externalId: 'group-direct-entry',
  568. contactId: 'contact-1',
  569. contactName: '王刚',
  570. content: '群里的消息',
  571. raw: { fromRoomId: 'room-123', senderId: 'contact-1' },
  572. });
  573. assert.equal(ignored.status, 'ignored_group_message');
  574. assert.equal(ctx.db.listConversations().length, 0);
  575. const legacyGroup = ctx.db.ensureConversation('contact-1', '历史群聊');
  576. ctx.db.insertMessage({
  577. conversationId: legacyGroup.id,
  578. externalId: 'legacy-group-message',
  579. direction: 'inbound',
  580. senderType: 'customer',
  581. content: '旧数据中的群消息',
  582. raw: { fromRoomId: 'room-legacy', senderId: 'contact-1' },
  583. });
  584. await assert.rejects(() => ctx.service.manualSend(legacyGroup.id, '不应发送'), /群聊仅用于监控/);
  585. assert.equal(ctx.sent.length, 0);
  586. } finally { ctx.close(); }
  587. });
  588. await check('客户群支持人工审核与无视风险全自动两种独立模式', async () => {
  589. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-group-agent-smoke-'));
  590. const messages = [{
  591. msgId: 'group-message-1',
  592. senderId: 'customer-1',
  593. senderName: '张三',
  594. fromRoomId: 'r-1',
  595. content: '明天下午可以看房吗',
  596. timestamp: '2026-07-23T08:00:00.000Z',
  597. }];
  598. const sent = [];
  599. const sendAttempts = [];
  600. const agentInputs = [];
  601. let sendShouldFail = false;
  602. let agentResponse = {
  603. content: '可以的,请问您明天下午几点方便?',
  604. confidence: 0.88,
  605. intent: '预约看房',
  606. reason: '客户明确询问看房时间',
  607. requiresHuman: false,
  608. citations: [],
  609. toolTrace: [],
  610. };
  611. const runtime = {
  612. config: { qiwei: { selfUserId: 'self-1', nickname: '王顾问' } },
  613. agent: {
  614. async run(input) {
  615. agentInputs.push(input);
  616. return agentResponse;
  617. },
  618. },
  619. qiwei: {
  620. async sendText(toId, content) {
  621. sendAttempts.push({ toId, content });
  622. if (sendShouldFail) return { isSendSuccess: false };
  623. sent.push({ toId, content });
  624. return { isSendSuccess: true };
  625. },
  626. },
  627. };
  628. const service = new GroupAgentService({
  629. projectRoot: dir,
  630. statePath: path.join(dir, 'group-agent.json'),
  631. runtime,
  632. getAccount: () => ({ uid: 'account-1', userId: 'self-1', nickname: '王顾问' }),
  633. loadGroups: () => ({ 'r-1': { roomName: '张三买房服务群', customerName: '张三' } }),
  634. loadMessages: () => messages,
  635. appendMessage: (roomId, message) => { messages.push({ ...message, fromRoomId: roomId }); return 'memory'; },
  636. });
  637. try {
  638. assert.equal(service.publicState('r-1').mode, 'review');
  639. const generated = await service.generate('r-1');
  640. assert.equal(generated.status, 'pending_review');
  641. assert.equal(generated.draft.requiresHuman, true);
  642. assert.equal(sent.length, 0);
  643. assert.equal(agentInputs[0].channelType, 'group');
  644. assert.match(agentInputs[0].directPrompt, /企业微信群聊客服 Agent/);
  645. const approved = await service.approve('r-1', generated.draft.id, '可以的,张三,请问您明天下午几点方便?');
  646. assert.equal(approved.status, 'sent');
  647. assert.deepEqual(sent, [{ toId: 'r-1', content: '可以的,张三,请问您明天下午几点方便?' }]);
  648. assert.equal(service.publicState('r-1').pendingReply, null);
  649. assert.equal(service.publicState('r-1').messages.at(-1).role, 'human');
  650. await assert.rejects(() => service.approve('r-1', generated.draft.id, '重复发送'), /已经是 sent/);
  651. await assert.rejects(() => service.generate('unconfirmed-room'), /尚未确认为客户群/);
  652. assert.throws(() => service.setMode('r-1', 'auto'), /需要明确确认/);
  653. assert.equal(service.setMode('r-1', 'auto', 'AUTO_SEND_GROUP_MESSAGES').mode, 'auto');
  654. agentResponse = {
  655. content: '三点可以,我先为您登记。',
  656. confidence: 0.1,
  657. intent: '预约看房',
  658. reason: '低置信回复仍由全自动模式放行',
  659. requiresHuman: true,
  660. citations: [],
  661. toolTrace: [],
  662. };
  663. const ingested = await service.ingestPolledMessage({
  664. msgType: 1,
  665. msgServerId: 'group-message-2',
  666. seq: 2,
  667. senderId: 'customer-1',
  668. senderName: '张三',
  669. fromRoomId: 'r-1',
  670. msgData: { content: '三点可以吗' },
  671. timestamp: Math.floor(Date.now() / 1000),
  672. }, { selfUserId: 'self-1' });
  673. assert.equal(ingested.status, 'auto_sent');
  674. assert.equal(agentInputs.length, 2);
  675. assert.equal(sent.length, 2);
  676. assert.deepEqual(sent.at(-1), { toId: 'r-1', content: '三点可以,我先为您登记。' });
  677. assert.equal(service.publicState('r-1').pendingReply, null);
  678. assert.equal(service.publicState('r-1').lastOutcome.action, 'group_message_auto_sent');
  679. assert.equal(messages.at(-1).rawData.source, 'group_agent_auto');
  680. sendShouldFail = true;
  681. const failed = await service.ingestPolledMessage({
  682. msgType: 1,
  683. msgServerId: 'group-message-3',
  684. seq: 3,
  685. senderId: 'customer-1',
  686. senderName: '张三',
  687. fromRoomId: 'r-1',
  688. msgData: { content: '能发个定位吗' },
  689. timestamp: Math.floor(Date.now() / 1000) + 1,
  690. }, { selfUserId: 'self-1' });
  691. assert.equal(failed.status, 'pending_review');
  692. assert.equal(failed.autoSendFailed, true);
  693. assert.equal(sent.length, 2);
  694. assert.equal(sendAttempts.length, 3);
  695. assert(service.publicState('r-1').pendingReply);
  696. assert(service.publicState('r-1').sendError);
  697. sendShouldFail = false;
  698. assert.equal(service.setMode('r-1', 'review').mode, 'review');
  699. const reviewed = await service.ingestPolledMessage({
  700. msgType: 1,
  701. msgServerId: 'group-message-4',
  702. seq: 4,
  703. senderId: 'customer-1',
  704. senderName: '张三',
  705. fromRoomId: 'r-1',
  706. msgData: { content: '四点也可以' },
  707. timestamp: Math.floor(Date.now() / 1000) + 2,
  708. }, { selfUserId: 'self-1' });
  709. assert.equal(reviewed.status, 'pending_review');
  710. assert.equal(sent.length, 2);
  711. assert.equal(service.publicState('r-1').mode, 'review');
  712. } finally {
  713. fs.rmSync(dir, { recursive: true, force: true });
  714. }
  715. });
  716. await check('同一业务待办只保留一张卡并聚合多条依据', async () => {
  717. const ctx = setup();
  718. try {
  719. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  720. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '预算200万' }], 'message-a');
  721. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '区域新北区' }], 'message-b');
  722. const tasks = ctx.db.listCustomerTasks(conversation.id);
  723. assert.equal(tasks.length, 1);
  724. assert.deepEqual(JSON.parse(tasks[0].evidence_json).map(item => item.text), ['预算200万', '区域新北区']);
  725. } finally { ctx.close(); }
  726. });
  727. await check('用途和购置时间补齐后资格确认待办自动完成', async () => {
  728. let turn = 0;
  729. const ctx = setup({ agentRun: async () => {
  730. turn += 1;
  731. return {
  732. content: '信息已记录。', confidence: 0.8, intent: '需求确认', reason: '测试', requiresHuman: false,
  733. profileUpdates: turn === 1 ? { budgetWan: 200 } : { purpose: '自住', timeline: '三个月内' },
  734. tasks: turn === 1 ? [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '预算200万' }] : [],
  735. alerts: [], citations: [], toolTrace: [],
  736. };
  737. } });
  738. try {
  739. const first = await ctx.service.ingestInbound({ externalId: 'profile-a', contactId: 'contact-1', contactName: '王刚', content: '预算200万' });
  740. assert.equal(ctx.db.listCustomerTasks(first.conversation.id)[0].status, 'open');
  741. await ctx.service.ingestInbound({ externalId: 'profile-b', contactId: 'contact-1', contactName: '王刚', content: '自住,计划三个月内购买' });
  742. const qualification = ctx.db.listCustomerTasks(first.conversation.id).find(item => item.business_key === 'qualification:purpose_and_timeline');
  743. assert.equal(qualification.status, 'done');
  744. assert.equal(qualification.resolution_reason, 'profile_condition_resolved');
  745. } finally { ctx.close(); }
  746. });
  747. await check('发送房源方案后重点方案待办自动完成', async () => {
  748. const ctx = setup();
  749. try {
  750. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  751. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'recommendation:shortlist', managedBy: 'rule', type: 'recommendation', title: '按已确认条件筛选并发送重点方案', evidence: '预算、区域、户型已明确' }], 'message-c');
  752. await ctx.service.manualSend(conversation.id, '已经为您筛选了三套重点房源方案,请查收。');
  753. const task = ctx.db.listCustomerTasks(conversation.id).find(item => item.business_key === 'recommendation:shortlist');
  754. assert.equal(task.status, 'done');
  755. assert.equal(task.resolution_reason, 'manual_recommendation_sent');
  756. } finally { ctx.close(); }
  757. });
  758. await check('旧数据库导入时合并重复业务项且不丢依据', async () => {
  759. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-import-'));
  760. const sourcePath = path.join(dir, 'legacy.db');
  761. const targetPath = path.join(dir, 'target.db');
  762. let source = new AgentWorkbenchDb(sourcePath, { defaultMode: 'review' });
  763. const conversation = source.ensureConversation('legacy-contact', '历史客户');
  764. source.close();
  765. const raw = new DatabaseSync(sourcePath);
  766. raw.exec('DROP INDEX IF EXISTS idx_customer_tasks_business_key');
  767. const timestamp = new Date().toISOString();
  768. const insert = raw.prepare(`INSERT INTO customer_tasks(id,conversation_id,fingerprint,business_key,managed_by,type,title,status,evidence,evidence_json,created_at,updated_at)
  769. VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`);
  770. insert.run('legacy-task-a', conversation.id, 'legacy-fp-a', '', 'agent', 'qualification', '确认客户用途与购置时间', 'open', '预算200万', '[]', timestamp, timestamp);
  771. insert.run('legacy-task-b', conversation.id, 'legacy-fp-b', '', 'agent', 'qualification', '确认客户用途与购置时间', 'open', '区域新北区', '[]', timestamp, timestamp);
  772. raw.close();
  773. const target = new AgentWorkbenchDb(targetPath, { defaultMode: 'review' });
  774. try {
  775. const result = target.importCompatibleDatabase(sourcePath);
  776. assert.equal(result.imported, true);
  777. const tasks = target.listCustomerTasks(conversation.id);
  778. assert.equal(tasks.length, 1);
  779. assert.equal(tasks[0].business_key, 'qualification:purpose_and_timeline');
  780. assert.equal(JSON.parse(tasks[0].evidence_json).length, 2);
  781. } finally {
  782. target.close();
  783. fs.rmSync(dir, { recursive: true, force: true });
  784. }
  785. });
  786. await check('Claude Code 提示词读取统一待办和预警主账', async () => {
  787. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-prompt-'));
  788. try {
  789. const client = new ClaudeCodeClient({ claudeWorkdir: dir, claudeSessionFile: path.join(dir, 'sessions.json') });
  790. const prompt = client.buildPrompt([{ role: 'user', content: '继续推荐' }], { customerIntelligence: {
  791. tasks: [{ businessKey: 'recommendation:shortlist', title: '发送重点方案', status: 'open' }],
  792. alerts: [{ businessKey: 'high_intent:core_demand_ready', title: '高意向', status: 'open' }],
  793. } });
  794. assert.match(prompt, /当前未完成待办/);
  795. assert.match(prompt, /recommendation:shortlist/);
  796. assert.match(prompt, /当前未解决预警/);
  797. assert.match(prompt, /high_intent:core_demand_ready/);
  798. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  799. });
  800. await check('企微官方待办同步使用可注入 stub 并保持幂等', async () => {
  801. const ctx = setup();
  802. try {
  803. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  804. const [task] = ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'recommendation:shortlist', type: 'recommendation', title: '发送重点方案' }]);
  805. let createCalls = 0;
  806. const sync = createCustomerTaskOfficialSync({
  807. db: ctx.db,
  808. searchTodoUsers: async ({ keyword }) => ({ status: 'ok', data: { users: [{ id: 'internal-user-1', name: keyword, alias: '' }] } }),
  809. createTodoKnowledge: async input => {
  810. createCalls += 1;
  811. assert.deepEqual(input.followerIds, ['internal-user-1']);
  812. return { status: 'ok', summary: { todoId: 'official-todo-stub' }, data: { todo: { id: 'official-todo-stub' } } };
  813. },
  814. });
  815. await sync(task.id, { owner: '内部同事', dueAt: '2026-07-20 18:00' });
  816. await sync(task.id, { owner: '内部同事', dueAt: '2026-07-20 18:00' });
  817. const updated = ctx.db.getCustomerTask(task.id);
  818. assert.equal(createCalls, 1);
  819. assert.equal(updated.official_todo_id, 'official-todo-stub');
  820. assert.equal(updated.official_sync_status, 'synced');
  821. assert.equal(updated.status, 'in_progress');
  822. } finally { ctx.close(); }
  823. });
  824. process.stdout.write(`${JSON.stringify({ status: 'ok', passed: results.length, results }, null, 2)}\n`);
  825. }
  826. main().catch(error => {
  827. process.stderr.write(`${error.stack || error.message}\n`);
  828. process.exitCode = 1;
  829. });