From 8c36296c7c9d86b18b3085a349f9411080b17784 Mon Sep 17 00:00:00 2001 From: Agent Workbench Dev Date: Fri, 6 Nov 2026 17:35:05 +0800 Subject: [PATCH] feat: expose reversible experience adoption with isolated optional failures --- docs/EXPERIENCE-DRAFTS-E-PLAN.md | 2 +- docs/QA-EXPERIENCE-DRAFTS-E.md | 18 ++- scripts/verify-experience-ui.mjs | 177 +++++++++++++++++++++++++ src/client/App.tsx | 2 +- src/client/ExperienceDraftControls.tsx | 71 ++++++++++ src/client/ProjectMemory.css | 30 +++++ src/client/ProjectMemoryPanel.tsx | 50 +++++-- src/client/types.ts | 15 ++- src/core/context/request-plan.mjs | 20 ++- src/core/memory/experience-drafts.mjs | 22 ++- src/core/memory/project-memory.mjs | 12 +- tests/experience-context.test.mjs | 147 ++++++++++++++++++++ tests/experience-drafts.test.mjs | 13 ++ 13 files changed, 552 insertions(+), 27 deletions(-) create mode 100644 scripts/verify-experience-ui.mjs create mode 100644 src/client/ExperienceDraftControls.tsx create mode 100644 tests/experience-context.test.mjs diff --git a/docs/EXPERIENCE-DRAFTS-E-PLAN.md b/docs/EXPERIENCE-DRAFTS-E-PLAN.md index 4f08d528..c195c157 100644 --- a/docs/EXPERIENCE-DRAFTS-E-PLAN.md +++ b/docs/EXPERIENCE-DRAFTS-E-PLAN.md @@ -10,4 +10,4 @@ D已随1.25.10正式交付。下一复用现有项目记忆、Skills和工程评 4. 用自有固定事实验证跨身份、原字节篡改、缺工件、源码变化、unknown用量、失败归因、重复修订、关闭/撤销、旧记录兼容与实际请求差异。随后做本机HTTP、现有面板网页/实际Electron及390px,故障只使可选经验不可用,不阻断原执行。 5. 只有独立载荷/安装/正式入口验证完成后才标用户功能交付。若后续涉及工作台自身修改,继续沿候选工作区、原检查/固定评测、当前来源和Git、独立发行及回滚,不改正在运行的发行目录。真实语义收益和F角色路由另冻新样本,不以固定HTTP代签。 -本文件是下一切片计划,尚未实现E。AD/AE真实成功、Claude原400、AF身份拒绝、AG三网络失败、unknown消费、重复读取普遍改善未知和Purge收益unknown全部保留。Mnemo消费包/自动导出和受托执行仍是独立接口工作,E不暗中接管其记忆或权限。 +2026-11-06阶段进度:E核心、现有面板与故障隔离已实现;最终相关79/79、独立HTTP/上下文24/24及网页/实际Electron各七组通过,详见QA-EXPERIENCE-DRAFTS-E.md。正式交付仍须独立1.25.11源码/程序、安装及保留状态升级,未完成前不称已部署。AD/AE真实成功、Claude原400、AF身份拒绝、AG三网络失败、unknown消费、重复读取普遍改善未知和Purge收益unknown全部保留。Mnemo消费包/自动导出和受托执行仍是独立接口工作,E不暗中接管其记忆或权限。 diff --git a/docs/QA-EXPERIENCE-DRAFTS-E.md b/docs/QA-EXPERIENCE-DRAFTS-E.md index 03af7595..f8d139f6 100644 --- a/docs/QA-EXPERIENCE-DRAFTS-E.md +++ b/docs/QA-EXPERIENCE-DRAFTS-E.md @@ -14,10 +14,20 @@ 新增公开诊断事实投影与持久化前来源重读后,定向复验17/17通过(core-2.tap)。阶段回顾:保留旧用户记忆、将经验默认排除、复用原检查核验;实际HTTP/UI与发行继续独立验收。早期只读搜索多次误用不存在路径/Windows通配路径,未修改数据,后续用rg目录搜索;这些命令错误不作为产品测试通过记录。 -## 待验证 +## HTTP、界面与故障隔离 -- 新HTTP路由、实际模型请求前后差异与可选经验故障隔离。 -- 原记忆面板、网页/实际Electron、390px与失败恢复。 -- 独立源码/程序归档、安装、正式入口与保留状态升级。 +第二阶段首轮独立candidate-1后端38项37过1失败:新增验证器只查system消息,漏掉preserve模式的user数据消息;context-debug保留,修正验证器后4/4通过(http-2.tap),未改前缀/透传行为。网页首轮工具箱与侧栏同名按钮定位失败;第二轮发现来源select的隐式标签会包含option文本,已补显式可访问名称。两原失败截图/DOM保留。build-1误用系统Node16,未完成构建;固定PATH到Node24后的build-2通过。 + +补强:原工件引用同时保存四级scope;可选经验发送快照失败只省略经验并记录projectMemoryIssue,原请求保存仍按原契约执行。上述改动需新候选定向复验与网页回看。 + +最终独立candidate-4后端SHA为`69f136a1c3697d21b7c42fe3ad62aec7453a8cc57624ba113e9ed537ca11117d`,538个src/scripts输入。新HTTP及上下文24/24通过(http-5.tap);扩大相关回归79/79通过(final-related.tap),包括原手写记忆、请求封存、前缀稳定和模型协议。损坏经验元数据、来源持久化失败和经验快照失败只使可选经验不可用;原手写记忆与普通请求存储仍沿原契约,未隐藏整体存储故障。 + +最终网页ui-web-6与实际Electron ui-electron-1均七组通过,各4次自有本机固定HTTP,真实模型请求0、页面异常0。覆盖原报告草稿、503编辑恢复、实际发送差异、撤销与反例/源码变化失效、跨会话返回来源和真实宿主重启保持;三配色文字抽样比值均不低于4.5,390px无横向溢出。已实际查看宽屏及窄屏截图。沿原项目记忆面板提供来源/修订/采纳操作,未新建控制台或改变完全访问权限。 + +中间失败继续保留:http-3/4的Run篡改夹具会触发原存储归属守卫并回滚,改为核对本次unverified与身份恢复;混合快照故障夹具需解析已JSON字符串化的输入。ui-web-3修复有初始正文的编辑框可访问名称,ui-web-4等待真实记忆加载后再测对比度。原日志、截图及首轮断言未删除或改写。build-2至build-5均通过。 + +阶段回顾:默认草稿、证据阶段与采用状态分离、来源四级归属和完整修订链均有实际契约验证。engineering_verified只认证所选原检查,经验结论与因果仍未证明。源码功能已完成;独立源码/程序归档、安装和正式入口尚待,当前正式仍1.25.10。 + +发行前复核补齐已归档损坏经验的隔离,避免原归档分支绕过结构核对。新candidate-5后端`8997fb2f946b440c87c4adbfee849e9b043f80fedba2b4af5be3eb631279b6ed`独立HTTP/核心25/25通过(final-isolation.tap);先前79项与两端七组仍按candidate-4来源保留,随包验收会使用最终新载荷。 本阶段真实模型请求0;真实网络异常、unknown计费、普遍重复读取改善未知与Purge收益unknown持续保留。 diff --git a/scripts/verify-experience-ui.mjs b/scripts/verify-experience-ui.mjs new file mode 100644 index 00000000..7bc0d4fe --- /dev/null +++ b/scripts/verify-experience-ui.mjs @@ -0,0 +1,177 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import net from 'node:net'; +import assert from 'node:assert/strict'; +import { createHash, randomUUID } from 'node:crypto'; +import { chromium, _electron } from 'playwright'; +import { fixture, compatibleFixture, completion, launchWorkbench, until } from '../tests/helpers.mjs'; +import { beginPlanTask } from '../tests/fixtures/task-plan-fixture.mjs'; +import { DeliveryReporter } from '../src/core/delivery-report.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(process.env.EXPERIENCE_QA_OUTPUT || '.qa/experience-drafts-e', (desktop ? 'electron-' : 'web-') + randomUUID()); +fs.mkdirSync(directory, { recursive: true }); +const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true }); +const passed = [], screenshots = [], errors = [], contrast = []; +let browser, application, controller, host, page, window, result; +const model = await compatibleFixture(t, () => completion([], '本机固定HTTP验收完成;未修改工程,不证明经验语义收益。')); +f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'owned-experience-ui', approvalMode: 'full' }); +f.session.title = 'E 经验来源本机验收'; +const run = beginPlanTask(f, '核对README,无需测试,不修改文件。'); run.stopReason = 'network_error'; +run.usage.unknownRequests = 1; run.usage.estimatedUnknownTokens = 19; f.store.save(f.session); +const firstReport = await new DeliveryReporter(f.store).create(f.session); +const secondReport = await new DeliveryReporter(f.store).create(f.session); +const consumer = f.store.createSession(f.project.id, 'E 请求差异本机验收'); f.store.close(); +const save = (name, value) => fs.writeFileSync(path.join(directory, name), JSON.stringify(value, null, 2)); +const mark = name => { passed.push(name); console.log('PASS ' + name); }; +async function shot(name) { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); } +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 }); +} +const documents = body => body.messages.filter(value => ['user', 'system'].includes(value.role) && value.content.includes('"project_memory":')) + .map(value => JSON.parse(value.content.slice(value.content.lastIndexOf('\n') + 1)).project_memory); +async function send() { + await host.api('/sessions/' + consumer.id + '/messages', { content: '说明本工程已有证据;无需测试,不修改文件。' }); + await until(async () => (await host.api('/sessions/' + consumer.id)).status === 'completed', 30000); + return documents(model.requests.at(-1).input); +} +async function openMemory() { + await page.getByRole('button', { name: '打开工具箱', exact: true }).click(); + const toolbox = page.getByRole('dialog', { name: '工具箱', exact: true }); + await toolbox.getByLabel('搜索工作台工具').fill('项目记忆'); await toolbox.getByRole('button', { name: '项目记忆', exact: true }).click(); + const modal = page.getByRole('dialog', { name: '项目记忆', exact: true }); + await modal.getByLabel('经验来源', { exact: true }).waitFor(); await modal.locator('.memory-summary').waitFor(); return modal; +} +async function sampleContrast() { + const values = await page.locator('.experience-source h4, .experience-source p, .experience-boundary, .experience-scope dt, .experience-scope dd, .experience-stages span').evaluateAll(nodes => { + const rgb = text => text.match(/[\d.]+/g)?.map(Number) ?? []; + const luminance = color => { const [r, g, b] = color.map(v => { const c = v / 255; return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4; }); return .2126 * r + .7152 * g + .0722 * b; }; + return nodes.filter(node => node.getBoundingClientRect().height > 0).map(node => { + const style = getComputedStyle(node), color = rgb(style.color); let parent = node, background; + while (parent) { const c = rgb(getComputedStyle(parent).backgroundColor); if (c.length === 3 || c[3] === 1) { background = c; break; } parent = parent.parentElement; } + const a = luminance(color), b = luminance(background ?? [255, 255, 255]); + return { text: node.textContent.slice(0, 45), foreground: style.color, background, ratio: (Math.max(a, b) + .05) / (Math.min(a, b) + .05) }; + }); + }); + contrast.push(...values); assert.ok(values.length > 5); assert.ok(values.every(row => row.ratio >= 4.5), JSON.stringify(values.filter(row => row.ratio < 4.5))); +} +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 = { url: controller.url, bootstrap: await controller.api('/bootstrap'), api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) }; + 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(); win.setContentSize(1440, 1080); }); await until(() => page.evaluate(() => innerWidth === 1440)); + assert.equal(await page.evaluate(() => typeof globalThis.process), 'undefined'); + } else { + host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318'); + browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1080 } }); await page.goto(host.url); + } + page.on('pageerror', error => errors.push(error.message)); await page.locator('.connection.connected').waitFor(); + await host.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'owned-experience-ui', apiKey: 'owned-experience-ui-key', approvalMode: 'full' }); + await page.getByLabel('当前项目').selectOption(f.project.id); await page.locator('.session-list button').filter({ hasText: f.session.title }).click(); + let modal = await openMemory(); const card = () => modal.locator('.memory-experience').filter({ hasText: '原失败仍需核对' }); + await modal.getByLabel('经验来源', { exact: true }).selectOption('delivery_report:' + firstReport.artifactId); + await modal.getByRole('button', { name: '生成经验草稿', exact: true }).click(); + let draft = modal.locator('.memory-experience').first(); await until(async () => (await draft.textContent()).includes('草稿 · 未采用')); + await draft.getByText('来源与修订(1)', { exact: true }).click(); await draft.getByText('所选原始事实', { exact: true }).click(); + assert.match(await draft.locator('pre').innerText(), /network_error/); assert.match(await draft.locator('pre').innerText(), /unknownRequests/); + assert.equal(model.requests.length, 0); await shot('source-draft'); + assert.equal((await send()).length, 0); + mark('explicit original report creates a default-off draft preserving network failure and unknown usage; actual HTTP omits it'); + + await draft.getByRole('button', { name: '修订草稿', exact: true }).click(); + await draft.getByLabel('经验标题', { exact: true }).fill('原失败仍需核对'); + await draft.getByLabel('经验内容', { exact: true }).fill('原报告记录网络失败,原因未知;后续成功不能解释原失败。'); + await draft.getByLabel('适用范围', { exact: true }).fill('当前工程、所选报告与相同源码'); + await draft.getByLabel('失效条件', { exact: true }).fill('源码或证据变化,以及新反例'); + const failSave = route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: '本机验收:修订保存暂不可用' }) }); + await page.route('**/memories/experiences/*/edit', failSave); + await draft.getByRole('button', { name: '保存草稿修订', exact: true }).click(); await draft.getByRole('alert').waitFor(); + assert.equal(await draft.getByLabel('经验内容', { exact: true }).inputValue(), '原报告记录网络失败,原因未知;后续成功不能解释原失败。'); await shot('save-error'); + await page.unroute('**/memories/experiences/*/edit', failSave); + await draft.getByRole('button', { name: '保存草稿修订', exact: true }).click(); + draft = card(); await until(async () => !(await draft.getByRole('button', { name: '保存草稿修订', exact: true }).count())); + await draft.getByRole('button', { name: '采用到本项目', exact: true }).click(); await draft.getByRole('button', { name: '撤销采用', exact: true }).waitFor(); + const [sent] = await send(); assert.equal(sent.entries[0].title, '原失败仍需核对'); assert.equal(sent.entries[0].experience.adoption, 'active'); + assert.equal(sent.entries[0].experience.engineering.conclusionVerified, false); + const envelopeMessage = model.requests.at(-1).input.messages.find(value => value.content?.includes('"memory_artifact":')); + const envelope = JSON.parse(envelopeMessage.content.slice(envelopeMessage.content.lastIndexOf('\n') + 1)); + const sentBefore = await host.api('/artifacts/' + envelope.memory_artifact.id + '?session=' + consumer.id); + save('sent-memory-before-withdrawal.json', sentBefore); + const originalSent = await host.api('/sessions/' + consumer.id + '/export'); + save('adopted-consumer.json', originalSent); await shot('adopted'); + mark('failed editing retains input; retry saves an immutable revision, explicit adoption reaches actual HTTP without certifying a conclusion'); + + for (const palette of ['green', 'blue', 'purple']) { + await page.evaluate(value => localStorage.setItem('orven-palette', value), palette); await page.reload(); await page.locator('.connection.connected').waitFor(); modal = await openMemory(); + assert.equal(await page.locator('html').getAttribute('data-palette'), palette); await sampleContrast(); await shot('palette-' + palette); + } + await resize(390, 844); await card().getByText('来源与修订(3)', { exact: true }).click(); + await card().getByRole('button', { name: '撤销采用', exact: true }).scrollIntoViewIfNeeded(); + assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390)); + assert.ok(await modal.evaluate(node => node.scrollWidth <= node.clientWidth + 1)); await shot('mobile-adopted'); + await card().getByRole('button', { name: '撤销采用', exact: true }).click(); await card().getByRole('button', { name: '采用到本项目', exact: true }).waitFor(); + assert.equal((await send()).length, 0); + const view = await host.api('/projects/' + f.project.id + '/memories'); assert.equal(view.memories[0].experience.revisions.length, 4); + const sentAfter = await host.api('/artifacts/' + envelope.memory_artifact.id + '?session=' + consumer.id); + assert.deepEqual(sentAfter, sentBefore); save('sent-memory-after-withdrawal.json', sentAfter); + mark('three palettes retain readable experience content; 390px adoption and withdrawal fit and future HTTP omits revoked content'); + + await card().getByRole('button', { name: '记录反例', exact: true }).click(); + await card().getByLabel('新反例', { exact: true }).fill('同条件后来仍发生网络错误;旧原因尚未验证。'); + await card().getByRole('button', { name: '记录反例并停用', exact: true }).click(); await until(async () => (await card().textContent()).includes('已过期')); + assert.match(await card().innerText(), /工程验证未确认/); await shot('mobile-counterexample'); + await resize(1440, 1080); await modal.getByLabel('经验来源', { exact: true }).selectOption('delivery_report:' + secondReport.artifactId); + await modal.getByRole('button', { name: '生成经验草稿', exact: true }).click(); + const second = modal.locator('.memory-experience').filter({ hasText: '交付报告经验草稿' }).first(); + await second.getByRole('button', { name: '采用到本项目', exact: true }).click(); await second.getByRole('button', { name: '撤销采用', exact: true }).waitFor(); + fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nOwned source changed after adoption.\n'); + await modal.getByRole('button', { name: '重新核对', exact: true }).click(); await until(async () => (await second.textContent()).includes('工程源码指纹已变化')); + assert.equal((await send()).length, 0); await shot('source-expired'); + mark('a new counterexample and a real source edit invalidate adoption while retaining the original facts and revisions'); + + const editor = modal.locator('.memory-editor'); await editor.getByLabel('标题', { exact: true }).fill('手动项目约定'); + await editor.getByLabel('内容', { exact: true }).fill('手写记忆沿用原入口和来源语义。'); await editor.getByRole('button', { name: '保存记忆', exact: true }).click(); + await modal.locator('.memory-card').filter({ hasText: '手动项目约定' }).waitFor(); + await page.reload(); await page.locator('.connection.connected').waitFor(); modal = await openMemory(); + assert.equal((await host.api('/projects/' + f.project.id + '/memories')).summary.current, 1); + assert.equal((await host.api('/model-center/selection')).config.capacityMode, 'passthrough'); + assert.equal((await host.api('/model-center/selection')).config.approvalMode, 'full'); + assert.equal(model.requests.length, 4); assert.deepEqual(errors, []); + mark('manual memory remains compatible; refresh preserves drafts, withdrawal, expiry, full access and passthrough settings'); + await modal.getByRole('button', { name: '关闭窗口', exact: true }).click(); + await page.locator('.session-list button').filter({ hasText: consumer.title }).click(); modal = await openMemory(); + await modal.getByRole('button', { name: '前往来源会话管理', exact: true }).first().click(); + await modal.getByLabel('经验来源', { exact: true }).selectOption('delivery_report:' + firstReport.artifactId); + assert.equal((await host.api('/projects/' + f.project.id + '/memories')).summary.current, 1); + mark('shared project memory links back to its actual source session and cannot be edited from another session'); + const beforeRestart = await host.api('/projects/' + f.project.id + '/memories'); + if (application) { await application.close(); application = null; if (controller && await controller.health()) await controller.stop(); controller = null; } + else { await browser.close(); browser = null; await host.close(); } + const restarted = await launchWorkbench(t, f.data, {}, { appRoot }); + assert.deepEqual((await restarted.api('/projects/' + f.project.id + '/memories')).memories, beforeRestart.memories); + assert.equal((await restarted.api('/model-center/selection')).config.approvalMode, 'full'); await restarted.close(); + assert.equal(model.requests.length, 4); mark('an actual host restart preserves all memory texts, source identities, revision chains, expiry and chosen access mode'); + result = { success: true, appRoot, actualElectron: desktop, passed, screenshots, errors, contrast, realModelRequests: 0, + localFixtureRequests: model.requests.length, officialServiceTouched: false, + serverSha256: createHash('sha256').update(fs.readFileSync(path.join(appRoot, 'dist-server/server.mjs'))).digest('hex') }; +} catch (error) { + if (page) try { await shot('failure'); fs.writeFileSync(path.join(directory, 'failure-dom.txt'), await page.locator('body').innerText()); } catch {} + result = { success: false, appRoot, actualElectron: desktop, passed, screenshots, errors, contrast, error: error.stack, realModelRequests: 0, + localFixtureRequests: model.requests.length, officialServiceTouched: false }; +} finally { + save('local-requests.json', model.requests.map(({ url, input }) => ({ url, input }))); + 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(); save('result.json', result); +} +console.log(JSON.stringify({ directory, ...result }, null, 2)); if (!result.success) process.exitCode = 1; diff --git a/src/client/App.tsx b/src/client/App.tsx index 456f8f78..89eab0eb 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -674,7 +674,7 @@ export default function App() { {engineOpen && session && selectedProject && setEngineOpen(false)}> { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} />} {researchOpen && setResearchOpen(false)}>
{report && }
} {modelCenterOpen && setModelCenterOpen(false)}> { setConfig(value); if (selection) setModelSelection(selection); }} />} - {memoryOpen && selectedProject && setMemoryOpen(false)}>} + {memoryOpen && selectedProject && setMemoryOpen(false)}>} {skillsOpen && selectedProject && setSkillsOpen(false)}>} {mcpOpen && selectedProject && setMcpOpen(false)}>} {workersOpen && session && setWorkersOpen(false)}> { setWorkersOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setWorkersOpen(false); showInspector('changes'); }} />} diff --git a/src/client/ExperienceDraftControls.tsx b/src/client/ExperienceDraftControls.tsx new file mode 100644 index 00000000..34f8c259 --- /dev/null +++ b/src/client/ExperienceDraftControls.tsx @@ -0,0 +1,71 @@ +import { useRef, useEffect, useState } from 'react'; +import { Archive, Check, Download, FilePenLine, Undo2 } from 'lucide-react'; +import type { ExperienceSourceView, ProjectMemory, Session } from './types'; +import { api, downloadArtifact } from './api'; + +const stages: Record = { observed: '已观察', model_suggested: '模型建议', source_checked: '来源已核对', + engineering_verified: '原检查已核对', user_confirmed: '用户已采用', rejected: '已拒绝', expired: '已失效' }; +const actionLabel: Record = { created: '生成草稿', edit: '修订', adopt: '采用', withdraw: '撤销', + reject: '拒绝', counterexample: '记录反例', expired: '失效', archive: '归档' }; + +export function ExperienceDraftControls({ memory, session, sourceView, refresh, onSelectSession }: { + memory: ProjectMemory; session: Session | null; sourceView: ExperienceSourceView | null; refresh: () => Promise; + onSelectSession?: (id: string) => void; +}) { + const experience = memory.experience!; + const [editing, setEditing] = useState(false), [counterexample, setCounterexample] = useState(false); + const [form, setForm] = useState({ title: memory.title, content: memory.content, applicability: experience.applicability, invalidWhen: experience.invalidWhen }); + const [note, setNote] = useState(''), [busy, setBusy] = useState(false), [problem, setProblem] = useState(''); + const alive = useRef(true); + useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); + const owner = memory.sessionId === session?.id; + const usable = memory.status === 'current' && !experience.stages.includes('rejected') && !experience.unavailableReason; + const change = async (action: string, fields = {}) => { + if (!session || !sourceView || busy) return; + setBusy(true); setProblem(''); + try { + await api('/sessions/' + session.id + '/memories/experiences/' + memory.id + '/' + action, + { cursor: sourceView.cursor, revision: experience.revision, ...fields }); + if (alive.current) { setEditing(false); setCounterexample(false); setNote(''); await refresh(); } + } catch (cause) { if (alive.current) setProblem(cause instanceof Error ? cause.message : '经验操作未保存,请重新核对。'); } + finally { if (alive.current) setBusy(false); } + }; + const download = async (id: string) => { + setProblem(''); + try { await downloadArtifact(memory.sessionId, id, 'orven-experience-' + id); } + catch (cause) { if (alive.current) setProblem(cause instanceof Error ? cause.message : '来源原文读取失败。'); } + }; + return
+
{experience.stages.map((stage, index) => {stages[stage] || stage})}
+
适用范围
{experience.applicability}
失效条件
{experience.invalidWhen}
+

