feat: v0.7.3 成本收口 · 状态一致 · 死账清理 — Prompt Cache 根治 + SSRF DNS Pinning + 87 用例扩充全量回归
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m47s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s
CI / 产物编译验证 (push) Successful in 9m55s

P1 修复面收口: Prompt Cache 根治(日期/记忆/附件三类易变内容出 system 入用户消息
  前置块 user-context.ts, system 跨 run 字节级稳定; Anthropic system 块数组化 +
  cache_control ephemeral 断言, DeepSeek 自动缓存前缀命中 — 多轮对话输入 token
  成本降数量级); 编辑重发/重新生成幽灵 Trace 双侧根治(DB truncateMessagesAfter
  同步过滤 metadata.traceSteps + 前端 trimTraceStepsByAnchor 镜像, 严格小于锚点
  时间戳, 同毫秒等值判废); sessions:deleteMessage 死通道全链路删除(渲染层零调用
  + message_count 漂移面); Ollama vision 能力门控全链路(MetonaModelInfo
  .supportsVision 贯穿 adapter/IPC/store/UI, model-capabilities.ts 三道判定纯函数,
  未知保守放行); 记忆固化节流(consolidation-policy 纯函数: 总开关 + 内容门控
  [回答>=200字符或存在成功工具调用] + 会话级 10 分钟频率窗口, 三 memory.* 配置键)

P2 安全纵深: SSRF DNS Pinning 关闭 rebinding 窗口(ssrf-guard 重构
  resolvePublicAddresses 单源; ssrf-dispatcher 以 undici Agent.connect.lookup
  钉死校验 IP, TLS SNI 保持原域名, 一次性 dispatcher 用后即毁; 代理激活显式
  退化为仅入口校验); web_fetch 重写手动逐跳重定向循环(每跳先校验后连接,
  替代 redirect:follow 内核跟跳的中间跳裸奔, 上限 5 跳); http_request 换用
  pinned fetch; web_search 可达性预检加固(私有 URL 零请求 + 不跟跳, 3xx 视为
  可达); Agent 浏览器 CORS 通配收紧为 Origin 回显 + Vary: Origin;
  ConfirmationHook.forgetSession 会话终态清理(会话删除/abort 联动/SubAgent
  终结三处接线, 根治 rememberedDecisions 泄漏)

P3 架构还债: agent.enableReflection 死配置全链路接线(main→shared→引擎→
  Orchestrator→设置开关, REFLECTING 状态真实可达); AgentLoopConfig.timeoutMs
  死字段删除; MemoryManager.cleanupExpired 挂入健康检查周期(expires_at 回收
  管道真实化); buildSafeEnv 收敛 utils/safe-env.ts 单源(run_command 与 MCP
  stdio 共用, 终结双实现漂移); Trace 生命周期治理(metadata 只保留最近 20 个
  run — keepRecentRuns 纯函数; JSONL 录制启动自动清理保留 200 个 + 设置页
  手动清理); SLO/健康快照可视化(app:healthSnapshot IPC + 设置页只读卡片 +
  审计链一键校验)

P4 能力演进: 会话标题 LLM 自动生成(TitleGenerator — 每会话幂等/并发重入复用
  同一 Promise/自定义标题不覆盖/失败静默回退, Sidebar 经 config:changed 实时
  刷新); MCP 自动重连(5s/15s/60s 退避最多 3 次, reconnecting 状态机,
  teardownConnection 内部拆除保留簿记 — 用户断开/开关关闭即时取消, 设置页
  显示第 N/3 次); 死循环检测 ABAB 乒乓模式(最近4轮 A→B→A→B 交替判定, 补齐
  docs 第五章"两状态反复切换"检测契约); i18n 第三阶段(ChatInput/LLMSettings/
  OnboardingWizard/MemoryViewer 主链路文案出层, zh-CN + en-US 双字典补齐)

