feat(tasks): review sourced requirements against current original evidence
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
.requirement-list { list-style: none; padding: 0; margin: 0; }
|
||||
.requirement-list > li { padding: 14px 0; border-top: 1px solid #dce7e2; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
|
||||
.requirement-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
|
||||
.requirement-heading strong { font-size: 13px; }
|
||||
.requirement-state { color: #674917; background: #fbf2df; padding: 2px 6px; border-radius: 3px; flex-shrink: 0; font-size: 11px; }
|
||||
.requirement-evidence_verified, .requirement-user_confirmed { color: #154b4a; background: #edf3f1; }
|
||||
.requirement-list summary, .requirement-history summary { cursor: pointer; color: #526a70; }
|
||||
.requirement-list blockquote, .requirement-quote { margin: 9px 0; border-left: 2px solid #bbcfc7; padding: 6px 12px; white-space: pre-wrap; font-size: 12px; max-height: 150px; overflow: auto; }
|
||||
.requirement-list code { font-size: 10px; overflow-wrap: anywhere; }
|
||||
.requirement-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 7px 0; }
|
||||
.requirement-confirm label { display: grid; gap: 6px; }
|
||||
.requirement-confirm textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; border: 1px solid #cbded3; border-radius: 5px; margin-bottom: 8px; }
|
||||
.requirement-history { font-size: 11px; margin-top: 12px; }
|
||||
.requirement-history p { display: grid; gap: 4px; }
|
||||
.requirement-editor { max-height: 72vh; overflow: auto; }
|
||||
.requirement-offsets { display: flex; gap: 12px; margin: 12px 0; }
|
||||
.requirement-offsets label { min-width: 0; font-size: 12px; }
|
||||
.requirement-panel button:focus-visible, .requirement-panel textarea:focus-visible, .requirement-editor :is(input, select, textarea):focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
|
||||
@media (max-width: 600px) { .requirement-heading { flex-direction: column; gap: 4px; } .requirement-panel .button { min-height: 36px; } }
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, FileText, Plus, RefreshCw } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import { Modal } from './components';
|
||||
import type { RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
|
||||
import './RequirementPanel.css';
|
||||
|
||||
const states: Record<string, string> = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
|
||||
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行' };
|
||||
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
|
||||
const clean = (row: RequirementItem) => ({ key: row.key, title: row.title, criterion: row.criterion, kind: row.kind, method: row.method,
|
||||
source: { kind: row.source.kind, id: row.source.id, start: row.source.start, end: row.source.end },
|
||||
...(row.kind === 'analysis' ? { tools: row.tools } : ['changes', 'results'].includes(row.kind) ? { paths: row.paths }
|
||||
: row.kind === 'checks' ? { checks: row.checks } : { viewport_width: row.viewport_width, actions: row.actions }) });
|
||||
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
|
||||
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
|
||||
|
||||
export function RequirementPanel({ session, busy, onSession, onError, openArtifact }: {
|
||||
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
|
||||
}) {
|
||||
const task = session.execution?.task, run = session.execution?.run;
|
||||
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
|
||||
const selected = useRef(identity); selected.current = identity;
|
||||
const generation = useRef(0), mutation = useRef(false);
|
||||
const [view, setView] = useState<RequirementView | null>(null), [loading, setLoading] = useState(false), [saving, setSaving] = useState(false);
|
||||
const [draft, setDraft] = useState<RequirementItem | null>(null), [picked, setPicked] = useState<Record<string, string>>({}), [notes, setNotes] = useState<Record<string, string>>({});
|
||||
const [notice, setNotice] = useState('');
|
||||
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
|
||||
useEffect(() => { generation.current++; setView(null); setDraft(null); setPicked({}); setNotes({}); setNotice(''); setSaving(false); mutation.current = false;
|
||||
return () => { generation.current++; }; }, [identity]);
|
||||
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, session.revision, session.status]);
|
||||
async function load() {
|
||||
if (!task || mutation.current) return;
|
||||
const scopeId = identity, request = ++generation.current; setLoading(true);
|
||||
try { const result = await api<RequirementView>(`/sessions/${session.id}/requirements?taskId=${task.id}`);
|
||||
if (selected.current === scopeId && generation.current === request) setView(result);
|
||||
} catch (error) { if (selected.current === scopeId && generation.current === request) onError(error); }
|
||||
finally { if (selected.current === scopeId && generation.current === request) setLoading(false); }
|
||||
}
|
||||
async function mutate(action: string, input: object) {
|
||||
if (!task || !run || !view || mutation.current) return;
|
||||
mutation.current = true; generation.current++; setSaving(true); setNotice(''); const scopeId = identity;
|
||||
try {
|
||||
const reply = await api<{ session: Session; requirements: RequirementView; verification?: { status: string; message?: string } }>(`/sessions/${session.id}/${action}`,
|
||||
{ taskId: task.id, runId: run.id, expected_revision: view.revision, ...input });
|
||||
if (selected.current !== scopeId) return;
|
||||
setView(reply.requirements); onSession(reply.session);
|
||||
setNotice(reply.verification?.status === 'error' ? reply.verification.message ?? '复核未通过,原失败已保留。' : action === 'requirements' ? '要求与原文来源已保存。' : '本次复核已记录。');
|
||||
if (action === 'requirements') setDraft(null);
|
||||
} catch (error) { if (selected.current === scopeId) onError(error); }
|
||||
finally { if (selected.current === scopeId) { mutation.current = false; setSaving(false); setLoading(false); } }
|
||||
}
|
||||
function edit(row?: RequirementItem) {
|
||||
const source = view?.sources[0]; if (!source) return;
|
||||
setDraft(row ? { ...clean(row), depends_on: [] } : { key: 'req_' + crypto.randomUUID().slice(0, 8), title: '', criterion: '', kind: 'analysis', method: 'evidence',
|
||||
source: { kind: source.kind, id: source.id, start: 0, end: source.text.length }, depends_on: [], ...scope('analysis') });
|
||||
}
|
||||
const source = view?.sources.find(row => row.id === draft?.source.id && row.kind === draft?.source.kind);
|
||||
return <section className="task-record-section requirement-panel" aria-label="要求与证据">
|
||||
<div className="record-heading"><h3>要求与证据</h3><span>{view?.items.length ?? 0} 项</span></div>
|
||||
<p className="record-footnote">逐项保留用户原文与实际依据,工程证据和用户体验分别记录。</p>
|
||||
<div className="plan-toolbar"><button className="text-button" disabled={loading || disabled} onClick={() => void load()}><RefreshCw size={13} />刷新复核</button>
|
||||
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified' || (view.items.length >= 24)} onClick={() => edit()}><Plus size={13} />记录要求</button></div>
|
||||
{notice && <p className="plan-notice" role="status">{notice}</p>}
|
||||
{view?.error && <p className="plan-problem" role="alert">{view.error}</p>}
|
||||
{!!view?.unreviewed_sources?.length && <p className="plan-problem">有 {view.unreviewed_sources.length} 份用户来源尚未审阅。核对原目标和追加要求后保存要求;旧复核记录保留。</p>}
|
||||
{view && !view.items.length && <p className="record-empty">尚未逐项记录要求。模型的完成答复保留在原会话中。</p>}
|
||||
<ol className="requirement-list">{view?.items.map(row => <li key={row.key}>
|
||||
<div className="requirement-heading"><strong>{row.title}</strong><span className={'requirement-state requirement-' + row.status}>{states[row.status ?? 'pending'] ?? row.status}</span></div>
|
||||
<p>{row.criterion}</p>
|
||||
<details><summary>用户原文 · {row.source.kind === 'goal' ? '原目标' : '追加要求'} · 要求修订 {row.revision}</summary>
|
||||
<blockquote>{row.source.quote}</blockquote><code>{row.source.id} [{row.source.start}, {row.source.end})</code></details>
|
||||
{row.error && <p className="plan-problem">{row.error}</p>}{row.last_rejection && <p className="plan-problem">原复核失败:{row.last_rejection.message}</p>}
|
||||
{row.user_note && <p>用户确认:{row.user_note}</p>}
|
||||
<div className="requirement-actions"><button className="text-button" disabled={disabled} onClick={() => edit(row)}>修订此要求</button>
|
||||
{row.proof_artifact_id && <button className="text-button" onClick={() => openArtifact(row.proof_artifact_id!)}><FileText size={13} />原复核记录</button>}</div>
|
||||
{row.method === 'evidence' && <div className="plan-evidence"><label>选择实际依据 · {kinds[row.kind]}<select aria-label={`要求依据 ${row.title}`} disabled={disabled} value={picked[row.key] ?? ''} onChange={event => setPicked(values => ({ ...values, [row.key]: event.target.value }))}>
|
||||
<option value="">选择此任务的原结果</option>{row.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}</select></label>
|
||||
<button className="button secondary" disabled={disabled || !picked[row.key]} onClick={() => void mutate('requirement-proofs', { key: row.key, evidence_id: picked[row.key] })}><Check size={13} />复核所选证据</button></div>}
|
||||
{row.method === 'user' && <div className="requirement-confirm"><label>实际体验与结论<textarea aria-label={`用户确认 ${row.title}`} rows={2} maxLength={1000} disabled={disabled} value={notes[row.key] ?? ''} onChange={event => setNotes(values => ({ ...values, [row.key]: event.target.value }))} /></label>
|
||||
<button className="button secondary" disabled={disabled || !notes[row.key]?.trim()} onClick={() => void mutate('requirement-proofs', { key: row.key, note: notes[row.key] })}>记录用户确认</button></div>}
|
||||
{row.method === 'not_requested' && <p className="record-footnote">检查未执行,不计为测试通过。</p>}
|
||||
</li>)}</ol>
|
||||
{!!view?.history?.length && <details className="requirement-history"><summary>原复核历史 · {view.history.length} 条</summary>{view.history.map(row => <p key={row.id}><button className="text-button" onClick={() => openArtifact(row.artifact_id)}>{row.key} · 修订 {row.revision} · {row.status === 'rejected' ? '未通过' : '已记录'}</button>{row.error && <span>{row.error}</span>}</p>)}</details>}
|
||||
{draft && view && <Modal title="记录用户要求" description="选定用户原文、验收范围和复核方式;修订保留旧要求与原失败。" wide onClose={() => { if (!saving) setDraft(null); }}>
|
||||
<form className="plan-editor requirement-editor" onSubmit={event => { event.preventDefault(); const rows = view.items.some(row => row.key === draft.key) ? view.items.map(row => row.key === draft.key ? clean(draft) : clean(row)) : [...view.items.map(clean), clean(draft)]; void mutate('requirements', { requirements: rows }); }}>
|
||||
<fieldset disabled={saving} className="plan-editor-step">
|
||||
<label>要求名称<input aria-label="要求名称" maxLength={100} required value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} /></label>
|
||||
<label>验收条件<textarea aria-label="要求验收条件" rows={2} required maxLength={300} value={draft.criterion} onChange={event => setDraft({ ...draft, criterion: event.target.value })} /></label>
|
||||
<label>用户原文来源<select aria-label="要求原文来源" value={draft.source.id} onChange={event => { const row = view.sources.find(value => value.id === event.target.value)!; setDraft({ ...draft, source: { kind: row.kind, id: row.id, start: 0, end: row.text.length } }); }}>{view.sources.map((row, i) => <option key={row.id} value={row.id}>{row.kind === 'goal' ? '原目标' : `追加要求 ${i}`} · {row.text.slice(0, 65)}</option>)}</select></label>
|
||||
<blockquote className="requirement-quote">{source?.text.slice(draft.source.start, draft.source.end)}</blockquote>
|
||||
<div className="requirement-offsets"><label>原文起点<input aria-label="原文起点" type="number" min={0} max={Math.max(0, (source?.text.length ?? 1) - 1)} value={draft.source.start} onChange={event => setDraft({ ...draft, source: { ...draft.source, start: Number(event.target.value) } })} /></label><label>原文终点<input aria-label="原文终点" type="number" min={draft.source.start + 1} max={source?.text.length} value={draft.source.end} onChange={event => setDraft({ ...draft, source: { ...draft.source, end: Number(event.target.value) } })} /></label></div>
|
||||
<label>复核方式<select aria-label="要求复核方式" value={draft.method} onChange={event => setDraft({ ...draft, method: event.target.value as RequirementItem['method'], ...(event.target.value === 'not_requested' ? { kind: 'checks', checks: ['test', 'build'] } : {}) })}><option value="evidence">核对实际证据</option><option value="user">用户体验确认</option><option value="not_requested">按用户约定不执行检查</option></select></label>
|
||||
{draft.method === 'evidence' && <><label>证据类别<select aria-label="要求证据类别" value={draft.kind} onChange={event => { const kind = event.target.value as TaskPlanStep['kind']; setDraft({ ...draft, kind, ...scope(kind) }); }}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
|
||||
{['results', 'changes'].includes(draft.kind) && <label>文件范围(每行一项)<textarea aria-label="要求文件范围" required value={draft.paths?.join('\n') ?? ''} onChange={event => setDraft({ ...draft, paths: event.target.value.split('\n').filter(Boolean) })} /></label>}
|
||||
{draft.kind === 'analysis' && <label>读取工具(逗号分隔)<input aria-label="要求读取工具" required value={draft.tools?.join(',') ?? ''} onChange={event => setDraft({ ...draft, tools: event.target.value.split(',').map(value => value.trim()) })} /></label>}
|
||||
{draft.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label="要求检查名称" required value={draft.checks?.join(',') ?? ''} onChange={event => setDraft({ ...draft, checks: event.target.value.split(',').map(value => value.trim()) })} /></label>}
|
||||
{draft.kind === 'browser' && <label>验收视口<select aria-label="要求验收视口" value={draft.viewport_width} onChange={event => setDraft({ ...draft, viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option></select></label>}</>}
|
||||
</fieldset><div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={() => setDraft(null)}>取消</button><button className="button primary" disabled={saving}>保存要求</button></div>
|
||||
</form></Modal>}
|
||||
</section>;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { RequestContextPanel } from './RequestContextPanel';
|
||||
import { WorkspacePanel } from './WorkspacePanel';
|
||||
import { BrowserPanel } from './BrowserPanel';
|
||||
import { TaskPlanPanel } from './TaskPlanPanel';
|
||||
import { RequirementPanel } from './RequirementPanel';
|
||||
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
|
||||
import { McpJobHistory } from './McpJobHistory';
|
||||
import './TaskPanel.css';
|
||||
@@ -26,6 +27,7 @@ stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与
|
||||
stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过';
|
||||
stopReasons.delivery_incomplete = '答复已收到,当前文件成果或要求的修改仍需核对';
|
||||
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
|
||||
stopReasons.requirements_incomplete = '用户要求仍有待复核、失效或未审阅来源';
|
||||
|
||||
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate, onOpenPreview }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onOpenPreview?:()=>void; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void> }) {
|
||||
const execution = session.execution, task = execution?.task;
|
||||
@@ -99,6 +101,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
</section>
|
||||
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
|
||||
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{task && <RequirementPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
|
||||
{task && !!execution?.mcpJobs?.length && <McpJobHistory session={session} jobs={execution.mcpJobs} busy={busy} onSession={onSession} onError={onError} />}
|
||||
|
||||
@@ -228,6 +228,17 @@ export interface TaskPlanView {
|
||||
contract_artifact_id?: string; contract_sha256?: string; checked_at?: string; error?: string;
|
||||
}
|
||||
export interface TaskPlanReply { session: Session; plan: TaskPlanView; verification?: { status: string; reused?: boolean; proof_id: string; message?: string } }
|
||||
export interface RequirementSource { kind: 'goal' | 'instruction'; id: string; text: string; sha256: string; at: string | null }
|
||||
export interface RequirementItem extends TaskPlanStep {
|
||||
method: 'evidence' | 'user' | 'not_requested'; source: { kind: string; id: string; start: number; end: number; quote?: string; sourceSha256?: string; at?: string | null };
|
||||
revision?: number; status?: string; error?: string | null; proof_id?: string | null; proof_artifact_id?: string | null; user_note?: string | null;
|
||||
evidence?: TaskPlanStepView['evidence']; candidates?: TaskPlanStepView['candidates']; last_rejection?: { message: string } | null;
|
||||
}
|
||||
export interface RequirementView {
|
||||
configured: boolean; task_id: string; revision: number; status: string; items: RequirementItem[]; sources: RequirementSource[];
|
||||
all_resolved: boolean; unreviewed_sources?: string[]; error?: string; note: string; contract_artifact_id?: string;
|
||||
history?: { id: string; key: string; revision: number; status: string; error: string | null; at: string; artifact_id: string }[];
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
|
||||
export interface WorkerDefinition { id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }
|
||||
|
||||
@@ -9,12 +9,13 @@ 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';
|
||||
import { RequirementReview } from './tasks/requirement-review.mjs';
|
||||
import { FileResults } from './tasks/file-results.mjs';
|
||||
import { taskContract } from '../shared/contracts/task-control.mjs';
|
||||
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
|
||||
|
||||
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
|
||||
existing_verified: '当前成果已核对,无新增修改', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
|
||||
existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
|
||||
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
|
||||
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
|
||||
|
||||
@@ -103,6 +104,7 @@ export class DeliveryReporter {
|
||||
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 requirements = await new RequirementReview(this.store, { planner }).inspect(session, { inspection });
|
||||
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; }
|
||||
@@ -125,6 +127,7 @@ export class DeliveryReporter {
|
||||
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'
|
||||
: requirements.configured && !requirements.all_resolved ? 'needs_requirements'
|
||||
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification'
|
||||
: hasFileScope && !fileDelivery.satisfied ? 'needs_results'
|
||||
: !check && !(hasFileScope && fileDelivery.satisfied && (contract.checks === 'skip' || contract.checks === 'unspecified' && task.verification.status === 'not_configured')) ? 'needs_checks'
|
||||
@@ -136,7 +139,8 @@ export class DeliveryReporter {
|
||||
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 ?? [],
|
||||
contract, delivery: task.delivery ?? null,
|
||||
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
|
||||
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
|
||||
requirements,
|
||||
fileResults, fileDelivery,
|
||||
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
|
||||
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
|
||||
@@ -199,6 +203,15 @@ export function renderDeliveryMarkdown(report) {
|
||||
}
|
||||
if (report.gitOutcome) lines.push('', report.gitOutcome.note);
|
||||
if (report.checkPolicy === 'not_requested') lines.push('', '测试约定:按用户要求未自动测试;不记作测试通过。');
|
||||
if (report.requirements) {
|
||||
lines.push('', '## 用户要求与证据', '', report.requirements.note, '', '复核状态:' + report.requirements.status,
|
||||
'', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const item of report.requirements.items) lines.push('| ' + [item.title + ' / ' + item.criterion,
|
||||
item.source.kind + ':' + item.source.id + ' [' + item.source.start + ',' + item.source.end + ') ' + item.source.quote,
|
||||
item.revision, item.status, item.error ?? item.user_note ?? item.proof_artifact_id ?? (item.status === 'not_requested' ? '按约定未执行,非测试通过' : '选择实际证据或完成用户验收')].map(escapeCell).join(' | ') + ' |');
|
||||
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
|
||||
if (report.requirements.error) lines.push('', report.requirements.error);
|
||||
}
|
||||
if (report.taskPlan?.configured) {
|
||||
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
|
||||
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
|
||||
|
||||
@@ -14,6 +14,7 @@ import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
import { currentBrowserVerification } from './browser/browser-manager.mjs';
|
||||
import { assertBrowserResolved } from '../shared/contracts/browser.mjs';
|
||||
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
|
||||
import { RequirementReview } from './tasks/requirement-review.mjs';
|
||||
import { assertMcpResolved } from './tools/mcp-contract.mjs';
|
||||
import { assertWorkersResolved, workerForProject } from '../shared/contracts/workers.mjs';
|
||||
|
||||
@@ -227,6 +228,7 @@ export class GitDelivery {
|
||||
const browser = await currentBrowserVerification(this.store, session, inspection);
|
||||
if (browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
|
||||
const taskPlan = await new TaskPlanManager(this.store).assertReady(session, { inspection });
|
||||
const requirements = await new RequirementReview(this.store).assertReady(session, { inspection });
|
||||
const files = await this.selectedFiles(session, project, snapshot);
|
||||
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
|
||||
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
|
||||
@@ -236,12 +238,14 @@ export class GitDelivery {
|
||||
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
|
||||
this.assertIdle(session, idleOptions); this.assertTask(session);
|
||||
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
|
||||
await new RequirementReview(this.store).assertReady(session, { expectedBinding: requirements.binding_sha256 });
|
||||
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
|
||||
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
|
||||
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
|
||||
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
|
||||
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
|
||||
...(taskPlan.configured ? { taskPlanId: taskPlan.plan_id, taskPlanRevision: taskPlan.revision, taskPlanBindingSha256: taskPlan.binding_sha256 } : {}),
|
||||
...(requirements.configured ? { requirementBindingSha256: requirements.binding_sha256 } : {}),
|
||||
...(browser.required ? { browserJobId: browser.jobId, browserPlanId: browser.planId, browserBuildSha256: browser.buildSha256 } : {}),
|
||||
protectedIndexSha256: protectedIndex(snapshot.stage, snapshot.flags, files.map(file => file.path)), diffArtifactId: diffArtifact.id,
|
||||
policy: { name: 'local-reviewed-snapshot', hooks: 'disabled', signing: 'unsigned', remote: 'none',
|
||||
@@ -294,6 +298,7 @@ export class GitDelivery {
|
||||
}
|
||||
|
||||
async verifyBrowserDelivery(session, plan, inspection) {
|
||||
await new RequirementReview(this.store).assertReady(session, { inspection, expectedBinding: plan.requirementBindingSha256 ?? null });
|
||||
await new TaskPlanManager(this.store).assertReady(session, { inspection, expectedBinding: plan.taskPlanBindingSha256 ?? null });
|
||||
assertBrowserResolved(this.store, session.projectId);
|
||||
const browser = await currentBrowserVerification(this.store, session, inspection);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { TaskPlanManager } from './task-plan-manager.mjs';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
|
||||
import { taskContract } from '../../shared/contracts/task-control.mjs';
|
||||
import { taskPlanInput, planHash, planError } from '../../shared/contracts/task-plans.mjs';
|
||||
import { readText } from '../../server/files.mjs';
|
||||
import { FileResults } from './file-results.mjs';
|
||||
|
||||
const same = (a, b) => planHash(a) === planHash(b);
|
||||
const now = () => new Date().toISOString();
|
||||
const checkKeys = (value, keys) => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
|
||||
throw planError('要求复核包含未声明字段。', 'input', 400);
|
||||
};
|
||||
const requiredText = (value, max) => {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > max || value.includes('\0')) throw planError('请填写有效的要求或复核说明。', 'input', 400);
|
||||
return value.trim();
|
||||
};
|
||||
export function requirementSources(task) {
|
||||
return [{ kind: 'goal', id: task.id, text: task.goal, at: task.createdAt ?? null },
|
||||
...(task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => ({ kind: 'instruction', id: row.id, text: row.content, at: row.createdAt ?? row.at ?? null }))]
|
||||
.map(row => ({ ...row, sha256: planHash({ kind: row.kind, id: row.id, text: row.text }) }));
|
||||
}
|
||||
function itemInput(value, sources) {
|
||||
checkKeys(value, ['key', 'title', 'criterion', 'source', 'kind', 'tools', 'paths', 'checks', 'viewport_width', 'actions', 'method']);
|
||||
checkKeys(value.source, ['kind', 'id', 'start', 'end']);
|
||||
const original = sources.find(row => row.kind === value.source.kind && row.id === value.source.id);
|
||||
const { start, end } = value.source;
|
||||
if (!original || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end <= start || end > original.text.length)
|
||||
throw planError('要求来源必须是当前Task用户原文的有效范围。', 'input', 400);
|
||||
const method = value.method ?? 'evidence';
|
||||
if (!['evidence', 'user', 'not_requested'].includes(method)) throw planError('复核方式无效。', 'input', 400);
|
||||
const { source, method: ignored, ...fields } = value;
|
||||
// Reuse the existing bounded evidence scopes; a statement alone never passes.
|
||||
const step = taskPlanInput({ expected_revision: 0, steps: [{ ...fields, depends_on: [] }] }).steps[0];
|
||||
if (method === 'not_requested' && step.kind !== 'checks') throw planError('仅检查约定可记录为未执行。', 'input', 400);
|
||||
return { ...step, method, source: { ...source, quote: original.text.slice(start, end), sourceSha256: original.sha256, at: original.at } };
|
||||
}
|
||||
const ledgerContract = row => ({ schemaVersion: 1, kind: 'task-requirements', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
|
||||
taskId: row.taskId, runId: row.runId, revision: row.revision, parentId: row.parentId, items: row.items, sources: row.sources, createdAt: row.createdAt });
|
||||
const proofContract = row => ({ schemaVersion: 1, kind: 'requirement-proof', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
|
||||
taskId: row.taskId, runId: row.runId, key: row.key, requirementSha256: row.requirementSha256, requirementRevision: row.requirementRevision,
|
||||
evidenceId: row.evidenceId, outcome: row.outcome, sourceFingerprint: row.sourceFingerprint, status: row.status, error: row.error,
|
||||
note: row.note, createdAt: row.createdAt });
|
||||
|
||||
// This ledger lives on the existing Task. It delegates all engineering proof
|
||||
// checks to TaskPlanManager and grants no tool, command or file permissions.
|
||||
export class RequirementReview {
|
||||
constructor(store, { planner = new TaskPlanManager(store), redact = String } = {}) { this.store = store; this.planner = planner; this.redact = redact; }
|
||||
current(session) { return this.store.owned('task', session.taskId, session.id).requirementRevisions?.at(-1) ?? null; }
|
||||
verifyRecord(session, row, kind, contract) {
|
||||
if (row.sessionId !== session.id || row.projectId !== session.projectId || row.taskId !== session.taskId) throw planError('要求记录不属于当前项目和Task。');
|
||||
const original = this.planner.artifact(session, row.contractArtifactId, kind, row.taskId, row.runId);
|
||||
if (original.artifact.sha256 !== row.contractSha256 || original.text !== JSON.stringify(contract(row))) throw planError('要求或复核记录与原工件不一致。');
|
||||
}
|
||||
write(session, run, row, kind, contract) {
|
||||
const artifact = this.store.artifactStore.write(session, run, contract(row), { kind });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
return { ...row, contractArtifactId: artifact.id, contractSha256: artifact.sha256 };
|
||||
}
|
||||
async evidence(session, item, id, inspection) {
|
||||
if (item.kind === 'results') {
|
||||
const result = new FileResults(this.store).verify(session, id, { current: false });
|
||||
if (result.taskId !== session.taskId || !item.paths.every(file => result.files.some(row => row.path === file)))
|
||||
throw planError('成果凭据不属于当前Task或未覆盖要求文件。');
|
||||
const files = result.files.filter(file => item.paths.includes(file.path));
|
||||
for (const file of files) if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256)
|
||||
throw planError('当前要求的成果文件SHA已变化。', 'stale');
|
||||
const artifact = this.store.owned('artifact', result.contractArtifactId, session.id);
|
||||
return { kind: 'file_result', id: result.id, runId: result.runId, scope: 'current_requirement_files',
|
||||
files: files.map(({ path, sha256, origin }) => ({ path, sha256, origin })),
|
||||
artifacts: [{ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes }] };
|
||||
}
|
||||
const outcome = await this.planner.evidence(session, item, id, { inspection });
|
||||
if (item.kind === 'analysis') {
|
||||
const record = this.store.owned('tool', id, session.id);
|
||||
const result = JSON.parse(this.planner.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId).text);
|
||||
if (record.tool === 'read_file' && (!result.sha256 || readText(this.store.project(session.projectId), result.path).sha256 !== result.sha256))
|
||||
throw planError('原读取对应旧文件SHA,请使用当前文件的实际读取。', 'stale');
|
||||
if (record.tool === 'inspect_project' && result.sourceFingerprint !== inspection.sourceFingerprint)
|
||||
throw planError('原工程观察对应旧源码输入。', 'stale');
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
save(session, input) { return this.planner.mutate(session, 'user', async () => {
|
||||
checkKeys(input, ['expected_revision', 'requirements']);
|
||||
const { task, run } = this.planner.task(session), previous = this.current(session), revision = previous?.revision ?? 0;
|
||||
if (previous) this.verifyRecord(session, previous, 'task-requirements', ledgerContract);
|
||||
if (input.expected_revision !== revision) throw planError('要求修订已变化,请刷新后保存。', 'stale');
|
||||
if (revision >= 24 || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > 24)
|
||||
throw planError('每个Task最多24项要求与24次修订。', 'input', 400);
|
||||
const sources = requirementSources(task), items = input.requirements.map(value => itemInput(value, sources));
|
||||
if (new Set(items.map(row => row.key)).size !== items.length || previous?.items.some(row => !items.some(item => item.key === row.key)))
|
||||
throw planError('要求ID需唯一;原要求不能删除,可修订并保留原记录。', 'input', 400);
|
||||
if (JSON.stringify(items).length > 24000) throw planError('要求范围过大,请缩小Task。', 'input', 400);
|
||||
for (const item of items) {
|
||||
if (item.method === 'not_requested' && taskContract(task).checks !== 'skip') throw planError('当前用户约定没有跳过检查,不能标为按约定未执行。');
|
||||
const old = previous?.items.find(row => row.key === item.key);
|
||||
const { revision: oldRevision, ...oldContent } = old ?? {};
|
||||
item.revision = old && same(oldContent, item) ? oldRevision : (oldRevision ?? 0) + 1;
|
||||
}
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id || !same(sources, requirementSources(task)))
|
||||
throw planError('保存期间原任务、来源或要求已变化。', 'stale');
|
||||
const row = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
||||
revision: revision + 1, parentId: previous?.id ?? null, items, sources, createdAt: now() }, 'task-requirements', ledgerContract);
|
||||
(task.requirementRevisions ??= []).push(row);
|
||||
this.store.save(session, { type: 'task.requirements_saved', detail: { id: row.id, revision: row.revision } });
|
||||
return row;
|
||||
}); }
|
||||
async inspect(session, { candidates = false, inspection = null } = {}) {
|
||||
const { task, run } = this.planner.task(session), ledger = this.current(session), sources = requirementSources(task);
|
||||
const base = { configured: !!ledger, task_id: task.id, revision: ledger?.revision ?? 0, sources, items: [], all_resolved: false, binding_sha256: null,
|
||||
note: '证据核对只证明所选范围;模型完成答复不等于业务验收。' };
|
||||
if (!ledger) return { ...base, status: 'not_recorded', unreviewed_sources: sources.map(row => row.id) };
|
||||
try { this.verifyRecord(session, ledger, 'task-requirements', ledgerContract); }
|
||||
catch (error) { return { ...base, status: 'unverified', error: this.redact(error.message) }; }
|
||||
const unreviewed = sources.filter(row => !ledger.sources.some(old => old.id === row.id && old.sha256 === row.sha256)).map(row => row.id);
|
||||
const items = [], proofs = task.requirementProofs ?? [];
|
||||
for (const item of ledger.items) {
|
||||
const source = sources.find(row => row.id === item.source.id && row.kind === item.source.kind);
|
||||
const proof = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item) && row.status === 'verified');
|
||||
const attempt = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item));
|
||||
let status = 'pending', error = null, outcome = null;
|
||||
try {
|
||||
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('原用户来源已变化。', 'stale');
|
||||
if (item.method === 'not_requested') {
|
||||
if (taskContract(task).checks !== 'skip') throw planError('当前检查约定已变化。', 'stale');
|
||||
status = 'not_requested';
|
||||
} else if (proof) {
|
||||
this.verifyRecord(session, proof, 'requirement-proof', proofContract);
|
||||
const sourceRead = item.kind === 'analysis' && this.store.core.tool.get(proof.evidenceId)?.tool === 'read_file';
|
||||
if (item.kind === 'analysis' || item.method === 'user') {
|
||||
inspection ??= await inspectProject(this.store.project(session.projectId));
|
||||
if (!inspection.scope.complete || !sourceRead && proof.sourceFingerprint !== inspection.sourceFingerprint) throw planError('复核后源码输入已变化。', 'stale');
|
||||
}
|
||||
if (item.method !== 'user') {
|
||||
outcome = await this.evidence(session, item, proof.evidenceId, inspection);
|
||||
if (!same(outcome, proof.outcome)) throw planError('实际记录与原复核结果不一致。', 'stale');
|
||||
}
|
||||
status = item.method === 'user' ? 'user_confirmed' : 'evidence_verified';
|
||||
} else if (attempt?.status === 'rejected') status = 'failed';
|
||||
} catch (cause) { status = cause.code === 'stale' ? 'stale' : 'unverified'; error = this.redact(cause.message); }
|
||||
items.push({ ...item, status, error, evidence: outcome, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
|
||||
user_note: status === 'user_confirmed' ? proof.note : null,
|
||||
last_rejection: attempt?.status === 'rejected' ? { id: attempt.id, message: attempt.error, at: attempt.createdAt } : null,
|
||||
...(candidates && item.method === 'evidence' ? { candidates: this.planner.candidates(session, item) } : {}) });
|
||||
}
|
||||
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('核对期间Task/Run或要求已变化。', 'stale');
|
||||
const resolved = !unreviewed.length && items.every(row => ['evidence_verified', 'user_confirmed', 'not_requested'].includes(row.status));
|
||||
return { ...base, items, unreviewed_sources: unreviewed, status: resolved ? 'resolved' : 'incomplete', all_resolved: resolved,
|
||||
history: proofs.map(row => ({ id: row.id, key: row.key, revision: row.requirementRevision, status: row.status, error: row.error, at: row.createdAt, artifact_id: row.contractArtifactId })),
|
||||
contract_artifact_id: ledger.contractArtifactId, contract_sha256: ledger.contractSha256,
|
||||
binding_sha256: resolved ? planHash({ ledger: ledger.contractSha256, proofs: items.map(row => [row.key, row.proof_id, row.status, row.evidence]) }) : null };
|
||||
}
|
||||
verify(session, input) { return this.planner.mutate(session, 'user', async () => {
|
||||
checkKeys(input, ['expected_revision', 'key', 'evidence_id', 'note']);
|
||||
const { task, run } = this.planner.task(session), ledger = this.current(session);
|
||||
if (!ledger || ledger.revision !== input.expected_revision) throw planError('要求修订已变化,请刷新后复核。', 'stale');
|
||||
this.verifyRecord(session, ledger, 'task-requirements', ledgerContract);
|
||||
const item = ledger.items.find(row => row.key === input.key);
|
||||
if (!item || item.method === 'not_requested') throw planError('请选择需要复核的当前要求。');
|
||||
if ((task.requirementProofs?.length ?? 0) >= 128) throw planError('复核记录已到上限,请缩小任务。');
|
||||
if (item.method === 'user' ? input.evidence_id !== undefined : input.note !== undefined) throw planError('用户确认和原证据核对不能混用。', 'input', 400);
|
||||
const note = item.method === 'user' ? requiredText(input.note, 1000) : null;
|
||||
let outcome = null, inspection = null, error = null;
|
||||
try {
|
||||
const source = requirementSources(task).find(row => row.kind === item.source.kind && row.id === item.source.id);
|
||||
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('用户要求来源已变化。', 'stale');
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
inspection = await inspectProject(this.store.project(session.projectId));
|
||||
if (!inspection.scope.complete) throw planError('源码范围不完整,不能复核。');
|
||||
if (item.method !== 'user') outcome = await this.evidence(session, item, input.evidence_id, inspection);
|
||||
} catch (cause) { error = this.redact(cause.message); }
|
||||
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('复核期间任务或要求已变化。', 'stale');
|
||||
const proof = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
||||
key: item.key, requirementSha256: planHash(item), requirementRevision: item.revision, evidenceId: input.evidence_id ?? null,
|
||||
sourceFingerprint: inspection?.sourceFingerprint ?? null, outcome, status: error ? 'rejected' : 'verified', error, note, createdAt: now() }, 'requirement-proof', proofContract);
|
||||
(task.requirementProofs ??= []).push(proof);
|
||||
this.store.save(session, { type: error ? 'task.requirement_rejected' : 'task.requirement_verified', detail: { id: proof.id, key: item.key } });
|
||||
return { status: error ? 'error' : 'completed', proof_id: proof.id, ...(error ? { message: error } : {}) };
|
||||
}); }
|
||||
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
|
||||
const view = await this.inspect(session, { inspection });
|
||||
if (view.configured && !view.all_resolved) throw planError('用户要求仍有待复核、失效或未审阅来源,请先核对要求与证据。', 'stale');
|
||||
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的要求或证据已变化,请重新预览。', 'stale');
|
||||
return view;
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -377,7 +377,7 @@ return async (request, response) => {
|
||||
}
|
||||
}
|
||||
if (method === 'POST' && workerForProject(store, session.projectId)
|
||||
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
|
||||
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|requirements|requirement-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
|
||||
if (method === 'GET' && action === 'evaluations') return json(response,runtime.evaluationManager().view(session));
|
||||
if (method === 'POST' && action === 'evaluations') {
|
||||
const batch=await runtime.evaluationManager().plan(session,await body(request));
|
||||
@@ -518,6 +518,19 @@ return async (request, response) => {
|
||||
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 });
|
||||
return json(response, plan);
|
||||
}
|
||||
if (method === 'GET' && action === 'requirements') {
|
||||
if (url.searchParams.get('taskId') !== session.taskId) throw Object.assign(new Error('所选任务已变化,请刷新要求与证据。'), { status: 409 });
|
||||
return json(response, await runtime.requirementReview().inspect(session, { candidates: true }));
|
||||
}
|
||||
if (method === 'POST' && ['requirements', 'requirement-proofs'].includes(action)) {
|
||||
const { taskId, runId, ...input } = await body(request);
|
||||
if (!taskId || !runId || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('原任务或运行已变化,未修改其他任务要求。'), { status: 409 });
|
||||
const manager = runtime.requirementReview();
|
||||
const result = action === 'requirements' ? await manager.save(session, input) : await manager.verify(session, input);
|
||||
const requirements = await manager.inspect(session, { candidates: true });
|
||||
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('保存结果属于原任务,请刷新当前任务。'), { status: 409 });
|
||||
return json(response, { session: store.publicSession(session), requirements, ...(action === 'requirement-proofs' ? { verification: result } : {}) });
|
||||
}
|
||||
if (method === 'GET' && action === 'file-results') return json(response, runtime.fileResults().inspect(session, { path: url.searchParams.get('path') }));
|
||||
if (method === 'POST' && ['file-results', 'file-results/complete'].includes(action)) {
|
||||
const { taskId, runId, ...input } = await body(request);
|
||||
|
||||
@@ -40,6 +40,7 @@ import { EngineRunner } from '../core/engines/engine-runner.mjs';
|
||||
import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs';
|
||||
import { browserPlanInput } from '../shared/contracts/browser.mjs';
|
||||
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
|
||||
import { RequirementReview } from '../core/tasks/requirement-review.mjs';
|
||||
import { FileResults } from '../core/tasks/file-results.mjs';
|
||||
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
|
||||
import { verifiedCheck } from '../core/delivery-report.mjs';
|
||||
@@ -164,6 +165,7 @@ export class Runtime {
|
||||
if (!delivery.satisfied) throw Object.assign(new Error(delivery.message), { status: 409 });
|
||||
const plan = await this.taskPlanner().inspect(session, { candidates: false });
|
||||
if (plan.configured && !plan.all_verified) throw Object.assign(new Error('原执行计划仍有未核验步骤,请先核对。'), { status: 409 });
|
||||
await this.requirementReview().assertReady(session);
|
||||
if (session.taskId !== taskId || session.runId !== runId || this.projectHasActivity(session.projectId) || !this.fileResults().completion(session).satisfied) throw Object.assign(new Error('核对期间任务、文件或活动已变化,请重新核对。'), { status: 409 });
|
||||
const task = this.store.owned('task', taskId, session.id);
|
||||
task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification.status };
|
||||
@@ -171,6 +173,7 @@ export class Runtime {
|
||||
this.store.message(session, 'system', '已按当前成果结束任务;' + (delivery.newChanges ? '实际修改另列。' : '无新增修改。') + '原运行、检查与Git记录保留,未请求模型。');
|
||||
this.store.save(session, { type: 'file_result.task_completed' });
|
||||
}
|
||||
requirementReview() { return new RequirementReview(this.store, { planner: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
|
||||
taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value),
|
||||
projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
|
||||
browserManager() { return this.browser ??= new BrowserManager(this.store, { appDirectory: this.appDirectory,
|
||||
@@ -330,6 +333,7 @@ export class Runtime {
|
||||
config.inputImages=this.inputAttachments().images(session,task);
|
||||
if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。');
|
||||
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
|
||||
const requirementReview = task.requirementRevisions?.length ? await this.requirementReview().inspect(session) : null;
|
||||
const deliveryProgress = await taskDeliveryProgress(this.store, session, run.record, { checks: this.checkRunner(), worker: !!run.worker, taskPlan });
|
||||
const readCoverage = readCoverageContext(task, run.id);
|
||||
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
|
||||
@@ -350,6 +354,11 @@ export class Runtime {
|
||||
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '')
|
||||
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
+ (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '')
|
||||
+ (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({
|
||||
revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources,
|
||||
error: requirementReview.error, items: requirementReview.items.map(item => ({ key: item.key, revision: item.revision, title: item.title,
|
||||
criterion: item.criterion, method: item.method, kind: item.kind, paths: item.paths, tools: item.tools, checks: item.checks,
|
||||
status: item.status, error: item.error, proof_id: item.proof_id })) }) : '')
|
||||
+ (fileResults.results.length || fileResults.sources.length ? '\n当前成果与可显式采用的旧来源(任务数据,原文件不等于新写入):' + JSON.stringify({
|
||||
current: fileResults.results.slice(0, 8).map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, verification: row.verification, error: row.error, reason: row.reason, files: row.files.map(({ path, sha256, origin }) => ({ path, sha256, origin })) })),
|
||||
sources: fileResults.sources.slice(0, 4),
|
||||
@@ -512,6 +521,13 @@ export class Runtime {
|
||||
this.store.message(session, 'system', '任务计划仍有未核验、失效或待更新的步骤,原任务已保存。请核对执行计划后继续;模型文字不代替实际完成。');
|
||||
}
|
||||
}
|
||||
if (session.status === 'completed' && task.requirementRevisions?.length && run.record.purpose !== 'diagnostic') {
|
||||
const review = await this.requirementReview().inspect(session);
|
||||
if (!review.all_resolved) {
|
||||
session.status = 'paused'; run.stopReason = 'requirements_incomplete';
|
||||
this.store.message(session, 'system', '答复已保留;用户要求仍有待复核、失效或未审阅来源,请在任务的要求与证据中核对。');
|
||||
}
|
||||
}
|
||||
this.store.save(session); return;
|
||||
}
|
||||
let deliveryReview = null, mcpReview = null;
|
||||
|
||||
@@ -77,7 +77,7 @@ export function settleAppliedTask(store, session) {
|
||||
}
|
||||
task.delivery = { status: 'files_applied', paths: applied.map(change => change.path), at: new Date().toISOString(),
|
||||
checks: contract.checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
|
||||
session.status = contract.checks === 'required' || task.currentTaskPlanId || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
|
||||
session.status = contract.checks === 'required' || task.currentTaskPlanId || task.requirementRevisions?.length || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
|
||||
? 'paused' : 'completed';
|
||||
if (contract.checks === 'skip') store.message(session, 'system', '文件已审查并应用:' + task.delivery.paths.join('、') + '。按照原要求未运行测试,可在文件列表打开结果。');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user