234 lines
22 KiB
JavaScript
234 lines
22 KiB
JavaScript
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
|
|
import fs from 'node:fs';
|
|
import { randomUUID } from 'node:crypto';
|
|
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';
|
|
import { inspectBuild } from '../browser/build-snapshot.mjs';
|
|
import { TASK_PLAN_LIMITS, taskPlanInput, taskProofInput, taskRequirements, taskPlanContract, taskProofContract, planHash, planError } from '../../shared/contracts/task-plans.mjs';
|
|
|
|
const at = () => new Date().toISOString();
|
|
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
const identity = artifact => ({ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes });
|
|
|
|
export class TaskPlanManager {
|
|
constructor(store, { redact = String, projectBusy = () => false } = {}) { this.store = store; this.redact = redact; this.projectBusy = projectBusy; this.active = new Map(); }
|
|
projectActive(projectId) { return [...this.active.values()].some(value => value.projectId === projectId); }
|
|
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
|
|
async settle(sessionId = null) { await Promise.allSettled([...this.active.values()].filter(value => !sessionId || value.sessionId === sessionId).map(value => value.promise)); }
|
|
async mutate(session, source, action) {
|
|
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw planError('项目正在执行操作,请结束后保存或核验计划。');
|
|
const id = randomUUID(), operation = { sessionId: session.id, projectId: session.projectId, promise: null };
|
|
this.active.set(id, operation);
|
|
try { operation.promise = Promise.resolve().then(action); return await operation.promise; }
|
|
finally { this.active.delete(id); }
|
|
}
|
|
task(session) {
|
|
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
|
|
if (run.taskId !== task.id) throw planError('计划的Task/Run归属已经变化。');
|
|
return { task, run };
|
|
}
|
|
artifact(session, id, kind, taskId = session.taskId, runId = null) {
|
|
const artifact = this.store.owned('artifact', id, session.id);
|
|
if (artifact.taskId !== taskId || kind && artifact.kind !== kind || runId && artifact.runId !== runId) throw planError('计划证据工件不属于原Task/Run或实际类别。');
|
|
const run = this.store.owned('run', artifact.runId, session.id);
|
|
if (run.taskId !== taskId) throw planError('证据工件的所属运行无效。');
|
|
return { artifact, text: this.store.artifactStore.read(artifact) };
|
|
}
|
|
current(session) {
|
|
const task = this.store.core.task.get(session.taskId);
|
|
return task?.currentTaskPlanId ? this.store.owned('task_plan', task.currentTaskPlanId, session.id) : null;
|
|
}
|
|
planFor(session, id) {
|
|
const plan = this.store.owned('task_plan', id, session.id);
|
|
if (plan.taskId !== session.taskId) throw planError('计划属于此前Task,不能用于当前任务。');
|
|
const { artifact, text } = this.artifact(session, plan.contractArtifactId, 'task-plan', plan.taskId, plan.runId);
|
|
if (artifact.sha256 !== plan.contractSha256 || text !== JSON.stringify(taskPlanContract(plan))
|
|
|| plan.requirementsSha256 !== planHash(plan.requirements)) throw planError('任务计划与封存的目标、步骤或依赖不一致。');
|
|
taskPlanInput({ expected_revision: plan.revision, steps: plan.steps }, this.store.config);
|
|
return plan;
|
|
}
|
|
assertUnchanged(session, plan, taskId, runId, requirementsSha256) {
|
|
if (session.taskId !== taskId || session.runId !== runId || this.current(session)?.id !== plan.id
|
|
|| planHash(taskRequirements(this.store.core.task.get(taskId))) !== requirementsSha256) throw planError('核对期间原任务、运行、目标或计划已变化,请刷新当前计划。', 'stale');
|
|
}
|
|
plan(session, options, { source = 'user' } = {}) { return this.mutate(session, source, () => this.planAction(session, options)); }
|
|
async planAction(session, options) {
|
|
const input = taskPlanInput(JSON.parse(this.redact(JSON.stringify(options))), this.store.config), { task, run } = this.task(session);
|
|
const requirements = taskRequirements(task), requirementsSha256 = planHash(requirements), previous = this.current(session);
|
|
if (previous) this.planFor(session, previous.id);
|
|
const revision = previous?.revision ?? 0;
|
|
if (previous && same(previous.steps, input.steps) && previous.requirementsSha256 === requirementsSha256
|
|
&& [revision, revision - 1].includes(input.expected_revision)) return previous;
|
|
if (task.status === 'completed') throw planError('已完成任务保留原计划,请为新增工作发送新任务。');
|
|
if (input.expected_revision !== revision) throw planError('计划视图已过期,请按当前revision保存。', 'stale');
|
|
if (revision >= ceiling(this.store, TASK_PLAN_LIMITS.revisions)) throw planError('任务计划已到修订上限,请缩小任务后继续。');
|
|
if (previous && (input.steps.length < previous.steps.length || previous.steps.some((step, index) => !same(step, input.steps[index])))) throw planError('已有步骤和通过条件不能删改;请保留原步骤并追加。');
|
|
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
|
for (const step of input.steps) for (const file of step.paths ?? []) safePath(this.store.project(session.projectId), file, true);
|
|
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id
|
|
|| planHash(taskRequirements(task)) !== requirementsSha256) throw planError('保存期间任务或计划已变化,请刷新后保存。', 'stale');
|
|
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
|
revision: revision + 1, parentPlanId: previous?.id ?? null, status: 'planned', createdAt: at(), requirements, requirementsSha256, steps: input.steps };
|
|
const artifact = this.store.artifactStore.write(session, run, taskPlanContract(plan), { kind: 'task-plan' });
|
|
plan.contractArtifactId = artifact.id; plan.contractSha256 = artifact.sha256;
|
|
this.store.core.artifact.set(artifact.id, artifact); task.currentTaskPlanId = plan.id;
|
|
return this.store.putRecord('task_plan', session, plan, 'task.plan_saved');
|
|
}
|
|
async inspection(session, cache) {
|
|
cache.inspection ??= inspectProject(this.store.project(session.projectId));
|
|
const inspection = await cache.inspection;
|
|
if (!inspection.scope.complete) throw planError('当前工程范围不完整,不能核验源码相关步骤。', 'stale');
|
|
return inspection;
|
|
}
|
|
async evidence(session, step, id, cache = {}) {
|
|
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);
|
|
if (run.taskId !== session.taskId) throw planError('证据运行不属于当前任务。');
|
|
if (step.kind === 'analysis') {
|
|
if (record.state !== 'completed' || !step.tools.includes(record.tool) || !record.resultArtifactId) throw planError('读取步骤需要已完成的所选只读工具原结果。');
|
|
const { artifact, text } = this.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId);
|
|
const result = JSON.parse(text);
|
|
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(value => value.id === record.callId);
|
|
if (!call || call.function.name !== record.tool || planHash(call.function.arguments) !== record.argsSha256) throw planError('原读取调用与参数哈希不一致。');
|
|
if (['failed', 'error', 'denied', 'unknown', 'interrupted'].includes(result.status)) throw planError('原读取结果失败或未知,不能作为已完成证据。');
|
|
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已审查应用的完整变更集。');
|
|
new ChangeSetManager(this.store).snapshots(session, record);
|
|
const files = step.paths.map(file => record.files.find(value => value.path === file));
|
|
for (const file of files) if (planHash(fs.readFileSync(safePath(this.store.project(session.projectId), file.path))) !== file.sha256) throw planError('已应用的目标文件已变化,需要核对新的实际改动。', 'stale');
|
|
return { kind, id: record.id, runId: record.runId, scope: 'current_applied_files', fingerprint: record.fingerprint,
|
|
files: files.map(file => ({ path: file.path, sha256: file.sha256, changeId: file.changeId })) };
|
|
}
|
|
const inspection = await this.inspection(session, cache);
|
|
if (record.sourceFingerprint !== inspection.sourceFingerprint) throw planError('原证据对应旧源码,请使用当前工程的实际结果。', 'stale');
|
|
if (step.kind === 'checks') {
|
|
const task = this.store.core.task.get(session.taskId);
|
|
if (record.status !== 'passed' || record.stale || task.verification.status !== 'passed' || task.verification.checkJobId !== record.id
|
|
|| !step.checks.every(name => record.results.some(result => result.name === name))) throw planError('检查步骤需要最新所属检查通过且覆盖全部所选名称。', 'stale');
|
|
const plan = new CheckRunner(this.store).planFor(session, record.planId), artifacts = [];
|
|
if (!plan.contractArtifactId || plan.sourceFingerprint !== record.sourceFingerprint) throw planError('检查缺少当前源码的封存执行范围。');
|
|
artifacts.push(identity(this.artifact(session, plan.contractArtifactId, 'check-plan', record.taskId, plan.runId).artifact));
|
|
for (const result of record.results) {
|
|
if (result.status !== 'passed' || result.exitCode !== 0 || !result.logArtifactId || result.kind === 'test'
|
|
&& (!result.tests?.total || result.tests.passed !== result.tests.total || result.tests.failed || result.tests.skipped || result.tests.cancelled)) throw planError('检查通过状态缺少退出码、真实测试数量或原日志。');
|
|
const log = this.artifact(session, result.logArtifactId, 'check-log', record.taskId, record.runId);
|
|
artifacts.push(identity(log.artifact));
|
|
if (result.kind === 'test' && result.engine !== 'python') {
|
|
const counted = parseTestEvidence(log.text, result.framework ?? plan.checks.find(check => check.name === result.name)?.framework);
|
|
if (!same(counted, result.tests)) throw planError('检查数量与原日志中的实际统计不一致。');
|
|
}
|
|
verifyPythonCheckEvidence(this.store, session, record, result);
|
|
for (const field of ['metricsArtifactId', 'inputArtifactId']) if (result[field]) artifacts.push(identity(this.artifact(session, result[field], null, record.taskId, record.runId).artifact));
|
|
}
|
|
return { kind, id: record.id, runId: record.runId, scope: 'current_source_checks', sourceFingerprint: record.sourceFingerprint,
|
|
checks: record.results.map(result => ({ name: result.name, exitCode: result.exitCode, tests: result.tests ?? null, compilation: result.compilation ?? null })), artifacts };
|
|
}
|
|
const plan = browserPlanFor(this.store, session, record.planId), original = verifyBrowserJob(this.store, session, record);
|
|
const latest = [...this.store.core.browser_plan.values()].findLast(value => value.sessionId === session.id && value.taskId === session.taskId && value.viewport.width === step.viewport_width);
|
|
if (record.status !== 'passed' || original.status !== 'passed' || !original.cleanup?.exited || !original.assertions?.total
|
|
|| original.assertions.passed !== original.assertions.total || latest?.id !== plan.id || plan.viewport.width !== step.viewport_width
|
|
|| step.actions.some(action => !original.steps.some(value => value.action === action && value.status === 'passed'))) throw planError('页面步骤需要所选视口最新计划的实际操作、断言通过及进程结束。', 'stale');
|
|
const build = await inspectBuild(this.store.project(session.projectId), plan.build.directory);
|
|
if (build.sha256 !== record.buildSha256) throw planError('页面构建已变化,请使用当前构建的实际浏览器结果。', 'stale');
|
|
return { kind, id: record.id, runId: record.runId, scope: 'current_build_browser', sourceFingerprint: record.sourceFingerprint,
|
|
buildSha256: record.buildSha256, viewport: plan.viewport, assertions: original.assertions, actions: step.actions,
|
|
artifacts: [identity(this.artifact(session, record.resultArtifactId, 'browser-result', record.taskId, record.runId).artifact)],
|
|
screenshots: record.screenshots.map(image => ({ artifactId: image.artifactId, sha256: image.sha256 })) };
|
|
}
|
|
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', 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 : ['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 }));
|
|
}
|
|
async inspect(session, { inspection = null, candidates = true } = {}) {
|
|
const plan = this.current(session);
|
|
if (!plan) return { configured: false, task_id: session.taskId, revision: 0, status: 'not_planned', steps: [], all_verified: false, binding_sha256: null };
|
|
try { this.planFor(session, plan.id); }
|
|
catch (error) { return { configured: true, plan_id: plan.id, revision: plan.revision, status: 'unverified', error: this.redact(error.message), steps: [], all_verified: false, binding_sha256: null }; }
|
|
const requirementsCurrent = plan.requirementsSha256 === planHash(taskRequirements(this.store.core.task.get(session.taskId)));
|
|
const proofs = this.proofs(session, plan), states = new Map(), cache = { inspection };
|
|
const evaluate = async key => {
|
|
if (states.has(key)) return states.get(key);
|
|
const step = plan.steps.find(value => value.key === key), dependencies = await Promise.all(step.depends_on.map(evaluate));
|
|
const proof = proofs.findLast(value => value.stepKey === key && value.status === 'verified'), attempt = proofs.findLast(value => value.stepKey === key);
|
|
let valid = false, error = null, evidence = null, code = null;
|
|
if (proof) try {
|
|
const stored = this.artifact(session, proof.contractArtifactId, 'task-proof', proof.taskId, proof.runId);
|
|
if (stored.artifact.sha256 !== proof.contractSha256 || stored.text !== JSON.stringify(taskProofContract(proof))
|
|
|| proof.planContractSha256 !== plan.contractSha256 || proof.requirementsSha256 !== plan.requirementsSha256 || proof.stepSha256 !== planHash(step)) throw planError('步骤证明与原计划、目标或工件不一致。');
|
|
evidence = await this.evidence(session, step, proof.evidenceId, cache);
|
|
if (!same(evidence, proof.outcome)) throw planError('原证明引用的执行记录或文件已经变化。', 'stale');
|
|
valid = true;
|
|
} catch (caught) { error = this.redact(caught.message); code = caught.code ?? 'invalid'; }
|
|
const blockers = dependencies.filter(value => value.status !== 'verified').map(value => value.key);
|
|
const status = !requirementsCurrent ? 'needs_update' : error ? code === 'stale' ? 'stale' : 'unverified' : blockers.length ? 'blocked' : valid ? 'verified' : 'ready';
|
|
const state = { ...step, status, blockers, evidence_verified: valid, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
|
|
evidence, error, ...(attempt?.status === 'rejected' ? { last_rejection: { id: attempt.id, message: attempt.error, at: attempt.createdAt } } : {}),
|
|
...(candidates ? { candidates: this.candidates(session, step) } : {}) };
|
|
states.set(key, state); return state;
|
|
};
|
|
for (const step of plan.steps) await evaluate(step.key);
|
|
const steps = plan.steps.map(step => states.get(step.key)), allVerified = requirementsCurrent && steps.every(step => step.status === 'verified');
|
|
return { configured: true, task_id: plan.taskId, plan_id: plan.id, revision: plan.revision, status: !requirementsCurrent ? 'needs_update' : allVerified ? 'verified' : 'incomplete',
|
|
requirements_current: requirementsCurrent, requirements_sha256: plan.requirementsSha256, contract_artifact_id: plan.contractArtifactId, contract_sha256: plan.contractSha256,
|
|
steps, verified_steps: steps.filter(step => step.status === 'verified').length, total_steps: steps.length, all_verified: allVerified,
|
|
ready_steps: steps.filter(step => step.status === 'ready').map(step => step.key), remaining_steps: steps.filter(step => step.status !== 'verified').map(step => step.key),
|
|
binding_sha256: allVerified ? planHash({ planId: plan.id, contractSha256: plan.contractSha256, proofs: steps.map(step => ({ key: step.key, id: step.proof_id, evidence: step.evidence })) }) : null,
|
|
checked_at: at(), note: '步骤核验绑定实际操作和当前证据;原用户要求与业务语义的完整验收另行记录。' };
|
|
}
|
|
verify(session, options, { source = 'user' } = {}) { return this.mutate(session, source, () => this.verifyAction(session, options)); }
|
|
async verifyAction(session, options) {
|
|
const input = taskProofInput(options), { task, run } = this.task(session), plan = this.planFor(session, input.plan_id);
|
|
if (this.current(session)?.id !== plan.id || plan.revision !== input.expected_revision || plan.requirementsSha256 !== planHash(taskRequirements(task))) throw planError('原计划视图或任务目标已变化,请刷新当前计划。', 'stale');
|
|
const step = plan.steps.find(value => value.key === input.step_key); if (!step) throw planError('当前计划没有这项步骤。');
|
|
let outcome = null, error = null;
|
|
try {
|
|
const view = await this.inspect(session, { candidates: false }), current = view.steps.find(value => value.key === step.key);
|
|
if (current.blockers.length) throw planError('先核验前置步骤:' + current.blockers.join('、'));
|
|
outcome = await this.evidence(session, step, input.evidence_id);
|
|
this.assertUnchanged(session, plan, task.id, run.id, plan.requirementsSha256);
|
|
const previous = this.proofs(session, plan).findLast(value => value.stepKey === step.key && value.status === 'verified');
|
|
if (previous?.evidenceId === input.evidence_id && same(previous.outcome, outcome) && current.evidence_verified) return { status: 'completed', step_key: step.key, proof_id: previous.id, reused: true };
|
|
} catch (caught) { error = this.redact(caught.message); }
|
|
this.assertUnchanged(session, plan, task.id, run.id, plan.requirementsSha256);
|
|
const proof = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
|
planId: plan.id, stepKey: step.key, stepSha256: planHash(step), planContractSha256: plan.contractSha256,
|
|
requirementsSha256: plan.requirementsSha256, status: error ? 'rejected' : 'verified', evidenceId: input.evidence_id,
|
|
outcome: error ? null : outcome, error, createdAt: at() };
|
|
const artifact = this.store.artifactStore.write(session, run, taskProofContract(proof), { kind: 'task-proof' });
|
|
proof.contractArtifactId = artifact.id; proof.contractSha256 = artifact.sha256; this.store.core.artifact.set(artifact.id, artifact);
|
|
this.store.putRecord('task_proof', session, proof, error ? 'task.proof_rejected' : 'task.proof_verified');
|
|
return { status: error ? 'error' : 'completed', step_key: step.key, proof_id: proof.id, proof_artifact_id: artifact.id,
|
|
...(error ? { message: error } : { evidence_verified: true, evidence: outcome }) };
|
|
}
|
|
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
|
|
const view = await this.inspect(session, { inspection, candidates: false });
|
|
if (view.configured && !view.all_verified) throw planError('任务计划仍有未核验、失效或待更新的步骤,请先完成原任务计划。', 'stale');
|
|
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的任务计划或证明已变化,请重新预览。', 'stale');
|
|
return view;
|
|
}
|
|
}
|