Skip to content

Proposal: Evolve Local Memory — from Full Injection to Extraction + On-Demand Retrieval + Layered Injection #2335

Closed as not planned

Description

@sunheyi6

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 at LOCAL_MEMORY_PROMPT_MAX_CHARS (12,000 chars).
  • Three read gates before injection: incognitoActive / memory.enabled / memory.agentReadEnabled.
  • memory.query / memory.mutate are 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

  1. Full injection: irrelevant memories consume context and dilute attention; growth is handled by truncation, not selection.
  2. Manual write path: memory relies on the user editing MEMORY.md; there is no automatic "conversation → memory" extraction.
  3. No retrieval: no BM25 / vector search / relevance ranking; the model has no on-demand memory access.
  4. 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 (reuse approve, chat_extracted source, settings_review_queue surface).
  • Suggested hook points: session-retirement-coordinator or an Automation task.

2. Hybrid retrieval + layered injection (read path)

Three-layer injection:

  1. Constant digest (profile-level, ~2K chars, always present);
  2. On-demand top-k (hybrid retrieval against the current message: BM25 relevance + recency decay + reference count; vector retrieval can be layered on later);
  3. 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 agentReadEnabled gate 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

  1. Boundary detection strategy for extraction (message count / tokens / topic drift / session end)?
  2. How to calibrate hybrid-retrieval scoring weights (BM25 vs recency vs reference count)?
  3. Should memory.query be exposed to the model as a tool (active retrieval) as a complement to proposal 2?
  4. Does typed memory need a migration path for existing MEMORY.md entries?

Related issues

中文版(点击展开 / 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)已实现但未接线到模型循环。

问题

  1. 全量注入:无关记忆占用上下文、稀释注意力;条目增多后只能靠「截断」,而非「筛选」。
  2. 写路径单一:记忆基本靠用户手动维护,缺少「会话 → 记忆」的自动抽取。
  3. 检索能力缺失:无 BM25 / 向量检索 / 相关性排序;模型侧也没有按需读取记忆的工具。
  4. 记忆无分层:事实、画像、会话摘要、可复用流程混在一个文档里,生命周期和注入策略无法区分。

提案(架构参考 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)。

开放问题

  1. 抽取流水线的边界判定策略(消息数 / token 数 / 话题漂移 / 会话结束)?
  2. 混合检索的评分权重(BM25 vs 时间衰减 vs 引用次数)如何标定?
  3. 是否需要把 memory.query 暴露为模型工具(主动读取)作为第 2 点的补充?
  4. 记忆类型化是否需要兼容迁移现有 MEMORY.md 条目?

关联 issue