测试: 737 → 824 用例(+87, 新增 8 个测试文件 + 扩展 3 个)。新覆盖: user-context
  分组/空值收缩/拼接契约、context-builder 字节级稳定性、Anthropic cache_control
  四态、consolidation-policy 九路判定矩阵、ssrf-dispatcher(pinned lookup/重定向
  解析/IP 校验)、forget-session 会话隔离、trace-lifecycle run 淘汰、
  trace-trim 严格小于边界、safe-env 净化矩阵、mcp-reconnect 退避状态机
  (fake timers)、title-generator 并发重入、SQLite 侧 truncate×TRACE 联动
  (Electron ABI)。测试驱动修复: GIT_*/ 注释终止块注释、重连计数被自身重试
  前置断开重置(拆 teardownConnection 保留簿记)、TitleGenerator 幂等占位与
  并发去重的检查顺序竞态(去重先于幂等)

版本: 0.7.3; README 同步(配置表新增 agent.enableReflection/memory.*/mcp.autoReconnect)

回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 771 通过 53 跳过
  (better-sqlite3 ABI); Electron ABI 全量 824/824 零跳过
This commit is contained in:
2026-08-30 09:44:43 +08:00
parent 26169b7be4
commit ebe45482b0
68 changed files with 4568 additions and 664 deletions
@@ -64,11 +64,23 @@ describe('ContextBuilder — isUsingFallbackRole 首次降级通知语义', () =
});
describe('ContextBuilder — 动态区注入', () => {
it('注入当前日期时间(含本地时区', () => {
it('v0.7.3 P1-1: 不再注入日期时间(prompt cache 前缀稳定性', () => {
const cb = new ContextBuilder();
const prompt = cb.buildSystemPrompt({ soul: 'x', memory: '' });
expect(prompt.dynamicReminders).toContain('## Current Date & Time');
expect(prompt.dynamicReminders).toMatch(/UTC[+-]/);
expect(prompt.dynamicReminders).not.toContain('## Current Date & Time');
expect(prompt.dynamicReminders).not.toMatch(/UTC[+-]/);
});
it('v0.7.3 P1-1: system 输出跨调用字节级稳定(同输入 → 同字节)', () => {
const cb = new ContextBuilder();
const files = { soul: 'x', memory: '## 用户偏好\n- 偏好深色主题' };
const a = cb.buildSystemPrompt(files, '/tmp/ws-demo');
const b = cb.buildSystemPrompt(files, '/tmp/ws-demo');
// 跨 run 缓存命中的前提:四分区逐字节一致(日期时间已移入用户消息前置块)
expect(a.roleDefinition).toBe(b.roleDefinition);
expect(a.outputConstraints).toBe(b.outputConstraints);
expect(a.safetyGuidelines).toBe(b.safetyGuidelines);
expect(a.dynamicReminders).toBe(b.dynamicReminders);
});
it('注入工作空间路径(动态区,路径可切换)', () => {
@@ -0,0 +1,94 @@
/**
* 用户上下文前置块测试(v0.7.3 P1-1
*
* 锁定三类动态内容(日期时间 / 记忆 / 附件提示)在用户消息前置块的
* 分组结构与空值收缩行为 —— 它们从 system prompt 迁出的契约面。
*/
import { describe, it, expect } from 'vitest';
import { buildUserContextPrefix, withUserContextPrefix } from '../user-context';
describe('buildUserContextPrefix', () => {
it('恒含头部说明与日期时间分区(唯一无条件分区)', () => {
const prefix = buildUserContextPrefix({ now: Date.UTC(2026, 7, 30, 6, 30) });
expect(prefix).toContain('[Contextual information for this message');
expect(prefix).toContain('## Current Date & Time');
});
it('无记忆/附件时不产出对应分区(空值收缩)', () => {
const prefix = buildUserContextPrefix({ now: Date.now() });
expect(prefix).not.toContain('## Relevant Memories (Retrieved)');
expect(prefix).not.toContain('## User Attachments (Direct Upload)');
});
it('记忆分区:条目格式与截断口径(沿用原 system 注入契约)', () => {
const prefix = buildUserContextPrefix({
now: Date.now(),
memories: [
{
id: 'm1',
type: 'semantic',
content: 'x'.repeat(500),
source: 'agent_thought',
importance: 0.9,
score: 0.8,
createdAt: Date.now(),
},
],
});
expect(prefix).toContain('## Relevant Memories (Retrieved)');
expect(prefix).toMatch(/\[1\] \(semantic, 重要度: 0\.9\)/);
// 内容截断到 200 字符
expect(prefix).toContain('x'.repeat(200));
expect(prefix).not.toContain('x'.repeat(201));
});
it('附件分区:图片提示禁止重复读图;文本截断标记透传', () => {
const prefix = buildUserContextPrefix({
now: Date.now(),
attachments: [
{ name: 'shot.png', type: 'image' },
{ name: 'big.log', type: 'text', truncated: true },
],
});
expect(prefix).toContain('## User Attachments (Direct Upload)');
expect(prefix).toContain('1. [image] shot.png');
expect(prefix).toContain('do NOT call view_image');
expect(prefix).toContain('2. [text file] big.log');
expect(prefix).toContain('TRUNCATED — only the first 512KB is included');
});
it('分区以 --- 分隔且以前缀分隔符收尾(调用方可直接拼接用户内容)', () => {
const prefix = buildUserContextPrefix({
now: Date.now(),
memories: [
{
id: 'm',
type: 'episodic',
content: 'c',
source: 'user_input',
importance: 0.5,
score: 0.5,
createdAt: Date.now(),
},
],
attachments: [{ name: 'a.txt', type: 'text' }],
});
expect(prefix).toMatch(/---\s*$/);
// 三个分区恰好两个内部 --- + 收尾 1 个 ---(共 3 个独立行)
expect(prefix.match(/^---$/gm)?.length ?? 0).toBe(3);
});
});
describe('withUserContextPrefix', () => {
it('前置块与用户内容拼接(前置块自带收尾分隔符)', () => {
const prefix = buildUserContextPrefix({ now: Date.now() });
const out = withUserContextPrefix(prefix, '你好,帮我写个脚本');
expect(out.startsWith(prefix)).toBe(true);
expect(out.endsWith('你好,帮我写个脚本')).toBe(true);
});
it('空前缀原样返回(契约防御)', () => {
expect(withUserContextPrefix('', 'hello')).toBe('hello');
});
});
+18 -17
View File
@@ -58,7 +58,10 @@ export class ContextBuilder {
*
* v0.3.14: 移除 AGENTS.md 和 USERS.md 的读取,SOUL.md 仅做角色定义
*/
buildSystemPrompt(workspaceFiles?: WorkspaceFiles, workspacePath?: string): {
buildSystemPrompt(
workspaceFiles?: WorkspaceFiles,
workspacePath?: string,
): {
roleDefinition: string;
outputConstraints: string;
safetyGuidelines: string;
@@ -76,23 +79,19 @@ export class ContextBuilder {
// ===== 动态区:记忆 =====
const dynamicParts: string[] = [];
// v0.3.14: 注入当前系统日期时间(每次构建时获取最新时间)
// 用于让 AI 准确理解"今天"、"昨天"等相对时间表达
// #43 修复: 时区硬编码 Asia/Shanghai 改为使用系统本地时区,跨时区用户显示正确
const now = new Date();
const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'Asia/Shanghai';
// 审查修复: 恢复 UTC 偏移显示,在时区名后附加 UTC 偏移,避免丢失时区偏移信息
const offset = -now.getTimezoneOffset() / 60;
const offsetStr = offset >= 0 ? `UTC+${offset}` : `UTC${offset}`;
const dateTimeStr = now.toLocaleString('zh-CN', {
timeZone: localTimezone,
hour12: false,
});
dynamicParts.push(`## Current Date & Time\n${dateTimeStr} (${localTimezone}, ${offsetStr})`);
// v0.7.3 P1-1 根治: 当前日期时间不再注入 system prompt —— 此前每次构建都
// 产生不同字节(秒级时间戳 + 时区),导致跨 run 的 system 前缀永不一致,
// DeepSeek 自动上下文缓存 / Anthropic 显式缓存全部 miss。现移入用户消息
// 前置块(@see user-context.ts),system 保持跨 run 字节级稳定。
// MEMORY.md 的 `> 创建时间/最后更新` 元数据行由 extractContent 剥离,
// 正文提取不受时间戳更新影响 —— 此处无需额外处理。
// 注入当前工作空间路径(动态区,路径可能切换故不放入静态区
// 注入当前工作空间路径(动态区,路径可能切换故不放入静态区
// 会话期间路径恒定,不破坏缓存)
if (workspacePath) {
dynamicParts.push(`## Current Workspace\nWorkspace root path: \`${workspacePath}\`\n\nAll relative paths in tool calls are resolved against this workspace root. Use this path when absolute paths are required (e.g., in run_command).`);
dynamicParts.push(
`## Current Workspace\nWorkspace root path: \`${workspacePath}\`\n\nAll relative paths in tool calls are resolved against this workspace root. Use this path when absolute paths are required (e.g., in run_command).`,
);
}
if (workspaceFiles?.memory) {
@@ -138,7 +137,9 @@ export class ContextBuilder {
} else {
// v0.3.18 修复: 降级时打 WARN 日志 + 设置标志,供 IPC 层读取后发 toast
this.lastUsedFallbackRole = true;
log.warn('[ContextBuilder] SOUL.md is missing or empty, falling back to default Metona identity');
log.warn(
'[ContextBuilder] SOUL.md is missing or empty, falling back to default Metona identity',
);
// 兜底身份定义(Metona 灵魂定义)
parts.push(`# Metona — 灵魂定义
> "想清楚再动手,做对比做快重要"
+140
View File
@@ -0,0 +1,140 @@
/**
* User Context Prefix — 每条用户消息的系统上下文前置块(v0.7.3 P1-1 根治)
*
* 背景(Prompt Cache 被打穿的根因):
* 此前「当前日期时间」「检索到的相关记忆」「附件提示」三类**每条消息都在变**
* 的内容被追加进 systemPrompt.dynamicReminders —— OpenAI 兼容系将其拼进首条
* system 消息、Anthropic 写入顶层 system 字段。任何一次变化都会使整个 system
* 前缀失配,DeepSeek 自动上下文缓存 / Anthropic 显式缓存全部 miss。长 system
* SOUL + 安全准则 + MEMORY.md)× 每 run 最多 20 轮迭代 × 全量重算输入 token,
* 成本与首字延迟被系统性放大。
*
* 现契约(单一事实来源):
* - system prompt 只保留跨 run 字节级稳定的内容(SOUL / 约束 / 安全准则 /
* 工作空间路径 / MEMORY.md 正文——其易变的 `> 最后更新` 元数据行本就被
* extractContent 剥离);Anthropic 侧对该稳定前缀打 cache_control 断言;
* - 易变内容(日期时间 / 记忆 / 附件提示)由本模块构建为**用户消息前置块**,
* 随当次请求注入首条 user 消息(LLM 语义等价:Claude Code 同款上下文注入位);
* - DB 持久化 / 前端展示 / 记忆固化 / 注入检测均使用**原始干净内容**,
* 前置块只存在于发给引擎的副本上。
*
* 纯函数、零副作用:可在 node vitest 下直接表测(稳定性/分组/空值收缩)。
*/
import type { SearchResult } from '../memory/manager';
/** 附件提示所需的元信息子集(与 agent-store AttachmentInfo 对齐的渲染端子集) */
export interface AttachmentHint {
name: string;
type: string;
truncated?: boolean;
}
export interface UserContextPrefixInput {
/** 当前时间戳(前置块内降精度到分钟,减少无意义抖动) */
now?: number;
/** 检索到的相关记忆(空数组时不产出记忆分区) */
memories?: SearchResult[];
/** 用户附件元信息(空数组/undefined 时不产出附件分区) */
attachments?: AttachmentHint[];
/**
* 时区标签(如 "Asia/Shanghai (UTC+8)")。
* 由调用方计算(Intl.DateTimeFormat().resolvedOptions().timeZone)——
* 本模块保持纯函数语义,不做 Electron/Intl 环境依赖。
*/
timezoneLabel?: string;
}
/** 记忆注入条目的内容截断(与原 dynamicReminders 注入口径一致) */
const MEMORY_EXCERPT_CHARS = 200;
/** 附件提示上限(与输入侧 5 个附件的硬上限对齐) */
const MAX_ATTACHMENT_HINTS = 8;
/**
* 构建用户消息上下文前置块。
*
* 输出形态(各分区以 `\n\n---\n\n` 分隔,整体以分隔符结尾,
* 调用方直接 `${prefix}${userContent}` 拼接):
* ```
* [Contextual information for this message — system-generated metadata, not part of the user's request.]
*
* ## Current Date & Time
* 2026/8/30 14:30:00 (Asia/Shanghai, UTC+8)
*
* ---
*
* ## Relevant Memories (Retrieved)
* [1] (semantic, 重要度: 0.9) ...
*
* ---
*
* ## User Attachments (Direct Upload)
* ...
* ```
*/
export function buildUserContextPrefix(input: UserContextPrefixInput): string {
const parts: string[] = [];
// ===== 分区 1:当前日期时间(降精度到分钟) =====
const now = input.now ?? Date.now();
const timezoneLabel = input.timezoneLabel ?? 'UTC';
const dateStr = new Date(now).toLocaleString('sv-SE', {
timeZone: undefined,
hour12: false,
}); // sv-SE 给出 ISO 形态 "2026-08-30 14:30:00"
parts.push(`## Current Date & Time\n${dateStr} (${timezoneLabel})`);
// ===== 分区 2:相关记忆注入(沿用原 system 注入的展示口径) =====
const memories = (input.memories ?? []).slice(0, 5);
if (memories.length > 0) {
const memorySection = memories
.map(
(m, i) =>
`[${i + 1}] (${m.type}, 重要度: ${m.importance.toFixed(1)}) ${m.content.slice(0, MEMORY_EXCERPT_CHARS)}`,
)
.join('\n');
parts.push(`## Relevant Memories (Retrieved)\n${memorySection}`);
}
// ===== 分区 3:附件提示(沿用原 system 注入的语义与文案契约) =====
const attachments = (input.attachments ?? []).slice(0, MAX_ATTACHMENT_HINTS);
if (attachments.length > 0) {
const attachmentList = attachments
.map((att, i) => {
const typeLabel =
att.type === 'image' ? 'image' : att.type === 'text' ? 'text file' : 'file';
// 文本附件被上传入口截断(512KB 上限)时,明确告知 LLM 内容不完整,
// 防止模型把残缺内容当作完整文件事实(v0.7.2 A5 契约延续)
const truncatedNote =
att.truncated === true
? ' (TRUNCATED — only the first 512KB is included; the full content is NOT available)'
: '';
const note =
att.type === 'image'
? 'already provided to you via vision capability — you can SEE it directly, do NOT call view_image or any tool to read it again'
: att.type === 'text'
? `content${truncatedNote} already inlined in the user message, do NOT search in workspace or read it again`
: 'uploaded directly by user, do NOT search in workspace';
return `${i + 1}. [${typeLabel}] ${att.name}${note}`;
})
.join('\n');
parts.push(
`## User Attachments (Direct Upload)\nThe following files were uploaded directly by the user to this conversation. They are inline attachments, NOT workspace files:\n${attachmentList}\n\n**IMPORTANT**: Images listed above are already visible to you in this conversation. Do NOT call \`view_image\`, \`read_file\`, or any file tool to read them — doing so wastes a tool call and may fail (they are not workspace files).`,
);
}
const header =
"[Contextual information for this message — system-generated metadata, not part of the user's request.]";
return `${header}\n\n${parts.join('\n\n---\n\n')}\n\n---\n\n`;
}
/**
* 将前置块与用户原始内容拼装为发送给引擎的消息内容。
* 空前缀(理论上不会发生——日期分区恒存在,但契约上防御)时原样返回。
*/
export function withUserContextPrefix(prefix: string, userContent: string): string {
if (!prefix) return userContent;
return `${prefix}${userContent}`;
}