feat: add source-bound project memory
This commit is contained in:
@@ -6,6 +6,8 @@
|
||||
|
||||
下一阶段[1.12执行方案](PLAN-1.12.md)按连接注册/专业界面、模型池、配置导入、运行巡检四个切片推进。轮询、跨品牌协议、多模态、自动导入和其他长期能力在各自实现与实际验证前均为计划。
|
||||
|
||||
2026-10-30源码进度:fb58a41已实现多连接、兼容Chat协议池路由、已确认格式导入与只读巡检;仍未作为新不可变发行部署。新增项目记忆管理支持跨会话查看、来源/工程指纹、到期/归档与不完整扫描降级,7项专项和全量312/312通过,桌面/390px已核对。模型上下文接入、真实模型池任务和WorkBuddy未知schema继续单独验收。
|
||||
|
||||
## 1. 能力的完成定义
|
||||
|
||||
“研究到机制”“模块实现”“契约检查通过”“真实工程验收通过”分别登记。只有实现进入产品、相关检查通过、用户场景有实际结果,才标为可交付。外部客户端的能力和本地其他项目中的模块,也分别记录,不能计入工作台现有能力。
|
||||
@@ -103,7 +105,7 @@
|
||||
| C02 执行状态与恢复 | 会话JSON保存,active/waiters在内存;重启不重放命令 | 独立Task/Run/Step身份、持久事件、检查点与未知结果核对 | CC-2、CU-1、DS-1 / storage、tasks / M1 | 在审批、调用、结果与落盘等切点中断;恢复不重复已完成副作用 |
|
||||
| C03 工程识别与索引 | 提供有界文件清单/文本搜索,没有工程索引 | 识别语言、入口、规则、脚本、依赖和Git;增量索引;符号/引用与必要的语义检索 | CU-2、DS-3 / context / M2 | 对Node/React/Python样本定位实际修改入口;代码变动后索引更新 |
|
||||
| C04 上下文与项目归属 | 有提取式消息投影、运行诊断和当前项目资料 | 为Run组合需求、规则、代码、错误与验证结果;引用来源;严格绑定项目 | CC-2、CU-1 / context、contracts / M1–M2 | 切换两个项目/任务后,错误与工具结果仍归属正确;大输出用工件引用 |
|
||||
| C05 长期项目记忆 | 保存聊天历史,没有可检验的长期事实 | 记住决策、约束、失败与有效做法;附commit/文件来源;失效重检;压缩保留目标和未完成项 | CC-2、WB-1 / context、storage / M4 | 长任务压缩/重启后完成标准不丢;过期代码事实被更新或标记 |
|
||||
| C05 长期项目记忆 | 项目所属持久条目、来源/工程指纹、到期/归档与不完整扫描降级已实现;尚未进入模型上下文 | 记住决策、约束、失败与有效做法;来源重检、上下文预算与压缩保留目标和未完成项 | CC-2、WB-1 / context、storage / M4 | 长任务压缩/重启后完成标准不丢;过期代码事实被更新或标记 |
|
||||
| C06 工具、Skills与MCP | 固定6工具,没有动态注册或外部工具契约 | 工具注册、schema与能力声明;版本锁定Skills/MCP;安装/调用有来源和范围 | CC-1、CU-1、WB-2 / tools / M3 | 未知工具、错误参数、工具失联有原调用身份;新工具可按契约接入 |
|
||||
| C07 执行控制 | 文件范围/基线检查、逐次命令确认与进程停止 | 操作范围、授权记录、预算、进程所有权、并发准入和取消传播;沿用用户已授权的范围 | CC-1、CU-1、DS-1 / tools、tasks / M1–M4 | 过期授权不能用于新Run;停止只处理所属任务;修改后的输入重新校验 |
|
||||
| C08 精确编辑与多文件变更 | 完整替换单文件提案,有备份与冲突拒绝 | patch、创建/改名/删除、多文件ChangeSet、基线校验、隔离应用与可恢复合并 | CU-2 / workspaces / M2 | 跨4文件修改保留无关内容;外部改动引起冲突;部分失败有明确状态 |
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
|
||||
A–D分别提交和验收。A先建立注册与归属,B依赖A,C使用A的连接契约,D贯穿每一切片;每次正式升级继续使用不可变发行目录和全量数据核对。新的真实模型验收在连接与用户安排就绪后执行。
|
||||
|
||||
2026-10-30开发状态:A–D首个切片已本地提交fb58a41,支持兼容Chat协议连接注册、内存凭据、轮询/权重与故障切换、已验证CCSwitch/工作台JSON导入及只读运行巡检。WorkBuddy schema、更多协议、真实模型与正式发行仍待单独验收。
|
||||
|
||||
项目记忆管理切片已完成项目隔离、来源SHA256/工程指纹、显式到期/归档和扫描不完整时的unverified状态;专项7/7、桌面/390px和固定环境全量312/312通过。当前记忆不进入通用执行快照,也尚未进入模型请求;下一切片仅在来源重新核对且完整预算允许时纳入上下文。源码核对表示来源仍匹配,不能证明用户记忆内容的业务结论正确。
|
||||
|
||||
## 专业界面与操作结构
|
||||
|
||||
用户需要持续交付工程的工作空间。桌面采用坚实的工程控制台:蓝黑文字、钢灰底、清楚的实体面板和高辨识操作状态;减少小字号、低对比细线和大块无用途留白。数字只显示实际量测结果。
|
||||
|
||||
@@ -338,3 +338,10 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- `ConfigImporter.apply` 保留既有来源自动同步偏好;同步只在来源指纹变化时导入,来源不变也更新`lastCheckedAt`。手动修改后的连接不被自动同步覆盖,并报告冲突;凭据始终只写入Provider内存。
|
||||
- 独立UI验收的可访问标签在原页面使用自定义label结构,模型池/连接操作按实际DOM定位;桌面1440px和手机390px截图均核对无横向溢出。巡检报告明确`modelRequests=0`。
|
||||
- 1.12代码仍未作为不可变发行部署;真实模型、WorkBuddy schema、加密凭据、多模态和移动远程配对属于后续切片,不能从本地夹具通过推断完成。
|
||||
|
||||
## 2026-10-30 项目记忆切片接续
|
||||
|
||||
- 项目记忆已保存在已有SQLite memory记录类型中,保留创建会话/Task/Run、来源和工程指纹;源码变化和到期持久化为memory.expired,显式归档需要来源会话。
|
||||
- 不完整工程扫描会将当前条目展示为unverified并禁止新增;明确引用的文件即使被清单排除,也单独比较SHA256。普通executionSnapshot不暴露记忆,因此inspect_session不能绕过复核。
|
||||
- 固定Node v24.22.1和隔离Python 3.10.11/pytest8.4.2后,全量312/312通过,0失败/取消/跳过,580409.4888ms。此前缺pytest失败仍保留;本次测试运行未写独立完整TAP,不冒称已有原TAP文件。
|
||||
- 项目记忆管理/界面通过不代表已进入模型上下文;下一切片需对current、来源完整性、字节/条目预算、数据标记和provider.redact建立真实本地HTTP请求证据。
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@
|
||||
"verify:browser": "node scripts/verify-browser.mjs",
|
||||
"verify:browser-ui": "node scripts/verify-browser-ui.mjs",
|
||||
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs",
|
||||
"verify:model-center": "node scripts/verify-model-center-ui.mjs"
|
||||
"verify:model-center": "node scripts/verify-model-center-ui.mjs",
|
||||
"verify:project-memory": "node scripts/verify-project-memory-ui.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
|
||||
@@ -380,3 +380,9 @@
|
||||
- 本地巡检只读检查Node、SQLite、最近工件和模型配置,不发送模型请求、不执行项目命令;前端专业模型中心覆盖桌面和390px窄屏。
|
||||
- 固定Node `v24.22.1`并设置隔离Python `3.10.11/pytest 8.4.2`后完整回归 **305/305通过**;最终构建通过。模型中心专项7/7通过;独立桌面/390px验收5组通过,0页面错误、0请求失败、0巡检模型请求。证据目录:`.qa/model-center-ui-69ae2c90-cd8d-461f-86ca-d598f56ce15e`。
|
||||
- 首轮304项的2项pytest失败是环境未注入解释器,已原样保留;本轮不覆盖该诊断。正式4318未重启、不读取Key、不发真实模型请求。
|
||||
# 2026-10-30 项目记忆接续
|
||||
|
||||
- 恢复fb58a41后的未提交记忆管理切片,读取AGENTS.md和既有计划;正式4318保持原服务和凭据,不执行真实模型调用。
|
||||
- 全量回归使用C:/Program Files/nodejs/node.exe v24.22.1及.qa/dev-task-plans/.qa/python-3.10/Scripts/python.exe:312通过,0失败/取消/跳过,耗时580409.4888ms,退出码0。本次原输出在执行工具记录中,未生成完整TAP文件。
|
||||
- 之前构建、7项记忆专项与1440px/390px界面验收已完成;界面证据为.qa/project-memory-ui-004a0733-3aa5-4a13-b8be-7c120a84d7a8/result.json。
|
||||
- 当前完成范围是持久记忆管理与来源失效;模型上下文接入仍待实现,先整理文档和本地提交,再独立验证下一切片。
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { chromium, expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench } from '../tests/helpers.mjs';
|
||||
|
||||
const evidenceDir = path.resolve('.qa', 'project-memory-ui-' + randomUUID());
|
||||
fs.mkdirSync(evidenceDir, { recursive: true });
|
||||
const disposers = [], t = { after: dispose => disposers.push(dispose) };
|
||||
const f = fixture(t); f.store.close();
|
||||
const host = await launchWorkbench(t, f.data);
|
||||
assert.notEqual(new URL(host.url).port, '4318');
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const project = f.project, session = f.session;
|
||||
const pageErrors = [], requestFailures = [], marks = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message));
|
||||
page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText));
|
||||
const mark = value => { marks.push(value); console.log('PASS ' + value); };
|
||||
|
||||
try {
|
||||
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); },
|
||||
{ projectId: project.id, sessionId: session.id });
|
||||
await page.goto(host.url); await page.waitForLoadState('networkidle');
|
||||
await page.getByRole('button', { name: '项目记忆', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '项目记忆', exact: true }); await expect(dialog).toBeVisible();
|
||||
await expect(dialog.locator('.memory-editor')).toBeVisible();
|
||||
const editor = dialog.locator('.memory-editor');
|
||||
await editor.getByLabel('标题', { exact: true }).fill('文件来源记忆');
|
||||
await editor.getByLabel('来源文件(可选)', { exact: true }).fill('README.md');
|
||||
await editor.getByLabel('内容', { exact: true }).fill('这条事实绑定README的实际字节和项目源码指纹。');
|
||||
await editor.getByRole('button', { name: '保存记忆', exact: true }).click();
|
||||
const firstCard = dialog.locator('.memory-card').filter({ hasText: '文件来源记忆' });
|
||||
await expect(firstCard).toContainText('当前'); await expect(firstCard).toContainText('来源 SHA');
|
||||
const initialExecution = await host.api('/sessions/' + session.id + '/execution');
|
||||
assert.equal(Object.hasOwn(initialExecution, 'memories'), false);
|
||||
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nExternal fixture change.\n');
|
||||
await dialog.getByRole('button', { name: '重新核对', exact: true }).click();
|
||||
await expect(firstCard).toContainText('已过期'); await expect(firstCard).toContainText('来源文件已变化');
|
||||
assert.equal((await host.api('/projects/' + project.id + '/memories')).summary.expired, 1);
|
||||
mark('source hashes remain visible and a changed file is explicitly expired with retained provenance');
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'desktop-expired-memory.png') });
|
||||
|
||||
await editor.getByLabel('标题', { exact: true }).fill('扫描范围记忆');
|
||||
await editor.getByLabel('来源文件(可选)', { exact: true }).fill('');
|
||||
await editor.getByLabel('内容', { exact: true }).fill('不完整工程扫描时不能把记忆冒充当前事实。');
|
||||
await editor.getByRole('button', { name: '保存记忆', exact: true }).click();
|
||||
const currentCard = dialog.locator('.memory-card').filter({ hasText: '扫描范围记忆' });
|
||||
await expect(currentCard).toContainText('当前');
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'oversized-source.mjs'), Buffer.alloc(1024 * 1024 + 1));
|
||||
await dialog.getByRole('button', { name: '重新核对', exact: true }).click();
|
||||
await expect(dialog.locator('.memory-scope-warning')).toContainText('源码扫描未覆盖完整工程');
|
||||
await expect(currentCard).toContainText('扫描不完整');
|
||||
await expect(editor.getByRole('button', { name: '保存记忆', exact: true })).toBeDisabled();
|
||||
const incomplete = await host.api('/projects/' + project.id + '/memories');
|
||||
assert.equal(incomplete.summary.current, 0); assert.equal(incomplete.summary.unverified, 1);
|
||||
assert.equal(incomplete.memories.find(value => value.title === '扫描范围记忆').status, 'unverified');
|
||||
assert.equal((await host.api('/sessions/' + session.id + '/execution')).memories, undefined);
|
||||
mark('incomplete inventory marks existing facts unverified and blocks new saves');
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390), '390px viewport must not overflow horizontally');
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'mobile-incomplete-memory.png'), fullPage: false });
|
||||
mark('390px memory review stays within the viewport with the incomplete-scan warning visible');
|
||||
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
|
||||
fs.writeFileSync(path.join(evidenceDir, 'result.json'), JSON.stringify({ url: host.url, viewportWidths: [1440, 390],
|
||||
assertions: marks, pageErrors, requestFailures, screenshots: ['desktop-expired-memory.png', 'mobile-incomplete-memory.png'] }, null, 2));
|
||||
console.log('EVIDENCE ' + evidenceDir);
|
||||
} finally {
|
||||
await browser.close();
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
}
|
||||
+5
-2
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Activity, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
|
||||
import { Activity, Brain, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
|
||||
import type { Bootstrap, Change, Config, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
|
||||
import { api, downloadBlob, exportSession, setToken } from './api';
|
||||
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
|
||||
@@ -10,6 +10,7 @@ import { ChangesInspector } from './ChangesInspector';
|
||||
import { ResearchPanel } from './ResearchPanel';
|
||||
import { EnginePanel } from './EnginePanel';
|
||||
import { ModelCenter } from './ModelCenter';
|
||||
import { ProjectMemoryPanel } from './ProjectMemoryPanel';
|
||||
|
||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
|
||||
@@ -66,6 +67,7 @@ export default function App() {
|
||||
const [reaOpen, setReaOpen] = useState(false);
|
||||
const [engineOpen, setEngineOpen] = useState(false);
|
||||
const [modelCenterOpen, setModelCenterOpen] = useState(false);
|
||||
const [memoryOpen, setMemoryOpen] = useState(false);
|
||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
||||
const chatEnd = useRef<HTMLDivElement>(null);
|
||||
@@ -500,7 +502,7 @@ export default function App() {
|
||||
if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path);
|
||||
}}>{file.kind === 'directory' ? <><span className="tree-chevron">{collapsed.has(file.path) ? <ChevronRight size={11} /> : <ChevronDown size={11} />}</span><Folder size={14} /></> : <><span className="tree-chevron" /><File size={13} /></>}<span>{filter ? file.path : file.name}</span></button>)}{filter && !visibleFiles.length && <p className="sidebar-hint">没有匹配的文件。</p>}</div>
|
||||
</div>
|
||||
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button onClick={openSettings}><Settings2 size={16} />模型连接<ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<small>v{version}</small></div></div>
|
||||
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button onClick={openSettings}><Settings2 size={16} />模型连接<ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<small>v{version}</small></div></div>
|
||||
</aside>
|
||||
<main className="task-pane">
|
||||
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
|
||||
@@ -552,6 +554,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} /></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} onConfig={setConfig} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
|
||||
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与决策绑定源码指纹,变化后自动要求重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel project={selectedProject} session={session} /></Modal>}
|
||||
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.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}
|
||||
@@ -0,0 +1,52 @@
|
||||
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 { api } from './api';
|
||||
import './ProjectMemory.css';
|
||||
|
||||
const statusLabel: Record<string, string> = { current: '当前', unverified: '扫描不完整', expired: '已过期', archived: '已归档' };
|
||||
|
||||
export function ProjectMemoryPanel({ project, session }: { project: Project; session: Session | null }) {
|
||||
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 [draft, setDraft] = useState({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' });
|
||||
const alive = useRef(true);
|
||||
const load = async () => {
|
||||
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); }
|
||||
};
|
||||
useEffect(() => { alive.current = true; void load(); return () => { alive.current = false; }; }, [project.id]);
|
||||
const create = async (event: FormEvent) => {
|
||||
event.preventDefault(); if (!session || !draft.content.trim()) return;
|
||||
setWorking(true); setError(''); setNotice('');
|
||||
try {
|
||||
await api('/sessions/' + session.id + '/memories', { title: draft.title || '未命名记忆', content: draft.content, tags: draft.tags.split(',').map(value => value.trim()).filter(Boolean), ...(draft.sourcePath.trim() ? { source: { kind: 'file', path: draft.sourcePath.trim() } } : {}), ...(draft.expiresAt ? { expiresAt: new Date(draft.expiresAt).toISOString() } : {}) });
|
||||
if (alive.current) { setDraft({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' }); setNotice('记忆已保存,并绑定当前源码指纹。'); await load(); }
|
||||
} catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆保存失败。'); }
|
||||
finally { if (alive.current) setWorking(false); }
|
||||
};
|
||||
const archive = async (memory: ProjectMemory) => {
|
||||
if (!session) return;
|
||||
setWorking(true); setError('');
|
||||
try { await api('/sessions/' + session.id + '/memories/' + memory.id + '/archive', {}); if (alive.current) { setNotice('已归档这条记忆。'); await load(); } }
|
||||
catch (cause) { if (alive.current) setError(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>
|
||||
{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 && !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>
|
||||
<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>;
|
||||
}
|
||||
@@ -101,6 +101,9 @@ export interface ContextHistory { planId: string; groups: ContextHistoryGroup[];
|
||||
export interface Task { id: string; goal: string; status: string; instructions: { id: string; content: string; createdAt: string; source?: string }[]; usage: Usage; budget: { maxTokens: number }; verification: { status: string; checkJobId: string | null }; origin: string; workspaceIdentity?: WorkspaceIdentity }
|
||||
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 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 } };
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { safePath } from '../../server/files.mjs';
|
||||
import { isId } from '../../shared/contracts/execution.mjs';
|
||||
|
||||
const MAX_TITLE = 240;
|
||||
const MAX_CONTENT = 16000;
|
||||
const MAX_TAGS = 12;
|
||||
const MAX_TAG = 48;
|
||||
const MAX_MEMORIES = 500;
|
||||
const sourceKinds = new Set(['project', 'file', 'artifact', 'session', 'task', 'run']);
|
||||
const at = () => new Date().toISOString();
|
||||
const memoryError = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const text = (value, maximum) => String(value ?? '').trim().slice(0, maximum);
|
||||
|
||||
function normalizeSource(source, session, store, inspection) {
|
||||
const value = source && typeof source === 'object' && !Array.isArray(source) ? source : {};
|
||||
const kind = text(value.kind || 'session', 20);
|
||||
if (!sourceKinds.has(kind)) throw memoryError('项目记忆来源类型不受支持。');
|
||||
const result = { kind, sourceFingerprint: inspection.sourceFingerprint };
|
||||
if (kind === 'file') {
|
||||
const relative = text(value.path, 1000).replaceAll('\\', '/');
|
||||
if (!relative) throw memoryError('文件来源需要相对路径。');
|
||||
const filename = safePath(store.project(session.projectId), relative, true);
|
||||
if (!fs.existsSync(filename) || !fs.lstatSync(filename).isFile()) throw memoryError('文件来源不存在或不是普通文件。', 404);
|
||||
const bytes = fs.readFileSync(filename);
|
||||
result.path = relative;
|
||||
result.sha256 = sha256(bytes);
|
||||
} else if (kind === 'artifact') {
|
||||
if (!isId(value.id)) throw memoryError('工件来源身份无效。');
|
||||
const artifact = store.core.artifact.get(value.id);
|
||||
if (!artifact || artifact.projectId !== session.projectId || artifact.sessionId !== session.id) throw memoryError('工件来源不属于当前项目或会话。', 404);
|
||||
result.id = artifact.id; result.kind = 'artifact'; result.artifactKind = artifact.kind; result.sha256 = artifact.sha256;
|
||||
} else if (kind === 'session') {
|
||||
const sourceSessionId = value.id === undefined ? session.id : value.id;
|
||||
if (!isId(sourceSessionId)) throw memoryError('会话来源身份无效。');
|
||||
const sourceSession = store.sessions.get(sourceSessionId);
|
||||
if (!sourceSession || sourceSession.projectId !== session.projectId) throw memoryError('会话来源不属于当前项目。', 404);
|
||||
result.id = sourceSessionId; result.label = sourceSession.title;
|
||||
} else if (kind === 'task') {
|
||||
const taskId = value.id === undefined ? session.taskId : value.id;
|
||||
if (!isId(taskId)) throw memoryError('任务来源需要已有任务。');
|
||||
const task = store.core.task.get(taskId);
|
||||
if (!task || task.projectId !== session.projectId || task.sessionId !== session.id) throw memoryError('任务来源不属于当前项目或会话。', 404);
|
||||
result.id = taskId; result.label = task.goal?.slice(0, 240);
|
||||
} else if (kind === 'run') {
|
||||
const runId = value.id === undefined ? session.runId : value.id;
|
||||
if (!isId(runId)) throw memoryError('运行来源需要已有运行。');
|
||||
const run = store.core.run.get(runId);
|
||||
if (!run || run.projectId !== session.projectId || run.sessionId !== session.id) throw memoryError('运行来源不属于当前项目或会话。', 404);
|
||||
result.id = runId; result.label = run.id;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function publicMemory(memory) {
|
||||
return structuredClone(memory);
|
||||
}
|
||||
|
||||
export class ProjectMemoryManager {
|
||||
constructor(store) { this.store = store; }
|
||||
|
||||
async inspect(projectId) {
|
||||
return inspectProject(this.store.project(projectId));
|
||||
}
|
||||
|
||||
async list(projectId, { includeExpired = true } = {}) {
|
||||
const project = this.store.project(projectId);
|
||||
const inspection = await inspectProject(project);
|
||||
const now = Date.now();
|
||||
const values = [...this.store.core.memory.values()]
|
||||
.filter(value => value.projectId === projectId)
|
||||
.sort((a, b) => (b.updatedAt || b.createdAt).localeCompare(a.updatedAt || a.createdAt));
|
||||
let changed = 0;
|
||||
const presented = [];
|
||||
for (const memory of values) {
|
||||
if (memory.status === 'archived') { presented.push(publicMemory(memory)); continue; }
|
||||
const timedOut = memory.expiresAt && Date.parse(memory.expiresAt) <= now;
|
||||
const fileSourceChanged = memory.source.kind === 'file' && this.fileSourceChanged(project, memory.source);
|
||||
const sourceChanged = fileSourceChanged || inspection.scope.complete && memory.sourceFingerprint !== inspection.sourceFingerprint;
|
||||
if ((sourceChanged || timedOut) && memory.status !== 'expired') {
|
||||
memory.status = 'expired';
|
||||
memory.expiredAt = at();
|
||||
memory.updatedAt = memory.expiredAt;
|
||||
memory.expiredReason = timedOut ? '记忆已到期,需重新核对后使用。'
|
||||
: fileSourceChanged ? '来源文件已变化、删除或不再是普通文件,需重新核对这条记忆。'
|
||||
: '工程源码指纹已变化,需重新核对这条记忆。';
|
||||
const session = this.store.sessions.get(memory.sessionId);
|
||||
if (session) this.store.putRecord('memory', session, memory, 'memory.expired');
|
||||
changed++;
|
||||
}
|
||||
const value = publicMemory(memory);
|
||||
if (memory.status === 'current' && !inspection.scope.complete) value.status = 'unverified';
|
||||
presented.push(value);
|
||||
}
|
||||
const memories = presented.filter(value => includeExpired || value.status === 'current').slice(0, MAX_MEMORIES);
|
||||
return {
|
||||
projectId, sourceFingerprint: inspection.sourceFingerprint, inspectedAt: inspection.inspectedAt,
|
||||
scope: inspection.scope, memories,
|
||||
summary: { current: presented.filter(value => 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 },
|
||||
rule: '源码指纹变化或到期后,记忆只能作为历史记录查看;源码扫描不完整时,不将其标为当前事实。',
|
||||
};
|
||||
}
|
||||
|
||||
async create(session, input = {}) {
|
||||
const project = this.store.project(session.projectId);
|
||||
const inspection = await inspectProject(project);
|
||||
if (!inspection.scope.complete) throw memoryError('本次工程源码扫描不完整,暂不能保存绑定工程版本的项目记忆;请先缩小工程范围或排除超预算文件。', 409);
|
||||
const title = text(input.title || '未命名记忆', MAX_TITLE);
|
||||
const content = String(input.content ?? '').trim();
|
||||
if (!content || content.length > MAX_CONTENT) throw memoryError('项目记忆内容不能为空且不能超过16000字符。');
|
||||
if (title.length < 1) throw memoryError('项目记忆标题不能为空。');
|
||||
const tags = Array.isArray(input.tags) ? [...new Set(input.tags.map(value => text(value, MAX_TAG)).filter(Boolean))].slice(0, MAX_TAGS) : [];
|
||||
if (input.tags !== undefined && !Array.isArray(input.tags)) throw memoryError('项目记忆标签需要数组。');
|
||||
let expiresAt = null;
|
||||
if (input.expiresAt !== undefined && input.expiresAt !== null && input.expiresAt !== '') {
|
||||
const parsed = Date.parse(String(input.expiresAt));
|
||||
if (!Number.isFinite(parsed)) throw memoryError('记忆到期时间无效。');
|
||||
expiresAt = new Date(parsed).toISOString();
|
||||
}
|
||||
const source = normalizeSource(input.source, session, this.store, inspection);
|
||||
const memory = {
|
||||
schemaVersion: 1, id: randomUUID(), projectId: session.projectId, sessionId: session.id,
|
||||
taskId: session.taskId ?? null, runId: session.runId ?? null, title, content,
|
||||
tags, source, sourceFingerprint: inspection.sourceFingerprint, status: 'current',
|
||||
createdAt: at(), updatedAt: at(), expiresAt, expiredAt: null, expiredReason: null, origin: 'user',
|
||||
};
|
||||
this.store.putRecord('memory', session, memory, 'memory.created');
|
||||
return publicMemory(memory);
|
||||
}
|
||||
|
||||
fileSourceChanged(project, source) {
|
||||
if (!source.path || !/^[a-f0-9]{64}$/i.test(source.sha256 ?? '')) return true;
|
||||
try {
|
||||
const filename = safePath(project, source.path, true);
|
||||
if (!fs.existsSync(filename) || !fs.lstatSync(filename).isFile()) return true;
|
||||
return sha256(fs.readFileSync(filename)) !== source.sha256;
|
||||
} catch { return true; }
|
||||
}
|
||||
|
||||
archive(session, id) {
|
||||
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 (memory.status !== 'archived') {
|
||||
memory.status = 'archived'; memory.updatedAt = at(); memory.archivedAt = memory.updatedAt;
|
||||
this.store.putRecord('memory', session, memory, 'memory.archived');
|
||||
}
|
||||
return publicMemory(memory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export function publicProjectMemory(value) { return publicMemory(value); }
|
||||
+25
-1
@@ -9,6 +9,7 @@ import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -33,6 +34,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);
|
||||
|
||||
function json(response, value, status = 200) {
|
||||
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
|
||||
@@ -72,6 +74,28 @@ return async (request, response) => {
|
||||
const method = request.method;
|
||||
const route = url.pathname;
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: true, uptimeMs: Date.now() - started });
|
||||
const projectMemoryMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/memories$/i);
|
||||
if (projectMemoryMatch && method === 'GET') {
|
||||
const includeExpired = url.searchParams.get('include_expired') !== '0';
|
||||
return json(response, await memories.list(projectMemoryMatch[1], { includeExpired }));
|
||||
}
|
||||
const sessionMemoryMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories$/i);
|
||||
if (sessionMemoryMatch && method === 'GET') {
|
||||
const session = store.session(sessionMemoryMatch[1]);
|
||||
const includeExpired = url.searchParams.get('include_expired') !== '0';
|
||||
return json(response, await memories.list(session.projectId, { includeExpired }));
|
||||
}
|
||||
const sessionMemoryArchiveMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories\/([a-f0-9-]+)\/archive$/i);
|
||||
if (sessionMemoryArchiveMatch && method === 'POST') {
|
||||
const session = store.session(sessionMemoryArchiveMatch[1]);
|
||||
await body(request);
|
||||
return json(response, memories.archive(session, sessionMemoryArchiveMatch[2]));
|
||||
}
|
||||
if (sessionMemoryMatch && method === 'POST') {
|
||||
const session = store.session(sessionMemoryMatch[1]);
|
||||
const input = await body(request);
|
||||
return json(response, await memories.create(session, input), 201);
|
||||
}
|
||||
if (route.startsWith('/api/model-center')) {
|
||||
const hub = provider.modelHub(store);
|
||||
const importer = () => hub.importer ??= new ConfigImporter(hub);
|
||||
@@ -119,7 +143,7 @@ return async (request, response) => {
|
||||
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
|
||||
environment: executionEnvironment(),
|
||||
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
|
||||
capabilities: { workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
capabilities: { workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
});
|
||||
if (method === 'GET' && route === '/api/diagnostics') {
|
||||
const selected = url.searchParams.get('session');
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
|
||||
export const EXECUTION_SCHEMA = 1;
|
||||
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof'];
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory'];
|
||||
export const timestamp = () => new Date().toISOString();
|
||||
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# Agent Workbench:核心代理能力研究与产品计划
|
||||
|
||||
## 2026-10-30 当前接续:项目记忆与上下文
|
||||
|
||||
1. [complete] 接续fb58a41后的项目记忆管理:项目隔离、来源/源码指纹、到期/归档、扫描不完整降级与桌面/390px界面;固定Node24/Python3.10环境全量312/312通过。
|
||||
2. [in_progress] 更新真实完成范围与本地提交;正式4318保持不可变1.11,不重启、不读取凭据、不发真实模型请求。
|
||||
3. [pending] 仅将重新核对为current的记忆加入有界模型上下文,保留来源、数据边界、凭据脱敏与完整请求预算;捕获实际本地HTTP请求验证隔离和排除规则。
|
||||
4. [pending] 接续长任务压缩/恢复、隔离worker、动态Skills/MCP及桌面/移动切片,按依赖和原结果逐项验收,不把计划或夹具结果登记为真实模型交付。
|
||||
|
||||
## 当前执行:1.11本地交付完成,1.12-A/B/C/D进入实现与验收
|
||||
|
||||
最新接续:main已封存1.11交付2bd7d48及报告散列修复0442c48;正式4318为1.11.0/PID19084,15项目/26全部会话(19可见/7归档)。原PID23080在断线期间退出,PID19084沿用原数据。验收期间公开hasKey由false变为true,升级保留原Provider和当前公开配置;本轮0模型请求,真实模型续接按用户选择暂缓。
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, launchWorkbench } from './helpers.mjs';
|
||||
import { ProjectMemoryManager } from '../src/core/memory/project-memory.mjs';
|
||||
|
||||
test('project memories persist across restart, keep source provenance, and are visible across tasks', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const created = await manager.create(f.session, { title: '接口约束', content: '本地服务只接受带工作台令牌的请求。', tags: ['架构', '安全'], source: { kind: 'file', path: 'README.md' } });
|
||||
assert.equal(created.status, 'current'); assert.equal(created.projectId, f.project.id); assert.equal(created.source.kind, 'file');
|
||||
assert.equal(created.source.path, 'README.md'); assert.match(created.source.sha256, /^[a-f0-9]{64}$/);
|
||||
const before = await manager.list(f.project.id); assert.equal(before.summary.current, 1); assert.equal(before.memories[0].content, created.content);
|
||||
f.store.close(); const reopened = new (f.store.constructor)(f.data); f.onCleanup(() => reopened.close());
|
||||
const restored = await new ProjectMemoryManager(reopened).list(f.project.id);
|
||||
assert.equal(restored.summary.current, 1); assert.equal(restored.memories[0].id, created.id);
|
||||
const second = reopened.createSession(f.project.id, '另一个任务'); f.onCleanup(() => reopened.close());
|
||||
const crossTask = await new ProjectMemoryManager(reopened).list(second.projectId);
|
||||
assert.equal(crossTask.memories.some(value => value.id === created.id), true);
|
||||
});
|
||||
|
||||
test('source changes expire current project memories and keep the original evidence', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const created = await manager.create(f.session, { title: '读取范围', content: 'README 是当前项目的说明入口。' });
|
||||
const cursor = f.store.eventCursor;
|
||||
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nChanged outside the workbench.\n');
|
||||
const after = await manager.list(f.project.id);
|
||||
const expired = after.memories.find(value => value.id === created.id);
|
||||
assert.equal(expired?.status, 'expired'); assert.match(expired?.expiredReason ?? '', /源码指纹/);
|
||||
assert.equal(expired?.sourceFingerprint, created.sourceFingerprint);
|
||||
assert.ok(f.store.eventCursor > cursor);
|
||||
assert.ok(f.store.eventsAfter(cursor).events.some(event => event.type === 'memory.expired' && event.payload?.recordId === created.id));
|
||||
assert.equal((await manager.list(f.project.id, { includeExpired: false })).memories.length, 0);
|
||||
});
|
||||
|
||||
test('incomplete source scans mark current memories unverified without expiring or reusing them', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const created = await manager.create(f.session, { title: '项目事实', content: '这条记忆绑定完整的工程快照。' });
|
||||
const oversized = path.join(f.projectRoot, 'oversized-source.mjs'); fs.writeFileSync(oversized, Buffer.alloc(1024 * 1024 + 1));
|
||||
const partial = await manager.list(f.project.id);
|
||||
assert.equal(partial.scope.complete, false); assert.equal(partial.summary.current, 0); assert.equal(partial.summary.unverified, 1);
|
||||
assert.equal(partial.memories.find(value => value.id === created.id)?.status, 'unverified');
|
||||
assert.equal(f.store.core.memory.get(created.id)?.status, 'current');
|
||||
assert.equal((await manager.list(f.project.id, { includeExpired: false })).memories.length, 0);
|
||||
await assert.rejects(manager.create(f.session, { content: '不能绑定不完整的工程快照。' }), /扫描不完整/);
|
||||
fs.rmSync(oversized);
|
||||
const restored = await manager.list(f.project.id);
|
||||
assert.equal(restored.scope.complete, true); assert.equal(restored.memories.find(value => value.id === created.id)?.status, 'current');
|
||||
});
|
||||
|
||||
test('explicit file provenance is rechecked even when the inventory excludes that path', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const filename = path.join(f.projectRoot, 'node_modules', 'owned-fixture', 'entry.mjs');
|
||||
fs.mkdirSync(path.dirname(filename), { recursive: true }); fs.writeFileSync(filename, 'export const value = 1;\n');
|
||||
const created = await manager.create(f.session, { title: '依赖入口', content: '这条记忆明确引用了文件内容。', source: { kind: 'file', path: 'node_modules/owned-fixture/entry.mjs' } });
|
||||
fs.writeFileSync(filename, 'export const value = 2;\n');
|
||||
const after = await manager.list(f.project.id);
|
||||
const expired = after.memories.find(value => value.id === created.id);
|
||||
assert.equal(after.scope.complete, true); assert.equal(expired?.status, 'expired'); assert.match(expired?.expiredReason ?? '', /来源文件已变化/);
|
||||
});
|
||||
|
||||
test('execution snapshots do not expose project memories before their source scope is validated', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const created = await manager.create(f.session, { title: '仅在项目页可见', content: '未验证前不能进入模型运行上下文。' });
|
||||
assert.equal(Object.hasOwn(f.store.executionSnapshot(f.session), 'memories'), false);
|
||||
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nExternal source change.\n');
|
||||
assert.equal(Object.hasOwn(f.store.executionSnapshot(f.session), 'memories'), false);
|
||||
const view = await manager.list(f.project.id);
|
||||
assert.equal(view.memories.find(value => value.id === created.id)?.status, 'expired');
|
||||
});
|
||||
|
||||
test('project memory records stay isolated and archive requires the owning session', async t => {
|
||||
const f = fixture(t), manager = new ProjectMemoryManager(f.store);
|
||||
const otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); fs.writeFileSync(path.join(otherRoot, 'README.md'), '# Other\n');
|
||||
const other = f.store.addProject(otherRoot), otherSession = f.store.createSession(other.id);
|
||||
const created = await manager.create(f.session, { title: '仅当前项目', content: '只属于第一个项目。' });
|
||||
assert.equal((await manager.list(other.id)).memories.length, 0);
|
||||
assert.throws(() => manager.archive(otherSession, created.id), /项目记忆不存在/);
|
||||
const archived = manager.archive(f.session, created.id); assert.equal(archived.status, 'archived');
|
||||
assert.equal((await manager.list(f.project.id)).memories[0].status, 'archived');
|
||||
});
|
||||
|
||||
test('project memory HTTP API exposes read-only source status and explicit writes', async t => {
|
||||
const f = fixture(t); f.store.close(); const host = await launchWorkbench(t, f.data); f.onCleanup(host.close);
|
||||
const project = await host.api('/projects', { root: f.projectRoot });
|
||||
const session = await host.api('/sessions', { projectId: project.id });
|
||||
const created = await host.api('/sessions/' + session.id + '/memories', { title: 'HTTP memory', content: 'Stored through the owned API.', source: { kind: 'project' } });
|
||||
assert.equal(created.status, 'current'); assert.equal(created.sourceFingerprint.length, 64); assert.equal(JSON.stringify(created).includes('apiKey'), false);
|
||||
const listed = await host.api('/projects/' + project.id + '/memories'); assert.equal(listed.summary.current, 1); assert.equal(listed.memories[0].id, created.id);
|
||||
const archived = await host.api('/sessions/' + session.id + '/memories/' + created.id + '/archive', {}); assert.equal(archived.status, 'archived');
|
||||
await host.close();
|
||||
});
|
||||
Reference in New Issue
Block a user