diff --git a/docs/TASK-AGREEMENT-C.md b/docs/TASK-AGREEMENT-C.md index 4f53d3b6..1291151c 100644 --- a/docs/TASK-AGREEMENT-C.md +++ b/docs/TASK-AGREEMENT-C.md @@ -21,3 +21,15 @@ 首网页末项因验收器先解除route再释放请求而失败;先等待原拦截处理结束再解除,保留原断言,复验6/6。实际Electron首轮隐藏窗口截图超时,改用既有showInactive后第二轮通过前4组,但验收器宿主适配未把写入传为POST而409;补齐适配后原6组全部通过。首日志`ui-first.log`、`ui-electron-first.log`、`ui-electron-recheck.log`与相应目录保留;没有重写失败、降低断言或修改正式配置。 阶段回顾:真实操作已证明本地草案可取消、审阅、保存、刷新、澄清及隔离迟到响应;不证明自动理解准确率、真实模型自主交付或禁止事项已经履行。下一补诊断原失败绑定和统一当前缺口/下一步,再独立发行及保留状态升级。 + +## 阶段三:诊断原归属与交付下一步 + +只读诊断在开始时封存原项目/会话/Task/Run、原目标、原错误事件及原字节SHA、检查约定和原检查引用。多轮诊断及诊断自身的新错误不会替换根执行失败;原绑定可重启恢复、核对原工件并拒绝跨Task/原错误变化/工件篡改。旧诊断缺少绑定时明确未核对,不补造历史。诊断提示及inspect_session都提供相同原绑定;工具仍由原只读白名单执行,诊断结束恢复原任务状态,不重放工具/检查。 + +交付报告拆出无工件写入的inspect,任务页与显式保存报告共用要求、文件、检查、计划、未知结果的现时核对和下一步。新只读delivery-status接口核对所选Task/Run;迟到结果不能写入别的任务。参考/边界只记用途,未知提示澄清,用户体验和工程证据分别保留。仅研究且所选实际读取已核对、没有修改和工程检查要求时,报告为研究范围已核对;显式no-test为按约定未测试,不能标成工程测试通过。原失败或未知操作仍阻止工程完成;诊断失败与原执行错误在报告内分别记录。 + +完整构建通过(首轮缺mjs类型声明的失败日志保留,补声明后通过)。首相关65项62通过3失败:两个新增scope测试数据错误携带tools而被原契约拒绝,另一个把每次生成的exportedAt当持久状态比较;修正测试数据,导出只排除生成时间、其余逐项精确比较,六项诊断专项6/6通过。原日志`closure-related-first.tap`,复验`closure-recheck.tap`;原62项包含Git实际进程退出/未知提交/原失败日志/要求修订等,未无故重复长恢复检查。诊断inspect_session补原绑定后,原只读/禁止写入等9/9补强复验通过(`diagnostic-tools-recheck.tap`)。 + +实际新网页5组、沙箱Electron5组通过,分别在`.qa/task-agreement/closure-web-924f3621-0bed-491b-869a-e44fa25550ee`、`closure-electron-1de044b1-84a3-415f-b3c1-b04cdafdfbbe`;1440/390px截图已实际回看,当前原目标、原错误、澄清入口和研究no-test可读。原工件可打开,显式报告与页面next step一致,刷新后保持,切换Task的迟到响应被忽略,模型历史不变。首关闭按钮定位、工件请求缺session及窄屏面板未展开的验收器失败保留原日志,修正入口后原断言通过;没有放宽产品门槛。 + +阶段回顾:本地原归属/当前事实/下一步已闭环,0真实模型请求、不接触正式Key/进程。参考及禁止文字不是履行证明,诊断绑定不是网络恢复证明,研究复核不是自主交付收益。下一版本同步、独立源码重建/三归档/三载荷实际入口/实际隔离安装、保留原PID/Provider正式升级与封存,完成前仍不标1.25已发行。 diff --git a/findings.md b/findings.md index 921c8bf3..c1d39ab2 100644 --- a/findings.md +++ b/findings.md @@ -1214,3 +1214,5 @@ Q发行复核:源码ZIP独立560输入/22编译完全一致,555跟踪输入 V调用前检查:新增11文件SHA断言首语法检查发现多一个右括号,已修正;此时尚无网络诊断/模型调用。保留首错误,语法检查通过后才冻结契约。 草案阶段:Electron截图需先showInactive;HostController.api使用{method,input},与launchWorkbench的简化api不同。两处验收器错误在新结果修正,原失败保留。参考/边界只记录,unknown仍阻止复核;UI分类变化应清除残留paths等旧字段。恢复时两次已知文件路径不存在,已按实际清单定位,未将其记作验证通过。 + +诊断闭环开发:原错误必须以所属非诊断Run/事件封存,不能以session.lastFailure跨Task借用;诊断自身失败仍保留原执行根因。报告读取拆成无工件写入的inspect与显式create,界面共用同一缺口结果。首构建缺.mjs类型声明已补,完整构建通过。闭环UI验收器首关闭按钮名、工件API缺session归属、窄屏需重新展开任务面板三问题均保留原日志,按既有真实入口逐项修正,未放宽产品断言。 diff --git a/progress.md b/progress.md index c9c7ffa0..ecf9d9b5 100644 --- a/progress.md +++ b/progress.md @@ -1767,3 +1767,6 @@ M最终Git索引核对:证据及manifest共746份/55074620字节,实际暂 V调用前检查:新增11文件SHA断言首语法检查发现多一个右括号,已修正;此时尚无网络诊断/模型调用。保留首错误,语法检查通过后才冻结契约。 1.25草案界面阶段:完整构建、旧网页7组、新网页6组及实际Electron6组通过。首route释放次序/隐藏窗口截图/POST适配失败原日志与目录保留;实际1440/390px截图回看、保存刷新、并发拒绝/输入保留与迟到Task隔离完成。真实模型0,正式1.24.9/原PID36552/Provider保持。下一诊断与报告闭环。 + +诊断闭环阶段:首相关65项62通过3测试数据失败,两个scope误带tools被原契约拒绝、一次误比生成时间;修正数据后6/6专项通过,原62通过保留。网页5/Electron5实际路径与1440/390px截图回看通过。原Task/Run/错误SHA封存、多轮诊断/新错误/跨Task/篡改/重开、无写入状态GET与显式报告一致已核对。最终完整构建通过,inspect_session额外提供原绑定的补强检查进行中。 +诊断inspect_session原绑定补强9/9通过;阶段三回顾完成并本地提交。 diff --git a/scripts/verify-task-follow-up-ui.mjs b/scripts/verify-task-follow-up-ui.mjs new file mode 100644 index 00000000..e08dea00 --- /dev/null +++ b/scripts/verify-task-follow-up-ui.mjs @@ -0,0 +1,89 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import net from 'node:net'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { chromium, _electron } from 'playwright'; +import { fixture, launchWorkbench, until } from '../tests/helpers.mjs'; +import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.mjs'; +import { RequirementReview } from '../src/core/tasks/requirement-review.mjs'; +import { HostController } from '../src/core/desktop/host-controller.mjs'; +import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs'; +import { projectEnvironment } from '../src/core/process-environment.mjs'; + +const desktop = process.argv.includes('--desktop'), appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.'); +const directory = path.resolve('.qa/task-agreement', (desktop ? 'closure-electron-' : 'closure-web-') + randomUUID()); fs.mkdirSync(directory, { recursive: true }); +const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t); +const originalRun = beginPlanTask(f, '修复原工程并通过测试,保留原失败。'); f.session.title = '原目标与诊断闭环'; +const failure = { id: randomUUID(), source: 'model_connection', kind: 'network', stage: 'model_request', title: '隔离夹具原连接错误', message: '隔离夹具:原POST结果未知,不得重放。', runId: originalRun.id }; +f.store.event(f.session, { kind: 'error', phase: 'failed', label: failure.title, diagnostic: failure }); +f.session.lastFailure = failure; f.store.core.task.get(f.session.taskId).verification.status = 'failed'; +const diagnostic = f.store.beginRun(f.session, '前面的错误是怎么回事?', false, f.store.config); +f.session.status = 'paused'; f.store.finishRun(f.session, diagnostic, 'diagnostic_answered', { status: 'completed' }); +const row = (session, extra = {}) => ({ key: 'scope', role: 'unknown', title: '确认原目标范围', criterion: '保留未知范围', kind: 'analysis', method: 'scope', + source: { kind: 'goal', id: session.taskId, start: 0, end: f.store.core.task.get(session.taskId).goal.length }, ...extra }); +const manager = new RequirementReview(f.store); await manager.save(f.session, { expected_revision: 0, requirements: [row(f.session)] }); +const original = f.session, other = f.store.createSession(f.project.id); f.session = other; +beginPlanTask(f, '仅研究README.md,不修改文件。无需测试。'); other.title = '按约定完成的研究范围'; const read = completeRead(f); +await manager.save(other, { expected_revision: 0, requirements: [row(other, { role: 'requirement', method: 'evidence', tools: ['read_file'] })] }); +await manager.verify(other, { expected_revision: 1, key: 'scope', evidence_id: read.id }); f.session = original; +const originalMessages = structuredClone(original.providerMessages); f.store.close(); +const passed = [], screenshots = [], errors = []; let browser, application, controller, host, page, window, result; +const mark = name => { passed.push(name); console.log('PASS ' + name); }; +const panel = () => page.getByLabel('当前缺口与下一步', { exact: true }); +async function select(session) { + if (!await page.getByLabel('当前项目').isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click(); + await page.getByLabel('当前项目').selectOption(f.project.id); await page.locator('.session-list button').filter({ hasText: session.title }).click(); + if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); +} +async function resize(width, height) { + if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); } + else await page.setViewportSize({ width, height }); +} +async function shot(name) { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); fs.writeFileSync(path.join(directory, name + '.txt'), await page.locator('body').innerText()); } +try { + if (desktop) { + const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve)); assert.notEqual(port, 4318); + controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start(); + host = { api: (route, input) => controller.api(route, input ? { method: 'POST', input } : {}), bootstrap: await controller.api('/bootstrap') }; + const executable = desktopExecutableIdentity(appRoot).path; + application = await _electron.launch({ executablePath: executable, args: [...(executable.toLowerCase().endsWith('agentworkbench.exe') ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 }); + page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive()); await resize(1440, 1080); + } else { host = await launchWorkbench(t, f.data, {}, { appRoot }); browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1080 } }); await page.goto(host.url); } + assert.equal(host.bootstrap.config.hasKey, false); page.on('pageerror', error => errors.push(error.message)); + await page.locator('.connection.connected').waitFor(); await select(original); + await until(async () => (await panel().innerText()).includes(failure.message)); + assert.match(await panel().innerText(), /澄清原文用途/); assert.match(await panel().innerText(), /答复已完成/); + assert.match(await page.getByLabel('任务记录', { exact: true }).innerText(), /修复原工程并通过测试/); + await panel().scrollIntoViewIfNeeded(); await shot('desktop-diagnostic'); + mark('completed read-only diagnostic shows the original execution error, unfinished goal and actionable unknown scope'); + await panel().getByRole('button', { name: '查看诊断原绑定', exact: true }).click(); + const artifact = page.getByRole('dialog', { name: '执行结果工件', exact: true }); await artifact.waitFor(); assert.match(await artifact.innerText(), new RegExp(originalRun.id)); + await artifact.getByRole('button', { name: '关闭窗口', exact: true }).click(); + await page.getByRole('button', { name: '生成交付报告', exact: true }).click(); await artifact.waitFor(); + assert.match(await artifact.innerText(), /原POST结果未知/); assert.match(await artifact.innerText(), /澄清原文用途/); await artifact.getByRole('button', { name: '关闭窗口', exact: true }).click(); + const statusUrl = '/sessions/' + original.id + '/delivery-status?taskId=' + original.taskId + '&runId=' + diagnostic.id; + const current = await host.api(statusUrl), saved = await host.api('/sessions/' + original.id); + const reportId = saved.execution.artifacts.findLast(value => value.kind === 'delivery-report').id; + const report = JSON.parse((await host.api('/artifacts/' + reportId + '?session=' + original.id + '&limit=64000')).content); assert.deepEqual(report.followUp, current.followUp); + mark('original diagnostic artifact opens and generated report uses the same current gaps and next step'); + await page.reload(); await page.locator('.connection.connected').waitFor(); await select(original); await until(async () => (await panel().innerText()).includes(failure.message)); + await resize(390, 844); if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); + await panel().scrollIntoViewIfNeeded(); assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true); await shot('narrow-diagnostic'); + mark('refresh and narrow layout retain the original Task, error and next action'); + await resize(1440, 1080); await select(other); await until(async () => (await panel().innerText()).includes('约定范围已核对,按约定未测试')); + assert.doesNotMatch(await panel().innerText(), /原POST结果未知/); const research = await host.api('/sessions/' + other.id); + assert.equal(research.execution.checks.length, 0); assert.equal(research.execution.task.contract.checks, 'skip'); await panel().scrollIntoViewIfNeeded(); await shot('research-no-test'); + mark('separately verified research closes its agreed scope without a fake test or another Task error'); + await select(original); await until(async () => (await panel().innerText()).includes(failure.message)); + let held = false, release, finished; const handled = new Promise(resolve => { finished = resolve; }); + await page.route('**/delivery-status?*', async route => { held = true; await new Promise(resolve => { release = resolve; }); try { await route.continue(); } finally { finished(); } }); + await panel().getByRole('button', { name: '刷新当前结果', exact: true }).click(); await until(() => held); await select(other); release(); await handled; await page.unroute('**/delivery-status?*'); + await until(async () => (await panel().innerText()).includes('约定范围已核对,按约定未测试')); assert.doesNotMatch(await panel().innerText(), /原POST结果未知/); + mark('late status response cannot overwrite another selected Task'); + const exported = await host.api('/sessions/' + original.id + '/export'); assert.deepEqual(exported.session.providerMessages, originalMessages); assert.deepEqual(errors, []); + fs.writeFileSync(path.join(directory, 'session.json'), JSON.stringify(exported, null, 2)); fs.writeFileSync(path.join(directory, 'report.json'), JSON.stringify(report, null, 2)); + result = { success: true, version: host.bootstrap.version, appRoot, actualElectron: desktop, passed, screenshots, errors, realModelRequests: 0, officialServiceTouched: false }; +} catch (error) { if (page) { await shot('failure').catch(() => {}); } result = { success: false, passed, screenshots, errors, error: error.stack, realModelRequests: 0 }; } +finally { if (application) await application.close(); if (browser) await browser.close(); if (controller && await controller.health()) await controller.stop(); for (const dispose of disposers.reverse()) await dispose(); fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); } +console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1; diff --git a/src/client/RequirementPanel.tsx b/src/client/RequirementPanel.tsx index 0b95f2b2..7db5b871 100644 --- a/src/client/RequirementPanel.tsx +++ b/src/client/RequirementPanel.tsx @@ -5,10 +5,8 @@ import { Modal } from './components'; import type { RequirementDraft, RequirementItem, RequirementView, Session, TaskPlanStep } from './types'; import { RequirementDraftEditor, RequirementScopeFields, requirementInput as clean, requirementRoles } from './RequirementDraftEditor'; import './RequirementPanel.css'; +import { requirementStates as states } from '../shared/contracts/task-follow-up.mjs'; -const states: Record = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对', - evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行', - scope_unknown: '范围待澄清', reference_recorded: '参考已记录', boundary_recorded: '边界已记录' }; const kinds: Record = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' }; 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'] }; diff --git a/src/client/TaskFollowUp.tsx b/src/client/TaskFollowUp.tsx new file mode 100644 index 00000000..f3c3031e --- /dev/null +++ b/src/client/TaskFollowUp.tsx @@ -0,0 +1,42 @@ +import { useEffect, useState } from 'react'; +import { api } from './api'; +import type { DeliveryStatus, Session } from './types'; + +export function TaskFollowUp({ session, openArtifact }: { session: Session; openArtifact: (id: string) => void }) { + const task = session.execution?.task, run = session.execution?.run; + const [value, setValue] = useState(null), [error, setError] = useState(''), [refresh, setRefresh] = useState(0), [loading, setLoading] = useState(false); + const identity = session.id + '/' + task?.id + '/' + run?.id; + const [loadedIdentity, setLoadedIdentity] = useState(''); + const active = ['running', 'awaiting_approval', 'stopping'].includes(session.status); + useEffect(() => { + let alive = true; + setError(''); + if (!task || !run || active) { setLoading(false); return; } + const timer = setTimeout(() => { + setLoading(true); setError(''); + api(`/sessions/${session.id}/delivery-status?taskId=${task.id}&runId=${run.id}`) + .then(result => { if (alive) { setValue(result); setLoadedIdentity(identity); } }) + .catch(reason => { if (alive) { setError(reason instanceof Error ? reason.message : String(reason)); setValue(null); } }) + .finally(() => { if (alive) setLoading(false); }); + }, 160); + return () => { alive = false; clearTimeout(timer); }; + }, [identity, session.revision, session.status, refresh]); + const current = loadedIdentity === identity ? value : null, diagnostic = current?.diagnostics.at(-1), context = diagnostic?.context; + return
+

