feat: verify existing file results and preserve honest task delivery

This commit is contained in:
Agent Workbench Dev
2026-11-02 14:30:38 +08:00
parent 0dc0325346
commit d5d9df8275
44 changed files with 1011 additions and 81 deletions
+2 -1
View File
@@ -29,6 +29,7 @@ export function DeliveryPanel({ session, busy, onSession, onError, openArtifact
const unresolved = jobs.some(job => job.requiresVerification);
const pending = session.changes.some(change => ['pending', 'conflict'].includes(change.status));
const hasApplied = session.changes.some(change => change.taskId === task?.id && change.status === 'applied');
const existingOnly = !hasApplied && !!session.execution?.fileResults?.length;
const reports = session.execution?.artifacts.filter(artifact => artifact.kind === 'delivery-report-markdown') ?? [];
const latestReport = reports.at(-1);
const waitingPlan = (session.execution?.deliveryPlans ?? []).filter(plan => plan.taskId === task?.id
@@ -105,7 +106,7 @@ export function DeliveryPanel({ session, busy, onSession, onError, openArtifact
<label className="form-field delivery-message">提交说明<textarea aria-label="提交说明" rows={2} value={message} maxLength={1600} disabled={busy || running} onChange={event => setMessage(event.target.value)} /></label>
<details className="delivery-author"><summary>Git署名</summary><p>默认采用项目Git署名;尚未配置时使用 Agent Workbench 本地身份。预览会展示实际署名。</p><label className="form-field">提交者姓名<input value={authorName} disabled={busy || running} onChange={event => setAuthorName(event.target.value)} placeholder="采用默认署名" autoComplete="off" /></label><label className="form-field">提交者邮箱<input type="email" value={authorEmail} disabled={busy || running} onChange={event => setAuthorEmail(event.target.value)} placeholder="采用默认邮箱" autoComplete="off" /></label></details>
<button type="button" className="button primary" aria-label="预览Git提交" disabled={!task || !hasApplied || pending || busy || running || unresolved || planning || !message.trim()} onClick={prepare}>{planning ? <LoaderCircle size={14} className="spin" /> : <GitCommitHorizontal size={14} />}预览Git提交</button>
{(!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
{existingOnly ? <p className="record-footnote">本任务沿用已有成果,无新增修改,不创建空提交。可生成报告核对成果与原检查。</p> : (!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
{jobs.slice().reverse().map(job => <div key={job.id} className={'delivery-job ' + (job.requiresVerification ? 'delivery-attention' : '')}>
<div className="record-heading"><Status value={job.status} /><code>{job.id.slice(0, 8)}</code>{active.includes(job.status) && <button type="button" className="text-button" onClick={() => api<Session>('/sessions/' + session.id + '/delivery-jobs/' + job.id + '/stop', {}).then(onSession).catch(onError)}>停止提交</button>}</div>
<time>{date(job.startedAt)} · {job.branch}</time>
+15
View File
@@ -0,0 +1,15 @@
.file-results .record-heading { flex-wrap: wrap; }
.file-result-row { border-top: 1px solid var(--line); padding: 13px 0; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-row > div:first-child { display: flex; flex-direction: column; gap: 2px; margin-bottom: 8px; }
.file-result-row small { color: var(--muted); font-size: 11px; }
.file-result-row > p { margin: 8px 0; }
.file-result-sha { display: block; font: 11px/1.65 "Cascadia Code", Consolas, monospace; overflow-wrap: anywhere; color: var(--muted); }
.file-result-error, .file-result-notice { padding: 9px 11px; background: #faf4e8; color: #684b19; border-left: 2px solid #b18c48; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-form { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 8px; }
.file-result-form summary { cursor: pointer; font-weight: 600; font-size: 12px; padding: 5px 0; }
.file-result-form label { display: flex; flex-direction: column; gap: 6px; margin: 12px 0; font-size: 12px; }
.file-result-form select, .file-result-form textarea { width: 100%; min-width: 0; border: 1px solid var(--line); border-radius: 5px; padding: 9px; background: var(--panel, #fff); font: inherit; color: inherit; }
.file-result-form pre { max-height: 230px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; background: #f3f6f4; border: 1px solid var(--line); padding: 10px; font: 11px/1.7 Consolas, monospace; }
.file-result-finish { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 9px; }
.file-result-outcome { padding: 10px; background: #edf7ef; color: #256148; font-size: 12px; line-height: 1.7; }
@media (max-width: 600px) { .file-results button, .file-result-form select { min-height: 42px; } .file-result-form textarea { font-size: 16px; } }
+83
View File
@@ -0,0 +1,83 @@
import { useEffect, useRef, useState } from 'react';
import { FileCheck2, FileText, LoaderCircle, RefreshCw } from 'lucide-react';
import { api } from './api';
import type { Session, FileResultView } from './types';
import './FileResultsPanel.css';
type View = { taskId: string; results: FileResultView[]; sources: { id: string; taskId: string; runId: string; reason: string; files: { path: string; sha256: string }[] }[] };
type File = { path: string; content: string; sha256: string; bytes: number };
export function FileResultsPanel({ session, busy, onSession, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task;
const [view, setView] = useState<View | null>(null), [files, setFiles] = useState<string[]>([]);
const [path, setPath] = useState(''), [file, setFile] = useState<File | null>(null), [source, setSource] = useState('');
const [reason, setReason] = useState(''), [notice, setNotice] = useState('');
const [loading, setLoading] = useState(false), [acting, setActing] = useState(false);
const scope = useRef(0), readRequest = useRef(0), viewRequest = useRef(0), flight = useRef(false);
const known = view?.sources.filter(row => row.files.some(file => file.path === path)) ?? [];
const current = view?.results.some(row => row.verification === 'current');
async function load() {
const id = scope.current, request = ++viewRequest.current; setLoading(true);
try {
const [result, inventory] = await Promise.all([api<View>('/sessions/' + session.id + '/file-results' + (path ? '?path=' + encodeURIComponent(path) : '')), api<{ files: { path: string; kind: string; bytes: number }[] }>('/projects/' + session.projectId + '/files')]);
if (scope.current !== id || viewRequest.current !== request) return;
setView(result); setFiles(inventory.files.filter(item => item.kind === 'file' && item.bytes <= 1024 * 1024).map(item => item.path));
} catch (error) { if (scope.current === id && viewRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id && viewRequest.current === request) setLoading(false); }
}
useEffect(() => {
scope.current++; readRequest.current++; flight.current = false; setActing(false); setView(null); setPath(''); setFile(null); setSource(''); setReason(''); setNotice(''); void load();
return () => { scope.current++; readRequest.current++; };
}, [session.id, task?.id]);
useEffect(() => { void load(); }, [session.execution?.fileResults?.at(-1)?.id, session.execution?.run?.id, session.status]);
async function choose(value: string) {
setPath(value); setFile(null); setSource(''); setNotice('');
const id = scope.current, request = ++readRequest.current, viewId = ++viewRequest.current;
setLoading(false);
if (!value) return;
try { const [result, currentView] = await Promise.all([api<File>('/projects/' + session.projectId + '/file?path=' + encodeURIComponent(value)), api<View>('/sessions/' + session.id + '/file-results?path=' + encodeURIComponent(value))]);
if (scope.current === id && readRequest.current === request) { setFile(result); if (viewRequest.current === viewId) setView(currentView); }
} catch (error) { if (scope.current === id && readRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
}
async function save(complete = false) {
if (!task || !session.execution?.run || flight.current) return;
if (!complete && (!file || file.path !== path || !reason.trim())) return;
const id = scope.current; viewRequest.current++; setLoading(false); flight.current = true; setActing(true); setNotice('');
try {
const result = await api<View & { session: Session }>('/sessions/' + session.id + '/file-results' + (complete ? '/complete' : ''), {
taskId: task.id, runId: session.execution.run.id,
...(!complete && file ? { files: [{ path: file.path, sha256: file.sha256, ...(source ? { source_result_id: source } : {}) }], reason } : {}),
});
if (scope.current !== id) return;
setView(result); onSession(result.session); setNotice(complete ? '任务已按当前成果结束,原运行和检查记录保留。' : '当前文件已核对并登记;未新增文件改动、测试或Git提交。');
} catch (error) { if (scope.current === id) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id) { flight.current = false; setActing(false); } }
}
return <section className="task-record-section file-results" aria-label="当前文件成果" aria-busy={loading || acting}>
<div className="record-heading"><FileCheck2 size={15} /><h3>当前文件成果</h3><span>{view?.results.length ?? 0} 份凭据</span></div>
<p className="record-footnote">已有文件可以核对后沿用。成果、实际修改、检查与提交分别保留。</p>
<button type="button" className="text-button" disabled={loading || acting} onClick={() => void load()}>{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}刷新成果状态</button>
{view?.results.map(row => <article className="file-result-row" key={row.id}>
<div><strong>{row.verification === 'current' ? '当前文件已核对' : row.verification === 'stale' ? '需要重新核对' : '原凭据需核查'}</strong><small>Task {row.taskId.slice(0, 8)} · Run {row.runId.slice(0, 8)}</small></div>
{row.files.map(item => <div key={item.path}><code>{item.path}</code><small className="file-result-sha">SHA-256 {item.sha256}</small>{item.origin && <p className="record-footnote">采用自 Task {item.origin.taskId.slice(0, 8)} · Run {item.origin.runId.slice(0, 8)}<br />原文件 SHA-256 {item.origin.sha256}</p>}
{row.verification !== 'current' && <button type="button" className="text-button" disabled={busy || acting} onClick={() => { void choose(item.path); setReason(row.reason); }}>重新打开此文件核对</button>}
</div>)}
<p>{row.reason}</p>{row.error && <p className="file-result-error">{row.error}</p>}
<button type="button" className="text-button" onClick={() => openArtifact(row.contractArtifactId)}><FileText size={13} />查看原成果凭据</button>
</article>)}
<details className="file-result-form">
<summary>核对已有文件</summary>
<label>选择项目内文件<select aria-label="成果文件" value={path} disabled={busy || acting || loading} onChange={event => void choose(event.target.value)}><option value="">选择一个文件</option>{files.map(value => <option key={value} value={value}>{value}</option>)}</select></label>
{path && <button type="button" className="text-button" disabled={busy || acting} onClick={() => void choose(path)}><RefreshCw size={13} />重新读取当前文件</button>}
{file && <><p className="record-footnote">{file.bytes.toLocaleString('zh-CN')} 字节 · 当前读取 SHA-256</p><code className="file-result-sha">{file.sha256}</code><pre aria-label="成果文件内容">{file.content.length > 12000 ? file.content.slice(0, 12000) + '\n…界面仅展开前12000字符;核对保存完整文件快照。' : file.content}</pre></>}
{!!known.length && <label>采用来源<select aria-label="成果来源" value={source} disabled={busy || acting} onChange={event => setSource(event.target.value)}><option value="">选择原任务成果</option>{known.map(row => <option key={row.id} value={row.id}>Task {row.taskId.slice(0, 8)} · {row.reason.slice(0, 60)}</option>)}</select></label>}
<label>采用原因<textarea aria-label="成果采用原因" rows={3} maxLength={600} placeholder="说明这个文件满足了当前任务的哪些要求" value={reason} disabled={busy || acting} onChange={event => setReason(event.target.value)} /></label>
<button type="button" className="button secondary" disabled={busy || acting || !file || !reason.trim() || !!known.length && !source} onClick={() => void save()}>{acting ? <LoaderCircle size={14} className="spin" /> : <FileCheck2 size={14} />}核对并采用此文件</button>
</details>
{current && task?.status !== 'completed' && <div className="file-result-finish"><p className="record-footnote">当前要求已满足时可结束。修改要求、原检查和执行计划仍需通过核对。</p><button type="button" className="button secondary" disabled={busy || acting} onClick={() => void save(true)}>按当前成果结束任务</button></div>}
{task?.delivery?.status === 'existing_verified' && <p className="file-result-outcome">结束时采用已有成果 · 无新增修改。当前有效性见逐项核对,检查与Git另列。</p>}
{notice && <p className="file-result-notice" role="status">{notice}</p>}
</section>;
}
+3 -1
View File
@@ -13,6 +13,7 @@ import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
@@ -21,7 +22,7 @@ stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持';
stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过';
stopReasons.delivery_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' }) : '执行中';
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> }) {
@@ -94,6 +95,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}><small>{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}</small><br />{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
{task && <TaskPlanPanel 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}
+5 -5
View File
@@ -5,16 +5,16 @@ import { Modal, Status } from './components';
import type { Session, TaskPlanReply, TaskPlanStep, TaskPlanView } from './types';
import './TaskPlanPanel.css';
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', checks: '工程检查', browser: '页面验收' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', results: '当前文件成果', checks: '工程检查', browser: '页面验收' };
const readTools = { inspect_project: '识别工程', read_file: '读取文件', list_files: '文件清单', search_files: '搜索文件', index_project: '工程索引', query_code: '定位符号', read_research_evidence: 'REA原结果', inspect_engine_checks: '引擎核验', read_browser_result: '原页面记录' };
const browserActions = { fill: '填写', select: '选择', click: '点击', assert_text: '文本断言', assert_count: '数量断言', assert_visible: '可见断言' };
const cleanStep = (step: TaskPlanStep): TaskPlanStep => ({ key: step.key, title: step.title, criterion: step.criterion, kind: step.kind, depends_on: [...step.depends_on],
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : step.kind === 'changes' ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : ['changes', 'results'].includes(step.kind) ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
: step.kind === 'checks' ? { checks: (step.checks ?? []).map(value => value.trim()).filter(Boolean) } : { viewport_width: step.viewport_width, actions: [...(step.actions ?? [])] }) });
const freshStep = (kind: TaskPlanStep['kind'] = 'analysis'): TaskPlanStep => ({ key: 'step_' + crypto.randomUUID().slice(0, 8), title: kinds[kind], criterion: '', kind, depends_on: [],
...(kind === 'analysis' ? { tools: ['inspect_project'] } : kind === 'changes' ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
...(kind === 'analysis' ? { tools: ['inspect_project'] } : ['changes', 'results'].includes(kind) ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
const scopeText = (step: TaskPlanStep) => step.kind === 'analysis' ? (step.tools ?? []).map(tool => readTools[tool as keyof typeof readTools] ?? tool).join(' / ')
: step.kind === 'changes' ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: ['changes', 'results'].includes(step.kind) ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: `${step.viewport_width}px · ${(step.actions ?? []).map(action => browserActions[action as keyof typeof browserActions]).join(' / ')}`;
export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact }: {
@@ -116,7 +116,7 @@ export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact
const next = freshStep(event.target.value as TaskPlanStep['kind']); setDraft(steps => steps.map((value, at) => at === index ? { ...next, key: value.key, title: value.title, criterion: value.criterion, depends_on: value.depends_on } : value));
}}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{step.kind === 'analysis' && <div className="plan-option-list"><span>可核验的读取结果(任一)</span>{Object.entries(readTools).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.tools?.includes(key) ?? false} onChange={event => update(index, { tools: event.target.checked ? [...(step.tools ?? []), key] : step.tools?.filter(tool => tool !== key) })} />{label}</label>)}</div>}
{step.kind === 'changes' && <label>改动文件(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{['changes', 'results'].includes(step.kind) && <label>{step.kind === 'results' ? '成果文件' : '改动文件'}(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{step.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={`步骤${index + 1}检查范围`} value={step.checks?.join(',') ?? ''} placeholder="test,build 或 python:test,python:compile" onChange={event => update(index, { checks: event.target.value.split(',') })} /></label>}
{step.kind === 'browser' && <><label>页面宽度<select aria-label={`步骤${index + 1}页面宽度`} value={step.viewport_width} onChange={event => update(index, { viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option>{![1280, 390].includes(step.viewport_width ?? 0) && <option value={step.viewport_width}>{step.viewport_width}px</option>}</select></label>
<div className="plan-option-list"><span>必须实际完成的操作</span>{Object.entries(browserActions).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.actions?.includes(key) ?? false} onChange={event => update(index, { actions: event.target.checked ? [...(step.actions ?? []), key] : step.actions?.filter(action => action !== key) })} />{label}</label>)}</div></>}
+2 -1
View File
@@ -12,7 +12,8 @@ export interface MobileTask extends MobileBrief {
browserObservations?:{id:string;tabId:string;url:string;title:string;createdAt:string;revision:string;scope:{complete:boolean};screenshotSha256:string}[];
inputAttachments?: import('./types').InputAttachment[];
budgetPause?: import('./types').BudgetPause|null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string }; delivery?: { status: string; paths: string[]; checks: string } } | null;
fileResults?: { id: string; taskId: string; runId: string; verification: string; reason: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; sha256: string } | null }[] }[];
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number;
+2
View File
@@ -5,6 +5,7 @@ import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, Refre
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
import { MobileInputImage } from './MobileInputImage';
import './file-results.css';
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
@@ -124,6 +125,7 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
{selectedTask.browserObservations?.slice(-1).map(observation=><MobileBrowserObservation key={observation.id} sessionId={selectedTask.id} observation={observation} onError={cause=>{if(cause instanceof MobileError&&[401,403].includes(cause.status))revoke(cause.message);else setError(cause instanceof Error?cause.message:'原网页截图读取失败。');}}/>)}
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
{!!selectedTask.fileResults?.length && <section className="mobile-file-results" aria-label="当前文件成果"><h2>当前文件成果</h2>{selectedTask.fileResults.map(result => <article key={result.id}><strong>{result.verification === 'current' ? '当前文件已核对' : '文件或要求已变化,请在电脑重新核对'}</strong><p>Task {result.taskId.slice(0, 8)} · Run {result.runId.slice(0, 8)}</p>{result.files.map(file => <p key={file.path}><strong>{file.path}</strong><br /><code>SHA-256 {file.sha256}</code>{file.origin && <><br />来源 Task {file.origin.taskId.slice(0, 8)} · Run {file.origin.runId.slice(0, 8)}<br /><code>原 SHA-256 {file.origin.sha256}</code></>}</p>)}<p>{result.reason}</p><details><summary>原成果凭据 SHA-256</summary><code>{result.contractSha256}</code></details></article>)}<p className="mobile-muted">已有成果与新增修改分开记录;测试、差异和Git结果见各自原记录。</p></section>}
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.stream && item.stream.status !== "completed" && <div className="mobile-stream"><strong>{item.stream.status === "receiving" ? "正在接收模型输出" : "模型输出未完成"}</strong><span>{item.stream.textCharacters ?? 0} 字符 · 片段不执行工具</span>{item.stream.textPreview && <pre>{item.stream.textPreview}</pre>}</div>}{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
{tab === 'changes' && <section className="mobile-changes"><div className="mobile-section-heading"><h2>当前任务的改动</h2><span>{selectedTask.changes.length} 个文件</span></div>{!selectedTask.changes.length && <p className="mobile-muted">尚未提出文件改动。</p>}{selectedTask.changes.map(change => <button key={change.id} className="mobile-file-row" disabled={!!busy || !fresh} onClick={() => void openDiff(change)}><FileDiff size={19} /><div><strong>{change.path}</strong><span>{stateLabel(change.status)} · <b>+{change.additions}</b> / −{change.deletions}</span></div><ChevronRight size={17} /></button>)}<p className="mobile-muted">手机可查看原差异;应用、恢复和 Git 提交在电脑审查。</p></section>}
+6
View File
@@ -0,0 +1,6 @@
.mobile-file-results { padding: 18px; border-block: 1px solid #d8e2dc; background: #f5f8f6; }
.mobile-file-results h2 { font-size: 16px; margin: 0 0 12px; }
.mobile-file-results article { padding: 12px 0; border-bottom: 1px solid #d8e2dc; font-size: 13px; line-height: 1.65; }
.mobile-file-results p { margin: 8px 0; }
.mobile-file-results code { font-size: 11px; overflow-wrap: anywhere; word-break: break-word; }
.mobile-file-results details summary { min-height: 42px; display: flex; align-items: center; cursor: pointer; }
+6 -1
View File
@@ -165,6 +165,11 @@ export interface ContextHistoryGroup {
export interface ContextHistory { planId: string; groups: ContextHistoryGroup[]; offset: number; totalGroups: number; truncated: boolean }
export interface Task { id: string; goal: string; status: string; instructions: { id: string; content: string; createdAt: string; source?: string }[]; usage: Usage; budget: { maxTokens: number }; verification: { status: string; checkJobId: string | null }; origin: string; workspaceIdentity?: WorkspaceIdentity }
export interface Task { contract?: { schemaVersion: number; goal: string; checks: string; inheritedFromTaskId?: string }; delivery?: { status: string; paths: string[]; at: string; checks: string } }
export interface FileResultView {
id: string; taskId: string; runId: string; source: string; reason: string; createdAt: string; verification: 'current' | 'stale' | 'invalid'; error: string | null;
contractArtifactId: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; resultId: string; sha256: string } | null }[];
}
export interface ExecutionSnapshot { fileResults?: Omit<FileResultView, 'verification' | 'error'>[] }
export interface Artifact { id: string; taskId: string | null; runId: string | null; kind: string; mediaType: string; sha256: string; bytes: number; createdAt: string; status: string }
export interface ArtifactPreview extends Artifact { content: string; offset: number; totalCharacters: number; truncated: boolean }
export interface ProjectMemorySource { kind: 'project' | 'file' | 'artifact' | 'session' | 'task' | 'run'; id?: string; path?: string; sha256?: string; sourceFingerprint: string; label?: string; artifactKind?: string }
@@ -200,7 +205,7 @@ export interface ChangeSet {
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
}
export interface TaskPlanStep {
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'checks' | 'browser'; depends_on: string[];
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'results' | 'checks' | 'browser'; depends_on: string[];
tools?: string[]; paths?: string[]; checks?: string[]; viewport_width?: number; actions?: string[];
}
export interface TaskPlanRecord { id: string; taskId: string; runId: string; revision: number; parentPlanId: string | null; steps: TaskPlanStep[]; contractArtifactId: string; contractSha256: string }
+8
View File
@@ -1,5 +1,6 @@
import { approvalBinding } from '../../shared/contracts/companion.mjs';
import { approvalKind } from '../../shared/approval-presentation.mjs';
import { FileResults } from '../tasks/file-results.mjs';
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
@@ -32,6 +33,13 @@ export function mobileSession(store, runtime, session, redact = String) {
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
};
if (task?.delivery) result.task.delivery = pick(task.delivery, ['status', 'paths', 'at', 'checks']);
if ([...store.core.file_result.values()].some(row => row.sessionId === session.id && row.taskId === session.taskId)) {
result.fileResults = new FileResults(store).inspect(session).results.slice(0, 8).map(row => ({
...pick(row, ['id', 'taskId', 'runId', 'createdAt', 'verification', 'contractSha256']), reason: row.reason,
files: row.files.map(file => ({ ...pick(file, ['path', 'sha256', 'bytes']), origin: file.origin ? pick(file.origin, ['taskId', 'runId', 'sha256']) : null })),
}));
}
// Only this explicit projection crosses the remote boundary. Never expose
// providerMessages, model configuration, tool input, host paths or full exports.
const clean = value => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(clean)
+1
View File
@@ -101,6 +101,7 @@ export function clearReadStreak(task) {
task.readProgress.sessionInspection = null;
task.readProgress.observations = [];
task.readProgress.checkPause = false;
task.readProgress.resultRepeats = 0;
}
export function recordFileRead(task, result, invocationId, runId) {
+27 -2
View File
@@ -9,8 +9,11 @@ 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 { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
@@ -48,6 +51,8 @@ export class DeliveryReporter {
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 resultManager = new FileResults(this.store), fileResults = resultManager.inspect(session).results, fileDelivery = resultManager.completion(session), contract = taskContract(task);
const hasFileScope = contract.kind === 'file' || fileResults.length > 0;
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)
@@ -119,13 +124,22 @@ 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'
: 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';
: 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'
: browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered'
: 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 ?? [],
contract, delivery: task.delivery ?? null,
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
fileResults, fileDelivery,
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
note: !fileDelivery.newChanges && hasFileScope ? '本任务无新增修改;未创建提交,已有用户修改保持原归属。' : '仅本任务实际应用的文件可进入Git交付预览。' },
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,
@@ -172,6 +186,17 @@ export function renderDeliveryMarkdown(report) {
'分支:' + (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.fileResults?.length) {
lines.push('', '## 当前已有成果', '', '成果核对保存当前文件与采用原因;不代表本任务新写入、测试通过或业务验收通过。', '',
'| 文件 | 当前核对 | 原文件 SHA256 | 来源 Task / Run | 凭据 |', '| --- | --- | --- | --- | --- |');
for (const result of report.fileResults) {
for (const file of result.files) lines.push('| ' + [file.path, result.verification, file.sha256,
file.origin ? file.origin.taskId + ' / ' + file.origin.runId + ' · 原SHA ' + file.origin.sha256 : '本次读取已有文件', result.contractArtifactId].map(escapeCell).join(' | ') + ' |');
lines.push('', '采用原因:' + result.reason, ...(result.error ? ['', result.error] : []));
}
}
if (report.gitOutcome) lines.push('', report.gitOutcome.note);
if (report.checkPolicy === 'not_requested') lines.push('', '测试约定:按用户要求未自动测试;不记作测试通过。');
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
+144
View File
@@ -0,0 +1,144 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { readText, readLines, safePath } from '../../server/files.mjs';
import { filePage } from '../context/read-budget.mjs';
import { planHash, planError } from '../../shared/contracts/task-plans.mjs';
import { fileResultInput, fileResultRequirements, fileResultRequirementsHash, changeRequirement, requestedFilePaths } from '../../shared/contracts/file-results.mjs';
const contract = ({ contractArtifactId, contractSha256, ...value }) => value;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
export class FileResults {
constructor(store) { this.store = store; }
records(session) { return [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId === session.taskId); }
artifact(session, id, kind, taskId, runId) {
const row = this.store.owned('artifact', id, session.id);
if (row.kind !== kind || row.taskId !== taskId || row.runId !== runId) throw planError('成果原工件的Task/Run或类别不一致。');
return { row, bytes: this.store.artifactStore.readBytes(row) };
}
original(session, record, depth = 0) {
if (depth > 16) throw planError('成果采用链超过16层,请重新核对独立成果范围。');
const run = this.store.owned('run', record.runId, session.id);
if (run.taskId !== record.taskId) throw planError('成果所属运行已不一致。');
const { row, bytes } = this.artifact(session, record.contractArtifactId, 'file-result', record.taskId, record.runId);
if (row.sha256 !== record.contractSha256 || !same(JSON.parse(bytes), contract(record))) throw planError('成果记录与封存原凭据不一致。');
for (const file of record.files) {
const source = this.artifact(session, file.snapshotArtifactId, 'file-result-source', record.taskId, record.runId);
if (source.row.sha256 !== file.sha256 || source.row.bytes !== file.bytes) throw planError('成果原文件快照不一致:' + file.path);
for (const read of file.reads) {
const invocation = this.store.owned('tool', read.invocationId, session.id);
if (invocation.taskId !== record.taskId || invocation.runId !== read.runId || invocation.tool !== 'read_file' || invocation.state !== 'completed'
|| invocation.requiresVerification || invocation.resultArtifactId !== read.artifactId || invocation.argsSha256 !== read.argsSha256) throw planError('成果原读取调用不一致:' + file.path);
const artifact = this.artifact(session, read.artifactId, 'tool-result', record.taskId, read.runId);
if (artifact.row.sha256 !== read.artifactSha256) throw planError('成果原读取工件已变化:' + file.path);
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(value => value.id === read.callId);
if (!call || call.function.name !== 'read_file' || planHash(call.function.arguments) !== read.argsSha256) throw planError('成果原读取参数已变化:' + file.path);
}
if (file.origin) {
const origin = this.original(session, this.store.owned('file_result', file.origin.resultId, session.id), depth + 1);
if (origin.taskId !== file.origin.taskId || origin.runId !== file.origin.runId || origin.contractSha256 !== file.origin.contractSha256
|| !origin.files.some(old => old.path === file.path && old.sha256 === file.origin.sha256)) throw planError('成果来源与原文件不一致:' + file.path);
}
}
return record;
}
verify(session, id, { current = true } = {}) {
const record = this.original(session, this.store.owned('file_result', id, session.id));
if (current) {
if (record.taskId !== session.taskId || record.requirementsSha256 !== fileResultRequirementsHash(this.store.owned('task', session.taskId, session.id))) throw planError('任务要求已变化,请按当前要求重新核对成果。', 'stale');
for (const file of record.files) {
try { if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256) throw new Error('SHA256不同'); }
catch (error) { throw planError('当前文件已变化或无法读取:' + file.path + '。请重新打开并核对。', 'stale'); }
}
}
return record;
}
reads(session, file, current) {
const project = this.store.project(session.projectId), spans = [], receipts = [];
const lineOffsets = [0]; for (let i = 0; i < current.content.length; i++) if (current.content[i] === '\n') lineOffsets.push(i + 1);
for (const callId of file.read_call_ids) {
const row = [...this.store.core.tool.values()].find(item => item.sessionId === session.id && item.taskId === session.taskId && item.callId === callId);
if (!row || row.tool !== 'read_file' || row.state !== 'completed' || row.requiresVerification) throw planError('需要本Task已完成的read_file原调用:' + callId);
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(item => item.id === callId);
if (!call || call.function.name !== row.tool || planHash(call.function.arguments) !== row.argsSha256) throw planError('原文件读取参数与账本不一致。');
const args = JSON.parse(call.function.arguments);
if (args.path !== file.path) throw planError('读取路径与采用路径不一致。');
const { row: artifact, bytes } = this.artifact(session, row.resultArtifactId, 'tool-result', row.taskId, row.runId);
const result = JSON.parse(bytes), { tool_invocation_id, ...page } = result;
if (result.sha256 !== file.sha256 || !same(page, filePage(readLines(project, args), args, { callId, maximumMessageBytes: result.maximum_message_bytes }))) throw planError('读取后文件或原分页结果已变化:' + file.path, 'stale');
const start = lineOffsets[result.range_start_line - 1];
if (start === undefined) throw planError('读取行范围无效。');
let end = start + result.next_offset;
if (result.next_offset === result.total_characters && result.range_end_line < result.total_lines) end++;
spans.push([start + result.offset, end]);
receipts.push({ invocationId: row.id, callId, runId: row.runId, artifactId: artifact.id, artifactSha256: artifact.sha256, argsSha256: row.argsSha256 });
}
let covered = 0;
for (const [start, end] of spans.sort((a, b) => a[0] - b[0])) { if (start > covered) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。'); covered = Math.max(covered, end); }
if (covered < current.content.length) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。');
return receipts;
}
record(session, input, { source = 'agent' } = {}) {
const args = fileResultInput(input, { source }), task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
if (!['agent', 'user'].includes(source) || run.taskId !== task.id || run.purpose === 'diagnostic' && source !== 'user') throw planError('诊断运行不能登记或替代原任务成果。');
const project = this.store.project(session.projectId), prepared = [];
for (const file of args.files) {
const current = readText(project, file.path);
if (current.sha256 !== file.sha256) throw planError('文件已在核对后变化:' + file.path + '。请重新打开文件。', 'stale');
let origin = null;
if (file.source_result_id) {
const original = this.verify(session, file.source_result_id, { current: false });
if (original.taskId === task.id) throw planError('同一Task请复用原成果ID或重新核对当前文件,不重复采用自身成果。');
const old = original.files.find(item => item.path === file.path);
if (!old) throw planError('原成果不包含所选文件:' + file.path);
origin = { resultId: original.id, taskId: original.taskId, runId: original.runId, sha256: old.sha256, contractArtifactId: original.contractArtifactId, contractSha256: original.contractSha256 };
} else {
const previous = [...this.store.core.file_result.values()].findLast(item => item.sessionId === session.id && item.taskId !== task.id && item.files.some(old => old.path === file.path));
if (previous) throw planError('已有旧任务成果,请显式选择原成果ID后采用:' + previous.id);
}
const reads = source === 'agent' ? this.reads(session, file, current) : [];
const bytes = fs.readFileSync(safePath(project, file.path));
if (planHash(bytes) !== file.sha256) throw planError('保存凭据期间文件已变化:' + file.path, 'stale');
prepared.push({ file, current, bytes, reads, origin });
}
const requirements = fileResultRequirements(task), requirementsSha256 = fileResultRequirementsHash(task);
const fingerprint = planHash({ requirementsSha256, files: prepared.map(({ file, origin }) => ({ path: file.path, sha256: file.sha256, origin: origin?.resultId ?? null })).sort((a,b) => a.path.localeCompare(b.path)) });
const previous = this.records(session).find(item => item.fingerprint === fingerprint);
if (previous) { this.verify(session, previous.id); return { status: 'completed', result_id: previous.id, reused: true, files: previous.files, message: '返回原成果凭据,未改写文件、重放工具或新增进展。' }; }
if (this.records(session).length >= 64) throw planError('本Task已保存64份成果,请缩小任务范围。');
const files = prepared.map(({ file, current, bytes, reads, origin }) => {
const snapshot = this.store.artifactStore.write(session, run, bytes, { kind: 'file-result-source', mediaType: 'text/plain' }); this.store.core.artifact.set(snapshot.id, snapshot);
return { path: file.path, sha256: file.sha256, bytes: current.bytes, snapshotArtifactId: snapshot.id, reads, origin };
});
const row = { schemaVersion: 1, kind: 'file-result', id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
createdAt: new Date().toISOString(), source, reason: args.reason, requirements, requirementsSha256, fingerprint, files, status: 'recorded' };
const receipt = this.store.artifactStore.write(session, run, row, { kind: 'file-result' }); this.store.core.artifact.set(receipt.id, receipt);
row.contractArtifactId = receipt.id; row.contractSha256 = receipt.sha256;
this.store.putRecord('file_result', session, row, 'file_result.recorded');
return { status: 'completed', result_id: row.id, reused: false, files: row.files, message: '已核对当前文件并封存已有成果;未创建文件改动、测试或Git提交。' };
}
inspect(session, { path = null } = {}) {
const results = this.records(session).slice(-64).reverse().map(row => {
try { this.verify(session, row.id); return { ...row, verification: 'current', error: null }; }
catch (error) { return { ...row, verification: error.code === 'stale' ? 'stale' : 'invalid', error: error.message }; }
});
const sources = [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId !== session.taskId && (!path || row.files.some(file => file.path === path))).slice(-12).reverse()
.map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, reason: row.reason, files: row.files.map(({ path, sha256 }) => ({ path, sha256 })) }));
return { taskId: session.taskId, results, sources };
}
completion(session) {
const task = this.store.owned('task', session.taskId, session.id), { results } = this.inspect(session);
const latest = new Map();
for (const change of session.changes.filter(item => item.taskId === task.id && item.status === 'applied')) latest.set(change.path, change);
const applied = [...latest.values()].filter(change => { try { return readText(this.store.project(session.projectId), change.path).sha256 === change.sha256 && change.baseSha256 !== change.sha256; } catch { return false; } });
const demand = changeRequirement(task), newApplied = applied.filter(change => !demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after);
const changed = newApplied.length > 0 && demand.paths.every(path => newApplied.some(change => change.path === path));
const current = results.filter(row => row.verification === 'current');
const paths = [...new Set([...applied.map(row => row.path), ...current.flatMap(row => row.files.map(file => file.path))])];
const targets = requestedFilePaths([task.contract?.goal ?? task.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
const missingPaths = targets.filter(path => !paths.includes(path));
return { satisfied: !missingPaths.length && (!demand.required || changed) && (applied.length > 0 || current.length > 0), requiresChange: demand.required && !changed, missingPaths,
status: applied.length ? 'files_applied' : 'existing_verified', paths,
resultIds: current.map(row => row.id), newChanges: applied.length, stale: results.filter(row => row.verification !== 'current').map(row => ({ id: row.id, error: row.error })) };
}
}
+10 -3
View File
@@ -4,6 +4,7 @@ import { safePath } from '../../server/files.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { ChangeSetManager } from '../workspaces/change-sets.mjs';
import { FileResults } from './file-results.mjs';
import { CheckRunner, parseTestEvidence } from '../check-runner.mjs';
import { verifyPythonCheckEvidence } from '../python-runtime.mjs';
import { browserPlanFor, verifyBrowserJob } from '../browser/browser-manager.mjs';
@@ -85,7 +86,7 @@ export class TaskPlanManager {
return inspection;
}
async evidence(session, step, id, cache = {}) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
const record = this.store.owned(kind, id, session.id);
if (record.taskId !== session.taskId || record.requiresVerification) throw planError('原证据不属于当前Task或结果仍待核对。');
const run = this.store.owned('run', record.runId, session.id);
@@ -100,6 +101,12 @@ export class TaskPlanManager {
return { kind, id: record.id, runId: record.runId, scope: 'historical_read_operation', tool: record.tool, callId: record.callId,
argsSha256: record.argsSha256, artifacts: [identity(artifact)] };
}
if (step.kind === 'results') {
const result = new FileResults(this.store).verify(session, record.id);
if (!step.paths.every(path => result.files.some(file => file.path === path))) throw planError('成果凭据尚未覆盖计划指定文件。');
return { kind, id: result.id, runId: result.runId, scope: 'current_existing_files', files: result.files.filter(file => step.paths.includes(file.path)).map(({ path, sha256, origin }) => ({ path, sha256, origin })),
artifacts: [identity(this.store.owned('artifact', result.contractArtifactId, session.id))] };
}
if (step.kind === 'changes') {
if (record.status !== 'completed' || record.direction !== 'apply' || !record.attemptedAt
|| !step.paths.every(file => record.files.some(value => value.path === file && value.writeAttempted && value.state === 'after'))) throw planError('步骤文件必须来自本Task已审查应用的完整变更集。');
@@ -147,11 +154,11 @@ export class TaskPlanManager {
}
proofs(session, plan) { return [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && value.planId === plan.id); }
candidates(session, step) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
return [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
.filter(value => step.kind !== 'analysis' || step.tools.includes(value.tool)).filter(value => step.kind !== 'browser' || this.store.core.browser_plan.get(value.planId)?.viewport.width === step.viewport_width)
.slice(-12).reverse().map(value => ({ id: value.id, status: value.stale ? 'stale' : value.status ?? value.state,
label: step.kind === 'analysis' ? value.tool : step.kind === 'changes' ? value.files.map(file => file.path).join('、')
label: step.kind === 'analysis' ? value.tool : ['changes', 'results'].includes(step.kind) ? value.files.map(file => file.path).join('、')
: step.kind === 'checks' ? value.results.map(result => result.name).join(' / ') : step.viewport_width + 'px · ' + (value.assertions?.passed ?? 0) + '项断言',
runId: value.runId }));
}
+14 -1
View File
@@ -348,7 +348,7 @@ return async (request, response) => {
}
}
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-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));
@@ -489,6 +489,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 === '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);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('任务或运行已切换,未修改其他任务成果。'), { status: 409 });
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请等待原操作结束后核对。'), { status: 409 });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (taskId !== session.taskId || runId !== session.runId || runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('核对期间任务或工程活动已变化。'), { status: 409 });
if (action === 'file-results/complete') {
if (Object.keys(input).length) throw Object.assign(new Error('结束任务不接受额外完成结论。'), { status: 400 });
await runtime.completeFileResults(session);
} else runtime.fileResults().record(session, input, { source: 'user' });
return json(response, { session: store.publicSession(session), ...runtime.fileResults().inspect(session) });
}
if (method === 'POST' && ['task-plans', 'task-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (typeof taskId !== 'string' || typeof runId !== 'string' || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('提交的任务或运行已变化,未修改其他任务计划。'), { status: 409 });
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.23.0';
export const APP_VERSION = '1.24.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+1
View File
@@ -68,6 +68,7 @@ export function projectContext(project) {
'工程任务先用inspect_project识别语言、脚本、规则与Git基线。plan_checks准备已识别npm或Python检查计划,run_checks请求用户确认后执行。Python支持python:test和python:compile,绑定unittest/pytest、实际解释器和源码;混合项目默认保留npm范围,明确选择Python名称才能执行。只凭回答不能声称检查通过。',
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
'已有文本文件满足当前目标时,完整分页读取后用verify_existing_files登记当前SHA和原read_call_ids,说明采用原因;跨Task须显式选择source_result_id。无需重写相同文件,不把旧成果冒充新写入;明确修改要求、测试和页面验收仍需各自真实证据。',
'跨文件修改的提案准备完整后,用prepare_change_set将本Task的change_id封存成整批审查。准备不表示应用;用户核对整个批次并确认,结果未知时先用工作台恢复入口核对,不重放文件写入。',
'复杂工程任务先了解实际范围,再用plan_task保存有限依赖步骤及真实通过条件;verify_task_step引用原工具调用、已应用批次或当前检查/页面job核验。不能删改原条件掩盖失败;inspect_task_plan核对未完成项,模型文字不代替步骤核验。简单问答无需新建工程计划。',
'浏览器实际观察的controls.selector已在该DOM核对仅匹配一个元素,优先使用此定位并核对当前页面变化。按钮的nth-of-type可能在多个父元素各匹配一次,不能假定唯一。浏览器失败返回原错误;根据实际字段修正新计划,不重复读完的同一页。',
+59 -4
View File
@@ -37,6 +37,10 @@ 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 { FileResults } from '../core/tasks/file-results.mjs';
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
import { verifiedCheck } from '../core/delivery-report.mjs';
import { currentBrowserVerification } from '../core/browser/browser-manager.mjs';
import { taskPlanInput, taskProofInput, PLAN_READ_TOOLS } from '../shared/contracts/task-plans.mjs';
import { taskPlanToolDefinitions } from '../shared/contracts/task-plan-tools.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
@@ -66,6 +70,7 @@ labels.act_browser_tab = '执行原页面固定动作';
labels.plan_task = '保存任务依赖计划';
labels.verify_task_step = '核验任务步骤原证据';
labels.inspect_task_plan = '核对任务计划与未完成项';
labels.verify_existing_files = '核对当前已有成果';
labels.read_registered_skill = '读取已登记技能修订';
labels.call_registered_mcp = '请求调用已登记MCP工具';
@@ -75,6 +80,7 @@ export function validateToolArgs(tool, args) {
if (tool === 'read_registered_skill') { skillReadInput(args); return; }
if (tool === 'call_registered_mcp') { mcpCallInput(args); return; }
if (tool === 'plan_task') { taskPlanInput(args); return; }
if (tool === 'verify_existing_files') { fileResultInput(args); return; }
if (tool === 'verify_task_step') { taskProofInput(args); return; }
if (tool === 'inspect_task_plan') { if (Object.keys(args).length) throw new Error('任务计划查询只读取当前Task,不接受执行命令。'); return; }
if (tool === 'inspect_browser_tabs') { if (Object.keys(args).length) throw new Error('标签页查询不接受附加参数。'); return; }
@@ -128,6 +134,39 @@ export class Runtime {
evaluationManager() { return this.evaluations ??= new EvaluationManager(this.store, this); }
workerManager() { return this.workers ??= new WorkerManager(this.store, this); }
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
fileResults() { return this.results ??= new FileResults(this.store); }
async fileDelivery(session) {
const task = this.store.owned('task', session.taskId, session.id), delivery = this.fileResults().completion(session);
if (!delivery.satisfied) return { ...delivery, stopReason: 'delivery_incomplete', message: delivery.requiresChange
? '当前要求包含修改,尚无对应追加要求之后的实际文件改动。已有成果核对不能代替修改。'
: '要求的文件尚无当前有效成果或已应用改动。' + (delivery.missingPaths.length ? '缺少:' + delivery.missingPaths.join('、') + '。' : '') + '请完整读取并核对已有成果,或生成可审查改动。' };
const policy = taskContract(task).checks;
if (policy !== 'skip' && (policy === 'required' || task.verification?.status !== 'not_configured')) {
const inspection = await inspectProject(this.store.project(session.projectId));
if (!verifiedCheck(this.store, session, inspection)) return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前工程检查尚无对应当前输入的通过证据,已有成果不能代替检查。' };
}
const browser = await currentBrowserVerification(this.store, session);
if (browser.required && browser.status !== 'passed') return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前页面验收尚未通过,已有成果不能代替页面检查。' };
return delivery;
}
async completeFileResults(session) {
if (this.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请停止或等待原操作结束后核对成果。'), { status: 409 });
const taskId = session.taskId, runId = session.runId;
if (workerForSession(this.store, session)) throw Object.assign(new Error('受限子任务不能独立结束父项目成果。'), { status: 409 });
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|| [...this.store.core.tool.values()].some(tool => tool.taskId === taskId && tool.requiresVerification)) throw Object.assign(new Error('仍有待审改动或未知结果,请先核对原操作。'), { status: 409 });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true }); assertWorkersResolved(this.store, session.projectId); assertMcpResolved(this.store, session.projectId); assertChangeSetsResolved(this.store, session.projectId);
const delivery = await this.fileDelivery(session);
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 });
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 };
session.status = 'completed';
this.store.message(session, 'system', '已按当前成果结束任务;' + (delivery.newChanges ? '实际修改另列。' : '无新增修改。') + '原运行、检查与Git记录保留,未请求模型。');
this.store.save(session, { type: 'file_result.task_completed' });
}
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,
@@ -290,6 +329,7 @@ export class Runtime {
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
.map(tool => ({ invocation_id: tool.id, call_id: tool.callId, tool: tool.tool, status: tool.state, requires_verification: true }));
const fileResults = this.fileResults().inspect(session);
const context = this.provider.redact(projectContext(run.project) + (run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget,
rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
@@ -299,6 +339,10 @@ export class Runtime {
goal: taskContract(task).goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract: taskContract(task),
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '')
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ (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),
}) : '')
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
@@ -308,7 +352,7 @@ export class Runtime {
}) : ''));
const skillCatalog = run.worker ? null : this.skillRegistry().catalog(session.projectId);
const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId);
const availableTools = [...toolDefinitions, ...taskPlanToolDefinitions, ...([...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
const availableTools = [...toolDefinitions, ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...([...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
...(mcpCatalog?.entries.length ? mcpToolDefinitions : []),
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
@@ -413,9 +457,12 @@ export class Runtime {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (run.record.purpose === 'diagnostic') { session.status = 'completed'; run.stopReason = 'diagnostic_answered'; }
else if (session.status === 'completed' && taskContract(task).kind === 'file' && !session.changes.some(change => change.taskId === task.id && change.status === 'applied')) {
session.status = 'paused'; run.stopReason = 'delivery_incomplete';
this.store.message(session, 'system', '答复已收到,但原目标要求的文件尚无已应用记录,不能视为文件交付完成。请生成可审查的文件改动。');
else if (session.status === 'completed' && taskContract(task).kind === 'file') {
const delivery = await this.fileDelivery(session);
if (!delivery.satisfied) {
session.status = 'paused'; run.stopReason = delivery.stopReason;
this.store.message(session, 'system', '答复已收到,但' + delivery.message);
} else task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
}
else if (session.status === 'completed' && taskContract(task).checks !== 'skip' && (['failed', 'stale', 'unknown', 'unverified', 'running'].includes(task.verification?.status)
|| taskContract(task).checks === 'required' && task.verification?.status !== 'passed')) {
@@ -563,6 +610,14 @@ export class Runtime {
result = { status: 'planned', plan_id: plan.id, revision: plan.revision, steps: plan.steps, contract_artifact_id: plan.contractArtifactId,
note: '计划已保存,步骤尚未核验;保留原目标和通过条件,按原工具结果核验,不直接标记完成。' }; }
else if (tool === 'inspect_task_plan') result = await this.taskPlanner().inspect(session, { candidates: false });
else if (tool === 'verify_existing_files') {
result = this.fileResults().record(session, args);
const task = this.store.core.task.get(run.taskId);
if (!result.reused) clearReadStreak(task);
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0 };
progress.resultRepeats = result.reused ? (progress.resultRepeats ?? 0) + 1 : 0;
if (progress.resultRepeats >= 3) { progress.pause = true; progress.warning = '连续核对同一成果没有推进任务,请使用原成果凭据继续交付。'; }
}
else if (tool === 'verify_task_step') result = await this.taskPlanner().verify(session, args, { source: 'agent' });
else if (tool === 'inspect_engine_checks') result = { status: 'completed', engine_checks: this.engineManager().jobs(session)
.filter(job => job.taskId === run.taskId).map(job => this.engineManager().summary(session, job)), note: '已保存的引擎连接核验;完整原记录使用report_artifact_id读取,查询不会启动引擎。' };
+3
View File
@@ -689,6 +689,9 @@ export class Store extends EventEmitter {
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
artifacts, checks: jobs,
...([...this.core.file_result.values()].some(value => value.sessionId === session.id && value.taskId === task?.id) ? {
fileResults: [...this.core.file_result.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
} : {}),
browsingTabs: [...this.core.browsing_tab.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
browsingActions: [...this.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
previewPlans: [...this.core.preview_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5),
+1
View File
@@ -10,6 +10,7 @@ CORE_KINDS.push('evaluation');
CORE_KINDS.push('environment_diagnostic','environment_plan','environment_job');
CORE_KINDS.push('preview_plan','preview_job');
CORE_KINDS.push('browsing_profile','browsing_tab','browsing_observation','browsing_action');
CORE_KINDS.push('file_result');
export const timestamp = () => new Date().toISOString();
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
+23
View File
@@ -0,0 +1,23 @@
// This recognizes explicit file actions only; it does not certify business semantics.
export const negatedFileAction = prefix => /(?:不要|无需|不需要|不用|禁止|不得|不必|勿|不允许|不能|不再|避免|不)(?:\s|再|去|进行|执行|直接|自动|擅自|任何|做|你)*(?:.{0,24}(?:或|和|以及)\s*)?$|\b(?:do not|don't|without|never|no need to|must not|cannot|can't)\b.{0,40}$|(?:解释|说明|分析|告诉我).{0,24}(?:怎么|如何)\s*$|\bhow\s+to\s*$/i.test(prefix);
export function requestedFilePaths(text) {
const paths = [];
for (const clause of String(text).split(/[,,;;。\n]/)) {
const action = /(?:创建|新建|保存|写入|修改|重写|修复|调整|替换)|\b(?:create|save|write|modify|rewrite|fix|change|replace)\b/i.exec(clause);
if (!action || negatedFileAction(clause.slice(0, action.index))) continue;
const suffix = clause.slice(action.index + action[0].length);
if (/\b(?:from|using|based on)\b|(?:根据|参考)/i.test(suffix.split(/(?:[\w\u3400-\u9fff@.-]+\/)*[\w\u3400-\u9fff@-]+\.(?:html?|svg|txt|md|json|[cm]?[jt]sx?|css|py|ya?ml)\b/i)[0])) continue;
for (const match of suffix.matchAll(/(?:[\w\u3400-\u9fff@.-]+\/)*[\w\u3400-\u9fff@-]+\.(?:html?|svg|txt|md|json|[cm]?[jt]sx?|css|py|ya?ml)\b/ig)) paths.push(match[0]);
}
return [...new Set(paths)];
}
export function changeRequirement(task) {
const positive = text => String(text).split(/[,,;;。\n]/).some(clause => {
const match = /(?:修改|重写|修复|改写|调整|新增功能|增加功能|删除|替换)|\b(?:modify|rewrite|fix|change|delete|replace)\b/i.exec(clause);
return match && !negatedFileAction(clause.slice(0, match.index));
});
const latest = (task.instructions ?? []).findLast(item => item.source !== 'review-action' && positive(item.content));
const goal = task.contract?.goal ?? task.goal;
return latest ? { required: true, after: latest.createdAt, text: latest.content, paths: requestedFilePaths(latest.content) }
: { required: positive(goal), after: task.createdAt, text: goal, paths: requestedFilePaths(goal) };
}
+38
View File
@@ -0,0 +1,38 @@
import { isId } from './execution.mjs';
import { isContinuation, taskContract } from './task-control.mjs';
import { planHash, planError, taskRequirements } from './task-plans.mjs';
export { requestedFilePaths, changeRequirement } from './file-intent.mjs';
export function fileResultInput(input, { source = 'agent' } = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['files', 'reason'].includes(key))
|| typeof input.reason !== 'string' || !input.reason.trim() || input.reason.length > 600 || input.reason.includes('\0')
|| !Array.isArray(input.files) || !input.files.length || input.files.length > 8) throw planError('成果核对需要1–8个文件和采用原因(最多600字)。', 'input', 400);
const files = input.files.map(file => {
if (!file || typeof file !== 'object' || Object.keys(file).some(key => !['path', 'sha256', 'read_call_ids', 'source_result_id'].includes(key))
|| typeof file.path !== 'string' || !file.path || file.path.length > 240 || /[\\:\0]/.test(file.path) || file.path.startsWith('/')
|| file.path.split('/').some(part => !part || part === '.' || part === '..') || !/^[a-f0-9]{64}$/.test(file.sha256)
|| file.source_result_id !== undefined && !isId(file.source_result_id)) throw planError('需要项目内文件路径、当前SHA256和有效来源ID。', 'input', 400);
const calls = file.read_call_ids ?? [];
if (!Array.isArray(calls) || calls.length > 128 || calls.some(id => typeof id !== 'string' || !id || id.length > 160) || new Set(calls).size !== calls.length
|| source === 'agent' && !calls.length || source === 'user' && calls.length) throw planError('模型需引用本Task实际read_file调用;用户核对由宿主直接读取。', 'input', 400);
return { path: file.path, sha256: file.sha256, read_call_ids: calls, ...(file.source_result_id ? { source_result_id: file.source_result_id } : {}) };
});
if (new Set(files.map(file => file.path.toLowerCase())).size !== files.length) throw planError('核对文件不能重复。', 'input', 400);
return { files, reason: input.reason.trim() };
}
export function fileResultRequirements(task) {
const value = taskRequirements(task);
value.instructions = value.instructions.filter(item => !isContinuation(item.content));
return structuredClone({ ...value, contract: taskContract(task) });
}
export const fileResultRequirementsHash = task => planHash(fileResultRequirements(task));
export const fileResultToolDefinitions = [{ type: 'function', function: {
name: 'verify_existing_files', description: '把已存在且满足当前要求的文本文件登记为当前成果,不改写文件、不代替测试或业务验收。先用本Task的read_file完整分页读取,再传当前SHA与原read_call_ids;跨Task采用须显式source_result_id。文件/要求变化凭据失效。明确修改要求仍需本Task实际修改。返回原成果ID,可用于results类计划步骤;相同文件不重复登记。',
parameters: { type: 'object', additionalProperties: false, required: ['files', 'reason'], properties: {
reason: { type: 'string', minLength: 1, maxLength: 600 }, files: { type: 'array', minItems: 1, maxItems: 8, items: { type: 'object', additionalProperties: false, required: ['path', 'sha256', 'read_call_ids'], properties: {
path: { type: 'string' }, sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, read_call_ids: { type: 'array', minItems: 1, maxItems: 128, items: { type: 'string' } }, source_result_id: { type: 'string' },
} } },
} },
} }];
+12 -2
View File
@@ -1,4 +1,5 @@
// Task intent is retained independently of short follow-ups and system actions.
import { changeRequirement, requestedFilePaths, negatedFileAction } from './file-intent.mjs';
export const isContinuation = content => /^(?:请)?(?:继续(?:完成|执行|开发|原任务|这个任务)?|接着(?:完成|执行)?|continue(?:\s+(?:the\s+)?(?:task|work))?)[。.!!\s]*$/i.test(String(content).trim());
export function isDiagnosticQuestion(content) {
@@ -29,15 +30,16 @@ function hasFileDeliveryRequest(goal) {
// Do not connect a past-tense modifier ("保存的原工件") to a later
// prohibition ("不修改文件") and turn a read into a delivery requirement.
const clauses = String(goal).split(/[,,;;。\n]|而是|但是|\bbut\b/i);
const action = /(?:创建|新建|保存|写入)(?!的|过的|好的|后的|下来的).{0,60}?(?:文件|HTML|[\w-]+\.(?:html?|txt|svg|md)\b)|\bcreate\b.{0,60}?\b(?:file|html|svg)\b/ig;
const action = /(?:创建|新建|保存|写入|修改|重写|修复|调整|替换)(?!的|过的|好的|后的|下来的).{0,60}?(?:文件|HTML|[\w-]+\.(?:html?|txt|svg|md)\b)|\b(?:create|modify|rewrite|fix|change|replace)\b.{0,60}?\b(?:file|html|svg)\b/ig;
return clauses.some(clause => [...clause.matchAll(action)].some(match => {
const prefix = clause.slice(0, match.index);
return !/(?:不要|无需|不需要|不用|禁止|不得|不必|勿|不允许|不能|不再|避免|不)(?:\s|再|去|进行|执行|直接|自动|擅自|你|任何)*(?:.{0,24}(?:或|和|以及)\s*)?$|\b(?:do not|don't|without|never|no need to|must not|cannot|can't)\b.{0,40}$/i.test(prefix);
return !negatedFileAction(prefix);
}));
}
export function updateTaskContract(task, instruction) {
const current = taskContract(task);
if (hasFileDeliveryRequest(instruction)) current.kind = 'file';
// Only an explicit new user instruction changes the check policy.
if (/无需(?:任何)?测试|不(?:需要|用|要)(?:进行|做|运行)?测试|\b(?:no tests?|without (?:running )?tests?)\b/i.test(instruction)) current.checks = 'skip';
else if (/(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(instruction)) current.checks = 'required';
@@ -65,6 +67,14 @@ export function settleAppliedTask(store, session) {
if (!applied.length) return;
if (!task) { if (!session.taskId) session.status = 'completed'; return; }
const contract = taskContract(task, id => store.core.task.get(id));
const demand = changeRequirement(task), recent = applied.filter(change => change.taskId === task.id && (!demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after));
const paths = new Set(applied.map(change => change.path));
const targets = requestedFilePaths([contract.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
if (targets.some(path => !paths.has(path)) || demand.required && (!recent.length || demand.paths.some(path => !recent.some(change => change.path === path)))) {
session.status = 'paused';
store.message(session, 'system', '文件已应用,但当前目标的文件范围或追加修改要求尚未满足,请按原目标继续核对。');
return;
}
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'
+2 -2
View File
@@ -3,9 +3,9 @@ export const taskPlanToolDefinitions = [
type: 'object', additionalProperties: false, required: ['expected_revision', 'steps'], properties: { expected_revision: { type: 'integer', minimum: 0 }, steps: { type: 'array', minItems: 1, maxItems: 12, items: {
type: 'object', additionalProperties: false, required: ['key', 'title', 'criterion', 'kind'], properties: {
key: { type: 'string', pattern: '^[a-z][a-z0-9_-]{0,39}$' }, title: { type: 'string', maxLength: 100 }, criterion: { type: 'string', maxLength: 300 },
kind: { type: 'string', enum: ['analysis', 'changes', 'checks', 'browser'] }, depends_on: { type: 'array', items: { type: 'string' }, maxItems: 12 },
kind: { type: 'string', enum: ['analysis', 'changes', 'results', 'checks', 'browser'] }, depends_on: { type: 'array', items: { type: 'string' }, maxItems: 12 },
tools: { type: 'array', description: 'analysis必填,只读工具名称,例如inspect_project/read_file/query_code。', items: { type: 'string' } },
paths: { type: 'array', description: 'changes必填,实际改动的项目相对文件路径。', items: { type: 'string' }, maxItems: 32 },
paths: { type: 'array', description: 'changes/results必填,项目相对文件路径。changes仅核验本Task实际应用;results核验verify_existing_files的当前文件成果。', items: { type: 'string' }, maxItems: 32 },
checks: { type: 'array', description: 'checks必填,实际检查名称,例如test/typecheck/build或python:test。', items: { type: 'string' }, maxItems: 6 },
viewport_width: { type: 'integer', description: 'browser必填,固定桌面/手机视口宽度。', minimum: 320, maximum: 1440 },
actions: { type: 'array', description: 'browser需要的实际操作,始终要求非空通过断言及进程退出。', items: { type: 'string', enum: ['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'] } },
+3 -3
View File
@@ -23,15 +23,15 @@ export function taskPlanInput(input) {
if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > TASK_PLAN_LIMITS.steps) throw planError('任务计划需要1–12个步骤。', 'input', 400);
const steps = input.steps.map(value => {
if (!object(value) || Object.keys(value).some(key => !['key', 'title', 'criterion', 'kind', 'depends_on', 'tools', 'paths', 'checks', 'viewport_width', 'actions'].includes(key))
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'results', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
const step = { key: value.key, title: text(value.title, 100, '步骤标题'), criterion: text(value.criterion, 300, '通过条件'), kind: value.kind,
depends_on: unique(value.depends_on ?? [], '前置依赖', TASK_PLAN_LIMITS.steps).sort() };
const allowed = value.kind === 'analysis' ? ['tools'] : value.kind === 'changes' ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
const allowed = value.kind === 'analysis' ? ['tools'] : ['changes', 'results'].includes(value.kind) ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
if (['tools', 'paths', 'checks', 'viewport_width', 'actions'].some(key => value[key] !== undefined && !allowed.includes(key))) throw planError('步骤证据字段与类别不一致。', 'input', 400);
if (value.kind === 'analysis') {
step.tools = unique(value.tools, '读取工具', PLAN_READ_TOOLS.length).sort();
if (!step.tools.length || step.tools.some(tool => !PLAN_READ_TOOLS.includes(tool))) throw planError('工程读取只能引用已声明的实际只读工具。', 'input', 400);
} else if (value.kind === 'changes') {
} else if (['changes', 'results'].includes(value.kind)) {
step.paths = unique(value.paths, '文件范围').sort();
if (!step.paths.length || step.paths.some(file => /[\\:\0]/.test(file) || file.startsWith('/') || file.split('/').some(part => !part || part === '..' || ['.git', '.hg', '.svn'].includes(part)))) throw planError('源码步骤需要项目内常规相对文件路径。', 'input', 400);
} else if (value.kind === 'checks') {