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
+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, {