feat: expose reversible experience adoption with isolated optional failures
This commit is contained in:
@@ -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不暗中接管其记忆或权限。
|
||||
|
||||
@@ -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持续保留。
|
||||
|
||||
@@ -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;
|
||||
+1
-1
@@ -674,7 +674,7 @@ export default function App() {
|
||||
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、受控工程运行与原记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onNavigate={async (projectId, sessionId) => { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} /></Modal>}
|
||||
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
|
||||
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} runModel={session?.execution?.run?.model} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} /></Modal>}
|
||||
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与决策绑定源码指纹,变化后自动要求重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} /></Modal>}
|
||||
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与经验保留来源,采用可撤销;源码变化后重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} onSelectSession={selectSession} /></Modal>}
|
||||
{skillsOpen && selectedProject && <Modal title="项目技能" description="管理当前项目的技能来源、版本与启用状态。" wide onClose={() => setSkillsOpen(false)}><SkillCenter key={selectedProject.id} projectId={selectedProject.id} busy={isRunning} /></Modal>}
|
||||
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
|
||||
{workersOpen && session && <Modal title="隔离协作" description="固定父子目标、独立工作区、预算与原成果审查。" wide onClose={() => setWorkersOpen(false)}><WorkerPanel key={session.id} session={session} config={config} busy={isRunning} onSession={acceptSession} onNavigate={async (projectId, sessionId, view) => { setWorkersOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setWorkersOpen(false); showInspector('changes'); }} /></Modal>}
|
||||
|
||||
@@ -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<string, string> = { observed: '已观察', model_suggested: '模型建议', source_checked: '来源已核对',
|
||||
engineering_verified: '原检查已核对', user_confirmed: '用户已采用', rejected: '已拒绝', expired: '已失效' };
|
||||
const actionLabel: Record<string, string> = { 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<void>;
|
||||
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 <div className="experience-detail">
|
||||
<div className="experience-stages">{experience.stages.map((stage, index) => <span key={stage + index}>{stages[stage] || stage}</span>)}</div>
|
||||
<dl className="experience-scope"><div><dt>适用范围</dt><dd>{experience.applicability}</dd></div><div><dt>失效条件</dt><dd>{experience.invalidWhen}</dd></div></dl>
|
||||
<p className="experience-boundary">{experience.engineering.verified ? '所选原工程检查通过核对;经验结论仍未验证。' : '记录了原始事实;尚无工程验证证明这条经验结论。'}失败原因与复用收益尚未证明。</p>
|
||||
<details className="experience-provenance"><summary>来源与修订({experience.revision})</summary>
|
||||
<dl><div><dt>任务 / 运行</dt><dd><code>{memory.taskId}<br />{memory.runId}</code></dd></div>
|
||||
<div><dt>来源模型 / 协议</dt><dd>{experience.provenance.model.model || '未记录'} · {experience.provenance.model.protocol} · 配置修订 {experience.provenance.model.configRevision ?? '未记录'}</dd></div>
|
||||
<div><dt>来源源码</dt><dd><code>{experience.provenance.sourceFingerprint || '原来源未记录;仅作历史草稿'}</code></dd></div></dl>
|
||||
<details><summary>所选原始事实</summary><pre>{JSON.stringify(experience.provenance.facts, null, 2)}</pre></details>
|
||||
<ul>{experience.provenance.refs.map(ref => <li key={ref.id}><span>{ref.kind} · <code>{ref.sha256.slice(0, 16)}</code></span><button type="button" className="text-button" onClick={() => void download(ref.id)}><Download size={13} />来源原文</button></li>)}</ul>
|
||||
<ol>{experience.revisions.map(ref => <li key={ref.artifactId}><span>修订 {ref.revision} · {actionLabel[ref.action] || ref.action} · <code>{ref.sha256.slice(0, 12)}</code></span><button type="button" className="text-button" onClick={() => void download(ref.artifactId)}>查看原修订</button></li>)}</ol>
|
||||
</details>
|
||||
{experience.counterexamples.length > 0 && <div className="experience-counterexamples"><strong>反例记录</strong>{experience.counterexamples.map((row, index) => <p key={index}>{row.note}<small>用户记录 · 工程验证未确认</small></p>)}</div>}
|
||||
{problem && <p className="memory-error" role="alert">{problem}</p>}
|
||||
{memory.status !== 'archived' && <div className="experience-actions">
|
||||
{!owner ? <button type="button" className="text-button" onClick={() => onSelectSession?.(memory.sessionId)} disabled={!onSelectSession}>前往来源会话管理</button> : <>
|
||||
{experience.adoption === 'active' ? <button type="button" className="button secondary" disabled={busy || !sourceView} onClick={() => void change('withdraw')}><Undo2 size={14} />撤销采用</button>
|
||||
: usable && <button type="button" className="button secondary" disabled={busy || !sourceView} onClick={() => void change('adopt')}><Check size={14} />采用到本项目</button>}
|
||||
{usable && <button type="button" className="text-button" disabled={busy || !sourceView} onClick={() => { setForm({ title: memory.title, content: memory.content, applicability: experience.applicability, invalidWhen: experience.invalidWhen }); setEditing(!editing); }}><FilePenLine size={14} />修订草稿</button>}
|
||||
<button type="button" className="text-button" disabled={busy || !sourceView} onClick={() => setCounterexample(!counterexample)}>记录反例</button>
|
||||
{!experience.stages.includes('rejected') && <button type="button" className="text-button" disabled={busy || !sourceView} onClick={() => void change('reject')}>拒绝这条经验</button>}
|
||||
<button type="button" className="text-button" disabled={busy || !sourceView} onClick={() => void change('archive')}><Archive size={13} />归档</button>
|
||||
</>}
|
||||
</div>}
|
||||
{editing && <form className="experience-edit memory-form-grid" onSubmit={event => { event.preventDefault(); void change('edit', form); }}>
|
||||
<label className="memory-full">经验标题<input aria-label="经验标题" required value={form.title} onChange={event => setForm({ ...form, title: event.target.value })} /></label>
|
||||
<label className="memory-full">经验内容<textarea aria-label="经验内容" required rows={5} value={form.content} onChange={event => setForm({ ...form, content: event.target.value })} /></label>
|
||||
<label>适用范围<textarea aria-label="适用范围" required rows={3} value={form.applicability} onChange={event => setForm({ ...form, applicability: event.target.value })} /></label>
|
||||
<label>失效条件<textarea aria-label="失效条件" required rows={3} value={form.invalidWhen} onChange={event => setForm({ ...form, invalidWhen: event.target.value })} /></label>
|
||||
<div className="memory-full experience-actions"><button type="submit" className="button secondary" disabled={busy}>保存草稿修订</button><button type="button" className="text-button" onClick={() => setEditing(false)}>取消修订</button><span>修订后停止采用,旧文本与失败证据保留。</span></div>
|
||||
</form>}
|
||||
{counterexample && <form className="experience-edit" onSubmit={event => { event.preventDefault(); void change('counterexample', { note }); }}><label>新反例<textarea aria-label="新反例" required rows={3} value={note} onChange={event => setNote(event.target.value)} placeholder="记录出现的反例和依据;不会把文字当作已通过的工程检查。" /></label><div className="experience-actions"><button type="submit" className="button secondary" disabled={busy || !note.trim()}>记录反例并停用</button><button type="button" className="text-button" onClick={() => setCounterexample(false)}>取消</button></div></form>}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,33 @@
|
||||
.project-memory{display:flex;flex-direction:column;min-height:0;background:#f8fafc;color:#15283f;padding:24px 28px;overflow:auto}.memory-overview{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;padding-bottom:18px;border-bottom:1px solid #cbd5df}.memory-eyebrow{display:flex;align-items:center;gap:7px;color:#2560a3;letter-spacing:.13em;font-size:10px;font-weight:700}.memory-overview h3{font-size:22px;margin:8px 0 5px}.memory-overview p{color:#5b6d83;font-size:12px;line-height:1.8}.memory-summary{display:flex;gap:16px;flex-wrap:wrap;padding:13px 0;color:#5d7088;font-size:12px}.memory-summary strong{color:#15283f;font-size:16px;margin-right:4px}.memory-summary code{color:#33577f}.memory-list{display:grid;gap:11px}.memory-card{padding:17px 18px;background:#fff;border:1px solid #cbd6e2;border-left:3px solid #2f806e;border-radius:6px}.memory-card.memory-expired{border-left-color:#b4772b;background:#fffaf0}.memory-card.memory-archived{border-left-color:#8b9aaa;background:#f4f7fa;opacity:.82}.memory-card-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.memory-card-heading h4{font-size:14px;flex:1;min-width:130px}.memory-card-heading time{font-size:11px;color:#74859a}.memory-state{padding:3px 7px;border:1px solid #b9d9cb;border-radius:4px;color:#216d5f;background:#e6f3ee;font-size:10px;font-weight:650}.memory-expired .memory-state{color:#8b5c12;background:#fff4d9;border-color:#e6d09d}.memory-archived .memory-state{color:#67788d;background:#e9eef3;border-color:#d1dbe4}.memory-content{font-size:13px;line-height:1.8;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:11px;color:#233b55}.memory-meta{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:12px;color:#6a7d92;font-size:11px}.memory-meta code{font-size:10px;color:#7b8ca1}.memory-tag{padding:3px 6px;background:#edf3f8;color:#4e6884;border-radius:3px}.memory-warning{display:flex;align-items:flex-start;gap:6px;color:#8b5c12;font-size:11px;line-height:1.7;margin-top:11px}.memory-card>.text-button{padding:8px 0;margin-top:8px}.memory-notice,.memory-error{display:flex;gap:7px;align-items:flex-start;padding:11px 13px;margin:15px 0 0;border-radius:5px;font-size:12px;line-height:1.7}.memory-notice{color:#216d5f;background:#e6f3ee;border:1px solid #b9d9cb}.memory-error{color:#a7353e;background:#fff0f0;border:1px solid #e8bac0}.memory-empty{display:grid;place-items:center;padding:38px 20px;margin:7px 0 17px;background:#fff;border:1px dashed #b5c6d7;border-radius:7px;color:#61738a;text-align:center}.memory-empty svg{color:#6c87a5;margin-bottom:10px}.memory-empty strong{color:#314b68;font-size:14px}.memory-empty p{font-size:12px;line-height:1.8;margin-top:7px;max-width:480px}.memory-editor{padding:19px 20px;margin-top:18px;border:1px solid #b2c6da;border-top:3px solid #2560a3;border-radius:7px;background:#fff}.memory-editor-heading{display:flex;align-items:flex-start;justify-content:space-between;color:#2560a3}.memory-editor-heading h4{font-size:15px;color:#15283f}.memory-editor-heading p{font-size:11px;color:#687a90;margin-top:5px;line-height:1.7}.memory-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:16px}.memory-form-grid label{display:flex;flex-direction:column;gap:7px;color:#4e637d;font-size:11px}.memory-form-grid input,.memory-form-grid textarea{border:1px solid #b9c8d6;border-radius:5px;padding:9px 10px;min-height:38px;font:inherit;color:#15283f;resize:vertical}.memory-form-grid input:focus,.memory-form-grid textarea:focus{outline:2px solid #2560a333;border-color:#2560a3}.memory-full{grid-column:1/-1}.memory-editor-footer{display:flex;align-items:center;justify-content:space-between;gap:15px;flex-wrap:wrap;margin-top:14px}.memory-editor-footer>span{display:flex;align-items:center;gap:6px;color:#67798e;font-size:11px}.memory-editor-footer svg{color:#2f806e}.project-memory button{min-height:36px}
|
||||
@media(max-width:620px){.project-memory{padding:18px 15px}.memory-overview{flex-direction:column}.memory-form-grid{grid-template-columns:1fr}.memory-full{grid-column:auto}.memory-editor{padding:17px 14px}.memory-card{padding:15px 13px}.memory-card-heading time{width:100%}}
|
||||
.memory-unverified .memory-state{color:#8a5b16;background:#fff7df;border-color:#ead39a}.memory-scope-warning{margin:14px 0;padding:12px 14px;line-height:1.7}
|
||||
.experience-source{padding:18px 0 22px;margin-bottom:18px;border-bottom:1px solid var(--orven-border,#cbd6e2)}
|
||||
.experience-source h4{font-size:14px;font-weight:600;color:var(--orven-ink,#15283f)}
|
||||
.experience-source p,.experience-boundary{font-size:12px;line-height:1.8;color:var(--orven-text,#4e637d)}
|
||||
.experience-source-picker{display:flex;align-items:flex-end;gap:12px;margin-top:12px}
|
||||
.experience-source-picker label{flex:1;min-width:0;display:grid;gap:7px;font-size:12px}
|
||||
.experience-source-picker select{width:100%;min-width:0;min-height:40px;padding:8px;border:1px solid var(--orven-border-strong,#b9c8d6);background:#fff;font:inherit}
|
||||
.experience-hint{margin-top:9px;overflow-wrap:anywhere}
|
||||
.memory-experience{border-left-color:var(--accent,#456652)}
|
||||
.experience-stages{display:flex;flex-wrap:wrap;gap:6px;margin-top:14px}
|
||||
.experience-stages span{font-size:11px;padding:3px 7px;background:var(--orven-surface-faint,#edf3f8);color:var(--orven-text,#4e637d);border-radius:4px}
|
||||
.experience-scope,.experience-provenance dl{display:grid;gap:9px;margin:14px 0;font-size:12px;line-height:1.7}
|
||||
.experience-scope>div,.experience-provenance dl>div{display:grid;grid-template-columns:78px minmax(0,1fr);gap:10px}
|
||||
.experience-detail dt{color:var(--orven-muted,#5b6d83)}
|
||||
.experience-detail dd{margin:0;min-width:0;overflow-wrap:anywhere;color:var(--orven-text,#233b55)}
|
||||
.experience-boundary{padding:10px 0;border-top:1px solid var(--orven-border-soft,#d1dbe4)}
|
||||
.experience-provenance,.experience-content{font-size:12px;line-height:1.8;margin-top:10px;color:var(--orven-text,#233b55)}
|
||||
.experience-detail summary,.experience-content summary{cursor:pointer;min-height:36px;padding:7px 0;font-weight:500}
|
||||
.experience-detail pre{max-height:350px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:var(--orven-canvas,#f4f7fa);font-size:11px}
|
||||
.experience-provenance ul,.experience-provenance ol{list-style:none;padding:0;margin:8px 0}
|
||||
.experience-provenance li{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:5px 0;border-bottom:1px solid var(--orven-border-soft,#d1dbe4)}
|
||||
.experience-provenance li>span{min-width:0;overflow-wrap:anywhere}
|
||||
.experience-provenance .text-button{flex-shrink:0}
|
||||
.experience-actions{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:12px}
|
||||
.experience-actions>span{font-size:11px;color:var(--orven-muted,#5b6d83)}
|
||||
.experience-edit{padding-top:12px;border-top:1px solid var(--orven-border-soft,#d1dbe4);margin-top:14px}
|
||||
.experience-edit label{display:grid;gap:7px;color:var(--orven-text,#233b55);font-size:12px}
|
||||
.experience-edit input,.experience-edit textarea{width:100%;padding:9px 10px;border:1px solid var(--orven-border-strong,#b9c8d6);font:inherit;resize:vertical;background:#fff;color:var(--orven-text,#233b55)}
|
||||
.experience-counterexamples{border-left:2px solid var(--orven-border-strong,#b9c8d6);padding-left:12px;font-size:12px;line-height:1.8;margin-top:14px}
|
||||
.experience-counterexamples small{display:block;color:var(--orven-muted,#5b6d83)}
|
||||
@media(max-width:620px){.experience-source-picker{align-items:stretch;flex-direction:column}.experience-source-picker .button{justify-content:center}.experience-provenance li{align-items:flex-start;flex-wrap:wrap}.experience-scope>div,.experience-provenance dl>div{grid-template-columns:1fr;gap:2px}.experience-actions{gap:10px}.experience-actions .button,.experience-actions .text-button{min-height:40px}}
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Archive, Brain, CircleHelp, LoaderCircle, Plus, RefreshCw, ShieldCheck } from 'lucide-react';
|
||||
import type { Project, ProjectMemory, ProjectMemoryView, Session } from './types';
|
||||
import type { ExperienceSourceView, Project, ProjectMemory, ProjectMemoryView, Session } from './types';
|
||||
import { api } from './api';
|
||||
import { ExperienceDraftControls } from './ExperienceDraftControls';
|
||||
import './ProjectMemory.css';
|
||||
|
||||
const statusLabel: Record<string, string> = { current: '当前', unverified: '扫描不完整', expired: '已过期', archived: '已归档' };
|
||||
|
||||
export function ProjectMemoryPanel({ project, session }: { project: Project; session: Session | null }) {
|
||||
export function ProjectMemoryPanel({ project, session, onSelectSession }: { project: Project; session: Session | null; onSelectSession?: (id: string) => void }) {
|
||||
const [view, setView] = useState<ProjectMemoryView | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [working, setWorking] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [sources, setSources] = useState<ExperienceSourceView | null>(null), [sourceId, setSourceId] = useState(''), [sourceError, setSourceError] = useState('');
|
||||
const [draft, setDraft] = useState({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' });
|
||||
const alive = useRef(true);
|
||||
const generation = useRef(0);
|
||||
const load = async () => {
|
||||
const request = ++generation.current;
|
||||
setLoading(true); setError('');
|
||||
try { const result = await api<ProjectMemoryView>('/projects/' + project.id + '/memories'); if (alive.current) setView(result); }
|
||||
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆读取失败。'); }
|
||||
finally { if (alive.current) setLoading(false); }
|
||||
const results = await Promise.allSettled([api<ProjectMemoryView>('/projects/' + project.id + '/memories'),
|
||||
session ? api<ExperienceSourceView>('/sessions/' + session.id + '/memories/experiences') : Promise.resolve(null)]);
|
||||
if (!alive.current || request !== generation.current) return;
|
||||
const [memories, evidence] = results;
|
||||
if (memories.status === 'fulfilled') setView(memories.value);
|
||||
else setError(memories.reason instanceof Error ? memories.reason.message : '项目记忆读取失败。');
|
||||
if (evidence.status === 'fulfilled') { setSources(evidence.value); setSourceError(''); }
|
||||
else { setSources(null); setSourceError(evidence.reason instanceof Error ? evidence.reason.message : '经验来源读取失败,可重新核对。'); }
|
||||
setLoading(false);
|
||||
};
|
||||
useEffect(() => { alive.current = true; void load(); return () => { alive.current = false; }; }, [project.id]);
|
||||
const create = async (event: FormEvent) => {
|
||||
@@ -38,15 +48,39 @@ export function ProjectMemoryPanel({ project, session }: { project: Project; ses
|
||||
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆归档失败。'); }
|
||||
finally { if (alive.current) setWorking(false); }
|
||||
};
|
||||
const createExperience = async () => {
|
||||
const source = sources?.sources.find(value => value.kind + ':' + value.id === sourceId);
|
||||
if (!session || !sources || !source) return;
|
||||
setWorking(true); setSourceError(''); setNotice('');
|
||||
try {
|
||||
const result = await api<{ memory: ProjectMemory; duplicate: boolean }>('/sessions/' + session.id + '/memories/experiences', { cursor: sources.cursor, source });
|
||||
if (alive.current) { setNotice(result.duplicate ? '该来源已有草稿,原修订与采用状态保持。' : '经验草稿已保存。尚未采用,不会进入模型请求。'); await load(); }
|
||||
} catch (cause) { if (alive.current) setSourceError(cause instanceof Error ? cause.message : '草稿生成失败,请重新核对来源。'); }
|
||||
finally { if (alive.current) setWorking(false); }
|
||||
};
|
||||
const memories = view?.memories ?? [];
|
||||
return <section className="project-memory" aria-label="项目记忆">
|
||||
<header className="memory-overview"><div><span className="memory-eyebrow"><Brain size={14} />PROJECT MEMORY</span><h3>项目记忆</h3><p>当前记忆按预算提供给本项目后续任务;来源匹配后仍需结合实际代码核对内容。</p></div><button type="button" className="button secondary" onClick={() => void load()} disabled={loading || working}><RefreshCw size={14} className={loading ? 'spin' : ''} />重新核对</button></header>
|
||||
<header className="memory-overview"><div><span className="memory-eyebrow"><Brain size={14} />PROJECT MEMORY</span><h3>项目记忆</h3><p>已采用的经验与手动记忆可用于本项目后续任务。经验草稿默认不使用,来源匹配仍需核对结论。</p></div><button type="button" className="button secondary" onClick={() => void load()} disabled={loading || working}><RefreshCw size={14} className={loading ? 'spin' : ''} />重新核对</button></header>
|
||||
{notice && <p className="memory-notice" role="status"><ShieldCheck size={14} />{notice}</p>}
|
||||
{error && <p className="memory-error" role="alert">{error}</p>}
|
||||
{view && <div className="memory-summary"><span><strong>{view.summary.current}</strong> 条当前记忆</span>{(view.summary.unverified ?? 0) > 0 && <span><strong>{view.summary.unverified}</strong> 条未能验证</span>}<span><strong>{view.summary.expired}</strong> 条需重新核对</span><span>源码 <code>{view.sourceFingerprint.slice(0, 12)}</code></span></div>}
|
||||
{view && <div className="memory-summary"><span><strong>{view.summary.current}</strong> 条当前可用</span><span><strong>{view.summary.drafts ?? 0}</strong> 条经验草稿</span>{(view.summary.unverified ?? 0) > 0 && <span><strong>{view.summary.unverified}</strong> 条未能验证</span>}<span><strong>{view.summary.expired}</strong> 条需重新核对</span><span>源码 <code>{view.sourceFingerprint.slice(0, 12)}</code></span></div>}
|
||||
<section className="experience-source" aria-label="从工程证据生成草稿"><div><h4>从工程证据生成草稿</h4><p>选择当前会话已有的交付报告、检查或工具结果。保留原失败和未知结果,不调用模型。</p></div>
|
||||
{sourceError && <p className="memory-error" role="alert">{sourceError}</p>}
|
||||
<div className="experience-source-picker"><label>经验来源<select aria-label="经验来源" value={sourceId} onChange={event => setSourceId(event.target.value)} disabled={loading || working || !sources}><option value="">选择已有来源…</option>{sources?.sources.map(source => <option key={source.kind + ':' + source.id} value={source.kind + ':' + source.id}>{source.label} · {source.id.slice(0, 8)}</option>)}</select></label><button type="button" className="button secondary" disabled={working || loading || !sourceId || !sources} onClick={() => void createExperience()}><Plus size={14} />生成经验草稿</button></div>
|
||||
{sources && !sources.sources.length && <p className="experience-hint">当前会话还没有可选择的工程证据。完成一次任务后,可回到这里选择原记录。</p>}
|
||||
{sources?.sources.filter(source => source.kind + ':' + source.id === sourceId).map(source => <p className="experience-hint" key={source.id}>原结果 {source.status} · Task {source.taskId.slice(0, 8)} · Run {source.runId.slice(0, 8)} · SHA <code>{source.sha256.slice(0, 16)}</code></p>)}
|
||||
</section>
|
||||
{view && !view.scope.complete && <p className="memory-warning memory-scope-warning" role="status"><CircleHelp size={14} />本次源码扫描未覆盖完整工程(已扫描 {view.scope.scannedFiles} 个文件,{view.scope.bytes.toLocaleString()} 字节);现有记忆暂标为“扫描不完整”,不会作为当前事实。请缩小项目范围或排除超预算文件后重新核对。</p>}
|
||||
{!memories.length && !loading && <div className="memory-empty"><Brain size={25} /><strong>这个项目还没有记忆</strong><p>保存架构决策、约束和经过核对的工程事实,后续任务可以直接查看来源。</p></div>}
|
||||
<div className="memory-list">{memories.map(memory => <article key={memory.id} className={'memory-card memory-' + memory.status}><div className="memory-card-heading"><span className="memory-state">{statusLabel[memory.status] || memory.status}</span><h4>{memory.title}</h4><time>{new Date(memory.updatedAt).toLocaleString('zh-CN')}</time></div><p className="memory-content">{memory.content}</p><div className="memory-meta"><span>来源:{memory.source.kind === 'file' ? memory.source.path : memory.source.label || memory.source.kind}</span>{memory.source.sha256 && <code>来源 SHA {memory.source.sha256.slice(0, 12)}</code>}<code>工程 {memory.sourceFingerprint.slice(0, 12)}</code>{memory.tags.map(tag => <span className="memory-tag" key={tag}>{tag}</span>)}</div>{memory.expiredReason && <p className="memory-warning"><CircleHelp size={14} />{memory.expiredReason}</p>}{memory.status !== 'archived' && <button type="button" className="text-button" disabled={working || memory.sessionId !== session?.id} onClick={() => void archive(memory)}><Archive size={13} />归档</button>}</article>)}</div>
|
||||
<div className="memory-list">{memories.map(memory => <article key={memory.id} className={'memory-card memory-' + memory.status + (memory.experience ? ' memory-experience' : '')}>
|
||||
<div className="memory-card-heading"><span className="memory-state">{memory.status !== 'current' ? statusLabel[memory.status] : memory.experience ? { draft: '草稿 · 未采用', active: '已采用', withdrawn: '已撤销' }[memory.experience.adoption] : '当前'}</span><h4>{memory.title}</h4><time>{new Date(memory.updatedAt).toLocaleString('zh-CN')}</time></div>
|
||||
{memory.experience && memory.content.length > 500 ? <details className="experience-content"><summary>查看草稿内容</summary><p className="memory-content">{memory.content}</p></details> : <p className="memory-content">{memory.content}</p>}
|
||||
<div className="memory-meta"><span>来源:{memory.source.kind === 'file' ? memory.source.path : memory.source.label || memory.source.kind}</span>{memory.source.sha256 && <code>来源 SHA {memory.source.sha256.slice(0, 12)}</code>}<code>工程 {memory.sourceFingerprint.slice(0, 12)}</code>{memory.tags.map(tag => <span className="memory-tag" key={tag}>{tag}</span>)}</div>
|
||||
{memory.expiredReason && <p className="memory-warning"><CircleHelp size={14} />{memory.expiredReason}</p>}
|
||||
{memory.experienceError && <p className="memory-warning"><CircleHelp size={14} />{memory.experienceError}</p>}
|
||||
{memory.experience ? <ExperienceDraftControls memory={memory} session={session} sourceView={sources} refresh={load} onSelectSession={onSelectSession} />
|
||||
: memory.origin !== 'experience' && memory.status !== 'archived' && <button type="button" className="text-button" disabled={working || memory.sessionId !== session?.id} onClick={() => void archive(memory)}><Archive size={13} />归档</button>}
|
||||
</article>)}</div>
|
||||
<form className="memory-editor" onSubmit={create}><div className="memory-editor-heading"><div><h4>保存一条项目记忆</h4><p>来源默认绑定当前会话;填写文件路径后会额外保存文件 SHA256。</p></div><Plus size={18} /></div><div className="memory-form-grid"><label>标题<input value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} maxLength={240} placeholder="例如:接口层必须保持本地鉴权" /></label><label>来源文件(可选)<input value={draft.sourcePath} onChange={event => setDraft({ ...draft, sourcePath: event.target.value })} placeholder="src/server/app.mjs" /></label><label>标签(逗号分隔)<input value={draft.tags} onChange={event => setDraft({ ...draft, tags: event.target.value })} placeholder="架构,约束" /></label><label>到期时间(可选)<input type="datetime-local" value={draft.expiresAt} onChange={event => setDraft({ ...draft, expiresAt: event.target.value })} /></label><label className="memory-full">内容<textarea required value={draft.content} onChange={event => setDraft({ ...draft, content: event.target.value })} maxLength={16000} rows={4} placeholder="记录可验证的事实、决策或限制……" /></label></div><div className="memory-editor-footer"><span><ShieldCheck size={14} />不会调用模型,也不会执行项目命令。</span><button type="submit" className="button primary" disabled={!session || working || !draft.content.trim() || Boolean(view && !view.scope.complete)}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}保存记忆</button></div></form>
|
||||
</section>;
|
||||
}
|
||||
|
||||
+13
-2
@@ -220,8 +220,19 @@ export interface ExecutionSnapshot { fileResults?: Omit<FileResultView, 'verific
|
||||
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 }
|
||||
export interface ProjectMemory { schemaVersion: number; id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; title: string; content: string; tags: string[]; source: ProjectMemorySource; sourceFingerprint: string; status: 'current' | 'unverified' | 'expired' | 'archived'; createdAt: string; updatedAt: string; expiresAt: string | null; expiredAt?: string | null; expiredReason?: string | null; archivedAt?: string; origin: string }
|
||||
export interface ProjectMemoryView { projectId: string; sourceFingerprint: string; inspectedAt: string; scope: { complete: boolean; scannedFiles: number; bytes: number; excludedFiles: number; maximumFiles: number; maximumBytes: number; note: string }; memories: ProjectMemory[]; summary: { current: number; unverified: number; expired: number; archived: number; total: number; invalidated: number }; rule: string }
|
||||
export interface ExperienceSource { kind: 'delivery_report' | 'check_job' | 'tool'; id: string; artifactId?: string; sha256: string; taskId: string; runId: string; label: string; status: string }
|
||||
export interface ExperienceSourceView { projectId: string; sessionId: string; cursor: { taskId: string | null; runId: string | null }; sources: ExperienceSource[] }
|
||||
export interface ExperienceDraft { protocol: string; revision: number; artifactId: string; sha256: string; adoption: 'draft' | 'active' | 'withdrawn'; stages: string[];
|
||||
applicability: string; invalidWhen: string; causalStatus: string; unavailableReason?: string;
|
||||
engineering: { verified: boolean; scope: string; conclusionVerified: boolean };
|
||||
provenance: { sourceKey: string; sourceFingerprint: string | null; selection: { kind: string; id: string; sha256: string };
|
||||
scope: { projectId: string; sessionId: string; taskId: string; runId: string };
|
||||
model: { model: string | null; protocol: string; configRevision: number | null };
|
||||
refs: { id: string; sha256: string; kind: string; bytes: number }[]; facts: Record<string, unknown> };
|
||||
counterexamples: { note: string; origin: string; recordedAt: string; engineeringVerified: boolean }[];
|
||||
revisions: { revision: number; artifactId: string; sha256: string; action: string; at: string }[] }
|
||||
export interface ProjectMemory { schemaVersion: number; id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; title: string; content: string; tags: string[]; source: ProjectMemorySource; sourceFingerprint: string; status: 'current' | 'unverified' | 'expired' | 'archived'; createdAt: string; updatedAt: string; expiresAt: string | null; expiredAt?: string | null; expiredReason?: string | null; archivedAt?: string; origin: string; experience?: ExperienceDraft | null; experienceError?: string }
|
||||
export interface ProjectMemoryView { projectId: string; sourceFingerprint: string; inspectedAt: string; scope: { complete: boolean; scannedFiles: number; bytes: number; excludedFiles: number; maximumFiles: number; maximumBytes: number; note: string }; memories: ProjectMemory[]; summary: { current: number; unverified: number; expired: number; archived: number; total: number; invalidated: number; drafts?: number; adopted?: number }; rule: string }
|
||||
export interface PythonRuntimeIdentity { status: string; logicalExecutable?: string | null; executable: string | null; version: string | null; sha256?: string; baseExecutable?: string; baseSha256?: string; message?: string; probe?: string }
|
||||
export interface CheckResult { id: string; name: string; kind: string; command: string; status: string; exitCode: number | null; durationMs: number; tests: { total: number; passed: number; failed: number; skipped: number; cancelled: number } | null; logArtifactId?: string; reason?: string;
|
||||
engine?: string; python?: { mode: string; runtime: PythonRuntimeIdentity; invocationId: string; inputSha256: string; runner: { path: string; sha256: string } };
|
||||
|
||||
@@ -369,7 +369,7 @@ export class RequestPlanner {
|
||||
}
|
||||
}
|
||||
// Optional catalogs and memory use only space left after goals, paired history and current code evidence.
|
||||
let memoryReference = null, memoryDocument = null;
|
||||
let memoryReference = null, memoryDocument = null, memoryIssue = null;
|
||||
if (projectMemory?.projectId === session.projectId && projectMemory.entries?.length) {
|
||||
memoryDocument = { ...projectMemory, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
|
||||
const memoryBudget = Math.min(inputBudget, targetInputTokens);
|
||||
@@ -381,8 +381,21 @@ export class RequestPlanner {
|
||||
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > memoryBudget) memoryDocument.entries.pop();
|
||||
}
|
||||
if (memoryDocument.entries.length) {
|
||||
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
|
||||
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
|
||||
try {
|
||||
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
|
||||
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
|
||||
} catch (error) {
|
||||
// A failed optional experience snapshot cannot block the user's
|
||||
// original task. Ordinary request/evidence persistence still applies.
|
||||
const manual = memoryDocument.entries.filter(entry => entry.experience?.protocol !== 'workbench.experience.v1');
|
||||
if (manual.length === memoryDocument.entries.length) throw error;
|
||||
memoryIssue = { kind: 'optional_experience_unavailable', stage: 'snapshot' };
|
||||
memoryDocument.entries = manual;
|
||||
if (manual.length) {
|
||||
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
|
||||
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
|
||||
} else { memoryReference = null; memoryDocument = null; }
|
||||
}
|
||||
}
|
||||
}
|
||||
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
|
||||
@@ -434,6 +447,7 @@ export class RequestPlanner {
|
||||
latestToolsArtifactId: latestReference?.id ?? null, latestToolsSha256: latestReference?.sha256 ?? null, latestToolsEntries: latestReference ? latestDocument.entries.length : 0,
|
||||
projectMemoryArtifactId: memoryReference?.id ?? null, projectMemorySha256: memoryReference?.sha256 ?? null,
|
||||
projectMemoryEntries: memoryReference ? memoryDocument.entries.length : 0,
|
||||
...(memoryIssue ? { projectMemoryIssue: memoryIssue } : {}),
|
||||
skillCatalogArtifactId: skillReference?.id ?? null, skillCatalogSha256: skillReference?.sha256 ?? null,
|
||||
skillCatalogEntries: skillReference ? skillDocument.entries.length : 0,
|
||||
mcpCatalogArtifactId: mcpReference?.id ?? null, mcpCatalogSha256: mcpReference?.sha256 ?? null,
|
||||
|
||||
@@ -21,8 +21,18 @@ const checkFact = row => ({ id: row.id, projectId: row.projectId, sessionId: row
|
||||
finishedAt: row.finishedAt ?? null, results: (row.results ?? []).map(resultFact) });
|
||||
|
||||
export const isExperience = memory => memory.origin === 'experience';
|
||||
export const experienceEligible = memory => !isExperience(memory) || memory.experience?.adoption === 'active'
|
||||
&& !memory.experience?.stages?.some(stage => ['expired', 'rejected'].includes(stage));
|
||||
export function experienceStructure(memory) {
|
||||
const value = memory.experience;
|
||||
return !!value && value.protocol === EXPERIENCE_PROTOCOL && Number.isSafeInteger(value.revision) && value.revision > 0
|
||||
&& ['draft', 'active', 'withdrawn'].includes(value.adoption) && Array.isArray(value.stages) && value.stages.every(stage => typeof stage === 'string')
|
||||
&& Array.isArray(value.revisions) && value.revisions.every(ref => ref && isId(ref.artifactId) && typeof ref.sha256 === 'string')
|
||||
&& Array.isArray(value.counterexamples) && value.counterexamples.every(row => row && typeof row.note === 'string')
|
||||
&& typeof value.applicability === 'string' && typeof value.invalidWhen === 'string' && !!value.engineering
|
||||
&& !!value.provenance?.model && !!value.provenance?.selection && !!value.provenance?.scope
|
||||
&& Array.isArray(value.provenance?.refs) && value.provenance.refs.every(ref => ref && isId(ref.id) && typeof ref.sha256 === 'string');
|
||||
}
|
||||
export const experienceEligible = memory => !isExperience(memory) || experienceStructure(memory) && memory.experience.adoption === 'active'
|
||||
&& !memory.experience.stages.some(stage => ['expired', 'rejected'].includes(stage));
|
||||
|
||||
// Only outward engineering facts are projected. Logs, model reasoning and
|
||||
// arbitrary report text are never mined for causal conclusions or instructions.
|
||||
@@ -54,7 +64,8 @@ export class ExperienceDrafts {
|
||||
const artifact = this.store.core.artifact.get(id);
|
||||
if (!owned(artifact, scope) || kind && artifact.kind !== kind) throw error('经验来源工件缺失或不属于所选项目、会话、任务和运行。');
|
||||
const bytes = this.store.artifactStore.readBytes(artifact);
|
||||
refs.push({ id: artifact.id, sha256: artifact.sha256, kind: artifact.kind, bytes: artifact.bytes });
|
||||
refs.push({ id: artifact.id, sha256: artifact.sha256, kind: artifact.kind, bytes: artifact.bytes,
|
||||
scope: { projectId: artifact.projectId, sessionId: artifact.sessionId, taskId: artifact.taskId, runId: artifact.runId } });
|
||||
return bytes.toString('utf8');
|
||||
}
|
||||
|
||||
@@ -72,7 +83,7 @@ export class ExperienceDrafts {
|
||||
const jobScope = { ...scope, runId: job.runId }, plan = this.store.core.check_plan.get(job.planId);
|
||||
if (!plan || !owned(plan, { ...scope, runId: plan?.runId }) || plan.taskId !== job.taskId) throw error('原检查计划归属不一致。');
|
||||
const contract = JSON.parse(this.artifact(plan.contractArtifactId, { ...scope, runId: plan.runId }, refs, 'check-plan'));
|
||||
if (contract.id !== plan.id || contract.projectId !== scope.projectId || contract.sessionId !== scope.sessionId || contract.taskId !== scope.taskId
|
||||
if (contract.id !== plan.id || contract.projectId !== scope.projectId || contract.sessionId !== scope.sessionId || contract.taskId !== scope.taskId || contract.runId !== plan.runId
|
||||
|| contract.sourceFingerprint !== job.sourceFingerprint || hash(contract.checks) !== hash(plan.checks)) throw error('原检查计划与检查记录不一致。');
|
||||
for (const result of job.results ?? []) if (result.logArtifactId) this.artifact(result.logArtifactId, jobScope, refs, 'check-log');
|
||||
const projected = checkFact(job); checks.push(projected); return projected;
|
||||
@@ -150,7 +161,7 @@ export class ExperienceDrafts {
|
||||
const artifact = this.store.core.artifact.get(ref.id);
|
||||
if (!artifact || artifact.sha256 !== ref.sha256 || artifact.bytes !== ref.bytes || artifact.kind !== ref.kind) throw error('经验原工件已变化或缺失。');
|
||||
// Referenced check plans can originate from an earlier Run of this Task.
|
||||
if (artifact.projectId !== memory.projectId || artifact.sessionId !== memory.sessionId || artifact.taskId !== memory.taskId) throw error('经验原工件归属已变化。');
|
||||
if (!owned(artifact, ref.scope) || artifact.projectId !== memory.projectId || artifact.sessionId !== memory.sessionId || artifact.taskId !== memory.taskId) throw error('经验原工件归属已变化。');
|
||||
this.store.artifactStore.readBytes(artifact);
|
||||
}
|
||||
if (source.selection.kind === 'check_job') {
|
||||
@@ -232,6 +243,7 @@ export class ExperienceDrafts {
|
||||
this.assertCursor(session, input.cursor);
|
||||
const initial = this.store.core.memory.get(id);
|
||||
if (!initial || !isExperience(initial) || initial.projectId !== session.projectId || initial.sessionId !== session.id) throw error('只能从来源会话修改这条经验。', 404);
|
||||
if (!experienceStructure(initial)) throw error('经验记录结构不完整,仅保留原记录,不参与请求。');
|
||||
if (!Number.isSafeInteger(input.revision) || initial.experience.revision !== input.revision) throw error('经验已更新,请刷新后再操作。');
|
||||
if (!['edit', 'adopt', 'withdraw', 'reject', 'counterexample', 'archive'].includes(action)) throw error('经验操作不受支持。', 400);
|
||||
const expected = cursor(session), inspection = ['edit', 'adopt'].includes(action) ? await inspectProject(this.store.project(session.projectId)) : null;
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from 'node:path';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { safePath } from '../../server/files.mjs';
|
||||
import { isId } from '../../shared/contracts/execution.mjs';
|
||||
import { ExperienceDrafts, isExperience, experienceEligible } from './experience-drafts.mjs';
|
||||
import { ExperienceDrafts, isExperience, experienceEligible, experienceStructure } from './experience-drafts.mjs';
|
||||
|
||||
const MAX_TITLE = 240;
|
||||
const MAX_CONTENT = 16000;
|
||||
@@ -109,6 +109,12 @@ export class ProjectMemoryManager {
|
||||
let changed = 0;
|
||||
const presented = [];
|
||||
for (const memory of values) {
|
||||
if (isExperience(memory) && !experienceStructure(memory)) {
|
||||
const value = publicMemory(memory);
|
||||
value.status = memory.status === 'archived' ? 'archived' : 'unverified'; value.experience = null;
|
||||
value.experienceError = '经验记录结构不完整,仅保留原记录,不参与模型请求。';
|
||||
presented.push(value); continue;
|
||||
}
|
||||
if (memory.status === 'archived') { presented.push(publicMemory(memory)); continue; }
|
||||
if (isExperience(memory)) {
|
||||
let value = publicMemory(memory);
|
||||
@@ -154,8 +160,8 @@ export class ProjectMemoryManager {
|
||||
projectId, sourceFingerprint: inspection.sourceFingerprint, inspectedAt: inspection.inspectedAt,
|
||||
scope: inspection.scope, memories,
|
||||
summary: { current: presented.filter(value => value.status === 'current' && experienceEligible(value)).length,
|
||||
drafts: presented.filter(value => isExperience(value) && value.experience.adoption === 'draft' && value.status === 'current').length,
|
||||
adopted: presented.filter(value => isExperience(value) && value.experience.adoption === 'active' && value.status === 'current').length,
|
||||
drafts: presented.filter(value => isExperience(value) && value.experience?.adoption === 'draft' && value.status === 'current').length,
|
||||
adopted: presented.filter(value => isExperience(value) && value.experience?.adoption === 'active' && value.status === 'current').length,
|
||||
unverified: presented.filter(value => value.status === 'unverified').length,
|
||||
expired: presented.filter(value => value.status === 'expired').length, archived: values.filter(value => value.status === 'archived').length,
|
||||
total: values.length, invalidated: changed },
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, compatibleFixture, completion, launchWorkbench } from './helpers.mjs';
|
||||
import { beginPlanTask } from './fixtures/task-plan-fixture.mjs';
|
||||
import { ProjectMemoryManager } from '../src/core/memory/project-memory.mjs';
|
||||
import { DeliveryReporter } from '../src/core/delivery-report.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
|
||||
|
||||
const documents = body => body.messages.filter(value => ['system', 'user'].includes(value.role) && value.content.includes('"project_memory":'))
|
||||
.map(value => JSON.parse(value.content.slice(value.content.lastIndexOf('\n') + 1)).project_memory);
|
||||
async function setup(t) {
|
||||
const f = fixture(t, { modernDefaults: true }), provider = new Provider(); provider.setKey('owned-experience-key');
|
||||
const model = await compatibleFixture(t, () => completion([], '本机固定HTTP结果,不修改工程。'));
|
||||
f.store.saveConfig({ mode: 'compatible', model: 'owned-experience-model', baseUrl: model.baseUrl, approvalMode: 'full' });
|
||||
const run = beginPlanTask(f, '只核对README,无需测试。');
|
||||
run.usage.unknownRequests = 1; run.usage.estimatedUnknownTokens = 19; run.stopReason = 'network_error'; f.store.save(f.session);
|
||||
const report = await new DeliveryReporter(f.store).create(f.session);
|
||||
const manager = new ProjectMemoryManager(f.store, { redact: value => provider.redact(value) });
|
||||
const sources = manager.experiences.sources(f.session), source = sources.sources.find(value => value.id === report.artifactId);
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
return { ...f, provider, model, manager, sources, source, runtime,
|
||||
change: (memory, action, fields = {}) => manager.experiences.change(f.session, memory.id, action, { cursor: sources.cursor, revision: memory.experience.revision, ...fields }),
|
||||
async send(session) {
|
||||
runtime.start(session.id, '说明当前工程可核对的经验;无需测试,不修改文件。'); await runtime.active.get(session.id).promise;
|
||||
assert.equal(session.status, 'completed', session.lastFailure?.message); return model.requests.at(-1).input;
|
||||
} };
|
||||
}
|
||||
|
||||
test('actual HTTP distinguishes draft, redacted adoption, withdrawal and immutable past send snapshots without limiting model tokens', async t => {
|
||||
const f = await setup(t), consumer = f.store.createSession(f.project.id, 'Experience consumer');
|
||||
const { memory } = await f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source });
|
||||
assert.equal(documents(await f.send(consumer)).length, 0);
|
||||
const edited = await f.change(memory, 'edit', { title: '原网络观测', content: '仅记录失败,原因未知。owned-experience-key', applicability: '本工程原来源', invalidWhen: '源码或证据变化' });
|
||||
const active = await f.change(edited, 'adopt');
|
||||
const body = await f.send(consumer), [sent] = documents(body);
|
||||
assert.ok(sent, JSON.stringify({ memoryView: await f.manager.list(f.project.id), systemMessages: body.messages.filter(value => value.role === 'system').map(value => value.content.slice(0, 180)) }, null, 2));
|
||||
assert.equal(sent.entries[0].experience.adoption, 'active'); assert.match(sent.entries[0].content, /已隐藏/);
|
||||
assert.equal(JSON.stringify(body).includes('owned-experience-key'), false);
|
||||
assert.equal(sent.entries[0].experience.provenance.facts.runs[0].usage.unknownRequests, 1);
|
||||
assert.equal(sent.entries[0].experience.engineering.verified, false);
|
||||
assert.equal(body.max_tokens, undefined); assert.equal(body.max_completion_tokens, undefined);
|
||||
const plan = [...f.store.core.context_plan.values()].filter(value => value.sessionId === consumer.id).at(-1);
|
||||
const snapshot = f.store.artifactStore.read(f.store.core.artifact.get(plan.projectMemoryArtifactId));
|
||||
assert.doesNotThrow(() => verifyPlanEvidence(f.store, consumer, plan));
|
||||
await f.change(active, 'withdraw'); assert.equal(documents(await f.send(consumer)).length, 0);
|
||||
assert.equal(f.store.artifactStore.read(f.store.core.artifact.get(plan.projectMemoryArtifactId)), snapshot);
|
||||
assert.doesNotThrow(() => verifyPlanEvidence(f.store, consumer, plan));
|
||||
assert.equal(f.model.requests.length, 3); assert.equal(f.store.config.approvalMode, 'full');
|
||||
});
|
||||
|
||||
test('unavailable experience and a failed expiration save omit only optional content while actual HTTP engineering continues', async t => {
|
||||
const f = await setup(t), consumer = f.store.createSession(f.project.id, 'Repair consumer');
|
||||
const created = (await f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source })).memory;
|
||||
await f.change(created, 'adopt');
|
||||
const artifact = f.store.core.artifact.get(f.source.id); fs.unlinkSync(path.join(f.store.artifactStore.root, artifact.relative));
|
||||
const save = f.store.storage.save.bind(f.store.storage);
|
||||
f.store.storage.save = (session, records, type, ...rest) => {
|
||||
if (type === 'memory.experience.expired') throw Error('Owned optional save failure');
|
||||
return save(session, records, type, ...rest);
|
||||
};
|
||||
assert.equal(documents(await f.send(consumer)).length, 0); assert.equal(f.model.requests.length, 1);
|
||||
assert.equal(f.store.core.memory.get(created.id).status, 'current');
|
||||
});
|
||||
|
||||
test('new local API persists explicit source selection, duplicate identity and revision guards, preserves raw bytes and does not request a model', async t => {
|
||||
const f = await setup(t), foreign = f.store.createSession(f.project.id, 'Foreign session');
|
||||
await f.runtime.stopAll(); f.store.close();
|
||||
const host = await launchWorkbench(t, f.data), path = '/sessions/' + f.session.id + '/memories/experiences';
|
||||
const sources = await host.api(path), source = sources.sources.find(value => value.id === f.source.id);
|
||||
const [first, duplicate] = await Promise.all([host.api(path, { source, cursor: sources.cursor }), host.api(path, { source, cursor: sources.cursor })]);
|
||||
assert.equal(first.memory.id, duplicate.memory.id); assert.equal(Number(first.duplicate) + Number(duplicate.duplicate), 1);
|
||||
const memory = first.memory;
|
||||
const active = await host.api(path + '/' + memory.id + '/adopt', { revision: memory.experience.revision, cursor: sources.cursor });
|
||||
assert.equal(active.experience.adoption, 'active');
|
||||
await assert.rejects(host.api(path + '/' + memory.id + '/withdraw', { revision: 1, cursor: sources.cursor }), /已更新/);
|
||||
await assert.rejects(host.api('/sessions/' + foreign.id + '/memories/experiences/' + memory.id + '/adopt', { revision: 2, cursor: { taskId: null, runId: null } }), /来源会话/);
|
||||
const raw = await host.api('/artifacts/' + source.id + '?session=' + f.session.id);
|
||||
assert.equal(raw.sha256, source.sha256); assert.equal(JSON.parse(raw.content).runId, source.runId);
|
||||
const withdrawn = await host.api(path + '/' + memory.id + '/withdraw', { revision: 2, cursor: sources.cursor });
|
||||
assert.equal(withdrawn.experience.adoption, 'withdrawn');
|
||||
assert.equal((await host.api('/projects/' + f.project.id + '/memories')).summary.current, 0);
|
||||
assert.equal(f.model.requests.length, 0);
|
||||
});
|
||||
|
||||
test('a task switch while asynchronous creation or adoption is inspecting cannot save a late mutation', async t => {
|
||||
const f = await setup(t);
|
||||
const pending = f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source });
|
||||
beginPlanTask(f, '新的用户任务,无需测试。');
|
||||
await assert.rejects(pending, /已切换/); assert.equal(f.store.core.memory.size, 0);
|
||||
const currentSources = f.manager.experiences.sources(f.session);
|
||||
const created = (await f.manager.experiences.create(f.session, { cursor: currentSources.cursor, source: f.source })).memory;
|
||||
const adoption = f.manager.experiences.change(f.session, created.id, 'adopt', { cursor: currentSources.cursor, revision: 1 });
|
||||
beginPlanTask(f, '再一个用户任务,无需测试。');
|
||||
await assert.rejects(adoption, /已切换/); assert.equal(f.store.core.memory.get(created.id).experience.adoption, 'draft');
|
||||
});
|
||||
|
||||
test('a failed optional experience send snapshot is recorded and does not block the original actual HTTP request', async t => {
|
||||
const f = await setup(t), consumer = f.store.createSession(f.project.id, 'Optional snapshot failure');
|
||||
const created = (await f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source })).memory;
|
||||
await f.change(created, 'adopt');
|
||||
const write = f.store.artifactStore.write.bind(f.store.artifactStore);
|
||||
f.store.artifactStore.write = (session, run, value, options) => {
|
||||
if (options?.kind === 'context-project-memory') throw Error('Owned experience snapshot unavailable');
|
||||
return write(session, run, value, options);
|
||||
};
|
||||
assert.equal(documents(await f.send(consumer)).length, 0);
|
||||
const plan = [...f.store.core.context_plan.values()].find(value => value.sessionId === consumer.id);
|
||||
assert.equal(plan.projectMemoryIssue.kind, 'optional_experience_unavailable');
|
||||
assert.equal(f.model.requests.length, 1); assert.doesNotThrow(() => verifyPlanEvidence(f.store, consumer, plan));
|
||||
});
|
||||
|
||||
test('optional experience snapshot failure retains compatible manual memory in the actual HTTP request', async t => {
|
||||
const f = await setup(t), consumer = f.store.createSession(f.project.id, 'Mixed memory snapshot');
|
||||
const created = (await f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source })).memory;
|
||||
await f.change(created, 'adopt');
|
||||
const manual = await f.manager.create(f.session, { content: '原有手写项目约定,不随经验故障丢失。' });
|
||||
const write = f.store.artifactStore.write.bind(f.store.artifactStore);
|
||||
f.store.artifactStore.write = (session, run, value, options) => {
|
||||
if (options?.kind === 'context-project-memory' && (typeof value === 'string' ? JSON.parse(value) : value).entries.some(entry => entry.experience)) throw Error('Owned experience-specific snapshot failure');
|
||||
return write(session, run, value, options);
|
||||
};
|
||||
const [sent] = documents(await f.send(consumer)); assert.deepEqual(sent.entries.map(value => value.id), [manual.id]);
|
||||
const plan = [...f.store.core.context_plan.values()].find(value => value.sessionId === consumer.id);
|
||||
assert.equal(plan.projectMemoryEntries, 1); assert.equal(plan.projectMemoryIssue.kind, 'optional_experience_unavailable');
|
||||
assert.doesNotThrow(() => verifyPlanEvidence(f.store, consumer, plan));
|
||||
});
|
||||
|
||||
test('malformed optional experience metadata remains unavailable while manual memory and actual HTTP continue', async t => {
|
||||
const f = await setup(t), consumer = f.store.createSession(f.project.id, 'Malformed optional metadata');
|
||||
const created = (await f.manager.experiences.create(f.session, { cursor: f.sources.cursor, source: f.source })).memory;
|
||||
const active = await f.change(created, 'adopt');
|
||||
const manual = await f.manager.create(f.session, { content: '手写记忆不受经验结构错误影响。' });
|
||||
f.store.core.memory.get(active.id).experience = null;
|
||||
const view = await f.manager.list(f.project.id);
|
||||
assert.equal(view.memories.find(row => row.id === active.id).status, 'unverified');
|
||||
assert.match(view.memories.find(row => row.id === active.id).experienceError, /结构不完整/);
|
||||
const stored = f.store.core.memory.get(active.id); stored.status = 'archived'; stored.experience = {};
|
||||
const archived = (await f.manager.list(f.project.id)).memories.find(row => row.id === active.id);
|
||||
assert.equal(archived.status, 'archived'); assert.equal(archived.experience, null);
|
||||
assert.match(archived.experienceError, /结构不完整/);
|
||||
const [sent] = documents(await f.send(consumer)); assert.deepEqual(sent.entries.map(row => row.id), [manual.id]);
|
||||
assert.equal(f.model.requests.length, 1);
|
||||
});
|
||||
@@ -96,6 +96,19 @@ test('source changes, missing original bytes and changed source ownership exclud
|
||||
});
|
||||
});
|
||||
|
||||
test('a changed immutable artifact Run is excluded for the request while the storage ownership guard restores its persisted identity', async t => {
|
||||
const f = await setup(t), active = await f.change((await f.create()).memory, 'adopt');
|
||||
const originalRunId = active.runId, artifact = f.store.core.artifact.get(f.source.id);
|
||||
const other = f.store.beginRun(f.session, '同任务另一运行', true, f.store.config);
|
||||
f.session.status = 'paused'; f.store.finishRun(f.session, other, 'owned_scope_fixture');
|
||||
artifact.runId = other.id;
|
||||
const view = await f.manager.list(f.project.id);
|
||||
assert.equal(view.memories[0].status, 'unverified', 'optional experience is unavailable on the failed persistence attempt');
|
||||
assert.equal(f.store.core.artifact.get(f.source.id).runId, originalRunId, 'the existing storage guard restores the immutable row');
|
||||
const restored = await f.manager.list(f.project.id); assert.equal(restored.memories[0].status, 'current');
|
||||
assert.equal(restored.memories[0].experience.revision, active.experience.revision);
|
||||
});
|
||||
|
||||
test('changed current or historical revision bytes and materialized text cannot enter requests', async t => {
|
||||
for (const scenario of ['current', 'history', 'text']) await t.test(scenario, async t => {
|
||||
const f = await setup(t), active = await f.change((await f.create()).memory, 'adopt');
|
||||
|
||||
Reference in New Issue
Block a user