Files
Agent-Workbench/src/core/delivery-report.mjs
T

229 lines
22 KiB
JavaScript
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 { inspectProject } from './project-inspector.mjs';
import { ChangeSetManager } from './workspaces/change-sets.mjs';
import { verifyPlanEvidence } from './context/request-plan.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { verifyPythonCheckEvidence } from './python-runtime.mjs';
import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-manager.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
export function verifiedCheck(store, session, inspection) {
const task = store.core.task.get(session.taskId);
const job = store.core.check_job.get(task?.verification.checkJobId);
if (!job || job.sessionId !== session.id || job.taskId !== task.id || job.projectId !== session.projectId
|| job.status !== 'passed' || job.stale || !inspection.scope.complete) return null;
const same = job.sourceFingerprint ? job.sourceFingerprint === inspection.sourceFingerprint : job.fingerprint === inspection.fingerprint;
if (!same || !job.results.length || job.results.some(result => result.status !== 'passed' || result.exitCode !== 0)
|| !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0 && result.tests.passed === result.tests.total && !result.tests.failed && !result.tests.skipped && !result.tests.cancelled)) return null;
for (const result of job.results) {
if (!result.logArtifactId) return null;
try {
const artifact = store.owned('artifact', result.logArtifactId, session.id);
if (artifact.taskId !== task.id || artifact.kind !== 'check-log') return null;
store.artifactStore.read(artifact);
verifyPythonCheckEvidence(store, session, job, result);
} catch { return null; }
}
return job;
}
export class DeliveryReporter {
constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; }
async create(session, { job = null, inspection = null } = {}) {
const taskId = session.taskId, runId = session.runId;
const task = this.store.owned('task', taskId, session.id);
const run = this.store.owned('run', runId, session.id);
const project = this.store.project(session.projectId);
await verifyWorkspaceProject(this.store, project);
inspection ??= await inspectProject(project);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 });
if (job && (job.sessionId !== session.id || job.taskId !== taskId)) throw new Error('提交记录不属于当前任务。');
const changes = session.changes.filter(change => change.taskId === taskId);
const jobs = [...this.store.core.delivery_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const check = verifiedCheck(this.store, session, inspection);
const requiresVerification = [...this.store.core.tool.values()].filter(value => value.taskId === taskId && value.requiresVerification)
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
const checkJobs = [...this.store.core.check_job.values()].filter(value => value.taskId === taskId);
const pythonEvidence = new Map();
for (const checkJob of checkJobs) if (!checkJob.stale && checkJob.sourceFingerprint === inspection.sourceFingerprint) {
for (const result of checkJob.results.filter(value => value.engine === 'python' && value.status === 'passed')) {
try { verifyPythonCheckEvidence(this.store, session, checkJob, result); pythonEvidence.set(result.id, { verified: true }); }
catch (error) {
pythonEvidence.set(result.id, { verified: false, error: error.message });
requiresVerification.push({ id: result.id, tool: 'python_check', status: 'evidence_unverified' });
}
}
}
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const changeSets = sets.map(set => {
let snapshotVerified = true, snapshotError = null;
try { new ChangeSetManager(this.store).snapshots(session, set); } catch (error) { snapshotVerified = false; snapshotError = error.message; }
return { id: set.id, taskId: set.taskId, runId: set.runId, status: set.status, fingerprint: set.fingerprint,
paths: set.files.map(file => file.path), snapshotVerified, snapshotError, requiresVerification: !!set.requiresVerification,
summary: set.summary, verifiedAt: set.verifiedAt ?? null, finishedAt: set.finishedAt ?? null };
});
requiresVerification.push(...changeSets.filter(set => set.requiresVerification || !set.snapshotVerified)
.map(set => ({ id: set.id, tool: 'change_set', status: set.status })));
const commits = jobs.filter(value => value.status === 'completed' && value.commit && value.sourceFingerprint === inspection.sourceFingerprint);
const contextCache = new Map();
const contextPlans = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === taskId).map(plan => {
let evidenceVerified = true, evidenceError = null;
try {
verifyPlanEvidence(this.store, session, plan, contextCache);
} catch (error) { evidenceVerified = false; evidenceError = error.message; }
return { id: plan.id, runId: plan.runId, stepId: plan.stepId, status: plan.status, requestSha256: plan.requestSha256, requestBytes: plan.requestBytes,
requestArtifactId: plan.requestArtifactId, planArtifactId: plan.artifactId, estimatedInputTokens: plan.estimatedInputTokens,
beforeInputTokens: plan.beforeInputTokens, beforeBytes: plan.beforeBytes, estimateMethod: plan.estimateMethod, budget: plan.budget,
archivedGroups: plan.archivedGroups, retainedMessages: plan.retainedMessages, actualUsage: plan.actualUsage, requestAttempts: plan.requestAttempts,
historyIndexArtifactId: plan.historyIndexArtifactId, historyIndexSha256: plan.historyIndexSha256,
workingSetArtifactId: plan.workingSetArtifactId ?? null, workingSetSha256: plan.workingSetSha256 ?? null,
workingSetEntries: plan.workingSetEntries ?? 0, workingSetViewVersion: plan.workingSetViewVersion ?? 1,
workingRetentionTokens: plan.workingRetentionTokens ?? 0,
latestToolsArtifactId: plan.latestToolsArtifactId ?? null, latestToolsSha256: plan.latestToolsSha256 ?? null,
latestToolsEntries: plan.latestToolsEntries ?? 0, evidenceVerified, evidenceError };
});
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
const deliveryReview = pendingDeliveryReview(this.store, session);
const browserVerification = await currentBrowserVerification(this.store, session, inspection);
const planner = new TaskPlanManager(this.store), taskPlan = await planner.inspect(session, { inspection, candidates: false });
const taskPlanHistory = [...this.store.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
try { planner.planFor(session, value.id); evidenceVerified = true; } catch (error) { evidenceError = error.message; }
return { id: value.id, runId: value.runId, revision: value.revision, parentPlanId: value.parentPlanId, steps: value.steps,
requirementsSha256: value.requirementsSha256, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256, evidenceVerified, evidenceError };
});
const taskProofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ id: value.id, runId: value.runId, planId: value.planId, stepKey: value.stepKey, status: value.status, evidenceId: value.evidenceId,
outcome: value.outcome, error: value.error, createdAt: value.createdAt, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256 }));
const browserChecks = [...this.store.core.browser_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
if (value.resultArtifactId) { try { verifyBrowserJob(this.store, session, value); evidenceVerified = true; } catch (error) { evidenceError = error.message; } }
if (value.requiresVerification || value.resultArtifactId && !evidenceVerified) requiresVerification.push({ id: value.id, tool: 'browser_check', status: 'evidence_unverified' });
return { id: value.id, taskId: value.taskId, runId: value.runId, planId: value.planId, status: value.status, summary: value.summary,
sourceFingerprint: value.sourceFingerprint, buildSha256: value.buildSha256, assertions: value.assertions, screenshots: value.screenshots,
resultArtifactId: value.resultArtifactId ?? null, resultSha256: value.resultSha256 ?? null, cleanup: value.cleanup ?? null,
requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null };
});
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 });
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
: deliveryReview || changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review'
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification' : !check ? 'needs_checks' : browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: commits.length ? 'verified_committed' : 'verified_uncommitted';
const report = {
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
project: { id: project.id, name: project.name, root: project.root }, workspace: projectWorkspaceIdentity(project),
task: { id: task.id, goal: task.goal, status: task.status, instructions: task.instructions, acceptance: task.acceptance ?? [],
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
source: { fingerprint: inspection.sourceFingerprint, scope: inspection.scope, gitHead: inspection.git.head, branch: inspection.git.branch },
runs: [...this.store.core.run.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, resumeOf: value.resumeOf,
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
sha256: value.sha256, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
changeSets,
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
contextPlans,
browserVerification, browserChecks,
taskPlan, taskPlanHistory, taskProofs,
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
results: value.results.map(result => ({ ...result, logExcerpt: undefined,
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null,
...(result.engine === 'python' ? { pythonEvidence: pythonEvidence.get(result.id) ?? { verified: false, state: 'historical_or_not_passed' } } : {}) })) })),
verifiedCheckJobId: check?.id ?? null,
deliveries: jobs.map(value => ({ id: value.id, status: value.status, commit: value.commit ?? null, expectedCommit: value.expectedCommit ?? null,
parent: value.parent, sourceFingerprint: value.sourceFingerprint, paths: value.paths, summary: value.summary, requiresVerification: !!value.requiresVerification,
workspacePreserved: value.workspacePreserved ?? null, indexPreserved: value.indexPreserved ?? null, finishedAt: value.finishedAt })),
requiresVerification,
limitations: ['本切片验证已选工程检查和提交范围;业务需求验收另行记录。', '提交为本地普通提交,不执行仓库hooks和GPG签名。', '请求输入为本地UTF-8估算;服务实际分词和用量另行记录。', '未配置模型单价,费用未知。'],
};
const safe = JSON.parse(this.redact(JSON.stringify(report)));
const markdown = renderDeliveryMarkdown(safe);
const jsonArtifact = this.store.artifactStore.write(session, run, safe, { kind: 'delivery-report' });
const markdownArtifact = this.store.artifactStore.write(session, run, markdown, { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
this.store.core.artifact.set(jsonArtifact.id, jsonArtifact); this.store.core.artifact.set(markdownArtifact.id, markdownArtifact);
if (job) { job.reportArtifactId = jsonArtifact.id; job.reportMarkdownArtifactId = markdownArtifact.id; }
this.store.save(session, { type: 'delivery.report', detail: { status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } });
return { report: safe, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id };
}
}
export function renderDeliveryMarkdown(report) {
const lines = ['# 项目交付报告', '', '**' + report.statusLabel + '**', '', '生成时间:' + report.generatedAt, '',
'项目:' + report.project.name, '项目目录:' + report.project.root, 'Task:' + report.task.id, '',
'## 任务与范围', '', report.task.goal, '',
'源码指纹:' + report.source.fingerprint, '当前Git HEAD:' + (report.source.gitHead ?? '未启用'),
'分支:' + (report.source.branch ?? '未记录'), '', report.task.note, '', '## 改动', '',
'| 文件 | 状态 | SHA256 |', '| --- | --- | --- |'];
for (const change of report.changes) lines.push('| ' + [change.path, change.status, change.sha256].map(escapeCell).join(' | ') + ' |');
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
'| 步骤 / 通过条件 | 状态 | 前置依赖 | 原证据 |', '| --- | --- | --- | --- |');
for (const step of report.taskPlan.steps) lines.push('| ' + [step.title + ' / ' + step.criterion, step.status,
step.depends_on.join(', ') || '无', step.evidence?.id ?? '尚未核验'].map(escapeCell).join(' | ') + ' |', ...(step.error ? ['', step.error, ''] : []));
if (report.taskPlan.error) lines.push('', report.taskPlan.error);
lines.push('', '任务计划固定实际操作范围;业务语义验收另行记录。', '', '### 原计划与核验工件', '');
for (const plan of report.taskPlanHistory ?? []) lines.push('计划 ' + plan.revision + ':' + plan.contractArtifactId + ' · SHA256 ' + plan.contractSha256);
for (const proof of report.taskProofs ?? []) lines.push('步骤 ' + proof.stepKey + ' · ' + proof.status + ':' + proof.contractArtifactId + ' · SHA256 ' + proof.contractSha256);
}
if (report.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
'交付保存在此分支;合并回来源项目需要另行审查。');
if (report.changeSets?.length) {
lines.push('', '## 多文件变更集', '', '| 批次 | 实际状态 | 快照 | 审查指纹 |', '| --- | --- | --- | --- |');
for (const set of report.changeSets) lines.push('| ' + [set.id, set.status, set.snapshotVerified ? 'SHA256校验通过' : '需要核对', set.fingerprint].map(escapeCell).join(' | ') + ' |',
'', set.summary ?? '', '');
}
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
if (pythonResults.length) {
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
for (const result of pythonResults) lines.push('| ' + [result.command, result.python.runtime.executable, result.python.runtime.version, result.metricsSha256 ?? '未返回'].map(escapeCell).join(' | ') + ' |',
'', '运行器SHA256:' + result.python.runner.sha256, '封存输入SHA256:' + result.python.inputSha256,
...(result.compilation ? ['语法编译:' + result.compilation.compiled + '/' + result.compilation.total + ' 个源码文件。'] : []));
}
if (report.browserChecks?.length || report.browserVerification?.required) {
lines.push('', '## 实际页面验收', '', '当前页面验收:' + report.browserVerification.status, '', '| 浏览器Job | 状态 | 实际断言 | 原结果SHA256 |', '| --- | --- | --- | --- |');
for (const check of report.browserChecks ?? []) {
lines.push('| ' + [check.id, check.status, check.assertions.passed + '/' + check.assertions.total, check.evidenceVerified ? check.resultSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
for (const image of check.screenshots) lines.push('', '截图 ' + image.label + ' · ' + image.width + '×' + image.height + ' · SHA256 ' + image.sha256);
}
lines.push('', '浏览器页面属于工程输入;观察或截图不代替断言,源码或构建变化后需要重新检查。', '');
}
lines.push('', '## Git交付', '');
if (report.deliveryReview) lines.push('Git提交预览已保存,等待确认。计划:' + report.deliveryReview.planId, '');
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
for (const delivery of report.deliveries) lines.push('- ' + delivery.status + ' · ' + (delivery.commit ?? '实际结果未确认') + ' · ' + delivery.paths.join(', '),
' ' + (delivery.summary ?? ''));
lines.push('', '## 模型与用量', '', '| Run | 模型 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
for (const run of report.runs) lines.push('| ' + [run.id, run.model?.mode === 'demo' ? '离线固定演示' : run.model?.model ?? '未记录',
run.status, run.usage?.totalTokens ?? 0].map(escapeCell).join(' | ') + ' |');
lines.push('', '累计已报告:' + (report.usage.totalTokens ?? 0) + ' tokens;未报告请求:' + (report.usage.unknownRequests ?? 0) + '。费用:未知。', '', '## 尚待确认', '');
if (report.contextPlans?.length) {
const at = lines.length - 2;
const contextLines = ['', '## 请求上下文', '', '| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |', '| --- | --- | --- | --- | --- | --- |'];
for (const plan of report.contextPlans) contextLines.push('| ' + [plan.id, plan.status, plan.estimatedInputTokens,
plan.actualUsage?.prompt_tokens ?? '未返回', plan.archivedGroups, plan.evidenceVerified ? plan.requestSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
lines.splice(at, 0, ...contextLines, '');
}
for (const value of report.requiresVerification) lines.push('- ' + value.tool + ' · ' + value.id + ' · ' + value.status);
for (const note of report.limitations) lines.push('- ' + note);
return lines.join('\n') + '\n';
}