Activity

  1. changed the title [-]提案:本地记忆演进 — 从全量注入到「抽取 + 按需检索 + 分层注入」[/-] [+]Proposal: Evolve Local Memory — from Full Injection to Extraction + On-Demand Retrieval + Layered Injection[/+] on Aug 6, 2026
  2. sunheyi6 commented on Aug 6, 2026

    @sunheyi6
    ContributorAuthor

    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 with kind=profile, or first-N workspace entries as fallback), capped by DIGEST_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.2 in one constants block.
    • buildLocalMemoryInjection(input, { sessionId, query?, digestMaxChars?, topK? }) → { digest?, retrieved? }, keeping the existing scope filter + redactSecrets; returns undefined-style empty result for backward compatibility with buildLocalMemoryPromptBody.

    1.2 New packages/storage/src/memory-fts-index.ts (SQLite FTS5, zero new deps)

    • MemoryFtsIndex: rebuild(markdown) (parse via parseLocalMemoryMarkdown, upsert by stable entry id, skip when content sha256 unchanged), search(query, { topK, kind?, scope? }), clear().
    • Rebuildable: index is derived from MEMORY.md; deleting it loses no memory (EverOS principle). Write strong / read eventual + retry.

    1.3 packages/runtime-host/src/server/memory-coordinator.ts

    • Extend readPromptProjection(sessionId, opts?: { query?: string }) — keep the three gates (incognitoActive / memory.enabled / memory.agentReadEnabled); when query is present, run FTS top-k (e.g. 5) and return { policy, digest?, retrieved?, body? }.

    1.4 packages/runtime-host/src/server/execution-model-composition.ts

    • readPromptState(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).
    • joinFragments order unchanged; missing query → current behavior (digest only).

    1.5 Tests

    • Extend core/src/__tests__/local-memory.test.ts (ranking + digest); new memory-fts-index.test.ts; update memory-coordinator.test.ts and execution-model-composition.test.ts.

    Phase 2 — Write path: extraction pipeline

    2.1 New packages/core/src/memory-extraction.ts

    • buildExtractionPrompt(transcriptWindow, { existingTitles }) — one LLM pass, JSON out (facts / preferences / decisions), dedupe against existing entries.
    • parseExtractionResult(text) → proposal drafts via existing appendLocalMemoryProposalDraft.

    2.2 New packages/runtime-host/src/server/memory-extraction-coordinator.ts

    • Per-(session, workspace) buffer; boundary = session end | N messages | explicit flush.
    • On boundary: one LLM call → proposals → PENDING.md via the existing revision-checked bundle writer (reuse HostMemoryCoordinator mutate/commit semantics).
    • Hook: session-retirement-coordinator.ts (session end) + optional Automation job.

    2.3 UI

    • No new surface: reuse the shipped settings_review_queue approval flow (chat_extracted source + approve).

    Phase 3 — Typed memory + offline consolidation

    3.1 packages/core/src/local-memory.ts

    • Add kind meta (profile | fact | episode | skill) to entry meta; update parseLocalMemoryMarkdown + writers; digest selects kind=profile. Migration: existing entries default kind=fact.

    3.2 Wire long-term-memory

    • Expose searchByKeys (facts) to retrieval as the fact tier; optionally expose memory.query as a model tool (open question 3).

    3.3 New packages/runtime-host/src/server/memory-consolidation-coordinator.ts + Automation cron

    • Weekly: dedupe near-duplicates (title/content similarity), conflict resolve (newer wins, record deprecated_by), archive stale (status=archived + archiveReason), re-extract facts. RuntimeEvent stays as evidence (sourceTurnId already exists).

    Phase 4 — Vector retrieval (optional, later)

    • SQLite-vec / LanceDB hybrid; queryRewriteEnabled; FTS5 remains the fallback path.

    Sequencing & risk

    • Phase 1 first: no schema break; without a query it reproduces today's behavior exactly.
    • Phase 2 reuses the shipped proposal/approval flow — no UI or protocol break.
    • Phase 3 is additive (new meta field) with a default migration.
    • Never regress: agentReadEnabled gate 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()。
    • 可重建:索引由 MEMORY.md 派生,删除索引不丢记忆(EverOS 原则);写强一致、读最终一致 + 重试。

    1.3 packages/runtime-host/src/server/memory-coordinator.ts

    • 扩展 readPromptProjection(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.ts

    • readPromptState(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.ts

    • buildExtractionPrompt(transcriptWindow, { existingTitles }) — 一次 LLM 抽取,JSON 输出(事实 / 偏好 / 决策),与存量条目去重。
    • parseExtractionResult(text) → 经现有 appendLocalMemoryProposalDraft 生成提案草稿。

    2.2 新增 packages/runtime-host/src/server/memory-extraction-coordinator.ts

    • 按 (session, workspace) 缓冲;边界 = 会话结束 | N 条消息 | 主动 flush。
    • 边界触发:一次 LLM 调用 → 提案 → 经现有修订号校验的 bundle 写入器落 PENDING.md(复用 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.ts

    • 条目 meta 增加 kind(profile | fact | episode | skill);更新 parseLocalMemoryMarkdown 与写入方;digest 只取 kind=profile。迁移:存量条目默认 kind=fact。

    3.2 接线 long-term-memory

    • 把 searchByKeys(事实)作为事实层接入检索;可选把 memory.query 暴露为模型工具(开放问题 3)。

    3.3 新增 packages/runtime-host/src/server/memory-consolidation-coordinator.ts + Automation cron

    • 每周:近似重复去重(标题/内容相似度)、冲突消解(新者优先,记 deprecated_by)、归档陈旧(status=archived + archiveReason)、重抽事实。RuntimeEvent 始终作为证据源(sourceTurnId 已存在)。

    Phase 4 — 向量检索(可选,二期)

    • SQLite-vec / LanceDB 混合检索;queryRewriteEnabled;FTS5 保留为兜底。

    顺序与风险

    • Phase 1 先行:无 schema 破坏;无 query 时行为与现状完全一致。
    • Phase 2 复用已上线的提案/审批流——无 UI、协议破坏。
    • Phase 3 纯增量(新 meta 字段)并带默认迁移。
    • 永不回退:agentReadEnabled 闸门始终是读取的唯一权威扼点。
  3. Astro-Han commented on Aug 8, 2026

    @Astro-Han
    Contributor

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions