Runtime 存储
源码目录:packages/desktop-runtime/src/adapters/store/
Runtime 把不同数据域分开持久化,使迁移、恢复和排障可以按领域进行。Thread event log 是线程状态真源,其他 store 不应暗中修改 thread snapshot。
数据布局
runtime-factory.ts 把选定 data root 的 runtime/ 作为 store 根。主要数据域如下,按首次使用创建,并非完整文件清单:
runtime/
├── config.json
├── secrets.json
├── features/ # Feature settings documents
├── secrets/ # versioned Feature secrets
├── projects.json
├── mcp.json
├── skills.json
├── plugins.json
├── user-skills/
├── plugin-skill-overrides/
├── plugins/
├── plugin-repositories/ # marketplace cache
├── attachments/
├── generated-images/
├── pc-local-policies/
├── memories/
├── usage.jsonl
├── threads.sqlite
├── threads/ # legacy import source
├── worktrees/ # managed workspace forks
├── workspace-dependencies/ # managed toolchains and package cache
└── temporary-workspace/准确受管文件名以 storage-file-name.ts、各 store 和 main data-root manifest 为准。
JSON 基础
json-file.ts
为小型 store 提供:
- JSON 读取。
- 缺失/default。
- 临时文件 + rename 原子写入。
- 错误保留上下文。
Store 自己负责 schema normalize,不能把任意 parsed object 直接当 contract state。
file-state-coordinator.ts
串行化同一文件的状态读写,避免多个 async mutation 基于旧 snapshot 互相覆盖。
storage-file-name.ts / security/runtime-id.ts
把 runtime ID 规范化为安全文件名,拒绝路径分隔符和逃逸。用户/模型给出的 ID 不能直接拼路径。
Config 与 secrets
file-config-store.ts
负责:
- Config defaults/normalize/save。
- Provider、models、task models。
- Approval、permission、style、global prompt、feature flags。
- Hooks 与 desktop/runtime settings。
- 对外 state 脱敏。
- Global prompt 等字段长度限制。
config.json 不保存 provider key;secrets.json 保存 provider API key 等 runtime 凭据,写入后尝试 chmod 0600,内容未经过 OS 加密。MCP 等使用 main credential vault 的凭据通过 native bridge 读写,不能把两种存储混为一谈。
Input 中未提供 key 表示不覆盖;不能把 UI 空输入误解释为删除已有 key。
Feature settings 与 secret revisions
packages/desktop-runtime/src/features/settings/file-feature-settings-registry.ts 将文档写入 features/<feature-id>/settings/<document-id>.json,记录 schema version、revision 和 secret revision 引用。配置的校验、迁移及 portable 属性由所属 Feature 声明,Core config store 只保留兼容迁移所需字段。
versioned-file-secret-store.ts 将敏感字段分离到 secrets/<feature-id>/<document-id>/ 下的版本文件,使用 0600 权限和 staged/finalize/recover 流程。它同样是本机 JSON 存储,不等同于 main 的 safeStorage vault;公开 settings 投影只包含脱敏信息。
SQLite thread store
sqlite-thread-store.ts
主线程数据库:
- WAL。
- Foreign keys。
- Transactions。
- Runtime owner lease/fencing。
- Thread summary。
- Snapshot checkpoint。
- Durable lifecycle events + bounded transient
runtime_eventstail。 - 独立
thread_messages顺序索引,用于游标分页。
关键字段/约束:
(thread_id, seq)唯一。- Event ID 唯一。
threads.last_seq。- Snapshot JSON +
snapshot_seq。 events_archived_through_seq与message_index_seq。runtime_ownerlease。
Append
事件和流式批次在事务中:
- 校验 owner/fencing,分配连续 seq。
- 写事件并用 reducer 更新内存投影;大于 4 KiB 的 JSON 在压缩确实更小时存为 gzip BLOB,小记录仍是 TEXT。
- 更新轻量线程摘要。生命周期边界同时推进检查点;其他记录按默认 1 秒窗口合并检查点。
- Commit 后发布整批事件。批次失败不发布其中任何事件,也不提交半批记录。
commitContextCompaction 在同一线程写入队列内验证捕获的活跃前缀指纹、检查点身份、
历史改写序号、取消和合并后预算,再写 thread.context_compacted。
覆盖范围随事件持久化,投影保留期间追加的完整后缀。候选过期返回未提交结果,
不使共享 event writer 进入故障状态;其模型 usage 独立记账。
thread.context_usage_calibrated 随事件立即落盘,但沿用 telemetry 的延迟检查点策略,
不因每次模型 usage 校准而额外强制重写线程检查点;事件尾部可以恢复该基线。
检查点使用 snapshot_format = 2:
threads.snapshot_json只保存线程头部和消息/回合数量,不再包含完整历史。thread_messages保存有序消息;thread_turn_checkpoints保存有序回合。- 同一检查点的头部、变化消息、变化回合和
snapshot_seq在一个事务中更新。 - Copy-on-write 引用用于跳过未改变的旧消息和旧回合。流式消息行按检查点更新,不随每个 delta 重写。
- 回合的采样步骤诊断引用
turn.step_snapshot事件,恢复时通过专用索引读取;原生 provider metadata 与完整步骤仍可恢复。 - 部分旧快照中的步骤早于事件日志,无法完整引用时保留内联记录。
消息分页读取当前缓存投影,包含已提交但尚未写入检查点的事件尾部;搜索合并缓存中的最新消息, 因此不需要通过读请求强制刷盘。采样仍只读取消息及必要线程状态。
message.delta、reasoning/item/plan delta、tool preview/output delta 在检查点后移入 gzip archive,
保留连续 seq 和无损事件重放。SSE 超过热尾保留边界时返回 canonical snapshot resync。
回合结算、取消和 Goal 核算按事件类型/turn 查询持久记录,不再解压无关的流式归档。
v5 移除事件 ID ledger 上重复的 seq 唯一索引;事件 ID 仍由 ledger 主键保证唯一, seq 由事件表主键保证唯一。大事件可以混合 TEXT 与 gzip BLOB。
Recovery
- 取得/续租 runtime owner。
- 拒绝第二个有效 runtime。
- 读取检查点头部、消息和回合,并恢复被引用的采样步骤。
- 重放
snapshot_seq后的 event tail。 - v1 → v2 原地增加 retention marker 和 message index;首次读取旧 thread 时回填索引。
- v4 → v5 在取得 runtime owner 后升级 schema;旧单体快照在首次读取对应会话时,事务内转换为分行检查点并压缩大事件。
- 释放的 SQLite 页先供后续写入复用;物理文件缩小需要离线
VACUUM,正常对话热路径不执行全库整理。 - 结算 stale streaming turn 由 server lifecycle 完成。
启动时需要读取哪些数据
Goal 和 Collaboration 的 Feature 投影使用 SQLite feature_projection_checkpoints 保存状态与已处理事件序号。读取时先校验 Feature 自己的 codec 和带 reducer 版本的 key,再回放检查点之后的事件;首次访问、版本变化或缓存损坏时从历史事件重建。检查点只是可重建缓存,历史事件仍是真源。Core 异常 turn 结算和 Goal 恢复仍在 runtime ready 前完成;Collaboration 的执行/交付账本仅在访问对应父线程时修复,不进行启动全量扫描。事件高水位直接查询线程序号,不加载或复制完整聊天记录。
异常 turn 结算从 store 提取活动 turn ID。分区 checkpoint 的小型 recovery 摘要随 checkpoint 一起保存活动 turn ID 和生成图片引用;只有 checkpoint 序号等于最新事件序号时才能使用。旧 checkpoint 缺少摘要时读取一次消息/turn 状态并补齐摘要,不还原历史模型请求快照或填充完整会话缓存;旧版快照或尚未 checkpoint 的事件尾仍走完整迁移和回放。Goal 启动恢复直接读取已枚举线程的 Feature 投影,不为检查线程存在而再次读取完整会话。
生成图片清理先枚举本地 asset ID,再读取 checkpoint 的图片引用摘要;旧 store 可回退到单个会话的一致消息快照,避免分页期间消息变动导致漏掉引用。没有本地图片时不读取历史,已找到全部候选引用时提前结束扫描。
消息分页在完整 checkpoint 上按消息索引只读取请求区间。页面含需要推断阶段的旧助手消息或需要结算取消状态的工具时,回退到完整消息投影;未完成 checkpoint 的事件尾仍先回放,保证分页与完整会话的内容一致。Automation 启动迁移先只检查首条消息,私有 seed 匹配后才读取旧欢迎消息,避免读取无关会话的后续正文。
Legacy JSON import
legacy-json-thread-reader.ts 支持旧 threads/*.json/.jsonl:
- 首次 SQLite 启动只读导入。
- 不截断旧文件。
- 不双写。
- 缺号/乱序等无法证明的损坏停止迁移。
- 有连续后续事件且最终 snapshot 可佐证时,特定重复 seq 可 last-writer-wins,并记录被替换信息。
Legacy import 测试使用冻结的历史 JSON/JSONL fixture,避免由当前实现动态生成旧格式而掩盖兼容性回归。
Attachments
file-attachment-store.ts:
- 本地文件只保存原路径引用和 metadata,不复制源文件;只有无本地路径的图片保存受管字节。
- 本地引用解析为精确文件的 direct-tool-only readable root,不进入 shell sandbox plan,也不新增写权限;已有 workspace/writable-root 权限仍适用。删除引用或 thread 不会删除用户的原文件。
- 受管图片验证名称、MIME 以及 PNG/JPEG/GIF/WebP 的真实文件签名;本地链接不设大小上限,无路径图片的单次托管请求保留独立的内存安全边界。
- 临时 asset 在 turn/thread 认领后转为持久化归属。
- Recovery 清理无主或不完整 staging。
- Thread 删除/消息截断时由协调层清理不再引用 asset。
本地路径不是 attachment ID,也不会进入 renderer 状态或线程事件。
Generated images
file-generated-image-store.ts:
- 保存图片 generation 的 managed asset。
- 校验受支持格式和大小。
- 提供 renderer preview / model attachment 读取。
- Recovery 根据 thread store 中仍被引用的 asset ID 保留,清理孤儿。
memory-phase2-workspace.ts 与 generated image 不属于同一生命周期。
MCP
file-mcp-store.ts:
mcp.json兼容mcpServers和 legacyservers。- 对外传输类型为
stdio或streamableHttp,存储适配器兼容旧配置拼写。 enabled控制服务器是否启用,allowedTools和disabledTools确定可用工具。启动和调用各有超时设置。可写字段见 MCP 配置契约。- Env/header secret 通过 native bridge/store 分离。
- List 只返回 key,不返回 value。
- 启动时迁移 legacy secrets。
MCP connection 由 packages/features/mcp/src/runtime 在内存中管理,不持久化 socket/session;FileMcpStore 与 legacy secret migration 仍由 desktop runtime 宿主持有。
Memory
file-memory-store.ts
Active root 固定为:
runtime/memories/支持:
- Global / project scope。
- Active / passive origin。
- Source thread/turn。
- Title、tags、summary。
- Query、create/delete/clear。
- Preview。
旧外部 storagePath 由 Electron main 的维护模式导入;正常 runtime 不再读取外部旧目录。
相关 helper
file-memory-store-model.ts:数据 normalize/merge。memory-storage-root.ts:active root ownership marker。memory-phase2-workspace.ts:增量 consolidation 的内部 workspace/baseline。
清空 memory 要验证 active root marker,不能接受任意路径。
Usage
packages/features/usage/src/runtime/file-usage-store.ts:
- Append-only
usage.jsonl。 - 按 thread/provider/model/time 查询。
- Summary/bucket 聚合。
- 带有
usageContext的模型调用结束时写一条记录,包括失败和取消;未报告的 Token 保持缺失,不能伪造为零。 source、result、durationMs均为可选字段,旧汇总记录无需迁移。- Config provider metadata 用于安全展示,不保存 API key。
模型调用 adapter 仅依赖 Core UsageRecorder 窄口;composition 在 Usage Runtime Feature 激活后把
usage.control 绑定到稳定 recorder proxy。查询、分页、bucket 聚合和持久化实现都不在 Core runtime。
请求记录写入成功后,宿主为仍存在的线程追加 usage.recorded Feature 事件。Usage renderer 通过现有事件订阅
重新查询当前线程用量,不依赖主回答的 turn.completed 或标题是否被采用;事件只用于失效通知,
Core reducer 仅推进序列,不将标题消耗计入主回答的 usage。
部分写入/坏尾行需要有明确读取策略,不能让一条坏记录抹掉全部历史。
Policy stores
file-persistent-tool-approval-store.ts
用户批准可持久化的操作后,工具审批协调器在这里保存相应的键。后续遇到同一组键时可以复用授权。MCP 服务器的启用状态和工具范围保存在 mcp.json。
file-policy-amendment-store.ts
保存 runtime permission/policy amendment。
旧 PC local exec/shell policy 只从 runtime/pc-local-policies/ 加载;main 负责从旧 home 路径维护导入。
Workspace project
FileWorkspaceProjectStore 位于 adapters/workspace/,但持久化 projects.json:
- Project ID/path/name/git root。
- List/add/archive/remove。
- 文件 list/read/search 限制在 project root。
- Temporary workspace 也通过 port 统一管理。
Search 实现独立为 WorkspaceSearchEngine,不把 ripgrep process 状态写入 project JSON。
Skill 与 Plugin
它们不位于 adapters/store/,但属于 runtime 数据:
skills.json保存 enable 状态和extraRoots目录列表,重启或升级后继续加载;旧文件缺少目录字段时按空列表读取。user-skills/<id>/SKILL.md保存用户 Skill。plugin-skill-overrides/<plugin>/<skill>/保存 Plugin Skill 的可编辑副本或删除标记,并按 Plugin 安装实例隔离。plugins.json保存安装所有权和 manifest 摘要。plugins/<id>/是 runtime 私有副本。
内置 skills/ 和默认 plugins/ 是应用只读资源,不在 runtime root 原地修改。
Debug trace
Conversation Debug Feature 的 InMemoryConversationDebugTraceStore 故意不落盘:
- 每 thread 最多 10,000 条。
- LRU 最多跟踪 50 个 thread。
- 返回
droppedBeforeSeq。 - Runtime 重启自然清空。
不要把它加入数据根备份或 thread recovery;启用状态由 device-local Feature settings 持久化,旧 developer_features 仅做一次性迁移输入。
修改持久化格式
- 明确 owner store。
- 加 normalize/default。
- 决定 lazy compatibility 还是显式 migration。
- 更新 main data-root manifest/validation。
- 保持原子写入或事务。
- 定义损坏输入、半写、并发和 recovery。
- 避免把 secret/private path 暴露到 state。
- 添加旧 fixture round-trip。
测试
packages/desktop-runtime/test/adapters/store/packages/desktop-runtime/test/integration/adapters/store/file-memory-store.test.tspackages/desktop-runtime/test/runtime/event-coordinated-thread-store.test.tspackages/desktop-runtime/test/integration/runtime-server/rest-runtime-state.test.ts- Contracts
packages/contracts/test/thread-events.*.test.ts
SQLite 修改还要覆盖 owner fencing、checkpoint tail、legacy import 和 close/WAL。