| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- /** 验收证据:完整分页、唯一输入、首次证明不可被后续复核替换。 */
- import assert from 'node:assert/strict';
- export async function readMatrixHistory(binding, roomId, { fetchImpl = fetch, maxPages = 100 } = {}) {
- const events = [], pages = [], seenEvents = new Set(), seenTokens = new Set();
- let from;
- for (let i = 0; i < maxPages; i++) {
- const url = new URL(binding.homeserver + '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages');
- url.searchParams.set('dir', 'b'); url.searchParams.set('limit', '200');
- if (from) url.searchParams.set('from', from);
- const response = await fetchImpl(url, { headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(20000) });
- assert.ok(response.ok, '服务器房间事件 HTTP ' + response.status);
- const data = await response.json();
- assert.ok(Array.isArray(data.chunk), '房间事件响应缺少 chunk,证据不足');
- pages.push({ start: data.start, end: data.end, count: data.chunk.length });
- for (const event of data.chunk) {
- assert.ok(event?.event_id, '房间事件缺少唯一ID,证据不足');
- if (!seenEvents.has(event.event_id)) { events.push(event); seenEvents.add(event.event_id); }
- }
- if (!data.end || (data.chunk.length === 0 && data.end === from)) return { events, pages, complete: true };
- assert.ok(!seenTokens.has(data.end), '房间事件分页不前进,证据不足,禁止重试发送');
- seenTokens.add(data.end); from = data.end;
- }
- throw Error('房间事件超过分页上限,证据不足,禁止重试发送');
- }
- export function taskProof(events, binding, action, inputNames = []) {
- const sent = events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(action.marker));
- assert.ok(sent.length <= 1, action.marker + ' 输入不是唯一一条;保留原证明,禁止继续发送');
- 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));
- const attachments = events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && inputNames.includes(e.content?.['com.fmode.file_card']?.name));
- 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));
- if (!sent.length || !replies.length || !completion) return null;
- 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 };
- }
- export function retainFirstProof(action, proof) {
- assert.equal(proof.sent.length, 1, '输入唯一性未通过,不能记录证明');
- if (action.proof) {
- assert.deepEqual(proof.sent, action.proof.sent, '复核不能更换首次已发送输入');
- if (action.proof.roomId) assert.equal(proof.roomId, action.proof.roomId, '复核必须在首次证明的原房间');
- (action.verifications ??= []).push(proof);
- }
- else { action.proof = proof; action.sentIds = [...proof.sent]; }
- }
- /** Existing thread identity wins; preview text is only a unique fallback before any identity exists. */
- export function resolveTaskThread(threads, action) {
- const originalRoot = action.threadRoot;
- const originalRoom = action.proof?.roomId ?? action.roomId;
- let matches = [];
- if (originalRoot) matches = threads.filter(thread => thread.threadRoot === originalRoot);
- else if (originalRoom) matches = threads.filter(thread => thread.roomId === originalRoom);
- else matches = threads.filter(thread => thread.lastPreview?.includes(action.marker));
- if (!matches.length) return undefined;
- assert.equal(matches.length, 1, '任务线程匹配不唯一,拒绝切换房间');
- if (originalRoom) assert.equal(matches[0].roomId, originalRoom, '任务线程已变更原房间,拒绝覆盖首次证明');
- if (action.proof?.roomId) assert.equal(matches[0].roomId, action.proof.roomId, '首次证明房间不一致');
- return matches[0];
- }
- function hasFileName(file, name) {
- return file.url?.endsWith(name) || file.url?.endsWith(name.replaceAll('_', '-'));
- }
- function belongsToAgent(file, agentId) {
- if (file.agentId === agentId) return true;
- // Legacy session-index rows may omit agentId; accept only their immutable container-scoped object path.
- return !file.agentId && file.url?.includes('/deliverables/' + agentId + '/');
- }
- /** A filename is one URL-backed object; duplicate report/index rows are allowed only for that URL and owner. */
- export function sessionFileObjects(files, agentId, roomId, names) {
- return names.map(name => {
- const rows = files.filter(file => hasFileName(file, name));
- const urls = [...new Set(rows.map(file => file.url))];
- assert.equal(urls.length, 1, '成果必须唯一对应对象URL ' + name);
- assert.ok(urls[0], '成果缺少对象URL ' + name);
- assert.ok(rows.every(file => belongsToAgent(file, agentId) && file.roomId === roomId), '成果来源行归属不一致 ' + name);
- return { name, url: urls[0], rows };
- });
- }
- /** Verify the currently opened room has only its own marker/files and a complete event history. */
- export function assertSessionIsolation(history, files, ownTask, otherTasks) {
- assert.equal(history.complete, true, '隔离事件分页未完成');
- assert.ok(history.events.some(event => event.type === 'm.room.message' && event.content?.body?.includes(ownTask.marker)), '当前房间缺少本任务消息证明');
- assert.ok(files.every(file => belongsToAgent(file, ownTask.agentId) && file.roomId === ownTask.roomId), '成果列表中存在其他容器或房间来源行');
- for (const other of otherTasks) {
- // A same-container artifact may be intentionally reused in this room; row ownership above is authoritative.
- if (ownTask.agentId && other.agentId === ownTask.agentId) continue;
- assert.ok(!history.events.some(event => event.type === 'm.room.message' && event.content?.body?.includes(other.marker)), '发现其他容器消息 ' + other.marker);
- for (const name of other.expectedFiles || []) {
- assert.ok(!files.some(file => hasFileName(file, name)), '发现其他容器成果 ' + name);
- }
- }
- return sessionFileObjects(files, ownTask.agentId, ownTask.roomId, ownTask.expectedFiles || []);
- }
- export async function checkRetryUnsent(waitForReady, readHistory, binding, marker) {
- await waitForReady();
- const history = await readHistory();
- assert.equal(history.complete, true, '重试前事件范围不完整,禁止重试');
- const sent = history.events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
- assert.equal(sent.length, 0, '该任务已在服务器,禁止再重试,只能回读原回执');
- return history;
- }
- export function newFrameLoader(before, after) {
- return !!(before?.loaderId && after?.loaderId && before.loaderId !== after.loaderId);
- }
- export async function waitForPreviewText(read, marker, { attempts = 60, pause = () => new Promise(resolve => setTimeout(resolve, 300)) } = {}) {
- for (let i = 0; i < attempts; i++) {
- try {
- const text = await read();
- if (typeof text === 'string' && text.includes(marker)) return text;
- } catch { /* 新文档解析期间 body/context 可短暂缺失,继续等待同一个目标loader。 */ }
- if (i + 1 < attempts) await pause();
- }
- throw Error('HTML目标文档在限时内未出现真实输入编号');
- }
- export function previewCardsMatch(names, visibleLabels, present) {
- const expected = names.map(name => '预览 ' + name);
- return present ? expected.every(x => visibleLabels.includes(x)) : expected.every(x => !visibleLabels.includes(x));
- }
- /** List visible-card exclusions from other containers, excluding the current task by stable marker. */
- export function otherTaskFiles(tasks, currentTask) {
- return tasks
- .filter(task => task.marker !== currentTask.marker && (!currentTask.agentId || task.agentId !== currentTask.agentId))
- .flatMap(task => task.expectedFiles || []);
- }
|