当前缺口与下一步

+ {active ?

等待所属运行、检查或审批结束,再核对当前结果。

: error ?

{error} 请刷新当前结果;原记录保留。

: current ? <> +

{current.followUp.statusLabel}

+

下一步:{current.followUp.nextStep}

+ {!!current.followUp.gaps.length &&
待处理事项 · {current.followUp.gaps.length}
    {current.followUp.gaps.map((gap, i) =>
  • {gap.label}

    {gap.nextStep}

  • )}
} + {diagnostic && context &&
+ 最近只读诊断 · {diagnostic.status === 'completed' ? '答复已完成' : diagnostic.status === 'failed' ? '诊断失败' : '尚未完成'} +

{diagnostic.question}

+ {diagnostic.failure &&

本次诊断错误:{diagnostic.failure.message}

} + {context.evidenceVerified ? <>

原执行:{context.originalRunId?.slice(0, 8) ?? '未记录'}

原错误:{context.failure?.value.message ?? '未记录具体错误;原因保持未知。'}

+ {context.check &&

原检查:{context.check.id.slice(0, 8)} · {context.check.status}

} :

{context.error ?? context.note}

} + {context.artifactId && } +
} +

{current.followUp.note}

+ :

正在核对当前目标、要求和原结果。

} +
; +} diff --git a/src/client/TaskPanel.css b/src/client/TaskPanel.css index b3ee7d98..0fc72977 100644 --- a/src/client/TaskPanel.css +++ b/src/client/TaskPanel.css @@ -5,6 +5,15 @@ .record-heading > span:not(.status) { margin-left: auto; font-size: 11px; color: var(--muted); } .record-heading > code { margin-left: auto; font-size: 11px; color: var(--muted); } .task-goal { line-height: 1.85; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; } +.task-follow-up { font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; } +.follow-up-next { margin: 10px 0; } +.task-follow-up summary { cursor: pointer; color: var(--teal); } +.task-follow-up ul { padding-left: 18px; } +.task-follow-up li { margin-top: 12px; } +.task-follow-up li p { margin-top: 3px; } +.diagnostic-origin { margin-top: 14px; padding-left: 10px; border-left: 2px solid #bd9654; } +.diagnostic-origin p { margin: 6px 0; white-space: pre-wrap; } +@media (max-width: 600px) { .task-follow-up .text-button { min-height: 44px; } } .record-id { display: inline-block; font-size: 10px; color: var(--muted); margin-top: 9px; } .task-instructions { margin-top: 14px; font-size: 11px; } .task-instructions summary { cursor: pointer; color: var(--teal); } diff --git a/src/client/TaskPanel.tsx b/src/client/TaskPanel.tsx index 3427cf02..b1f132c1 100644 --- a/src/client/TaskPanel.tsx +++ b/src/client/TaskPanel.tsx @@ -17,6 +17,7 @@ import './TaskPanel.css'; import { EnvironmentPanel } from './EnvironmentPanel'; import { PreviewPanel } from './PreviewPanel'; import { FileResultsPanel } from './FileResultsPanel'; +import { TaskFollowUp } from './TaskFollowUp'; const stopReasons: Record = { model_identity: '模型返回型号需要核对', 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'); @@ -100,6 +101,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp {!!task.instructions.length &&
追加要求 · {task.instructions.length}{task.instructions.map(instruction =>

{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}
{instruction.content}

)}
} :

