acceptance-evidence.mjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /** 验收证据:完整分页、唯一输入、首次证明不可被后续复核替换。 */
  2. import assert from 'node:assert/strict';
  3. export async function readMatrixHistory(binding, roomId, { fetchImpl = fetch, maxPages = 100 } = {}) {
  4. const events = [], pages = [], seenEvents = new Set(), seenTokens = new Set();
  5. let from;
  6. for (let i = 0; i < maxPages; i++) {
  7. const url = new URL(binding.homeserver + '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages');
  8. url.searchParams.set('dir', 'b'); url.searchParams.set('limit', '200');
  9. if (from) url.searchParams.set('from', from);
  10. const response = await fetchImpl(url, { headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(20000) });
  11. assert.ok(response.ok, '服务器房间事件 HTTP ' + response.status);
  12. const data = await response.json();
  13. assert.ok(Array.isArray(data.chunk), '房间事件响应缺少 chunk,证据不足');
  14. pages.push({ start: data.start, end: data.end, count: data.chunk.length });
  15. for (const event of data.chunk) {
  16. assert.ok(event?.event_id, '房间事件缺少唯一ID,证据不足');
  17. if (!seenEvents.has(event.event_id)) { events.push(event); seenEvents.add(event.event_id); }
  18. }
  19. if (!data.end || (data.chunk.length === 0 && data.end === from)) return { events, pages, complete: true };
  20. assert.ok(!seenTokens.has(data.end), '房间事件分页不前进,证据不足,禁止重试发送');
  21. seenTokens.add(data.end); from = data.end;
  22. }
  23. throw Error('房间事件超过分页上限,证据不足,禁止重试发送');
  24. }
  25. export function taskProof(events, binding, action, inputNames = []) {
  26. const sent = events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(action.marker));
  27. assert.ok(sent.length <= 1, action.marker + ' 输入不是唯一一条;保留原证明,禁止继续发送');
  28. const replies = events.filter(e => e.sender === binding.agentMxId && e.type === 'm.room.message' && e.content?.['fmode.kind'] !== 'process' && e.content?.body?.includes(action.marker) && e.origin_server_ts >= (sent[0]?.origin_server_ts ?? Infinity));
  29. const attachments = events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && inputNames.includes(e.content?.['com.fmode.file_card']?.name));
  30. const completion = events.find(e => e.sender === binding.agentMxId && e.type === 'm.reaction' && e.content?.['m.relates_to']?.key === '✅' && [...sent, ...attachments, ...replies].some(x => x.event_id === e.content?.['m.relates_to']?.event_id));
  31. if (!sent.length || !replies.length || !completion) return null;
  32. return { sent: sent.map(e => e.event_id), attachments: attachments.map(e => e.event_id), reply: replies.map(e => e.event_id), completion: completion.event_id, roomId: action.roomId, body: replies[0].content.body };
  33. }
  34. export function retainFirstProof(action, proof) {
  35. assert.equal(proof.sent.length, 1, '输入唯一性未通过,不能记录证明');
  36. if (action.proof) {
  37. assert.deepEqual(proof.sent, action.proof.sent, '复核不能更换首次已发送输入');
  38. if (action.proof.roomId) assert.equal(proof.roomId, action.proof.roomId, '复核必须在首次证明的原房间');
  39. (action.verifications ??= []).push(proof);
  40. }
  41. else { action.proof = proof; action.sentIds = [...proof.sent]; }
  42. }
  43. /** Existing thread identity wins; preview text is only a unique fallback before any identity exists. */
  44. export function resolveTaskThread(threads, action) {
  45. const originalRoot = action.threadRoot;
  46. const originalRoom = action.proof?.roomId ?? action.roomId;
  47. let matches = [];
  48. if (originalRoot) matches = threads.filter(thread => thread.threadRoot === originalRoot);
  49. else if (originalRoom) matches = threads.filter(thread => thread.roomId === originalRoom);
  50. else matches = threads.filter(thread => thread.lastPreview?.includes(action.marker));
  51. if (!matches.length) return undefined;
  52. assert.equal(matches.length, 1, '任务线程匹配不唯一,拒绝切换房间');
  53. if (originalRoom) assert.equal(matches[0].roomId, originalRoom, '任务线程已变更原房间,拒绝覆盖首次证明');
  54. if (action.proof?.roomId) assert.equal(matches[0].roomId, action.proof.roomId, '首次证明房间不一致');
  55. return matches[0];
  56. }
  57. function hasFileName(file, name) {
  58. return file.url?.endsWith(name) || file.url?.endsWith(name.replaceAll('_', '-'));
  59. }
  60. function belongsToAgent(file, agentId) {
  61. if (file.agentId === agentId) return true;
  62. // Legacy session-index rows may omit agentId; accept only their immutable container-scoped object path.
  63. return !file.agentId && file.url?.includes('/deliverables/' + agentId + '/');
  64. }
  65. /** A filename is one URL-backed object; duplicate report/index rows are allowed only for that URL and owner. */
  66. export function sessionFileObjects(files, agentId, roomId, names) {
  67. return names.map(name => {
  68. const rows = files.filter(file => hasFileName(file, name));
  69. const urls = [...new Set(rows.map(file => file.url))];
  70. assert.equal(urls.length, 1, '成果必须唯一对应对象URL ' + name);
  71. assert.ok(urls[0], '成果缺少对象URL ' + name);
  72. assert.ok(rows.every(file => belongsToAgent(file, agentId) && file.roomId === roomId), '成果来源行归属不一致 ' + name);
  73. return { name, url: urls[0], rows };
  74. });
  75. }
  76. /** Verify the currently opened room has only its own marker/files and a complete event history. */
  77. export function assertSessionIsolation(history, files, ownTask, otherTasks) {
  78. assert.equal(history.complete, true, '隔离事件分页未完成');
  79. assert.ok(history.events.some(event => event.type === 'm.room.message' && event.content?.body?.includes(ownTask.marker)), '当前房间缺少本任务消息证明');
  80. assert.ok(files.every(file => belongsToAgent(file, ownTask.agentId) && file.roomId === ownTask.roomId), '成果列表中存在其他容器或房间来源行');
  81. for (const other of otherTasks) {
  82. // A same-container artifact may be intentionally reused in this room; row ownership above is authoritative.
  83. if (ownTask.agentId && other.agentId === ownTask.agentId) continue;
  84. assert.ok(!history.events.some(event => event.type === 'm.room.message' && event.content?.body?.includes(other.marker)), '发现其他容器消息 ' + other.marker);
  85. for (const name of other.expectedFiles || []) {
  86. assert.ok(!files.some(file => hasFileName(file, name)), '发现其他容器成果 ' + name);
  87. }
  88. }
  89. return sessionFileObjects(files, ownTask.agentId, ownTask.roomId, ownTask.expectedFiles || []);
  90. }
  91. export async function checkRetryUnsent(waitForReady, readHistory, binding, marker) {
  92. await waitForReady();
  93. const history = await readHistory();
  94. assert.equal(history.complete, true, '重试前事件范围不完整,禁止重试');
  95. const sent = history.events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
  96. assert.equal(sent.length, 0, '该任务已在服务器,禁止再重试,只能回读原回执');
  97. return history;
  98. }
  99. export function newFrameLoader(before, after) {
  100. return !!(before?.loaderId && after?.loaderId && before.loaderId !== after.loaderId);
  101. }
  102. export async function waitForPreviewText(read, marker, { attempts = 60, pause = () => new Promise(resolve => setTimeout(resolve, 300)) } = {}) {
  103. for (let i = 0; i < attempts; i++) {
  104. try {
  105. const text = await read();
  106. if (typeof text === 'string' && text.includes(marker)) return text;
  107. } catch { /* 新文档解析期间 body/context 可短暂缺失,继续等待同一个目标loader。 */ }
  108. if (i + 1 < attempts) await pause();
  109. }
  110. throw Error('HTML目标文档在限时内未出现真实输入编号');
  111. }
  112. export function previewCardsMatch(names, visibleLabels, present) {
  113. const expected = names.map(name => '预览 ' + name);
  114. return present ? expected.every(x => visibleLabels.includes(x)) : expected.every(x => !visibleLabels.includes(x));
  115. }
  116. /** List visible-card exclusions from other containers, excluding the current task by stable marker. */
  117. export function otherTaskFiles(tasks, currentTask) {
  118. return tasks
  119. .filter(task => task.marker !== currentTask.marker && (!currentTask.agentId || task.agentId !== currentTask.agentId))
  120. .flatMap(task => task.expectedFiles || []);
  121. }