{experience.engineering.verified ? '所选原工程检查通过核对;经验结论仍未验证。' : '记录了原始事实;尚无工程验证证明这条经验结论。'}失败原因与复用收益尚未证明。

+
来源与修订({experience.revision}) +
任务 / 运行
{memory.taskId}
{memory.runId}
+
来源模型 / 协议
{experience.provenance.model.model || '未记录'} · {experience.provenance.model.protocol} · 配置修订 {experience.provenance.model.configRevision ?? '未记录'}
+
来源源码
{experience.provenance.sourceFingerprint || '原来源未记录;仅作历史草稿'}
+
所选原始事实
{JSON.stringify(experience.provenance.facts, null, 2)}
+
    {experience.provenance.refs.map(ref =>
  • {ref.kind} · {ref.sha256.slice(0, 16)}
  • )}
+
    {experience.revisions.map(ref =>
  1. 修订 {ref.revision} · {actionLabel[ref.action] || ref.action} · {ref.sha256.slice(0, 12)}
  2. )}
+
+ {experience.counterexamples.length > 0 &&
反例记录{experience.counterexamples.map((row, index) =>

{row.note}用户记录 · 工程验证未确认

)}
} + {problem &&

{problem}

} + {memory.status !== 'archived' &&
+ {!owner ? : <> + {experience.adoption === 'active' ? + : usable && } + {usable && } + + {!experience.stages.includes('rejected') && } + + } +
} + {editing &&
{ event.preventDefault(); void change('edit', form); }}> + +