feat: verify existing file results and preserve honest task delivery
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import fs from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readText, readLines, safePath } from '../../server/files.mjs';
|
||||
import { filePage } from '../context/read-budget.mjs';
|
||||
import { planHash, planError } from '../../shared/contracts/task-plans.mjs';
|
||||
import { fileResultInput, fileResultRequirements, fileResultRequirementsHash, changeRequirement, requestedFilePaths } from '../../shared/contracts/file-results.mjs';
|
||||
|
||||
const contract = ({ contractArtifactId, contractSha256, ...value }) => value;
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
export class FileResults {
|
||||
constructor(store) { this.store = store; }
|
||||
records(session) { return [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId === session.taskId); }
|
||||
artifact(session, id, kind, taskId, runId) {
|
||||
const row = this.store.owned('artifact', id, session.id);
|
||||
if (row.kind !== kind || row.taskId !== taskId || row.runId !== runId) throw planError('成果原工件的Task/Run或类别不一致。');
|
||||
return { row, bytes: this.store.artifactStore.readBytes(row) };
|
||||
}
|
||||
original(session, record, depth = 0) {
|
||||
if (depth > 16) throw planError('成果采用链超过16层,请重新核对独立成果范围。');
|
||||
const run = this.store.owned('run', record.runId, session.id);
|
||||
if (run.taskId !== record.taskId) throw planError('成果所属运行已不一致。');
|
||||
const { row, bytes } = this.artifact(session, record.contractArtifactId, 'file-result', record.taskId, record.runId);
|
||||
if (row.sha256 !== record.contractSha256 || !same(JSON.parse(bytes), contract(record))) throw planError('成果记录与封存原凭据不一致。');
|
||||
for (const file of record.files) {
|
||||
const source = this.artifact(session, file.snapshotArtifactId, 'file-result-source', record.taskId, record.runId);
|
||||
if (source.row.sha256 !== file.sha256 || source.row.bytes !== file.bytes) throw planError('成果原文件快照不一致:' + file.path);
|
||||
for (const read of file.reads) {
|
||||
const invocation = this.store.owned('tool', read.invocationId, session.id);
|
||||
if (invocation.taskId !== record.taskId || invocation.runId !== read.runId || invocation.tool !== 'read_file' || invocation.state !== 'completed'
|
||||
|| invocation.requiresVerification || invocation.resultArtifactId !== read.artifactId || invocation.argsSha256 !== read.argsSha256) throw planError('成果原读取调用不一致:' + file.path);
|
||||
const artifact = this.artifact(session, read.artifactId, 'tool-result', record.taskId, read.runId);
|
||||
if (artifact.row.sha256 !== read.artifactSha256) throw planError('成果原读取工件已变化:' + file.path);
|
||||
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(value => value.id === read.callId);
|
||||
if (!call || call.function.name !== 'read_file' || planHash(call.function.arguments) !== read.argsSha256) throw planError('成果原读取参数已变化:' + file.path);
|
||||
}
|
||||
if (file.origin) {
|
||||
const origin = this.original(session, this.store.owned('file_result', file.origin.resultId, session.id), depth + 1);
|
||||
if (origin.taskId !== file.origin.taskId || origin.runId !== file.origin.runId || origin.contractSha256 !== file.origin.contractSha256
|
||||
|| !origin.files.some(old => old.path === file.path && old.sha256 === file.origin.sha256)) throw planError('成果来源与原文件不一致:' + file.path);
|
||||
}
|
||||
}
|
||||
return record;
|
||||
}
|
||||
verify(session, id, { current = true } = {}) {
|
||||
const record = this.original(session, this.store.owned('file_result', id, session.id));
|
||||
if (current) {
|
||||
if (record.taskId !== session.taskId || record.requirementsSha256 !== fileResultRequirementsHash(this.store.owned('task', session.taskId, session.id))) throw planError('任务要求已变化,请按当前要求重新核对成果。', 'stale');
|
||||
for (const file of record.files) {
|
||||
try { if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256) throw new Error('SHA256不同'); }
|
||||
catch (error) { throw planError('当前文件已变化或无法读取:' + file.path + '。请重新打开并核对。', 'stale'); }
|
||||
}
|
||||
}
|
||||
return record;
|
||||
}
|
||||
reads(session, file, current) {
|
||||
const project = this.store.project(session.projectId), spans = [], receipts = [];
|
||||
const lineOffsets = [0]; for (let i = 0; i < current.content.length; i++) if (current.content[i] === '\n') lineOffsets.push(i + 1);
|
||||
for (const callId of file.read_call_ids) {
|
||||
const row = [...this.store.core.tool.values()].find(item => item.sessionId === session.id && item.taskId === session.taskId && item.callId === callId);
|
||||
if (!row || row.tool !== 'read_file' || row.state !== 'completed' || row.requiresVerification) throw planError('需要本Task已完成的read_file原调用:' + callId);
|
||||
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(item => item.id === callId);
|
||||
if (!call || call.function.name !== row.tool || planHash(call.function.arguments) !== row.argsSha256) throw planError('原文件读取参数与账本不一致。');
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
if (args.path !== file.path) throw planError('读取路径与采用路径不一致。');
|
||||
const { row: artifact, bytes } = this.artifact(session, row.resultArtifactId, 'tool-result', row.taskId, row.runId);
|
||||
const result = JSON.parse(bytes), { tool_invocation_id, ...page } = result;
|
||||
if (result.sha256 !== file.sha256 || !same(page, filePage(readLines(project, args), args, { callId, maximumMessageBytes: result.maximum_message_bytes }))) throw planError('读取后文件或原分页结果已变化:' + file.path, 'stale');
|
||||
const start = lineOffsets[result.range_start_line - 1];
|
||||
if (start === undefined) throw planError('读取行范围无效。');
|
||||
let end = start + result.next_offset;
|
||||
if (result.next_offset === result.total_characters && result.range_end_line < result.total_lines) end++;
|
||||
spans.push([start + result.offset, end]);
|
||||
receipts.push({ invocationId: row.id, callId, runId: row.runId, artifactId: artifact.id, artifactSha256: artifact.sha256, argsSha256: row.argsSha256 });
|
||||
}
|
||||
let covered = 0;
|
||||
for (const [start, end] of spans.sort((a, b) => a[0] - b[0])) { if (start > covered) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。'); covered = Math.max(covered, end); }
|
||||
if (covered < current.content.length) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。');
|
||||
return receipts;
|
||||
}
|
||||
record(session, input, { source = 'agent' } = {}) {
|
||||
const args = fileResultInput(input, { source }), task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
|
||||
if (!['agent', 'user'].includes(source) || run.taskId !== task.id || run.purpose === 'diagnostic' && source !== 'user') throw planError('诊断运行不能登记或替代原任务成果。');
|
||||
const project = this.store.project(session.projectId), prepared = [];
|
||||
for (const file of args.files) {
|
||||
const current = readText(project, file.path);
|
||||
if (current.sha256 !== file.sha256) throw planError('文件已在核对后变化:' + file.path + '。请重新打开文件。', 'stale');
|
||||
let origin = null;
|
||||
if (file.source_result_id) {
|
||||
const original = this.verify(session, file.source_result_id, { current: false });
|
||||
if (original.taskId === task.id) throw planError('同一Task请复用原成果ID或重新核对当前文件,不重复采用自身成果。');
|
||||
const old = original.files.find(item => item.path === file.path);
|
||||
if (!old) throw planError('原成果不包含所选文件:' + file.path);
|
||||
origin = { resultId: original.id, taskId: original.taskId, runId: original.runId, sha256: old.sha256, contractArtifactId: original.contractArtifactId, contractSha256: original.contractSha256 };
|
||||
} else {
|
||||
const previous = [...this.store.core.file_result.values()].findLast(item => item.sessionId === session.id && item.taskId !== task.id && item.files.some(old => old.path === file.path));
|
||||
if (previous) throw planError('已有旧任务成果,请显式选择原成果ID后采用:' + previous.id);
|
||||
}
|
||||
const reads = source === 'agent' ? this.reads(session, file, current) : [];
|
||||
const bytes = fs.readFileSync(safePath(project, file.path));
|
||||
if (planHash(bytes) !== file.sha256) throw planError('保存凭据期间文件已变化:' + file.path, 'stale');
|
||||
prepared.push({ file, current, bytes, reads, origin });
|
||||
}
|
||||
const requirements = fileResultRequirements(task), requirementsSha256 = fileResultRequirementsHash(task);
|
||||
const fingerprint = planHash({ requirementsSha256, files: prepared.map(({ file, origin }) => ({ path: file.path, sha256: file.sha256, origin: origin?.resultId ?? null })).sort((a,b) => a.path.localeCompare(b.path)) });
|
||||
const previous = this.records(session).find(item => item.fingerprint === fingerprint);
|
||||
if (previous) { this.verify(session, previous.id); return { status: 'completed', result_id: previous.id, reused: true, files: previous.files, message: '返回原成果凭据,未改写文件、重放工具或新增进展。' }; }
|
||||
if (this.records(session).length >= 64) throw planError('本Task已保存64份成果,请缩小任务范围。');
|
||||
const files = prepared.map(({ file, current, bytes, reads, origin }) => {
|
||||
const snapshot = this.store.artifactStore.write(session, run, bytes, { kind: 'file-result-source', mediaType: 'text/plain' }); this.store.core.artifact.set(snapshot.id, snapshot);
|
||||
return { path: file.path, sha256: file.sha256, bytes: current.bytes, snapshotArtifactId: snapshot.id, reads, origin };
|
||||
});
|
||||
const row = { schemaVersion: 1, kind: 'file-result', id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
||||
createdAt: new Date().toISOString(), source, reason: args.reason, requirements, requirementsSha256, fingerprint, files, status: 'recorded' };
|
||||
const receipt = this.store.artifactStore.write(session, run, row, { kind: 'file-result' }); this.store.core.artifact.set(receipt.id, receipt);
|
||||
row.contractArtifactId = receipt.id; row.contractSha256 = receipt.sha256;
|
||||
this.store.putRecord('file_result', session, row, 'file_result.recorded');
|
||||
return { status: 'completed', result_id: row.id, reused: false, files: row.files, message: '已核对当前文件并封存已有成果;未创建文件改动、测试或Git提交。' };
|
||||
}
|
||||
inspect(session, { path = null } = {}) {
|
||||
const results = this.records(session).slice(-64).reverse().map(row => {
|
||||
try { this.verify(session, row.id); return { ...row, verification: 'current', error: null }; }
|
||||
catch (error) { return { ...row, verification: error.code === 'stale' ? 'stale' : 'invalid', error: error.message }; }
|
||||
});
|
||||
const sources = [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId !== session.taskId && (!path || row.files.some(file => file.path === path))).slice(-12).reverse()
|
||||
.map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, reason: row.reason, files: row.files.map(({ path, sha256 }) => ({ path, sha256 })) }));
|
||||
return { taskId: session.taskId, results, sources };
|
||||
}
|
||||
completion(session) {
|
||||
const task = this.store.owned('task', session.taskId, session.id), { results } = this.inspect(session);
|
||||
const latest = new Map();
|
||||
for (const change of session.changes.filter(item => item.taskId === task.id && item.status === 'applied')) latest.set(change.path, change);
|
||||
const applied = [...latest.values()].filter(change => { try { return readText(this.store.project(session.projectId), change.path).sha256 === change.sha256 && change.baseSha256 !== change.sha256; } catch { return false; } });
|
||||
const demand = changeRequirement(task), newApplied = applied.filter(change => !demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after);
|
||||
const changed = newApplied.length > 0 && demand.paths.every(path => newApplied.some(change => change.path === path));
|
||||
const current = results.filter(row => row.verification === 'current');
|
||||
const paths = [...new Set([...applied.map(row => row.path), ...current.flatMap(row => row.files.map(file => file.path))])];
|
||||
const targets = requestedFilePaths([task.contract?.goal ?? task.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
|
||||
const missingPaths = targets.filter(path => !paths.includes(path));
|
||||
return { satisfied: !missingPaths.length && (!demand.required || changed) && (applied.length > 0 || current.length > 0), requiresChange: demand.required && !changed, missingPaths,
|
||||
status: applied.length ? 'files_applied' : 'existing_verified', paths,
|
||||
resultIds: current.map(row => row.id), newChanges: applied.length, stale: results.filter(row => row.verification !== 'current').map(row => ({ id: row.id, error: row.error })) };
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { safePath } from '../../server/files.mjs';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
|
||||
import { ChangeSetManager } from '../workspaces/change-sets.mjs';
|
||||
import { FileResults } from './file-results.mjs';
|
||||
import { CheckRunner, parseTestEvidence } from '../check-runner.mjs';
|
||||
import { verifyPythonCheckEvidence } from '../python-runtime.mjs';
|
||||
import { browserPlanFor, verifyBrowserJob } from '../browser/browser-manager.mjs';
|
||||
@@ -85,7 +86,7 @@ export class TaskPlanManager {
|
||||
return inspection;
|
||||
}
|
||||
async evidence(session, step, id, cache = {}) {
|
||||
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
|
||||
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
|
||||
const record = this.store.owned(kind, id, session.id);
|
||||
if (record.taskId !== session.taskId || record.requiresVerification) throw planError('原证据不属于当前Task或结果仍待核对。');
|
||||
const run = this.store.owned('run', record.runId, session.id);
|
||||
@@ -100,6 +101,12 @@ export class TaskPlanManager {
|
||||
return { kind, id: record.id, runId: record.runId, scope: 'historical_read_operation', tool: record.tool, callId: record.callId,
|
||||
argsSha256: record.argsSha256, artifacts: [identity(artifact)] };
|
||||
}
|
||||
if (step.kind === 'results') {
|
||||
const result = new FileResults(this.store).verify(session, record.id);
|
||||
if (!step.paths.every(path => result.files.some(file => file.path === path))) throw planError('成果凭据尚未覆盖计划指定文件。');
|
||||
return { kind, id: result.id, runId: result.runId, scope: 'current_existing_files', files: result.files.filter(file => step.paths.includes(file.path)).map(({ path, sha256, origin }) => ({ path, sha256, origin })),
|
||||
artifacts: [identity(this.store.owned('artifact', result.contractArtifactId, session.id))] };
|
||||
}
|
||||
if (step.kind === 'changes') {
|
||||
if (record.status !== 'completed' || record.direction !== 'apply' || !record.attemptedAt
|
||||
|| !step.paths.every(file => record.files.some(value => value.path === file && value.writeAttempted && value.state === 'after'))) throw planError('步骤文件必须来自本Task已审查应用的完整变更集。');
|
||||
@@ -147,11 +154,11 @@ export class TaskPlanManager {
|
||||
}
|
||||
proofs(session, plan) { return [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && value.planId === plan.id); }
|
||||
candidates(session, step) {
|
||||
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
|
||||
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
|
||||
return [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
|
||||
.filter(value => step.kind !== 'analysis' || step.tools.includes(value.tool)).filter(value => step.kind !== 'browser' || this.store.core.browser_plan.get(value.planId)?.viewport.width === step.viewport_width)
|
||||
.slice(-12).reverse().map(value => ({ id: value.id, status: value.stale ? 'stale' : value.status ?? value.state,
|
||||
label: step.kind === 'analysis' ? value.tool : step.kind === 'changes' ? value.files.map(file => file.path).join('、')
|
||||
label: step.kind === 'analysis' ? value.tool : ['changes', 'results'].includes(step.kind) ? value.files.map(file => file.path).join('、')
|
||||
: step.kind === 'checks' ? value.results.map(result => result.name).join(' / ') : step.viewport_width + 'px · ' + (value.assertions?.passed ?? 0) + '项断言',
|
||||
runId: value.runId }));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user