Repository navigation
Closed as not planned
Closed as not planned
Copy link
Description
Proposal: Evolve Local Memory — from Full Injection to Extraction + On-Demand Retrieval + Layered Injection
Background
Current local-memory ("model context readable") pipeline (execution-model-composition.ts → memory-coordinator.readPromptProjection → core/local-memory.ts#buildLocalMemoryPromptBody):
- On every system-prompt build, all active entries of MEMORY.md are injected into the system prompt as a
<local-memory>block, filtered only by scope (workspace entries always present; session entries only for the current session), truncated atLOCAL_MEMORY_PROMPT_MAX_CHARS(12,000 chars). - Three read gates before injection:
incognitoActive/memory.enabled/memory.agentReadEnabled. memory.query/memory.mutateare client-protocol operations (settings UI browse / edit / proposal review) — not exposed to the model as tools.long-term-memory(SQLite:memory_items/memory_item_keys/memory_item_sources, incl.searchByKeys) is implemented but not wired into the model loop.
Problems
- Full injection: irrelevant memories consume context and dilute attention; growth is handled by truncation, not selection.
- Manual write path: memory relies on the user editing MEMORY.md; there is no automatic "conversation → memory" extraction.
- No retrieval: no BM25 / vector search / relevance ranking; the model has no on-demand memory access.
- Untyped memory: facts, profiles, episode summaries, and reusable procedures live in one document with no distinct lifecycle or injection strategy.
Proposal (architecture informed by EverOS: markdown as source of truth + derived rebuildable index + boundary-triggered extraction + offline consolidation)
1. Conversation → memory extraction pipeline (write path)
- Buffer session messages per
(session, workspace); on a boundary trigger (session end / N messages / explicit flush), run one LLM extraction pass producing candidate memories (facts / preferences / decisions). - Candidates are written to PENDING.md (reuse existing
appendLocalMemoryProposalDraft); the user approves them in the settings review queue (reuseapprove,chat_extractedsource,settings_review_queuesurface). - Suggested hook points:
session-retirement-coordinatoror an Automation task.
2. Hybrid retrieval + layered injection (read path)
Three-layer injection:
- Constant digest (profile-level, ~2K chars, always present);
- On-demand top-k (hybrid retrieval against the current message: BM25 relevance + recency decay + reference count; vector retrieval can be layered on later);
- Fallback truncation (keep the existing 12K cap).
- Conflict rule: order by recency, newer wins (following EverOS's claude-code plugin
<relevant-memories>block). - Keep the
agentReadEnabledgate before injection. - Index layer: SQLite FTS5 (zero new dependencies) first; optional SQLite-vec / LanceDB later. The index must be rebuildable from MEMORY.md ("deleting the index loses no memory"): strong write consistency, eventual read consistency with retry.
3. Typed memory
| Type | Storage | Injection strategy |
|---|---|---|
| profile (evolving user/project picture) | single-file rewrite | constant digest |
| atomic facts (single-sentence stable facts) | SQLite memory_items (reuse searchByKeys) |
on-demand retrieval only |
| episode (session summaries) | per-session/per-day append | not injected, searchable only |
| skill (reusable procedures) | fused with existing skill system | registered as skill |
4. Offline consolidation (optional, phase 2)
- Weekly automation (reuse Automation cron): cluster and merge fragmented memories, resolve conflicts, archive stale entries, re-extract facts (analogous to EverOS OME
reflect_episodes).
Open questions
- Boundary detection strategy for extraction (message count / tokens / topic drift / session end)?
- How to calibrate hybrid-retrieval scoring weights (BM25 vs recency vs reference count)?
- Should
memory.querybe exposed to the model as a tool (active retrieval) as a complement to proposal 2? - Does typed memory need a migration path for existing MEMORY.md entries?
Related issues
- Title: feat(memory): add an automatic long-term memory lifecycle #1615 —
feat(memory): add an automatic long-term memory lifecycle— complementary: covers the write path & lifecycle (extraction, consolidation, recall, feedback, forgetting); this proposal covers the read path & retrieval architecture (full injection → on-demand hybrid retrieval + layered injection). Both overlap on several points and together form a complete design. - refactor(core): inject the SHA-256 digest in local-memory.ts and unify the meta-value sanitizer #1414 —
refactor(core): SHA-256 digest in local-memory.ts— implementation detail of the memory document encoding. - Instrument prompt composition so the trace can answer "full of what" #2323 — prompt composition observability ("full of what") — context budget attribution incl. memory; relevant to the injection-budget critique here.
- roadmap: durable agent platform #544 —
roadmap: durable agent platform— tracking umbrella; body references Memory items.
中文版(点击展开 / Chinese version)
背景与现状
当前「本地记忆(模型上下文可读取)」的实现链路(execution-model-composition.ts → memory-coordinator.readPromptProjection → core/local-memory.ts#buildLocalMemoryPromptBody):
- 每次构建系统提示时,把 MEMORY.md 中全部 active 条目注入 system prompt(
<local-memory>块),仅按 scope 过滤(workspace 全带 / session 只带当前会话),超过LOCAL_MEMORY_PROMPT_MAX_CHARS(12,000 字符)直接截断。 - 读取闸门三道:
incognitoActive/memory.enabled/memory.agentReadEnabled,全过才注入。 memory.query/memory.mutate是客户端协议操作(设置界面浏览、编辑、提案审批),未暴露为模型工具。long-term-memory(SQLite:memory_items/memory_item_keys/memory_item_sources,含searchByKeys)已实现但未接线到模型循环。
问题
- 全量注入:无关记忆占用上下文、稀释注意力;条目增多后只能靠「截断」,而非「筛选」。
- 写路径单一:记忆基本靠用户手动维护,缺少「会话 → 记忆」的自动抽取。
- 检索能力缺失:无 BM25 / 向量检索 / 相关性排序;模型侧也没有按需读取记忆的工具。
- 记忆无分层:事实、画像、会话摘要、可复用流程混在一个文档里,生命周期和注入策略无法区分。
提案(架构参考 EverOS:markdown 为真相 + 派生可重建索引 + 边界触发抽取 + 离线整合)
1. 会话 → 记忆抽取流水线(写路径)
- 会话消息按
(session, workspace)积累 buffer;边界触发(会话结束 / N 条消息 / 主动 flush)时做一次 LLM 抽取,产出候选记忆(事实 / 偏好 / 决策)。 - 候选写入 PENDING.md(复用现有
appendLocalMemoryProposalDraft),用户在设置「审核队列」批准后转正(复用approve/chat_extracted来源 /settings_review_queue审批面)。 - 落点建议:
session-retirement-coordinator或 Automation 任务。
2. 混合检索 + 分层注入(读路径)
- 注入三层:① 恒定 digest(profile 级,约 2K 字符,每轮带);② 按需 top-k(BM25 相关度 + 时间衰减 + 引用次数,后续可叠加向量);③ 兜底截断(保留 12K 上限)。
- 冲突规则:按时间倒序,更新者优先(参考 EverOS claude-code 插件
<relevant-memories>块)。 - 保留
agentReadEnabled闸门在注入点之前。 - 索引层:SQLite FTS5(零新依赖)起步,可选 SQLite-vec / LanceDB 演进;索引由 MEMORY.md 可重建(「删索引不丢记忆」),写强一致、读最终一致 + 重试兜底。
3. 记忆类型化
| 类型 | 存储 | 注入策略 |
|---|---|---|
| profile(用户/项目画像,可演化) | 单文件重写 | 恒定 digest |
| atomic facts(单句稳定事实) | SQLite memory_items(复用现有 searchByKeys) |
仅按需检索 |
| episode(会话摘要) | 按会话/日期追加 | 不主动注入,仅检索 |
| skill(可复用流程) | 与现有 skill 系统融合 | 注册为 skill |
4. 离线整合(可选,二期)
- 每周自动化(复用 Automation cron):聚类合并碎片记忆、冲突消解、归档陈旧条目、重新抽取事实(对应 EverOS OME
reflect_episodes)。
开放问题
- 抽取流水线的边界判定策略(消息数 / token 数 / 话题漂移 / 会话结束)?
- 混合检索的评分权重(BM25 vs 时间衰减 vs 引用次数)如何标定?
- 是否需要把
memory.query暴露为模型工具(主动读取)作为第 2 点的补充? - 记忆类型化是否需要兼容迁移现有 MEMORY.md 条目?
关联 issue
- Title: feat(memory): add an automatic long-term memory lifecycle #1615 — feat(memory):自动长期记忆生命周期(互补:写路径与生命周期 vs 本提案的读路径与检索架构)
- refactor(core): inject the SHA-256 digest in local-memory.ts and unify the meta-value sanitizer #1414 — local-memory.ts SHA-256 digest 重构(实现细节)
- Instrument prompt composition so the trace can answer "full of what" #2323 — prompt 组成可观测性(上下文归因,含 memory)
- roadmap: durable agent platform #544 — durable agent platform 路线图(tracking 伞)
Metadata
Metadata
Assignees
Labels
No labels
Activity
[-]提案:本地记忆演进 — 从全量注入到「抽取 + 按需检索 + 分层注入」[/-][+]Proposal: Evolve Local Memory — from Full Injection to Extraction + On-Demand Retrieval + Layered Injection[/+]sunheyi6 commentedon Aug 6, 2026
Concrete Implementation Plan (file-level)
Proposal #2335 mapped to the current codebase. Phased so each step degrades gracefully to today's behavior.
Phase 1 — Read path: layered injection + hybrid retrieval
1.1
packages/core/src/local-memory.ts(pure functions, unit-testable)selectDigestEntries(parsed, opts)→ entries for the constant digest (default: entries withkind=profile, or first-N workspace entries as fallback), capped byDIGEST_MAX_CHARS = 2_000.rankMemoryEntries(entries, query, ctx)→ BM25-lite relevance + recency decay + reference count:score = bm25(title, content, query) + w1·exp(−ageDays/τ) + w2·min(refs, 8), tunablesτ=60d, w1=0.3, w2=0.2in one constants block.buildLocalMemoryInjection(input, { sessionId, query?, digestMaxChars?, topK? })→{ digest?, retrieved? }, keeping the existing scope filter +redactSecrets; returnsundefined-style empty result for backward compatibility withbuildLocalMemoryPromptBody.1.2 New
packages/storage/src/memory-fts-index.ts(SQLite FTS5, zero new deps)MemoryFtsIndex:rebuild(markdown)(parse viaparseLocalMemoryMarkdown, upsert by stable entry id, skip when content sha256 unchanged),search(query, { topK, kind?, scope? }),clear().1.3
packages/runtime-host/src/server/memory-coordinator.tsreadPromptProjection(sessionId, opts?: { query?: string })— keep the three gates (incognitoActive/memory.enabled/memory.agentReadEnabled); whenqueryis present, run FTS top-k (e.g. 5) and return{ policy, digest?, retrieved?, body? }.1.4
packages/runtime-host/src/server/execution-model-composition.tsreadPromptState(input, sessionId, omitMemory, query?)— thread the latest user message as the query.renderMemoryPrompt(digest, retrieved):<local-memory>= digest (constant profile layer);<relevant-memories>= retrieved top-k, recency-desc, "newer wins on conflict" note (mirrors EverOS plugin).joinFragmentsorder unchanged; missing query → current behavior (digest only).1.5 Tests
core/src/__tests__/local-memory.test.ts(ranking + digest); newmemory-fts-index.test.ts; updatememory-coordinator.test.tsandexecution-model-composition.test.ts.Phase 2 — Write path: extraction pipeline
2.1 New
packages/core/src/memory-extraction.tsbuildExtractionPrompt(transcriptWindow, { existingTitles })— one LLM pass, JSON out (facts / preferences / decisions), dedupe against existing entries.parseExtractionResult(text)→ proposal drafts via existingappendLocalMemoryProposalDraft.2.2 New
packages/runtime-host/src/server/memory-extraction-coordinator.ts(session, workspace)buffer; boundary = session end | N messages | explicit flush.HostMemoryCoordinatormutate/commit semantics).session-retirement-coordinator.ts(session end) + optional Automation job.2.3 UI
settings_review_queueapproval flow (chat_extractedsource +approve).Phase 3 — Typed memory + offline consolidation
3.1
packages/core/src/local-memory.tskindmeta (profile | fact | episode | skill) to entry meta; updateparseLocalMemoryMarkdown+ writers; digest selectskind=profile. Migration: existing entries defaultkind=fact.3.2 Wire
long-term-memorysearchByKeys(facts) to retrieval as the fact tier; optionally exposememory.queryas a model tool (open question 3).3.3 New
packages/runtime-host/src/server/memory-consolidation-coordinator.ts+ Automation crondeprecated_by), archive stale (status=archived+archiveReason), re-extract facts.RuntimeEventstays as evidence (sourceTurnIdalready exists).Phase 4 — Vector retrieval (optional, later)
queryRewriteEnabled; FTS5 remains the fallback path.Sequencing & risk
agentReadEnabledgate stays the single read-authority choke point.中文版(点击展开 / Chinese version)
具体改造方案(文件级)
提案 #2335 对应当前代码库的落地映射。分阶段推进,每阶段都能平滑回退到现有行为。
Phase 1 — 读路径:分层注入 + 混合检索
1.1
packages/core/src/local-memory.ts(纯函数,可单测)selectDigestEntries(parsed, opts)→ 恒定 digest 的条目(默认kind=profile,无则回退取前 N 条 workspace 条目),上限DIGEST_MAX_CHARS = 2_000。rankMemoryEntries(entries, query, ctx)→ BM25-lite 相关度 + 时间衰减 + 引用次数:score = bm25 + w1·e^(−ageDays/τ) + w2·min(refs, 8),常数集中一处便于调参(τ=60d, w1=0.3, w2=0.2)。buildLocalMemoryInjection(input, { sessionId, query?, digestMaxChars?, topK? })→{ digest?, retrieved? },保留现有 scope 过滤 +redactSecrets;空结果与buildLocalMemoryPromptBody向后兼容。1.2 新增
packages/storage/src/memory-fts-index.ts(SQLite FTS5,零新依赖)MemoryFtsIndex:rebuild(markdown)(经parseLocalMemoryMarkdown解析,按稳定 entry id 增量 upsert,content sha256 未变则跳过)、search(query, { topK, kind?, scope? })、clear()。1.3
packages/runtime-host/src/server/memory-coordinator.tsreadPromptProjection(sessionId, opts?: { query?: string }):三道闸门(incognitoActive/memory.enabled/memory.agentReadEnabled)不变;有 query 时走 FTS top-k(如 5 条),返回{ policy, digest?, retrieved?, body? }。1.4
packages/runtime-host/src/server/execution-model-composition.tsreadPromptState(input, sessionId, omitMemory, query?):透传最新用户消息作 query。renderMemoryPrompt(digest, retrieved):<local-memory>= digest(恒定画像层);<relevant-memories>= 检索 top-k,时间倒序 + 「冲突时新者优先」说明(参考 EverOS 插件)。joinFragments顺序不变;无 query 时保持现状(仅 digest)。1.5 测试
core/src/__tests__/local-memory.test.ts(排序 + digest);新增memory-fts-index.test.ts;更新memory-coordinator.test.ts、execution-model-composition.test.ts。Phase 2 — 写路径:抽取流水线
2.1 新增
packages/core/src/memory-extraction.tsbuildExtractionPrompt(transcriptWindow, { existingTitles })— 一次 LLM 抽取,JSON 输出(事实 / 偏好 / 决策),与存量条目去重。parseExtractionResult(text)→ 经现有appendLocalMemoryProposalDraft生成提案草稿。2.2 新增
packages/runtime-host/src/server/memory-extraction-coordinator.ts(session, workspace)缓冲;边界 = 会话结束 | N 条消息 | 主动 flush。HostMemoryCoordinator的 mutate/commit 语义)。session-retirement-coordinator.ts(会话收尾)+ 可选 Automation 任务。2.3 UI
settings_review_queue审批流(chat_extracted来源 +approve)。Phase 3 — 类型化记忆 + 离线整合
3.1
packages/core/src/local-memory.tskind(profile | fact | episode | skill);更新parseLocalMemoryMarkdown与写入方;digest 只取kind=profile。迁移:存量条目默认kind=fact。3.2 接线
long-term-memorysearchByKeys(事实)作为事实层接入检索;可选把memory.query暴露为模型工具(开放问题 3)。3.3 新增
packages/runtime-host/src/server/memory-consolidation-coordinator.ts+ Automation crondeprecated_by)、归档陈旧(status=archived+archiveReason)、重抽事实。RuntimeEvent始终作为证据源(sourceTurnId已存在)。Phase 4 — 向量检索(可选,二期)
queryRewriteEnabled;FTS5 保留为兜底。顺序与风险
agentReadEnabled闸门始终是读取的唯一权威扼点。Astro-Han commentedon Aug 8, 2026
Consolidating this proposal into #1615 so the memory lifecycle has one architecture authority. Please preserve the unique read-path requirements from this thread—bounded digest injection, on-demand hybrid retrieval, a rebuildable index, provenance, and graceful fallback—alongside #1615’s extraction, consolidation, feedback, correction, and forgetting lifecycle. Split implementation issues only after the combined contract is accepted.