feat: preserve source-bound experience drafts and reversible adoption

This commit is contained in:
Agent Workbench Dev
2026-11-06 17:06:29 +08:00
parent c1d30bbe82
commit 52cd60f226
9 changed files with 524 additions and 8 deletions
+23
View File
@@ -0,0 +1,23 @@
# E:经验草稿与可回滚采纳验收
2026-11-06开始。基线c1d30bbe,按EXPERIENCE-DRAFTS-E-PLAN.md实施。D/1.25.10原证据保持;本文只记录E实际范围,不代签模型语义收益、F角色路由、Mnemo导出/委托或Purge收益。
## 核心切片
复用memory记录与不可变工件。显式选取来源会话的交付报告、原检查或工具结果;核对project/session/task/run及原字节,只投影外显事实。草稿默认不参与请求,full权限不自动采用。工具来源缺少源码指纹时仅保留历史草稿,不能补造适用版本。
证据阶段与采用状态分离:source_checked核对来源,engineering_verified只表示所选原检查通过复核,conclusionVerified始终false;用户采用不会补造工程验证或失败原因。每次编辑/采用/撤销/拒绝/反例/失效/归档均保留不可变修订和父SHA;编辑停止采用,反例使经验失效,原成功/失败/unknown保持。
稳定来源键防重复,包括拒绝/归档后的重复请求。变更需当前任务游标和修订号;来源会话之外不可修改。可选经验保存失效失败时,本次视图排除经验,原工程可以继续;旧手写记忆的行为保持。
首轮`.qa/experience-drafts-e/core-1.tap`:34/34(包含17条既有记忆管理/上下文测试和新增固定事实场景/子测试),0失败/取消/跳过。实际运行原检查的失败3例与后续通过3例均保留,来源草稿不把两者合成一次成功。新HTTP路由、UI及发行此时尚未验收。
新增公开诊断事实投影与持久化前来源重读后,定向复验17/17通过(core-2.tap)。阶段回顾:保留旧用户记忆、将经验默认排除、复用原检查核验;实际HTTP/UI与发行继续独立验收。早期只读搜索多次误用不存在路径/Windows通配路径,未修改数据,后续用rg目录搜索;这些命令错误不作为产品测试通过记录。
## 待验证
- 新HTTP路由、实际模型请求前后差异与可选经验故障隔离。
- 原记忆面板、网页/实际Electron、390px与失败恢复。
- 独立源码/程序归档、安装、正式入口与保留状态升级。
本阶段真实模型请求0;真实网络异常、unknown计费、普遍重复读取改善未知与Purge收益unknown持续保留。
+6
View File
@@ -1329,3 +1329,9 @@ D回顾:字符串SHA必须与请求计划同用原字节;只保存“准备
D正式回顾:1.25.10沿原Store热升级时可保持旧配置完全不补写,设置接口仍默认false;新配置选择只在用户显式保存时落盘。两ZIP/784输入重建29/29、随包与正式两端/严格final exact均通过,原Provider和原事实保持。E不能直接借用现有ProjectMemoryManager.create生成经验,因为它直接标origin=user/status=current;下一需独立保存草稿证据阶段和采用状态,保留现有手动记忆语义,未实现前不注入。
D源码UI实际回看:已查看默认关闭的1440px设置窗口和390px真实回读。复用Orven三色变量/工具箱/任务观察,没有新增独立控制台;窄屏按钮均可达,因果未证实、原观察/实际请求/回读依据显示清楚。网页7组通过;独立backend-candidate-2/a33704da上的HTTP1项与源码Runtime12项共13/13通过。candidate-1漏hot-upgrade/host-launcher,宿主登记拒绝,原api-round-2保持;新候选补齐原宿主必需输入,不改守卫。
# E经验草稿:实现接续(2026-11-06)
- 基线c1d30bbe,工作树干净;D已交付,E尚无实现。
- 现有ProjectMemoryManager.create直接保存user/current,context只选current;必须兼容用户手写记忆,并为经验增加独立采用状态和证据,不把指纹匹配等同结论正确。
- 复用ProjectMemoryPanel和memory CORE记录,保留Orven三配色/原入口;以来源选择→事实草稿→可编辑范围/反例→采用/撤销串联,不新增控制台。
- 首次搜索曾对Windows目录使用rg通配路径,产生os error 123(只读,无改动);后续改为目录或rg --files。
+6
View File
@@ -1987,3 +1987,9 @@ D第二切片收口:实际Electron7组同样通过,0页面错误/真实模
1.25.10准备完整build通过、安装/发行27/27与热升级模型中心5/5通过。补测旧配置没有提醒字段时GET保持false且不写原数据、显式启用才保存新修订。只读预检曾误以为/model-center包含config,实际在/model-center/selection;未写入,按实测修正新驱动。该版本保留旧Store可能没有公开新字段,比较只许原配置exact或声明新增false投影,其余原事实保持;正式当前仍1.25.9/71628/空闲/102项目/五条凭据存在。
1.25.10正式交付:来源7f87feeb/候选20261106081255613,源码1153项/程序11038项ZIP字节SHA/CRC通过,784输入离线重建29编译文件0差异;实际隔离stage/activate/start、随包网页/Electron各7及核心10通过。跨版首夹具漏/config.mode而在升级前拒绝,原失败保留;修正原接口输入后实际1.25.9→1.25.10同PID/合成凭据/原数据exact,开关跨实际重启保持。唯一正式安装318172ms,保留PID71628/instance/Provider;升级与正式网页4/Electron5后两次严格exact,102项目127会话53148原表行/导出/5244工件/模型中心保持、修订123/开放策略/五条Key存在状态不变,提醒关闭,空闲/窗口0/9229关闭。137份81380817字节逐SHA封存;0真实模型,不续跑用户工程,旧1.25.9修订例外与所有失败不改。E仅另写来源/采用分离计划,接续提交与增量推送。
# E阶段接续(2026-11-06)
- 核心首轮34/34、公开诊断投影/持久化前来源重读补强后17/17通过,证据.qa/experience-drafts-e/core-{1,2}.tap;新HTTP/UI/发行仍未完成。回顾见docs/QA-EXPERIENCE-DRAFTS-E.md,按范围本地提交后继续界面。
- 已读AGENTS、E计划、当前阶段计划、项目记忆及产品UI/前端/文件计划技能;session-catchup未发现需要恢复的未提交实现。
- 当前基线c1d30bbe,开始核心来源/状态设计;尚未运行E测试、模型请求、正式安装或变更正式配置。
+267
View File
@@ -0,0 +1,267 @@
import { createHash, randomUUID } from 'node:crypto';
import { inspectProject } from '../project-inspector.mjs';
import { isId } from '../../shared/contracts/execution.mjs';
export const EXPERIENCE_PROTOCOL = 'workbench.experience.v1';
const at = () => new Date().toISOString();
const copy = value => structuredClone(value);
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const error = (message, status = 409) => Object.assign(new Error(message), { status });
const string = value => typeof value === 'string' ? value.trim() : '';
const owned = (row, scope) => row && row.projectId === scope.projectId && row.sessionId === scope.sessionId
&& row.taskId === scope.taskId && row.runId === scope.runId;
const cursor = session => ({ taskId: session.taskId ?? null, runId: session.runId ?? null });
const model = row => ({ model: row?.model ?? null, protocol: row?.protocol ?? (row?.mode === 'demo' ? 'demo' : 'chat-completions'),
configRevision: row?.configRevision ?? null, connectionId: row?.modelConnectionId ?? null, credentialRevision: row?.modelCredentialRevision ?? null });
const usage = row => row ? copy(row) : null;
const resultFact = result => ({ id: result.id, kind: result.kind, name: result.name, engine: result.engine ?? null,
status: result.status, exitCode: result.exitCode ?? null, tests: result.tests ?? null, logArtifactId: result.logArtifactId ?? null });
const checkFact = row => ({ id: row.id, projectId: row.projectId, sessionId: row.sessionId, taskId: row.taskId, runId: row.runId,
planId: row.planId, status: row.status, sourceFingerprint: row.sourceFingerprint ?? null, stale: !!row.stale,
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));
// Only outward engineering facts are projected. Logs, model reasoning and
// arbitrary report text are never mined for causal conclusions or instructions.
export class ExperienceDrafts {
constructor(store, { redact = value => value } = {}) { this.store = store; this.redact = redact; }
assertCursor(session, expected) {
if (!expected || hash(cursor(session)) !== hash({ taskId: expected.taskId ?? null, runId: expected.runId ?? null }))
throw error('任务或运行已切换,请重新选择经验来源。');
}
sources(session) {
const rows = [];
for (const artifact of this.store.core.artifact.values()) if (artifact.projectId === session.projectId && artifact.sessionId === session.id && artifact.kind === 'delivery-report')
rows.push({ kind: 'delivery_report', id: artifact.id, artifactId: artifact.id, sha256: artifact.sha256,
taskId: artifact.taskId, runId: artifact.runId, label: '交付报告 · ' + artifact.createdAt, status: 'snapshot' });
for (const row of this.store.core.check_job.values()) if (row.projectId === session.projectId && row.sessionId === session.id && row.finishedAt)
rows.push({ kind: 'check_job', id: row.id, sha256: hash(checkFact(row)), taskId: row.taskId, runId: row.runId,
label: '工程检查 · ' + row.status + ' · ' + row.finishedAt, status: row.status });
for (const row of this.store.core.tool.values()) if (row.projectId === session.projectId && row.sessionId === session.id && row.resultArtifactId) {
const artifact = this.store.core.artifact.get(row.resultArtifactId);
if (artifact) rows.push({ kind: 'tool', id: row.id, artifactId: artifact.id, sha256: artifact.sha256,
taskId: row.taskId, runId: row.runId, label: row.tool + ' · ' + row.state, status: row.state });
}
return { projectId: session.projectId, sessionId: session.id, cursor: cursor(session), sources: rows.reverse() };
}
artifact(id, scope, refs, kind) {
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 });
return bytes.toString('utf8');
}
collect(session, selection) {
if (!selection || !isId(selection.id) || !['delivery_report', 'check_job', 'tool'].includes(selection.kind)) throw error('请选择已有交付报告、原检查或工具结果。', 400);
const row = (selection.kind === 'delivery_report' ? this.store.core.artifact : this.store.core[selection.kind === 'tool' ? 'tool' : 'check_job']).get(selection.id);
if (!row || row.projectId !== session.projectId || row.sessionId !== session.id || !isId(row.taskId) || !isId(row.runId)) throw error('经验来源不属于当前项目和会话。', 404);
const scope = { projectId: session.projectId, sessionId: session.id, taskId: row.taskId, runId: row.runId };
const task = this.store.core.task.get(row.taskId), run = this.store.core.run.get(row.runId);
if (!task || task.projectId !== scope.projectId || task.sessionId !== scope.sessionId || !owned({ ...run, runId: run?.id }, scope)) throw error('经验来源的任务或运行归属无法核对。');
const refs = [], checks = [];
let fingerprint = null, fact, sourceSha;
const readCheck = job => {
if (!job || job.projectId !== scope.projectId || job.sessionId !== scope.sessionId || job.taskId !== scope.taskId || !job.finishedAt) throw error('原工程检查缺失、未结束或归属不一致。');
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
|| 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;
};
if (selection.kind === 'delivery_report') {
const report = JSON.parse(this.artifact(row.id, scope, refs, 'delivery-report'));
if (report.kind !== 'engineering-delivery' || report.project?.id !== scope.projectId || report.task?.id !== scope.taskId || report.runId !== scope.runId) throw error('交付报告原文归属不一致。');
fingerprint = report.source?.fingerprint ?? null;
// Preserve the report's original failed/stale checks. Never re-sign a
// historical report using a later passing check or a later model reply.
for (const original of report.checks ?? []) {
const job = this.store.core.check_job.get(original.id);
readCheck(job);
if (hash((original.results ?? []).map(resultFact)) !== hash((job.results ?? []).map(resultFact)) || original.status !== job.status)
throw error('交付报告与原检查事实不一致。');
}
fact = { kind: 'delivery_report', schemaVersion: report.schemaVersion, status: report.status, checkPolicy: report.checkPolicy ?? null,
verifiedCheckJobId: report.verifiedCheckJobId ?? null, checks: (report.checks ?? []).map(value => ({ id: value.id, status: value.status, stale: value.stale,
results: (value.results ?? []).map(resultFact) })),
runs: (report.runs ?? []).map(value => ({ id: value.id, status: value.status, stopReason: value.stopReason ?? null, model: model(value.model), usage: usage(value.usage) })),
diagnostics: (report.diagnostics ?? []).map(value => ({ runId: value.runId, status: value.status, stopReason: value.stopReason ?? null,
failure: value.failure ? { kind: value.failure.kind, code: value.failure.code, httpStatus: value.failure.httpStatus,
stage: value.failure.stage, message: value.failure.message } : null })),
usage: usage(report.usage), limitations: report.limitations ?? [] };
sourceSha = row.sha256;
} else if (selection.kind === 'check_job') {
fact = { kind: 'check_job', check: readCheck(row), model: model(run.model), usage: usage(run.usage) };
fingerprint = row.sourceFingerprint ?? null; sourceSha = hash(checkFact(row));
} else {
const result = JSON.parse(this.artifact(row.resultArtifactId, scope, refs, 'tool-result'));
fact = { kind: 'tool', tool: row.tool, state: row.state, status: result.status ?? 'unknown', exitCode: result.exit_code ?? result.exitCode ?? null,
requiresVerification: row.requiresVerification === true || result.requires_verification === true, path: typeof result.path === 'string' ? result.path : null,
resultSha256: refs[0].sha256, argsSha256: row.argsSha256, model: model(run.model), usage: usage(run.usage) };
fingerprint = result.source_fingerprint ?? result.sourceFingerprint ?? null; sourceSha = refs[0].sha256;
}
if (selection.sha256 !== sourceSha) throw error('所选来源已变化,请刷新后重新选择。');
return { protocol: EXPERIENCE_PROTOCOL, scope, selection: { kind: selection.kind, id: selection.id, sha256: sourceSha },
refs, sourceFingerprint: fingerprint, facts: JSON.parse(this.redact(JSON.stringify(fact))),
model: model(run.model), sourceKey: hash({ ...scope, kind: selection.kind, id: selection.id, sha256: sourceSha }),
// This flag is about the original selected checks, never a verdict on
// the user's edited lesson. The existing checker remains authoritative.
engineeringCandidate: checks.filter(value => value.status === 'passed' && !value.stale).map(value => value.id) };
}
payload(memory) {
const value = copy(memory);
delete value.experience.revisions; delete value.experience.artifactId; delete value.experience.sha256;
return value;
}
verifySnapshot(memory) {
if (!isExperience(memory) || memory.experience?.protocol !== EXPERIENCE_PROTOCOL) throw error('经验版本不可识别。');
const scope = { projectId: memory.projectId, sessionId: memory.sessionId, taskId: memory.taskId, runId: memory.runId }, refs = [];
const original = JSON.parse(this.artifact(memory.experience.artifactId, scope, refs, 'experience-revision'));
if (refs[0].sha256 !== memory.experience.sha256 || hash(original) !== hash(this.payload(memory))) throw error('经验修订与不可变原文不一致。');
const revisions = memory.experience.revisions;
if (!Array.isArray(revisions) || revisions.length !== memory.experience.revision || revisions.at(-1)?.sha256 !== refs[0].sha256) throw error('经验修订链不一致。');
let parent = null;
for (let index = 0; index < revisions.length; index++) {
const ref = revisions[index], data = JSON.parse(this.artifact(ref.artifactId, scope, [], 'experience-revision'));
const artifact = this.store.core.artifact.get(ref.artifactId);
if (artifact.sha256 !== ref.sha256 || data.id !== memory.id || data.experience.revision !== index + 1 || data.experience.parentSha256 !== parent)
throw error('经验历史修订缺失或已变化。');
parent = ref.sha256;
}
return original;
}
verify(memory, inspection) {
this.verifySnapshot(memory);
const source = memory.experience.provenance;
const session = this.store.sessions.get(memory.sessionId);
if (!session || hash(source.scope) !== hash({ projectId: memory.projectId, sessionId: memory.sessionId, taskId: memory.taskId, runId: memory.runId })) throw error('经验来源身份已变化。');
for (const ref of source.refs) {
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('经验原工件归属已变化。');
this.store.artifactStore.readBytes(artifact);
}
if (source.selection.kind === 'check_job') {
const job = this.store.core.check_job.get(source.selection.id);
if (!owned(job, source.scope) || hash(checkFact(job)) !== source.selection.sha256) throw error('原检查事实已变化。');
}
if (source.selection.kind === 'tool') {
const tool = this.store.core.tool.get(source.selection.id);
if (!owned(tool, source.scope) || tool.resultArtifactId !== source.refs[0]?.id || tool.argsSha256 !== source.facts.argsSha256 || tool.state !== source.facts.state) throw error('原工具事实已变化。');
}
if (!source.sourceFingerprint || source.sourceFingerprint !== memory.sourceFingerprint) throw error('原来源没有可核对的源码指纹,仅保留为历史草稿。');
if (inspection.scope.complete && memory.sourceFingerprint !== inspection.sourceFingerprint) throw error('工程源码指纹已变化,经验需重新核对。');
return inspection.scope.complete;
}
save(session, memory, action) {
const value = copy(memory), previous = value.experience.sha256 ?? null;
value.updatedAt = at(); value.experience.revision++; value.experience.parentSha256 = previous;
value.experience.lastAction = action;
const run = this.store.core.run.get(value.runId);
const artifact = this.store.artifactStore.write(session, run, this.payload(value), { kind: 'experience-revision' });
this.store.core.artifact.set(artifact.id, artifact);
value.experience.artifactId = artifact.id; value.experience.sha256 = artifact.sha256;
value.experience.revisions.push({ revision: value.experience.revision, artifactId: artifact.id, sha256: artifact.sha256, action, at: value.updatedAt });
this.store.putRecord('memory', session, value, 'memory.experience.' + action);
return copy(value);
}
async create(session, input = {}) {
this.assertCursor(session, input.cursor);
const expected = cursor(session), inspection = await inspectProject(this.store.project(session.projectId));
this.assertCursor(session, expected);
const provenance = this.collect(session, input.source);
const duplicate = [...this.store.core.memory.values()].find(value => value.projectId === session.projectId && isExperience(value)
&& value.experience?.provenance?.sourceKey === provenance.sourceKey);
if (duplicate) { this.verifySnapshot(duplicate); return { memory: copy(duplicate), duplicate: true }; }
const fingerprint = provenance.sourceFingerprint ?? inspection.sourceFingerprint;
let engineeringVerified = false;
if (inspection.scope.complete && fingerprint === inspection.sourceFingerprint && provenance.engineeringCandidate.length) {
const { verifiedCheck } = await import('../delivery-report.mjs');
this.assertCursor(session, expected);
const check = verifiedCheck(this.store, { ...session, taskId: provenance.scope.taskId, runId: provenance.scope.runId }, inspection);
engineeringVerified = !!check && provenance.engineeringCandidate.includes(check.id);
}
this.assertCursor(session, expected);
if (hash(this.collect(session, input.source)) !== hash(provenance)) throw error('生成草稿期间原来源发生变化,请重新选择。');
// A competing create may finish while the optional original-check verifier
// is loading. Deduplicate again at the synchronous persistence boundary.
const raced = [...this.store.core.memory.values()].find(value => isExperience(value) && value.experience?.provenance?.sourceKey === provenance.sourceKey);
if (raced) { this.verifySnapshot(raced); return { memory: copy(raced), duplicate: true }; }
const now = at(), kindLabel = { delivery_report: '交付报告', check_job: '工程检查', tool: '工具结果' }[provenance.selection.kind];
const facts = provenance.facts;
const content = kindLabel + '原始事实:' + JSON.stringify(facts, null, 2)
+ '\n以上只记录实际成功、失败或未知;原因与经验收益尚未证明。';
const memory = { schemaVersion: 2, id: randomUUID(), ...provenance.scope, title: kindLabel + '经验草稿', content, tags: ['经验草稿'],
source: { kind: 'artifact', id: provenance.refs[0].id, sha256: provenance.refs[0].sha256, sourceFingerprint: fingerprint,
artifactKind: provenance.refs[0].kind }, sourceFingerprint: fingerprint, status: 'current', origin: 'experience',
createdAt: now, updatedAt: now, expiresAt: null, expiredAt: null, expiredReason: null,
experience: { protocol: EXPERIENCE_PROTOCOL, revision: 0, revisions: [], adoption: 'draft',
stages: ['observed', 'source_checked', ...(engineeringVerified ? ['engineering_verified'] : [])],
engineering: { verified: engineeringVerified, scope: 'selected-original-checks-only', conclusionVerified: false },
provenance, applicability: '仅本项目、所选来源与当前源码版本;结论仍需结合实际工程核对。',
invalidWhen: '源码、来源或适用范围变化,或出现新反例时停止采用。', counterexamples: [], causalStatus: 'unproven' } };
if (!provenance.sourceFingerprint || inspection.scope.complete && fingerprint !== inspection.sourceFingerprint) {
memory.status = 'expired'; memory.expiredAt = now; memory.expiredReason = '原来源没有匹配当前工程的源码指纹,仅保留历史草稿。';
memory.experience.stages.push('expired');
}
return { memory: this.save(session, memory, 'created'), duplicate: false };
}
expire(memory, reason) {
if (memory.status === 'expired' || memory.status === 'archived') return copy(memory);
const value = copy(memory); value.status = 'expired'; value.expiredAt = at(); value.expiredReason = reason;
if (!value.experience.stages.includes('expired')) value.experience.stages.push('expired');
return this.save(this.store.sessions.get(value.sessionId), value, 'expired');
}
async change(session, id, action, input = {}) {
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 (!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;
this.assertCursor(session, expected);
const current = this.store.core.memory.get(id);
if (current !== initial || current.experience.revision !== input.revision) throw error('经验已更新,请刷新后再操作。');
this.verifySnapshot(current);
if (current.status === 'archived') throw error('归档经验只能查看原记录。');
if (inspection) {
if (!this.verify(current, inspection)) throw error('源码扫描不完整,经验暂不能采用或修订。');
if (current.status !== 'current' || current.experience.stages.includes('rejected')) throw error('已失效或拒绝的经验保留为历史,请选择新的来源。');
}
const value = copy(current), experience = value.experience;
if (action === 'edit') {
for (const key of ['title', 'content']) { if (!string(input[key])) throw error('经验标题和内容不能为空。', 400); value[key] = string(input[key]); }
for (const key of ['applicability', 'invalidWhen']) { if (!string(input[key])) throw error('请填写适用范围和失效条件。', 400); experience[key] = string(input[key]); }
value.content = this.redact(value.content); value.title = this.redact(value.title);
experience.applicability = this.redact(experience.applicability); experience.invalidWhen = this.redact(experience.invalidWhen);
experience.adoption = 'draft'; experience.stages = experience.stages.filter(stage => stage !== 'user_confirmed');
} else if (action === 'adopt') {
experience.adoption = 'active'; if (!experience.stages.includes('user_confirmed')) experience.stages.push('user_confirmed');
} else if (action === 'withdraw' || action === 'reject') {
experience.adoption = 'withdrawn';
if (action === 'reject' && !experience.stages.includes('rejected')) experience.stages.push('rejected');
} else if (action === 'counterexample') {
if (!string(input.note)) throw error('请说明新反例,原失败记录会保留。', 400);
experience.counterexamples.push({ note: this.redact(string(input.note)), origin: 'user', recordedAt: at(), engineeringVerified: false });
value.status = 'expired'; value.expiredAt = at(); value.expiredReason = '新增反例,经验已失效;反例为用户记录,尚未代签工程验证。';
experience.stages.push('expired'); experience.adoption = 'withdrawn';
} else { value.status = 'archived'; value.archivedAt = at(); experience.adoption = 'withdrawn'; }
return this.save(session, value, action);
}
}
+33 -5
View File
@@ -5,6 +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';
const MAX_TITLE = 240;
const MAX_CONTENT = 16000;
@@ -90,7 +91,7 @@ function publicMemory(memory) {
}
export class ProjectMemoryManager {
constructor(store) { this.store = store; }
constructor(store, options = {}) { this.store = store; this.experiences = new ExperienceDrafts(store, options); }
async inspect(projectId) {
const project = this.store.project(projectId);
@@ -109,6 +110,25 @@ export class ProjectMemoryManager {
const presented = [];
for (const memory of values) {
if (memory.status === 'archived') { presented.push(publicMemory(memory)); continue; }
if (isExperience(memory)) {
let value = publicMemory(memory);
try {
const complete = this.experiences.verify(memory, inspection);
if (!complete && memory.status === 'current') value.status = 'unverified';
} catch (cause) {
try {
value = this.experiences.expire(memory, cause.message);
if (memory.status !== 'expired' && value.status === 'expired') changed++;
} catch {
// An optional experience must never stop the original engineering
// task when its expiration cannot be persisted. Exclude this view.
value = publicMemory(this.store.core.memory.get(memory.id) ?? memory);
value.status = 'unverified';
}
value.experience.unavailableReason = cause.message;
}
presented.push(value); continue;
}
const timedOut = memory.expiresAt && Date.parse(memory.expiresAt) <= now;
const fileSourceChanged = memory.source.kind === 'file' && this.fileSourceChanged(project, memory.source);
const provenanceChanged = memory.source.kind !== 'file' && this.provenanceChanged(memory);
@@ -129,11 +149,13 @@ export class ProjectMemoryManager {
if (memory.status === 'current' && !inspection.scope.complete) value.status = 'unverified';
presented.push(value);
}
const memories = presented.filter(value => includeExpired || value.status === 'current').slice(0, ceiling(this.store, MAX_MEMORIES));
const memories = presented.filter(value => includeExpired || value.status === 'current' && experienceEligible(value)).slice(0, ceiling(this.store, MAX_MEMORIES));
return {
projectId, sourceFingerprint: inspection.sourceFingerprint, inspectedAt: inspection.inspectedAt,
scope: inspection.scope, memories,
summary: { current: presented.filter(value => value.status === 'current').length,
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,
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 },
@@ -192,7 +214,7 @@ export class ProjectMemoryManager {
async context(session, { redact = value => value, maxEntries = ceiling(this.store, MEMORY_CONTEXT_LIMITS.entries), maxBytes = ceiling(this.store, MEMORY_CONTEXT_LIMITS.bytes) } = {}) {
// No scan or context overhead for projects without memory.
if (![...this.store.core.memory.values()].some(value => value.projectId === session.projectId && value.status === 'current')) return null;
if (![...this.store.core.memory.values()].some(value => value.projectId === session.projectId && value.status === 'current' && experienceEligible(value))) return null;
let view;
try { view = await this.list(session.projectId, { includeExpired: false }); }
catch (error) {
@@ -210,7 +232,12 @@ export class ProjectMemoryManager {
if (document.entries.length >= entryLimit) break;
const entry = JSON.parse(redact(JSON.stringify({ id: memory.id, title: memory.title, content: memory.content, tags: memory.tags,
source: memory.source, sourceFingerprint: memory.sourceFingerprint, sessionId: memory.sessionId,
taskId: memory.taskId, runId: memory.runId, createdAt: memory.createdAt, expiresAt: memory.expiresAt })));
taskId: memory.taskId, runId: memory.runId, createdAt: memory.createdAt, expiresAt: memory.expiresAt,
...(isExperience(memory) ? { experience: { protocol: memory.experience.protocol, revision: memory.experience.revision,
artifactId: memory.experience.artifactId, sha256: memory.experience.sha256, adoption: memory.experience.adoption,
stages: memory.experience.stages, engineering: memory.experience.engineering, causalStatus: memory.experience.causalStatus,
provenance: memory.experience.provenance, applicability: memory.experience.applicability,
invalidWhen: memory.experience.invalidWhen, counterexamples: memory.experience.counterexamples } } : {}) })));
document.entries.push(entry);
// Measure escaped UTF-8 JSON, keep whole entries, and try smaller entries after an oversized one.
if (Buffer.byteLength(JSON.stringify(document), 'utf8') > byteLimit) document.entries.pop();
@@ -222,6 +249,7 @@ export class ProjectMemoryManager {
const memory = this.store.core.memory.get(id);
if (!memory || memory.projectId !== session.projectId) throw memoryError('项目记忆不存在。', 404);
if (memory.sessionId !== session.id) throw memoryError('只能从来源会话归档这条项目记忆。', 409);
if (isExperience(memory)) throw memoryError('经验归档需要当前修订号,请在经验操作中刷新后归档。', 409);
if (memory.status !== 'archived') {
memory.status = 'archived'; memory.updatedAt = at(); memory.archivedAt = memory.updatedAt;
this.store.putRecord('memory', session, memory, 'memory.archived');
+13 -1
View File
@@ -55,7 +55,7 @@ const research = [
{ id: 'context', title: 'Claude Code:上下文与恢复', file: 'research/CONTEXT-RECOVERY.md', description: '压缩预算、摘要校验、会话链与未完成调用。' },
{ id: 'tools', title: 'Claude Code:工具循环', file: 'research/TOOL-LOOP.md', description: '参数校验、队列、并发安全与权限判断。' },
];
const memories = new ProjectMemoryManager(store);
const memories = new ProjectMemoryManager(store, { redact: value => provider.redact(value) });
function json(response, value, status = 200) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
@@ -168,6 +168,18 @@ return async (request, response) => {
return json(response, await memories.list(projectMemoryMatch[1], { includeExpired }));
}
const sessionMemoryMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories$/i);
const experienceMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories\/experiences(?:\/([a-f0-9-]+)\/(edit|adopt|withdraw|reject|counterexample|archive))?$/i);
if (experienceMatch) {
const session = store.session(experienceMatch[1]);
if (method === 'GET' && !experienceMatch[2]) return json(response, memories.experiences.sources(session));
if (method === 'POST') {
if (workerForProject(store, session.projectId)) throw workerConflict('请从来源项目的记忆入口管理经验。');
const input = await body(request);
return json(response, experienceMatch[2]
? await memories.experiences.change(session, experienceMatch[2], experienceMatch[3], input)
: await memories.experiences.create(session, input), experienceMatch[2] ? 200 : 201);
}
}
if (sessionMemoryMatch && method === 'GET') {
const session = store.session(sessionMemoryMatch[1]);
const includeExpired = url.searchParams.get('include_expired') !== '0';
+1 -1
View File
@@ -234,7 +234,7 @@ export class Runtime {
budgetResumes(){return this.resumes??=new BudgetResume(this.store,this.provider,this);}
resumeBudget(id,input){const session=this.store.session(id),plan=this.budgetResumes().verify(session,input);return this.start(id,'',true,{resumePlan:plan});}
engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); }
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); }
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store, { redact: value => this.provider.redact(value) }); }
checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, {
taskPlans: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
skillRegistry() { return this.skills ??= new SkillRegistry(this.store, {
+10 -1
View File
@@ -1044,4 +1044,13 @@ F收尾:57d075e修正独立编译QA路径,6d09ac8封存差异;202610302320
2. [complete] Runtime实际提交/wire SHA/不可变请求核对、默认关闭与持久偏好、同Run回读、取消/迟到及故障隔离;最终独立后端23/23、相关95/95,来源区别见QA。
3. [complete] 原观察面板与工具箱设置,网页/实际Electron各7组通过;原失败、截图及最后后端补强来源分别保留,阶段回顾并提交。
4. [complete] 1.25.10两ZIP/784输入重建29文件、实际隔离安装/跨版保持、随包两端各7及核心10、正式安装318172ms和网页4/桌面5/严格final exact;137份81380817字节封存。
5. [pending] E经验草稿与可回滚采用,仅计划docs/EXPERIENCE-DRAFTS-E-PLAN.md。真实供应商、重复读取普遍改善与Purge收益不在D代签。
5. [in_progress] E经验草稿与可回滚采用,按docs/EXPERIENCE-DRAFTS-E-PLAN.md实施;真实供应商、重复读取普遍改善与Purge收益不在D/E代签。
## E阶段(2026-11-06)
1. [complete] 核心来源/状态/不可变修订与兼容已实现;首轮34/34及补强后17/17通过,QA记录阶段边界。
2. [in_progress] 原记忆面板与HTTP接入,来源选择/草稿编辑/采用/撤销/反例/失效,不增加工程执行批准。
3. [pending] 自有固定事实与实际HTTP请求差异、旧记忆兼容、异常隔离;网页、实际Electron和390px核心路径。
4. [pending] 独立源码/程序发行、隔离安装/跨版保持及正式入口验证,封存、回顾、提交、增量推送。
历史失败、unknown用量、网络异常和Purge收益unknown保持;本阶段不请求真实模型、不续跑旧实验/用户项目、不读真实Key、不委派,不恢复额度。
+165
View File
@@ -0,0 +1,165 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
import { createDeliveryProject, applyDeliveryFix } from './fixtures/delivery-project.mjs';
import { ProjectMemoryManager } from '../src/core/memory/project-memory.mjs';
import { DeliveryReporter } from '../src/core/delivery-report.mjs';
import { CheckRunner } from '../src/core/check-runner.mjs';
import { Store } from '../src/server/store.mjs';
const cursor = session => ({ taskId: session.taskId, runId: session.runId });
async function setup(t) {
const f = fixture(t, { modernDefaults: true }), manager = new ProjectMemoryManager(f.store);
const run = beginPlanTask(f, '解释原README,不修改,无需测试。');
run.usage = { requests: 1, inputTokens: 0, outputTokens: 0, totalTokens: 0, unknownRequests: 1, estimatedUnknownTokens: 121 };
run.stopReason = 'network_error'; f.store.save(f.session);
const report = await new DeliveryReporter(f.store).create(f.session);
const source = manager.experiences.sources(f.session).sources.find(value => value.id === report.artifactId);
return { ...f, manager, run, report, source,
create: () => manager.experiences.create(f.session, { cursor: cursor(f.session), source }),
change: (memory, action, fields = {}) => manager.experiences.change(f.session, memory.id, action,
{ cursor: cursor(f.session), revision: memory.experience.revision, ...fields }) };
}
test('experience drafts preserve original failures and unknown usage, deduplicate, persist and remain out of context even with full access', async t => {
const f = await setup(t), { memory } = await f.create();
assert.equal(f.store.config.approvalMode, 'ask'); f.store.saveConfig({ approvalMode: 'full' });
assert.equal(memory.origin, 'experience'); assert.equal(memory.experience.adoption, 'draft');
assert.deepEqual(memory.experience.stages, ['observed', 'source_checked']);
assert.equal(memory.experience.causalStatus, 'unproven'); assert.equal(memory.experience.engineering.verified, false);
assert.equal(memory.experience.provenance.facts.runs[0].usage.unknownRequests, 1);
assert.equal(memory.experience.provenance.facts.runs[0].stopReason, 'network_error');
assert.equal(memory.experience.provenance.scope.runId, f.run.id);
assert.equal(memory.experience.provenance.selection.sha256, f.source.sha256);
assert.equal(await f.manager.context(f.session), null);
const duplicate = await f.create(); assert.equal(duplicate.duplicate, true); assert.equal(duplicate.memory.id, memory.id);
assert.equal(f.store.core.memory.size, 1); assert.equal(f.store.core.artifact.get(memory.experience.artifactId).kind, 'experience-revision');
f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
const manager = new ProjectMemoryManager(reopened), view = await manager.list(f.project.id);
assert.equal(view.summary.drafts, 1); assert.equal(view.summary.current, 0);
assert.equal(view.memories[0].experience.revisions.length, 1); assert.equal(await manager.context(reopened.session(f.session.id)), null);
});
test('user adoption is independent from engineering verification; edits withdraw the active text and preserve every revision', async t => {
const f = await setup(t), { memory } = await f.create();
const active = await f.change(memory, 'adopt'); assert.equal(active.experience.adoption, 'active');
assert.ok(active.experience.stages.includes('user_confirmed')); assert.ok(!active.experience.stages.includes('engineering_verified'));
const sent = await f.manager.context(f.session); assert.equal(sent.entries[0].experience.revision, 2);
const edited = await f.change(active, 'edit', { title: '网络观测', content: '网络失败的原因尚未确定。', applicability: '本项目所选报告', invalidWhen: '新网络或源码证据出现' });
assert.equal(edited.experience.adoption, 'draft'); assert.equal(await f.manager.context(f.session), null);
assert.equal(edited.experience.revisions.length, 3); f.manager.experiences.verifySnapshot(edited);
const original = JSON.parse(f.store.artifactStore.read(f.store.core.artifact.get(memory.experience.artifactId)));
assert.equal(original.content, memory.content); assert.equal(original.experience.adoption, 'draft');
const readopted = await f.change(edited, 'adopt'), withdrawn = await f.change(readopted, 'withdraw');
assert.equal(withdrawn.experience.adoption, 'withdrawn'); assert.equal(await f.manager.context(f.session), null);
assert.equal(sent.entries[0].experience.adoption, 'active', 'past snapshots remain facts of their send time');
await assert.rejects(f.change(edited, 'adopt'), /已更新/);
});
test('counterexamples expire adoption, preserve the original failure and cannot claim engineering verification', async t => {
const f = await setup(t), active = await f.change((await f.create()).memory, 'adopt');
const expired = await f.change(active, 'counterexample', { note: '后续同条件仍失败,旧归因不成立。' });
assert.equal(expired.status, 'expired'); assert.equal(expired.experience.adoption, 'withdrawn');
assert.equal(expired.experience.counterexamples[0].engineeringVerified, false);
assert.equal(expired.experience.provenance.facts.runs[0].stopReason, 'network_error');
assert.equal(await f.manager.context(f.session), null); await assert.rejects(f.change(expired, 'adopt'), /已失效/);
});
test('foreign identities, stale source SHA, late cursor and stale revisions cannot change another experience', async t => {
const f = await setup(t), { memory } = await f.create();
const other = f.store.createSession(f.project.id, 'Another task');
await assert.rejects(f.manager.experiences.create(other, { source: f.source, cursor: cursor(other) }), /不属于/);
await assert.rejects(f.manager.experiences.change(other, memory.id, 'adopt', { cursor: cursor(other), revision: 1 }), /来源会话/);
await assert.rejects(f.manager.experiences.create(f.session, { cursor: cursor(f.session), source: { ...f.source, sha256: '0'.repeat(64) } }), /来源已变化/);
await assert.rejects(f.manager.experiences.change(f.session, memory.id, 'adopt', { cursor: { taskId: null, runId: null }, revision: 1 }), /已切换/);
const root = path.join(f.root, 'foreign'); fs.mkdirSync(root); fs.writeFileSync(path.join(root, 'README.md'), '# Other');
const foreign = f.store.createSession(f.store.addProject(root).id);
await assert.rejects(f.manager.experiences.create(foreign, { cursor: cursor(foreign), source: f.source }), /不属于/);
assert.equal(f.store.core.memory.get(memory.id).experience.revision, 1);
});
test('source changes, missing original bytes and changed source ownership exclude adopted experience', async t => {
for (const scenario of ['source', 'bytes', 'ownership', 'missing']) await t.test(scenario, async t => {
const f = await setup(t), active = await f.change((await f.create()).memory, 'adopt');
const artifact = f.store.core.artifact.get(f.source.id);
if (scenario === 'source') fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nchanged');
if (scenario === 'bytes') fs.writeFileSync(path.join(f.store.artifactStore.root, artifact.relative), 'tampered');
if (scenario === 'ownership') artifact.sessionId = f.store.createSession(f.project.id).id;
if (scenario === 'missing') fs.unlinkSync(path.join(f.store.artifactStore.root, artifact.relative));
assert.equal(await f.manager.context(f.session), null);
const view = await f.manager.list(f.project.id), expired = view.memories.find(value => value.id === active.id);
assert.equal(expired.status, 'expired'); assert.equal(expired.experience.provenance.selection.sha256, f.source.sha256);
assert.equal(expired.experience.revisions[0].artifactId, active.experience.revisions[0].artifactId);
});
});
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');
if (scenario === 'text') f.store.core.memory.get(active.id).content = 'Forged lesson';
else {
const id = scenario === 'current' ? active.experience.artifactId : active.experience.revisions[0].artifactId;
const artifact = f.store.core.artifact.get(id); fs.writeFileSync(path.join(f.store.artifactStore.root, artifact.relative), '{}');
}
assert.equal(await f.manager.context(f.session), null);
assert.notEqual((await f.manager.list(f.project.id)).memories[0].status, 'current');
});
});
test('experience persistence failure excludes optional content while manual memory compatibility remains intact', async t => {
const f = await setup(t), active = await f.change((await f.create()).memory, 'adopt');
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nchanged');
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 experience persistence failure');
return save(session, records, type, ...rest);
};
assert.equal(await f.manager.context(f.session), null);
assert.equal(f.store.core.memory.get(active.id).status, 'current', 'failed saves cannot silently rewrite stored history');
f.store.storage.save = save;
const manual = await f.manager.create(f.session, { title: '手动约定', content: '保留当前项目约定。' });
const context = await f.manager.context(f.session); assert.deepEqual(context.entries.map(value => value.id), [manual.id]);
assert.equal(manual.origin, 'user'); assert.equal(manual.schemaVersion, 1);
});
test('rejected and archived experience is not silently reactivated by duplicate generation', async t => {
const f = await setup(t), rejected = await f.change((await f.create()).memory, 'reject');
assert.ok(rejected.experience.stages.includes('rejected')); assert.equal((await f.create()).memory.id, rejected.id);
await assert.rejects(f.change(rejected, 'adopt'), /拒绝/);
const archived = await f.change(rejected, 'archive'); assert.equal(archived.status, 'archived');
assert.equal((await f.create()).memory.experience.adoption, 'withdrawn'); assert.equal(await f.manager.context(f.session), null);
});
test('tools without source fingerprints remain historical drafts and do not manufacture checked engineering outcomes', async t => {
const f = await setup(t), tool = completeRead(f);
const source = f.manager.experiences.sources(f.session).sources.find(value => value.kind === 'tool' && value.id === tool.id);
const { memory } = await f.manager.experiences.create(f.session, { cursor: cursor(f.session), source });
assert.equal(memory.experience.provenance.facts.tool, 'read_file'); assert.equal(memory.status, 'expired');
assert.equal(memory.experience.engineering.verified, false); assert.equal(await f.manager.context(f.session), null);
});
test('actual original failed and passing check jobs remain distinct; engineering verification never certifies edited conclusions', async t => {
const f = fixture(t), manager = new ProjectMemoryManager(f.store), checks = new CheckRunner(f.store);
f.onCleanup(() => checks.stopAll()); createDeliveryProject(f);
const failed = await (await checks.start(f.session, (await checks.plan(f.session)).id)).promise;
assert.equal(failed.status, 'failed');
const source = manager.experiences.sources(f.session).sources.find(value => value.id === failed.id);
const original = (await manager.experiences.create(f.session, { source, cursor: cursor(f.session) })).memory;
assert.equal(original.experience.provenance.facts.check.results[0].tests.failed, 3);
assert.equal(original.experience.engineering.verified, false);
applyDeliveryFix(f);
const passed = await (await checks.start(f.session, (await checks.plan(f.session)).id)).promise;
assert.equal(passed.status, 'passed');
const passedSource = manager.experiences.sources(f.session).sources.find(value => value.id === passed.id);
const fresh = (await manager.experiences.create(f.session, { source: passedSource, cursor: cursor(f.session) })).memory;
assert.equal(fresh.experience.engineering.verified, true); assert.equal(fresh.experience.engineering.conclusionVerified, false);
assert.ok(fresh.experience.stages.includes('engineering_verified'));
const report = await new DeliveryReporter(f.store).create(f.session);
const reportSource = manager.experiences.sources(f.session).sources.find(value => value.id === report.artifactId);
const reportDraft = (await manager.experiences.create(f.session, { source: reportSource, cursor: cursor(f.session) })).memory;
assert.deepEqual(reportDraft.experience.provenance.facts.checks.map(value => value.status), ['failed', 'passed']);
assert.equal(f.store.core.memory.get(original.id).content, original.content);
});