发送任务后,这里保存目标、每次运行和实际结果。

} + {task && } {task && } {task && } {task && } @@ -112,6 +114,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp {run ? <>
{run.id.slice(0, 8)}
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' &&

这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。

} {run.purpose === 'diagnostic' &&

本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。

} + {run.purpose === 'diagnostic' && run.diagnosticContext &&

原执行 {run.diagnosticContext.originalRunId?.slice(0, 8) ?? '未记录'}

}
{run.workspaceIdentity && <>
执行目录
{run.workspaceIdentity.root}
{run.workspaceIdentity.branch && <>
独立分支
{run.workspaceIdentity.branch}
}}
开始 / 结束
{time(run.startedAt)}
{time(run.finishedAt)}
模型轮次 / 工具
{run.steps} / {run.toolCalls}
已报告用量
{number(run.usage?.totalTokens)} tokens
输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}
{!!run.usage?.unknownRequests && <>
未报告用量
{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens
}
本次预算
{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮
任务累计
{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens
diff --git a/src/client/types.ts b/src/client/types.ts index 3810f574..8a1b4452 100644 --- a/src/client/types.ts +++ b/src/client/types.ts @@ -149,6 +149,18 @@ export interface TurnObservation { } export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } } export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] } +export interface Run { question?: string; diagnosticContext?: { artifactId: string; sha256: string; originalRunId: string | null } } +export interface DiagnosticContext { + artifactId?: string; originalRunId?: string | null; evidenceVerified: boolean; historical?: boolean; note?: string; error?: string; + failure?: { id: string; eventId: string; runId: string; sha256: string; value: RuntimeFailure } | null; + check?: { id: string; runId: string; status: string } | null; +} +export interface DeliveryStatus { + requirementsRevision: number; + followUp: { taskId: string; runId: string; goal: string; taskStatus: string; status: string; statusLabel: string; nextStep: string; note: string; + gaps: { kind: string; id: string; label: string; nextStep: string }[] }; + diagnostics: { runId: string; status: string; stopReason: string | null; question: string; failure?: RuntimeFailure | null; context: DiagnosticContext }[]; +} export interface TaskCheckpoint { id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string; status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string; diff --git a/src/core/delivery-report.mjs b/src/core/delivery-report.mjs index 43c9c972..100e6c36 100644 --- a/src/core/delivery-report.mjs +++ b/src/core/delivery-report.mjs @@ -14,9 +14,12 @@ import { inspectTurnProgress } from './context/turn-progress-recorder.mjs'; import { FileResults } from './tasks/file-results.mjs'; import { taskContract } from '../shared/contracts/task-control.mjs'; import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs'; +import { inspectDiagnosticContext } from './tasks/diagnostic-context.mjs'; +import { deliveryFollowUp, requirementNextStep, requirementStates } from '../shared/contracts/task-follow-up.mjs'; const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查', existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对', + research_verified: '约定研究范围已核对,无新增修改', scope_verified: '约定范围已核对,按约定未测试', needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' }; const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' '); @@ -44,7 +47,7 @@ export function verifiedCheck(store, session, inspection) { export class DeliveryReporter { constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; } - async create(session, { job = null, inspection = null } = {}) { + async inspect(session, { job = null, inspection = null } = {}) { const taskId = session.taskId, runId = session.runId; const task = this.store.owned('task', taskId, session.id); const run = this.store.owned('run', runId, session.id); @@ -125,15 +128,22 @@ export class DeliveryReporter { requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null }; }); if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 }); + const researchScope = !hasFileScope && !changes.some(change => change.status === 'applied') && requirements.configured && requirements.all_resolved + && requirements.items.some(item => (item.role ?? 'requirement') === 'requirement' && ['evidence', 'user'].includes(item.method)) + && requirements.items.every(item => item.method === 'scope' || item.method === 'not_requested' || item.method === 'user' || item.kind === 'analysis') + && (contract.checks === 'skip' || !['failed', 'stale', 'unknown', 'unverified'].includes(task.verification.status)); + const needsChecks = !check && !(contract.checks !== 'required' && (researchScope || hasFileScope && fileDelivery.satisfied + && (contract.checks === 'skip' || contract.checks === 'unspecified' && task.verification.status === 'not_configured'))); 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' + : needsChecks ? 'needs_checks' : browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks' - : hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered' + : researchScope && !check ? contract.checks === 'skip' ? 'scope_verified' : 'research_verified' + : 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], @@ -141,7 +151,11 @@ export class DeliveryReporter { 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: requirements.status, note: '源码和检查证据不代替业务需求验收。' }, - requirements, + requirements, runId, + diagnostics: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId && value.purpose === 'diagnostic') + .map(value => ({ runId: value.id, status: value.status, stopReason: value.stopReason, question: value.question, + failure: session.events.findLast(event => event.runId === value.id && event.kind === 'error')?.diagnostic ?? null, + context: inspectDiagnosticContext(this.store, session, value) })), turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId) .map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })), fileResults, fileDelivery, @@ -150,7 +164,7 @@ export class DeliveryReporter { 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, + engine: value.engine, purpose: value.purpose ?? 'execution', status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason, consumption: structuredClone(value.consumption ?? []), ...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })), usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null }, @@ -176,14 +190,22 @@ export class DeliveryReporter { requiresVerification, limitations: ['本切片验证已选工程检查和提交范围;业务需求验收另行记录。', '提交为本地普通提交,不执行仓库hooks和GPG签名。', '请求输入为本地UTF-8估算;服务实际分词和用量另行记录。', '未配置模型单价,费用未知。'], }; - const safe = JSON.parse(this.redact(JSON.stringify(report))); - const markdown = renderDeliveryMarkdown(safe); - const jsonArtifact = this.store.artifactStore.write(session, run, safe, { kind: 'delivery-report' }); + report.followUp = deliveryFollowUp(report); + return JSON.parse(this.redact(JSON.stringify(report))); + } + + async create(session, options = {}) { + const taskId = session.taskId, runId = session.runId; + const report = await this.inspect(session, options); + if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 }); + const run = this.store.owned('run', runId, session.id), job = options.job; + const markdown = renderDeliveryMarkdown(report); + const jsonArtifact = this.store.artifactStore.write(session, run, report, { kind: 'delivery-report' }); const markdownArtifact = this.store.artifactStore.write(session, run, markdown, { kind: 'delivery-report-markdown', mediaType: 'text/markdown' }); this.store.core.artifact.set(jsonArtifact.id, jsonArtifact); this.store.core.artifact.set(markdownArtifact.id, markdownArtifact); if (job) { job.reportArtifactId = jsonArtifact.id; job.reportMarkdownArtifactId = markdownArtifact.id; } - this.store.save(session, { type: 'delivery.report', detail: { status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } }); - return { report: safe, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id }; + this.store.save(session, { type: 'delivery.report', detail: { status: report.status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } }); + return { report, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id }; } } @@ -211,10 +233,24 @@ export function renderDeliveryMarkdown(report) { '', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |'); 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(' | ') + ' |'); + item.revision, requirementStates[item.status] ?? item.status, [item.error, item.user_note, item.proof_artifact_id, requirementNextStep(item)].filter(Boolean).join(' · ')].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.followUp) { + lines.push('', '## 当前缺口与下一步', '', report.followUp.note, '', '原目标:' + report.followUp.goal, '', '下一步:' + report.followUp.nextStep); + for (const gap of report.followUp.gaps) lines.push('', '- ' + gap.label + ':' + gap.nextStep); + } + if (report.diagnostics?.length) { + lines.push('', '## 只读诊断与原执行', '', '诊断答复不核销原目标、原失败或未知操作。'); + for (const diagnostic of report.diagnostics) { + const context = diagnostic.context; + lines.push('', '诊断Run:' + diagnostic.runId + ' · ' + diagnostic.status, '问题:' + diagnostic.question, + ...(diagnostic.failure ? ['本次诊断错误:' + diagnostic.failure.message] : []), + context.evidenceVerified ? '原执行:' + (context.originalRunId ?? '未记录') + ' · 原失败:' + (context.failure?.value.message ?? '未记录具体错误;原因保持未知。') + : '原失败绑定未核对:' + (context.error ?? context.note), '原工件:' + (context.artifactId ?? '旧记录未封存')); + } + } if (report.turnObservations?.some(row => row.recorded || row.error)) { lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。'); for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), ''); diff --git a/src/core/tasks/diagnostic-context.mjs b/src/core/tasks/diagnostic-context.mjs new file mode 100644 index 00000000..afe7c14c --- /dev/null +++ b/src/core/tasks/diagnostic-context.mjs @@ -0,0 +1,45 @@ +import { createHash } from 'node:crypto'; + +const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'); +const owned = (value, session, taskId) => value?.sessionId === session.id && value.projectId === session.projectId && value.taskId === taskId; + +// Preserve the execution being explained even if the diagnostic itself fails. +// These are original observations, not permission to repeat an operation. +export function bindDiagnosticContext(store, session, task, run) { + const runs = [...store.core.run.values()].filter(value => owned(value, session, task.id) && value.purpose !== 'diagnostic'); + const error = session.events.findLast(event => event.taskId === task.id + && runs.some(value => value.id === event.runId) && (event.kind === 'error' || event.kind === 'tool' && event.phase === 'failed')); + const value = error ? structuredClone(error.diagnostic ?? { source: error.kind, title: error.label, message: error.output ?? '', occurredAt: error.createdAt }) : null; + const check = [...store.core.check_job.values()].findLast(value => owned(value, session, task.id)); + const snapshot = { schemaVersion: 1, projectId: session.projectId, sessionId: session.id, taskId: task.id, runId: run.id, + goal: task.contract?.goal ?? task.goal, taskStatusBefore: task.status, originalRunId: error?.runId ?? check?.runId ?? runs.at(-1)?.id ?? null, + failure: error ? { id: value.id ?? error.id, eventId: error.id, runId: error.runId, sha256: hash(value), value } : null, + verification: structuredClone(task.verification ?? null), + check: check ? { id: check.id, runId: check.runId, status: check.status, sourceFingerprint: check.sourceFingerprint ?? null, + logs: check.results.map(result => ({ id: result.logArtifactId ?? null, sha256: store.core.artifact.get(result.logArtifactId)?.sha256 ?? null })) } : null, + note: '绑定原执行及原失败;只读诊断答复不构成原目标交付,不重放工具或检查。' }; + const artifact = store.artifactStore.write(session, run, snapshot, { kind: 'diagnostic-context' }); + store.core.artifact.set(artifact.id, artifact); + return { artifactId: artifact.id, sha256: artifact.sha256, originalRunId: snapshot.originalRunId }; +} + +export function inspectDiagnosticContext(store, session, run) { + if (!run.diagnosticContext) return { evidenceVerified: false, historical: true, note: '旧诊断未封存原失败绑定,不能补造所属错误。' }; + try { + if (!owned(run, session, session.taskId)) throw new Error('诊断不属于当前Task。'); + const reference = run.diagnosticContext, artifact = store.owned('artifact', reference.artifactId, session.id); + if (artifact.taskId !== run.taskId || artifact.runId !== run.id || artifact.kind !== 'diagnostic-context' || artifact.sha256 !== reference.sha256) + throw new Error('诊断原工件身份或SHA无法核对。'); + const value = JSON.parse(store.artifactStore.read(artifact)); + if (!owned(value, session, run.taskId) || value.runId !== run.id || value.originalRunId !== reference.originalRunId) + throw new Error('诊断原项目/Task/Run绑定不一致。'); + if (value.originalRunId && !owned(store.core.run.get(value.originalRunId), session, run.taskId)) throw new Error('原执行不属于此Task。'); + if (value.failure) { + const event = session.events.find(row => row.id === value.failure.eventId); + const original = event?.diagnostic ?? (event ? { source: event.kind, title: event.label, message: event.output ?? '', occurredAt: event.createdAt } : null); + if (!event || event.taskId !== run.taskId || event.runId !== value.failure.runId || hash(original) !== value.failure.sha256 || hash(value.failure.value) !== value.failure.sha256) + throw new Error('原失败记录已变化或无法核对。'); + } + return { ...value, ...reference, evidenceVerified: true }; + } catch (error) { return { ...run.diagnosticContext, evidenceVerified: false, error: error.message }; } +} diff --git a/src/server/app.mjs b/src/server/app.mjs index 74f58bc8..83329346 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -701,6 +701,12 @@ return async (request, response) => { else await runtime.gitDelivery().reconcile(session, deliveryJob[1]); return json(response, store.publicSession(session)); } + if (method === 'GET' && action === 'delivery-status') { + if (url.searchParams.get('taskId') !== session.taskId || url.searchParams.get('runId') !== session.runId) + throw Object.assign(new Error('所选原任务或运行已变化,请刷新后核对。'), { status: 409 }); + const report = await runtime.gitDelivery().reporter.inspect(session); + return json(response, { followUp: report.followUp, diagnostics: report.diagnostics, requirementsRevision: report.requirements.revision }); + } if (method === 'POST' && action === 'delivery-reports') { await body(request); await runtime.gitDelivery().report(session); return json(response, store.publicSession(session), 201); diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs index f7cd7c1a..c5263920 100644 --- a/src/server/runtime.mjs +++ b/src/server/runtime.mjs @@ -15,6 +15,7 @@ import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs'; import { now, repairToolPairs } from './store.mjs'; import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs'; +import { inspectDiagnosticContext } from '../core/tasks/diagnostic-context.mjs'; import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs'; import { tokenBudgetState,checkModelDispatchBudget } from '../shared/contracts/model-reservation.mjs'; import { taskToolAllowed, taskContract } from '../shared/contracts/task-control.mjs'; @@ -355,13 +356,14 @@ export class Runtime { project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state) + '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({ goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract, - }) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '') + }) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question + + '\n所属原执行与失败(核对失败时保持未知,不根据其它项目补造原因):' + JSON.stringify(inspectDiagnosticContext(this.store, session, run.record)) : '') + '\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, + criterion: item.criterion, role: item.role ?? 'requirement', source: item.source, 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 })) })), @@ -626,7 +628,7 @@ export class Runtime { if (error.diagnostic?.kind === 'model_identity') run.stopReason = 'model_identity'; const diagnostic = error.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'agent_loop', kind: 'runtime', title: '工作台任务需要处理', message: this.provider.redact(error.message ?? String(error)), occurredAt: now() }; - session.lastFailure = { ...diagnostic, runId: run.id }; + session.lastFailure = { ...diagnostic, projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id }; const message = this.store.message(session, 'system', diagnostic.message); session.failure = { ...session.lastFailure, messageId: message.id }; this.store.event(session, { kind: 'error', source: diagnostic.source, label: diagnostic.title, phase: 'failed', @@ -666,7 +668,8 @@ export class Runtime { const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata)); if (!['act_browser_tab','prepare_environment','run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running'); else this.store.save(session); - if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) }; + if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session), + ...(run.record.purpose === 'diagnostic' ? { diagnosticContext: inspectDiagnosticContext(this.store, session, run.record) } : {}) }; else if (tool === 'read_registered_skill') { verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id)); result = this.skillRegistry().read(session, run.record, args, { maximumMessageBytes, callId: call.id }); diff --git a/src/server/store.mjs b/src/server/store.mjs index b053b19e..a1797c2b 100644 --- a/src/server/store.mjs +++ b/src/server/store.mjs @@ -4,6 +4,7 @@ import path from 'node:path'; import { EventEmitter } from 'node:events'; import { randomUUID, createHash } from 'node:crypto'; import { lastSessionFailure } from './diagnostics.mjs'; +import { bindDiagnosticContext } from '../core/tasks/diagnostic-context.mjs'; import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database.mjs'; import { ArtifactStore } from '../core/storage/artifact-store.mjs'; import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs'; @@ -506,7 +507,10 @@ export class Store extends EventEmitter { if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 }); const run = createRun(session, task, config, resume || continuing ? previousRunId : null); run.purpose = purpose; - if (purpose === 'diagnostic') { run.question = String(content); run.taskStatusBefore = task.status; } + if (purpose === 'diagnostic') { + run.question = String(content); run.taskStatusBefore = task.status; + run.diagnosticContext = bindDiagnosticContext(this, session, task, run); + } if (instructionSource) run.source = instructionSource; if(resumePlan){task.budget.maxTokens=config.maxTaskTokens;run.resumePlanId=resumePlan.id;resumePlan.status='consumed';resumePlan.newRunId=run.id;} run.workspaceIdentity = structuredClone(workspaceIdentity); diff --git a/src/shared/contracts/task-follow-up.d.mts b/src/shared/contracts/task-follow-up.d.mts new file mode 100644 index 00000000..45253f11 --- /dev/null +++ b/src/shared/contracts/task-follow-up.d.mts @@ -0,0 +1,4 @@ +import type { RequirementItem } from '../../client/types'; +export const requirementStates: Record; +export function resolvedRequirement(item: RequirementItem): boolean; +export function requirementNextStep(item: RequirementItem): string; diff --git a/src/shared/contracts/task-follow-up.mjs b/src/shared/contracts/task-follow-up.mjs new file mode 100644 index 00000000..c1502a9b --- /dev/null +++ b/src/shared/contracts/task-follow-up.mjs @@ -0,0 +1,36 @@ +export const requirementStates = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对', + evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行', + scope_unknown: '范围待澄清', reference_recorded: '参考已记录', boundary_recorded: '边界已记录' }; +export const resolvedRequirement = item => ['evidence_verified', 'user_confirmed', 'not_requested', 'reference_recorded', 'boundary_recorded'].includes(item.status); +export function requirementNextStep(item) { + if (item.status === 'scope_unknown') return '澄清原文用途、业务范围及验收方式后修订此项。'; + if (item.status === 'reference_recorded') return '已记录参考用途;不自动要求修改或交付该文件。'; + if (item.status === 'boundary_recorded') return '已记录禁止事项;是否遵守仍需实际证据,不计为验收通过。'; + if (item.status === 'not_requested') return '按约定未执行检查;不计为测试通过,原失败保留。'; + if (item.status === 'evidence_verified') return '所选范围的原证据已核对;其它要求分别复核。'; + if (item.status === 'user_confirmed') return '用户体验结论已记录;不代替工程检查。'; + if (item.error) return item.error + ' 核对当前输入和原记录后重新选择证据。'; + return item.method === 'user' ? '实际体验此项后记录用户结论。' : '选择属于当前Task、要求修订及当前输入的实际证据进行复核。'; +} + +// Both the task page and saved report use this same read-only assessment. +export function deliveryFollowUp(report) { + const gaps = []; + const add = (kind, id, label, nextStep) => gaps.push({ kind, id, label, nextStep }); + for (const item of report.requiresVerification) add('unknown', item.id, item.tool + '结果需要核对', '核对原输入、原工件和实际副作用;不要重放已进入执行的操作。'); + for (const item of report.changes.filter(row => ['pending', 'conflict'].includes(row.status))) add('review', item.id, item.path + '等待审查', '在改动面板核对差异与冲突后决定是否应用。'); + if (report.deliveryReview) add('review', report.deliveryReview.planId, 'Git交付等待审查', '核对当前交付预览后确认或撤回。'); + if (report.requirements.error) add('requirements', report.task.id, '要求原记录无法核对', report.requirements.error); + for (const id of report.requirements.unreviewed_sources ?? []) add('source', id, '用户原文尚未审阅', '从原文整理草案或手动记录要求,确认用途和验收范围。'); + for (const item of report.requirements.items.filter(row => !resolvedRequirement(row))) add('requirement', item.key, item.title + ' · ' + (requirementStates[item.status] ?? item.status), requirementNextStep(item)); + for (const item of report.taskPlan.steps.filter(row => row.status !== 'verified')) add('plan', item.key, item.title + '尚未核验', '核对当前计划步骤、依赖和原实际证据。'); + if (report.status === 'needs_results') add('files', report.task.id, '当前文件成果仍需核对', '回到原目标,在文件成果中核对当前字节与要求的修改范围。'); + if (report.status === 'needs_checks') add('checks', report.task.id, '工程检查尚未通过当前输入核验', '查看原检查与失败日志;需要修复时继续原目标,检查仍须审批。'); + if (report.status === 'needs_browser_checks') add('browser', report.task.id, '页面验收仍待完成', '核对当前构建、所属页面计划和原验收结果。'); + const latestDiagnostic = report.diagnostics?.at(-1); + if (latestDiagnostic && !latestDiagnostic.context.evidenceVerified) add('diagnostic', latestDiagnostic.runId, '诊断的原失败绑定未核对', latestDiagnostic.context.error ?? latestDiagnostic.context.note); + return { taskId: report.task.id, runId: report.runId, goal: report.task.goal, taskStatus: report.task.status, status: report.status, + statusLabel: report.statusLabel, gaps, nextStep: gaps[0]?.nextStep ?? (report.status === 'in_progress' ? '等待所属运行、检查或审批结束,按原目标核对结果。' + : report.status === 'verified_uncommitted' ? '核对要求与当前结果;需要Git交付时先准备预览并审查。' : '查看已核对的范围与原证据;需要新增工作时明确追加要求。'), + note: '诊断答复完成仅表示解释结束;原目标、原失败和未知结果继续保留。' }; +} diff --git a/task_plan.md b/task_plan.md index 9afaa911..88d4b31a 100644 --- a/task_plan.md +++ b/task_plan.md @@ -7,8 +7,8 @@ 1. [complete] 核对现有要求/Task约定/诊断与真实入口,范围及验收案例已记docs/TASK-AGREEMENT-C.md;草案只保留原文待审阅,参考文件不变成输出。 2. [complete] 本地有界草案/来源修订/跨Task/篡改/HTTP重启及显式范围接到原账本,首21项20通过1失败(旧编译宿主)保留,重建后原21/21通过,阶段回顾后本地提交。 3. [complete] 草案审阅/范围保存刷新/澄清/旧修订拒绝/迟到响应隔离,网页6组与实际Electron6组、1440/390px和构建通过;旧要求网页7组通过。三份验收器首失败保留,回顾见TASK-AGREEMENT-C,阶段提交。 -4. [in_progress] 诊断绑定原失败/Task/Run,报告与任务显示同一当前缺口/下一步;不重放命令、不丢原目标或把诊断算交付,相关验证与回顾提交。 -5. [pending] 完整构建、冻结来源/独立发行/安装/保留状态正式升级、原证据封存/离线/索引复核、最终回顾与本地提交;按实际完成报告,不把localhost夹具当真实自主交付。 +4. [complete] 诊断封存原Task/Run/错误SHA,保留诊断自身错误和原目标;任务页与报告共用当前缺口/下一步。相关首65项62通过3测试数据失败、专项6/6复验;网页/Electron各5组和构建通过,原失败与回顾保持。 +5. [in_progress] 版本同步、完整构建、冻结来源/独立发行/安装/保留状态正式升级、原证据封存/离线/索引复核、最终回顾与本地提交;按实际完成报告,不把localhost夹具当真实自主交付。 恢复首次宽读发生截断,随后限定已知文件短段;一次PowerShell rg目录通配失败改-g过滤。只读失败和截断不作验证通过。session-catchup无待同步输出,工作区干净。 diff --git a/tests/diagnostic-follow-up.test.mjs b/tests/diagnostic-follow-up.test.mjs new file mode 100644 index 00000000..78dbb21b --- /dev/null +++ b/tests/diagnostic-follow-up.test.mjs @@ -0,0 +1,114 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { fixture, launchWorkbench } from './helpers.mjs'; +import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs'; +import { Runtime } from '../src/server/runtime.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Store } from '../src/server/store.mjs'; +import { RequirementReview } from '../src/core/tasks/requirement-review.mjs'; +import { inspectDiagnosticContext } from '../src/core/tasks/diagnostic-context.mjs'; +import { DeliveryReporter, renderDeliveryMarkdown } from '../src/core/delivery-report.mjs'; + +const answer = { message: { role: 'assistant', content: '只读解释已完成,原任务仍待处理。' }, usage: { prompt_tokens: 10, completion_tokens: 4 } }; +function originalFailure(f) { + const original = beginPlanTask(f, '修复原工程并通过测试'); + f.session.status = 'failed'; + const diagnostic = { id: randomUUID(), source: 'model_connection', kind: 'network', stage: 'model_request', title: '原连接失败', message: '原POST结果未知,不得重放。', runId: original.id }; + const event = f.store.event(f.session, { kind: 'error', phase: 'failed', diagnostic }); + f.session.lastFailure = diagnostic; f.store.save(f.session); + return { original, diagnostic, event }; +} +const requirement = (f, extra = {}) => ({ key: 'research', role: 'requirement', title: '解释原工程', criterion: '核对原读取', kind: 'analysis', tools: ['read_file'], method: 'evidence', + source: { kind: 'goal', id: f.session.taskId, start: 0, end: f.store.core.task.get(f.session.taskId).goal.length }, ...extra }); + +test('diagnostic failures and repeated questions retain the original execution error, task, checks and read-only authority', async t => { + const f = fixture(t), origin = originalFailure(f), provider = new Provider(); let round = 0; + provider.complete = async (_config, _messages, _project, _signal, _progress, _plan, tools) => { + assert.ok(tools.every(tool => !['propose_file', 'run_command', 'run_checks'].includes(tool.function.name))); + if (round++ === 0) throw new Error('本次诊断自身的独立错误'); + return answer; + }; + const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll()); + const task = f.store.core.task.get(f.session.taskId); task.verification.status = 'failed'; + const instructions = structuredClone(task.instructions); + runtime.start(f.session.id, '前面的错误是怎么回事?'); await runtime.active.get(f.session.id).promise; + const first = f.store.core.run.get(f.session.runId), context = inspectDiagnosticContext(f.store, f.session, first); + assert.equal(first.status, 'failed'); assert.equal(context.evidenceVerified, true); + assert.equal(context.originalRunId, origin.original.id); assert.equal(context.failure.id, origin.diagnostic.id); + assert.deepEqual(context.failure.value, origin.diagnostic); assert.equal(f.session.lastFailure.runId, first.id); + runtime.start(f.session.id, '请解释刚才执行的错误'); await runtime.active.get(f.session.id).promise; + const second = f.store.core.run.get(f.session.runId), next = inspectDiagnosticContext(f.store, f.session, second); + assert.equal(second.status, 'completed'); assert.equal(second.stopReason, 'diagnostic_answered'); + assert.equal(next.failure.sha256, context.failure.sha256); assert.equal(next.originalRunId, origin.original.id); + assert.equal(f.session.status, 'failed'); assert.equal(task.status, 'failed'); assert.equal(task.verification.status, 'failed'); + assert.deepEqual(task.instructions, instructions); assert.equal(f.session.changes.length, 0); assert.equal(f.store.core.check_job.size, 0); + const report = await new DeliveryReporter(f.store).inspect(f.session); + assert.equal(report.status, 'needs_checks'); assert.equal(report.diagnostics.length, 2); assert.match(renderDeliveryMarkdown(report), /原POST结果未知/); + assert.match(report.diagnostics[0].failure.message, /诊断自身的独立错误/); +}); + +test('diagnostic binding survives reopen, rejects foreign Task references and detects original error or artifact tampering', t => { + const f = fixture(t), origin = originalFailure(f), run = f.store.beginRun(f.session, '解释下这个错误', false, f.store.config); + f.session.status = 'failed'; f.store.finishRun(f.session, run, 'diagnostic_answered', { status: 'completed' }); f.store.close(); + const restored = new Store(f.data); f.onCleanup(() => restored.close()); const session = restored.session(f.session.id), saved = restored.core.run.get(run.id); + assert.equal(inspectDiagnosticContext(restored, session, saved).failure.id, origin.diagnostic.id); + assert.equal(inspectDiagnosticContext(restored, { ...session, taskId: randomUUID() }, saved).evidenceVerified, false); + const event = session.events.find(value => value.id === origin.event.id); event.diagnostic.message += 'changed'; + assert.match(inspectDiagnosticContext(restored, session, saved).error, /原失败/); event.diagnostic.message = origin.diagnostic.message; + const artifact = restored.core.artifact.get(saved.diagnosticContext.artifactId); fs.writeFileSync(path.join(restored.artifactStore.root, artifact.relative), 'corrupt'); + assert.match(inspectDiagnosticContext(restored, session, saved).error, /校验/); +}); + +test('a new Task never adopts a previous Task error from session.lastFailure', t => { + const f = fixture(t); originalFailure(f); + f.store.core.task.get(f.session.taskId).status = 'completed'; const current = beginPlanTask(f, '只解释当前新工程'); + const run = f.store.beginRun(f.session, '前面的错误是怎么回事?', false, f.store.config), context = inspectDiagnosticContext(f.store, f.session, run); + assert.equal(context.evidenceVerified, true); assert.equal(context.failure, null); assert.equal(context.originalRunId, current.id); + assert.equal(context.taskId, current.taskId); +}); + +test('verified research and explicit no-test scopes do not demand an unrelated test job or claim engineering success', async t => { + for (const skip of [false, true]) { + const f = fixture(t); beginPlanTask(f, '只研究原README.md,不修改。' + (skip ? '无需测试。' : '')); const read = completeRead(f); + const manager = new RequirementReview(f.store), rows = [requirement(f), requirement(f, { key: 'ref', role: 'reference', method: 'scope' }), + requirement(f, { key: 'boundary', role: 'prohibition', method: 'scope' })].map(value => { if (value.method === 'scope') delete value.tools; return value; }); + await manager.save(f.session, { expected_revision: 0, requirements: rows }); + await manager.verify(f.session, { expected_revision: 1, key: 'research', evidence_id: read.id }); + const reporter = new DeliveryReporter(f.store), report = await reporter.inspect(f.session); + assert.equal(report.status, skip ? 'scope_verified' : 'research_verified'); assert.equal(report.verifiedCheckJobId, null); + assert.equal(f.store.core.check_job.size, 0); assert.equal(report.followUp.gaps.length, 0); + const text = renderDeliveryMarkdown(report); assert.match(text, /不自动要求修改/); assert.match(text, /是否遵守仍需实际证据/); + if (!skip) { f.store.core.task.get(f.session.taskId).verification.status = 'failed'; assert.equal((await reporter.inspect(f.session)).status, 'needs_checks'); } + } +}); + +test('unknown scope and unknown operations remain actionable even after a diagnostic answer or read proof', async t => { + const f = fixture(t); beginPlanTask(f, '研究原工程,无需测试。'); const read = completeRead(f), manager = new RequirementReview(f.store); + const unknownScope = requirement(f, { key: 'unknown', role: 'unknown', method: 'scope' }); delete unknownScope.tools; + await manager.save(f.session, { expected_revision: 0, requirements: [requirement(f), unknownScope] }); + await manager.verify(f.session, { expected_revision: 1, key: 'research', evidence_id: read.id }); + const reporter = new DeliveryReporter(f.store), report = await reporter.inspect(f.session); + assert.equal(report.status, 'needs_requirements'); assert.match(report.followUp.nextStep, /澄清原文用途/); + f.store.core.tool.get(read.id).requiresVerification = true; + const unknown = await reporter.inspect(f.session); assert.equal(unknown.status, 'needs_verification'); assert.match(unknown.followUp.nextStep, /不要重放/); +}); + +test('delivery status HTTP is read-only, selection-bound and equal to the saved report after host restart', async t => { + const f = fixture(t); const origin = originalFailure(f); + const diagnostic = f.store.beginRun(f.session, '这个报错是什么意思', false, f.store.config); + f.session.status = 'failed'; f.store.finishRun(f.session, diagnostic, 'diagnostic_answered', { status: 'completed' }); f.store.close(); + let host = await launchWorkbench(t, f.data); const route = '/sessions/' + f.session.id; + const url = route + '/delivery-status?taskId=' + f.session.taskId + '&runId=' + diagnostic.id; + const before = await host.api(route + '/export'), view = await host.api(url), after = await host.api(route + '/export'); + const { exportedAt: beforeAt, ...beforeData } = before, { exportedAt: afterAt, ...afterData } = after; + assert.ok(beforeAt && afterAt); assert.deepEqual(afterData, beforeData); assert.equal(view.diagnostics[0].context.failure.id, origin.diagnostic.id); + await assert.rejects(host.api(url.replace(diagnostic.id, origin.original.id)), /所选原任务或运行/); + await host.api(route + '/delivery-reports', {}); + const saved = await host.api(route), reportArtifact = saved.execution.artifacts.findLast(row => row.kind === 'delivery-report'); + const report = JSON.parse((await host.api('/artifacts/' + reportArtifact.id + '?session=' + f.session.id + '&limit=64000')).content); + assert.deepEqual(report.followUp, view.followUp); + await host.close(); host = await launchWorkbench(t, f.data); assert.deepEqual((await host.api(url)).followUp, view.followUp); +}); diff --git a/tests/task-control.test.mjs b/tests/task-control.test.mjs index 3e7af6b1..df74eff8 100644 --- a/tests/task-control.test.mjs +++ b/tests/task-control.test.mjs @@ -82,6 +82,8 @@ test('diagnostic answers retain the unfinished task, limits and check result, an assert.equal(f.session.changes.length, 0); assert.ok(!fs.existsSync(path.join(f.projectRoot, 'unwanted.txt'))); const denied = JSON.parse(f.session.providerMessages.find(message => message.tool_call_id === 'bad-diagnostic-write').content); assert.equal(denied.status, 'error'); assert.match(denied.message, /只读/); + const inspected = JSON.parse(f.session.providerMessages.find(message => message.tool_call_id === 'inspect-error').content); + assert.equal(inspected.diagnosticContext.evidenceVerified, true); assert.equal(inspected.diagnosticContext.taskId, taskId); f.runtime.start(f.session.id, '继续完成'); await f.wait(); assert.equal(f.session.taskId, taskId); assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'verification_incomplete');