Skip to content

Title: feat(memory): add an automatic long-term memory lifecycle #1615

Description

@YayoiNanoka

Problem

Maka currently provides a local MEMORY.md / PENDING.md workflow for storing and injecting approved memory entries.

This provides basic persistent memory, but it still requires explicit maintenance and does not form a complete long-term memory lifecycle. In particular, Maka cannot yet automatically:

  • extract durable information from completed sessions;
  • consolidate related information across sessions;
  • recall more detailed memory when MEMORY.md is insufficient;
  • collect feedback about whether recalled memory was useful or incorrect;
  • correct or forget outdated memory at a sufficiently fine granularity.

Treating an entire session as the smallest memory unit would also be too coarse. A session may contain several independent memory points, and invalidating one point should not remove everything learned from that session.

Desired outcome

Maka should have an automatic background memory pipeline that:

  • extracts durable information from eligible sessions;
  • stores independently manageable memory points;
  • maintains MEMORY.md and memory_summary.md;
  • supports keyword-based recall;
  • records recall feedback;
  • corrects or forgets individual memory points without deleting unrelated memories;
  • keeps existing RuntimeEvent data as the original evidence source.

The first implementation should focus on the memory lifecycle itself. Embedding-based or vector retrieval can be considered separately.

Alternatives or workarounds

The existing MEMORY.md / PENDING.md workflow can continue to support manually reviewed memory entries, but it requires explicit user maintenance and does not provide automatic extraction, consolidation, feedback, or forgetting.

中文翻译

问题

Maka 当前提供了基于 MEMORY.md 和 PENDING.md 的本地记忆流程,用于保存并注入经过批准的记忆。

这已经提供了基础的持久化记忆能力,但仍然需要显式维护,尚未形成完整的长期记忆生命周期。Maka 目前还不能自动完成:

  • 从已结束的 Session 中提取具有长期价值的信息;
  • 跨 Session 整理和合并相关信息;
  • 当 MEMORY.md 信息不足时读取更详细的记忆;
  • 记录召回的记忆是否有用或存在错误;
  • 以足够细的粒度修正或遗忘过时记忆。

如果把整个 Session 作为最小记忆单位,粒度也会过粗。一个 Session 可能包含多个独立记忆点,其中一条失效时,不应该删除这个 Session 中的所有记忆。

期望结果

Maka 应当具有自动运行的后台记忆流程,能够:

  • 从符合条件的 Session 中提取长期信息;
  • 保存可以独立管理的记忆点;
  • 维护 MEMORY.md 和 memory_summary.md;
  • 支持关键词召回;
  • 记录记忆使用反馈;
  • 独立修正或遗忘某个记忆点;
  • 保留现有 RuntimeEvent 作为原始证据来源。

第一版应优先实现完整的记忆生命周期。Embedding 或向量检索可以作为独立功能后续考虑。

替代方案或临时做法

当前 MEMORY.md / PENDING.md 流程仍然可以支持人工审核的记忆,但需要用户显式维护,也不能自动完成提取、整理、反馈和遗忘。

Activity

  1. YayoiNanoka commented on Jul 29, 2026

    @YayoiNanoka
    ContributorAuthor

    I have a concrete design proposal for this issue.

    The proposal is based on the Codex long-term memory pipeline, with two main changes for Maka:

    1. Use memory_item instead of an entire session as the smallest unit for recall, feedback, correction, and forgetting.
    2. Stop normal recall at memory_item instead of continuing into raw session records.

    Proposed pipeline

    Session RuntimeEvents
        ↓
    Phase 1 extraction
        ├── raw_memory: one structured extraction per session
        └── memory_item[]: zero or more atomic memories
                ↓
            SQLite storage
                ↓
    Phase 2 consolidation
        ├── MEMORY.md
        └── memory_summary.md
    

    Data and storage

    • RuntimeEvent remains the canonical source for recovery, replay, and auditing.
    • raw_memory stores one structured extraction for each processed session.
    • memory_item is the smallest unit for storage, recall, feedback, correction, and forgetting.
    • SQLite stores memory items, provenance, lifecycle state, recall records, and feedback.
    • MEMORY.md is a searchable projection of active memory items.
    • memory_summary.md is a compact routing summary included in the agent prompt.

    Maka does not need to store a separate copy of the original rollout because the existing RuntimeEvents already provide the underlying evidence.

    Phase 1: session extraction

    A background job periodically selects sessions that:

    • have been idle for at least 6 hours;
    • were updated within the last 10 days.

    For every eligible session, an agent determines whether it contains durable information. A valuable session may produce one raw_memory and multiple memory_item records. Sessions without durable information may produce no memory items.

    Phase 2: consolidation

    The consolidation agent processes added, modified, and inactive memory-item diffs.

    It should:

    1. update the corresponding parts of MEMORY.md;
    2. merge overlapping memory;
    3. correct conflicting or outdated content;
    4. remove content supported only by inactive memory items;
    5. regenerate memory_summary.md after MEMORY.md is current.

    Recall and feedback

    memory_summary.md
        ↓
    search MEMORY.md
        ↓ if more detail is required
    read the referenced memory_item
    

    Each searchable part of MEMORY.md should retain the related memory_item_id values.

    After a turn, the agent records whether each recalled item was useful, ignored, not applicable, or contradicted. Feedback is attached to the individual memory item.

    Forgetting

    memory_item reaches a forgetting condition
        ↓
    mark it inactive
        ↓
    Phase 2 updates MEMORY.md and memory_summary.md
        ↓
    physically delete it after a recovery period
    

    Forgetting one item must not delete other memory items from the same session or delete the original RuntimeEvents.

    MEMORY.md format

    The existing Codex-style structure can mostly be preserved:

    # Task Group
    
    scope:
    applies_to:
    
    ## Task 1
    
    ### memory_items
    
    ### keywords
    
    ## User preferences
    
    ## Reusable knowledge
    
    ## Failures and how to do differently

    The main format change is replacing rollout_summary_files with memory_items. A Task represents a logical task or memory topic rather than one session.

    Implementation direction

    The existing Markdown parsing, prompt injection, path-safety checks, redaction, backup, restore, and RuntimeEvent storage can be reused.

    The main new work would be:

    • background Phase 1 extraction;
    • SQLite models for raw_memory and memory_item;
    • provenance and lifecycle tracking;
    • diff-based Phase 2 consolidation;
    • keyword recall;
    • hidden memory-item citations;
    • item-level feedback and forgetting;
    • removal of the PENDING.md approval workflow.

    I would like to work on this issue. If this direction looks reasonable, please assign it to me. I can start with a backend/runtime-focused implementation and open a draft PR once the scope is confirmed.

    中文翻译

    我对这个 Issue 有一套具体的设计方案。

    方案以 Codex 的长期记忆流程为基础,但针对 Maka 做两项主要调整:

    1. 使用 memory_item 作为召回、反馈、修正和遗忘的最小单位,而不是整个 Session。
    2. 正常召回在 memory_item 层结束,不再继续读取原始 Session 记录。

    整体流程

    Session RuntimeEvents
        ↓
    Phase 1 提取
        ├── raw_memory:每个 Session 一份结构化提取结果
        └── memory_item[]:零条或多条原子记忆
                ↓
            SQLite 存储
                ↓
    Phase 2 整理
        ├── MEMORY.md
        └── memory_summary.md
    

    数据与存储

    • RuntimeEvent 继续作为恢复、回放和审计的原始事实来源。
    • raw_memory 保存每个已处理 Session 的结构化提取结果。
    • memory_item 是存储、召回、反馈、修正和遗忘的最小单位。
    • SQLite 保存记忆、来源关系、生命周期、召回记录和反馈。
    • MEMORY.md 是有效记忆的可搜索文本投影。
    • memory_summary.md 是注入 Agent Prompt 的压缩导航。

    Maka 不需要再保存一份原始 rollout,因为现有 RuntimeEvent 已经能够提供底层证据。

    Phase 1:Session 记忆提取

    后台任务定期筛选:

    • 至少 6 小时没有更新;
    • 对话发生在最近 10 天内的 Session。

    Agent 判断 Session 是否包含具有长期价值的信息。一个有价值的 Session 可以生成一份 raw_memory 和多条 memory_item;没有长期价值时可以不生成记忆。

    Phase 2:全局整理

    整理 Agent 根据新增、修改和失效的 memory-item diff 工作:

    1. 修改 MEMORY.md 中对应的内容;
    2. 合并重叠记忆;
    3. 修正冲突或过时信息;
    4. 删除只由失效记忆支持的内容;
    5. 在 MEMORY.md 更新后重新生成 memory_summary.md。

    召回与反馈

    memory_summary.md
        ↓
    搜索 MEMORY.md
        ↓ 信息不足
    读取对应的 memory_item
    

    MEMORY.md 中每段可召回内容都应保留相关的 memory_item_id。

    Turn 结束后,Agent 记录每条召回记忆是有用、被忽略、不适用还是存在矛盾。反馈落到具体的 memory_item。

    遗忘

    memory_item 达到遗忘条件
        ↓
    标记 inactive
        ↓
    Phase 2 更新 MEMORY.md 和 memory_summary.md
        ↓
    恢复期结束后物理删除
    

    遗忘一条记忆不会删除同一 Session 中的其他记忆,也不会删除原始 RuntimeEvent。

    MEMORY.md 格式

    整体保留 Codex 的结构:

    # Task Group
    
    scope:
    applies_to:
    
    ## Task 1
    
    ### memory_items
    
    ### keywords
    
    ## User preferences
    
    ## Reusable knowledge
    
    ## Failures and how to do differently

    主要修改是将 rollout_summary_files 替换为 memory_items。Task 表示逻辑任务或记忆主题,而不是一个 Session。

    实现方向

    现有的 Markdown 解析、Prompt 注入、路径安全、脱敏、备份恢复和 RuntimeEvent 存储可以继续复用。

    主要新增工作包括:

    • Phase 1 后台提取;
    • raw_memory 和 memory_item 的 SQLite 模型;
    • 来源和生命周期管理;
    • 基于 diff 的 Phase 2 整理;
    • 关键词召回;
    • 隐藏的 memory-item 引用;
    • 原子级反馈和遗忘;
    • 删除 PENDING.md 审批流程。

    我希望负责实现这个 Issue。如果这个方向合理,请将 Issue 分配给我。范围确认后,我可以先从 backend/runtime 开始,并提交一个 Draft PR。

  2. YayoiNanoka commented on Jul 29, 2026

    @YayoiNanoka
    ContributorAuthor

    I would like to work on this issue. If this direction looks reasonable, please assign it to me.

  3. Astro-Han commented on Jul 29, 2026

    @Astro-Han
    Contributor

    Thanks for the detailed proposal — the direction is sound, and I'm assigning this to you. Two of your core judgments are right and I want them kept: memory_item as the smallest unit, and stopping recall at memory_item instead of re-reading raw session records.

    Four decisions before you start.

    1. Dropping PENDING.md is approved. Removing an abstraction layer is a win. But apply the same razor to raw_memory: with RuntimeEvent already serving as the evidence source and extraction becoming incremental (see 2), one structured extraction per session may be a layer that no longer earns its place. Justify it or drop it.

    2. Extraction reuses the current agent and its context — no separate background extraction job. Instead of a background job scanning idle sessions and re-feeding session content to the model, extraction happens as a wrap-up step inside the live turn, where the session content is already in context. This means:

    • the "idle >= 6 hours / updated within 10 days" selection logic is no longer needed;
    • extraction must live in packages/runtime (the turn loop is there), not in apps/desktop/src/main, where today's memory service sits — settle the layering in the first PR;
    • you need to define the trigger point precisely: extracting on every turn would be noisy, so specify what counts as a wrap-up.

    Phase 2 consolidation stays asynchronous — it is a cross-session diff consumer and is unaffected.

    3. Please answer one design question before implementing: who owns MEMORY.md? Today it is a user-authored, user-editable file and the single source of truth. Your proposal demotes it to a projection of SQLite that the consolidation agent rewrites. What happens to a hand-edited MEMORY.md on the next consolidation pass? Every other part of the design hangs on this answer.

    4. Split into separate PRs, each independently buildable, reviewable, and revertable:

    1. SQLite model for memory_item — schema, provenance, lifecycle state. No agent calls; fully testable offline. Settles the layering question from (2).
    2. Extraction at turn wrap-up, reusing the current agent context, writing into (1).
    3. Phase 2 consolidation and the MEMORY.md / memory_summary.md projection, plus removal of the PENDING.md workflow. The removal cannot land before the projection exists, or there is a window with no write path.
    4. Recall: memory_summary.md prompt injection, keyword search over MEMORY.md, and reading the referenced memory_item.

    Feedback and forgetting are out of scope here — open a separate issue. Turn-level self-reported usefulness is the least certain part of the chain and the most invasive to the turn loop; it should not block the extract -> consolidate -> recall path from landing.

    One more thing not covered in the proposal: local memory currently defaults to agentReadEnabled: false. Automatic extraction is fine, but automatic injection should stay behind that setting. Incognito sessions must be excluded from extraction.

    中文翻译

    感谢详细的提案 —— 方向是合理的,Issue 分配给你。你的两个核心判断是对的,希望保留:memory_item 作为最小单位,以及召回止步于 memory_item 而不回读原始 Session 记录。

    动工前有四个决定。

    1. 同意删除 PENDING.md。 去掉一个抽象层是好事。但请对 raw_memory 用同一把剃刀:既然 RuntimeEvent 已经是证据来源,提取又改为增量进行(见第 2 点),"每个 Session 一份结构化提取"可能已经是一个不再值得存在的层。请论证它的必要性,否则去掉。

    2. 提取复用当前 Agent 及其上下文,不设独立的后台提取任务。 不再由后台任务扫描闲置 Session 并把内容重新喂给模型,而是在实时 turn 的收尾阶段提取,此时 Session 内容已经在上下文中。这意味着:

    • "闲置 >= 6 小时 / 最近 10 天内更新"的筛选逻辑不再需要;
    • 提取必须放在 packages/runtime(turn 循环在那里),而不是当前记忆服务所在的 apps/desktop/src/main —— 分层问题在第一个 PR 就要定下来;
    • 你需要精确定义触发时机:每个 turn 都提取会很吵,请明确什么算收尾。

    Phase 2 整理保持异步 —— 它是跨 Session 的 diff 消费者,不受影响。

    3. 实现前请先回答一个设计问题:MEMORY.md 归谁所有? 今天它是用户编写、用户可编辑的文件,也是唯一事实来源。你的提案把它降级为 SQLite 的投影,由整理 Agent 重写。那么用户手动编辑过的 MEMORY.md,在下一次整理时会怎样?设计的其余部分都挂在这个答案上。

    4. 拆成多个 PR,每个都能独立构建、独立 review、独立 revert:

    1. memory_item 的 SQLite 模型 —— schema、来源关系、生命周期状态。不涉及 Agent 调用,可完全离线测试。顺带解决第 2 点的分层问题。
    2. turn 收尾时的提取,复用当前 Agent 上下文,写入 ①。
    3. Phase 2 整理与 MEMORY.md / memory_summary.md 投影,以及删除 PENDING.md 流程。删除不能早于投影机制落地,否则会出现没有写入路径的空窗期。
    4. 召回:memory_summary.md 注入 Prompt、MEMORY.md 关键词搜索、读取引用的 memory_item。

    反馈与遗忘不在本 Issue 范围内 —— 请另开 Issue。turn 级的自评有用性是整条链路中最不确定、对 turn 循环侵入最强的一环,不应该阻塞 提取 → 整理 → 召回 这条主路径落地。

    提案未覆盖的一点:本地记忆当前默认 agentReadEnabled: false。自动提取可以,但自动注入仍应受该设置管控。Incognito Session 必须排除在提取之外。

  4. Astro-Han commented on Jul 29, 2026

    @Astro-Han
    Contributor

    Follow-up after studying OpenAI's Dreaming announcement (2026-06-04). Two additions to the scope defined above. The rest of that comment stands unchanged — including removing PENDING.md outright in PR ③.

    1. The proposal needs evaluation criteria, and they gate everything else

    The most transferable thing in OpenAI's write-up is not the architecture — it's that they treat memory as a capability with evals, not as a storage feature. They define what "good memory" means as three measurable objectives and track each across versions (2024 saved memories → 2025 Dreaming V0 → 2026 Dreaming V3):

    1. Carry forward useful context — you tell it something once, and it is still there in later sessions.
    2. Follow preferences and constraints — a stated preference keeps shaping behavior afterwards.
    3. Stay current over time — their framing: "The user is planning their birthday party for next Saturday"; eventually, Sunday arrives. Their test is whether the model answers correctly on prompts where the passage of time materially affects the correct answer.

    The proposal as written is a pure engineering description — schema, pipeline, lifecycle states — with no statement of how we would know whether the memory is any good. Without that, there is no way to tell whether a Phase 2 consolidation pass improved or degraded the store, prompt iteration is guesswork, and PR ④ (recall) has nothing to accept against.

    Please define one acceptance criterion per objective before PR ①. They must be deterministic and CI-runnable on the fake backend with fixture sessions — not "run a real model and eyeball it".

    Also worth borrowing: the three failure modes they name as the reason for the rewrite — staleness, correctness, scalability. Staleness is the one existing designs consistently underestimate.

    2. Time semantics must land in the PR ① schema

    Their headline capability is temporal revision: "You're going to Singapore in July" becomes "You went to Singapore in July 2026" once the trip ends, with no user action.

    This is a fourth Phase 2 operation, distinct from the ones currently listed. Merging needs overlapping memories; conflict correction needs contradictory evidence. State advancement needs neither — only the passage of time. Today's proposal folds "outdated" into "conflicting", but the mechanisms have nothing in common.

    So memory_item needs to carry, at minimum:

    • event time vs. record time — when the asserted fact happens/held, separate from when we extracted it (today there are only lifecycle timestamps);
    • whether the assertion is time-bounded or evergreen — "prefers Rust" does not expire; "is refactoring the auth module" does.

    This has to be in the first PR. Adding these fields later means a data migration.

    For context on why this matters at our scale too: OpenAI cited a ~5x reduction in serving compute as the prerequisite for making dreaming practical, alongside a quality bar. Both gates are real, and the quality gate is the one point 1 above exists to enforce.

    中文翻译

    研究了 OpenAI 的 Dreaming 公告(2026-06-04)之后的补充。在上面已定的范围上增加两条。上一条评论的其余部分不变 —— 包括在 PR ③ 中直接删除 PENDING.md。

    1. 提案缺少评测口径,而它是其余一切的前提

    OpenAI 那篇里最值得借鉴的不是架构,而是他们把记忆当成一个有 eval 的能力来做,而不是一个存储功能。他们把"什么算好记忆"定义成三个可衡量的目标,并逐版本追踪(2024 saved memories → 2025 Dreaming V0 → 2026 Dreaming V3):

    1. 承接有用的上下文 —— 说过一次,后续会话里依然在。
    2. 遵循偏好与约束 —— 表达过的偏好会持续影响之后的行为。
    3. 随时间保持时效 —— 他们的表述:"用户在计划下周六的生日派对",而周日终会到来。 评测方式是看模型在时间流逝会实质改变正确答案的问题上是否答对。

    当前提案是纯工程描述 —— schema、pipeline、生命周期状态 —— 没有说明我们凭什么判断这套记忆好不好。缺了这个,就无法判断一次 Phase 2 整理是改善了还是劣化了记忆库,Prompt 迭代全靠猜,PR ④(召回)也没有可验收的依据。

    请在 PR ① 之前为每个目标定义一条验收判据。判据必须是确定性的、可在 CI 中基于 fake backend 和固定 fixture session 运行 —— 不能是"跑一次真实模型然后凭感觉看"。

    另外值得借鉴的是他们给出的三个失败模式,也是这次重写的动因:陈旧(staleness)、正确性(correctness)、可扩展性(scalability)。其中陈旧是各类设计最容易低估的一个。

    2. 时间语义必须落进 PR ① 的 schema

    他们的招牌能力是时间态改写:行程结束后,"用户 7 月要去新加坡" 自动变成 "用户 2026 年 7 月去过新加坡",无需用户操作。

    这是 Phase 2 的第四类操作,和当前列出的都不同。合并需要有重叠的记忆;纠正冲突需要有矛盾的证据。而状态推进两者都不需要,只需要时间流逝。 当前提案把"过时"并进了"冲突",但两者的机制毫无共同之处。

    因此 memory_item 至少需要携带:

    • 事件时间 vs 记录时间 —— 断言所指的事实发生/成立的时间,与我们提取它的时间分开(目前只有生命周期时间戳);
    • 该断言是有时效的还是常青的 —— "偏好 Rust" 不会过期,"正在重构 auth 模块" 会。

    这必须放在第一个 PR。之后再加这些字段意味着要做数据迁移。

    补充一点规模上的参照:OpenAI 提到把 dreaming 的推理算力削减约 5 倍,是让它可实际铺开的前提,同时还要过质量门槛。两道门都是真实存在的,而质量这道门正是上面第 1 点要解决的。

  5. YayoiNanoka commented on Jul 30, 2026

    @YayoiNanoka
    ContributorAuthor

    Thanks for the review. I agree with the adjusted scope. Below is the updated design direction before implementation.

    1. Responses to the previous comments

    1. Whether to keep raw_memory

    Persisted raw_memory will be removed. During memory extraction, it may still exist temporarily as an intermediate result used to generate memory_items. It will be discarded after processing and will not participate in long-term storage or recall.

    2. Where memory extraction lives and when it runs

    Memory extraction will live in packages/runtime and reuse the current Agent and its existing context. There will be no separate background task that scans idle Sessions and feeds them back into a model.

    I am currently considering three triggers:

    1. When context compaction runs, extract memories from the unprocessed RuntimeEvents covered by that compaction.
    2. Provide the Agent with a memory extraction tool. When the Agent identifies information worth retaining long term, it can invoke the tool to process events from the previous extraction point through the current Turn. If the current Session has never been processed, extraction starts from the beginning of the conversation.
    3. When the user explicitly asks to remember something or modify long-term memory, the Agent invokes the tool to extract or update memory directly from the current Turn.

    All three entry points will use the same extraction pipeline and persist the processed RuntimeEvent cursor to avoid duplicate extraction. Phase 2 will continue to consume memory_item changes asynchronously.

    3. Who owns MEMORY.md

    The intended interaction is similar to ChatGPT Memory: users will not edit MEMORY.md directly, but they can describe in natural language what should be remembered, changed, or deleted. The Agent will use a Memory Tool to update the corresponding memory_items and then regenerate MEMORY.md.

    4. Whether feedback and forgetting belong in this Issue

    Feedback and forgetting will not be included in the scope of this Issue.

    5. How agentReadEnabled and Incognito Sessions are handled

    agentReadEnabled will continue to control memory use rather than memory extraction:

    • when false, memories may be extracted and saved, but they must not be injected into the Prompt or recalled automatically;
    • when true, memory injection and recall are allowed;
    • Incognito Sessions must not extract, save, inject, or recall long-term memory.

    6. Adding temporal semantics to memory_item

    As suggested, memories will distinguish between:

    • evergreen memories;
    • time-bounded memories.

    Each memory_item will separately record when the memory was written and the start and end times of the event it describes. A periodic background process will check time-bounded memories and update their current state as time advances.

    7. Defining deterministic acceptance criteria

    Evaluation will have two layers.

    The first layer will use fixed subsets sampled from two public benchmarks for end-to-end comparative evaluation:

    • LongMemEval: evaluates information extraction, multi-Session reasoning, preferences, knowledge updates, temporal reasoning, and abstention, using Recall@K and QA accuracy;
    • MSC: evaluates multi-Session conversational coherence and personalization, using METEOR and BERTScore.

    Maka and Codex will be evaluated with the same model, test data, and runtime parameters. We will compare memory recall, final-answer accuracy, and dialogue-quality metrics. Because model generation and some scoring steps are not fully deterministic, these benchmark results will evaluate overall quality but will not be the sole CI gate.

    The second layer will select a small number of scenarios covering the same capabilities and convert them into fixed Session fixtures. These tests will use a fake backend, a fake clock, exact database assertions, recall traces, and Markdown snapshots as deterministic CI acceptance criteria.

    Goal Fixed scenario Deterministic pass condition
    Carry useful context across Sessions Session A provides a durable project fact; Session B asks a related question The expected memory_item_id is created and recalled; Session B receives the correct content without unrelated memory
    Follow preferences and constraints Session A specifies “use pnpm, not npm”; Session B asks to install dependencies The applicable preference is included in the model request and the fake backend returns the fixed pnpm result; a separate non-applicable scenario verifies that the preference is not injected unconditionally
    Remain correct over time A fixture records a future trip and the fake clock advances beyond its end The future assertion is no longer projected or recalled as current state, and Phase 2 produces the expected historical state

    Public benchmarks measure real semantic quality, while fixed fixtures provide deterministic acceptance. The two will be reported separately and cannot replace one another.

    2. Choosing the MEMORY.md format

    I have not yet decided whether Codex's Task Group / Task structure or Memoh's memory bundle is a better fit for Maka. The comparison below explains the trade-off and proposes a Memoh-inspired candidate.

    The Codex format is well suited to coding Agents because it organizes operational knowledge around projects and tasks. However, it does not align perfectly with the proposed Maka design:

    • a memory_item is an atomic memory, while a Codex Task may combine multiple conclusions and sources;
    • preferences, identity, and temporary state do not necessarily belong to a Task;
    • changing one memory may require the Agent to rewrite a larger Task section;
    • positions such as Task 1 and Task 2 are not stable identifiers.

    A Memoh-style structure could map more directly to Maka's storage and recall granularity:

    MEMORY.md
    memory/
    ├── preference/
    ├── identity/
    ├── context/
    ├── knowledge/
    ├── failure/
    └── note/
    

    Each active memory_item would correspond to an automatically generated concept file:

    ---
    id: <memory_item_id>
    kind: <memory type>
    scope: <global or workspace>
    applies_to: <applicability boundary>
    keywords: [<keyword>, ...]
    temporal_kind: <evergreen or bounded>
    event_time_start: <optional>
    event_time_end: <optional>
    recorded_at: <recorded time>
    updated_at: <updated time>
    ---
    
    <memory content>

    Complete provenance, lifecycle state, usage counts, and other backend management metadata would remain in SQLite.

    MEMORY.md would become a human-readable index organized by semantic role:

    # MEMORY
    
    ## User preferences and constraints
    
    - [<title>](memory/preference/<slug>.md) — <short summary>
    
    ## Identity
    
    - [<title>](memory/identity/<slug>.md) — <short summary>
    
    ## Current context and plans
    
    - [<title>](memory/context/<slug>.md) — <short summary>
    
    ## Reusable knowledge and procedures
    
    - [<title>](memory/knowledge/<slug>.md) — <short summary>
    
    ## Failures and recovery
    
    - [<title>](memory/failure/<slug>.md) — <short summary>

    This keeps the useful semantic categories from the Codex format while removing the Task hierarchy and allowing every index entry to resolve directly to one memory_item. The normal recall path would be:

    memory_summary.md
        ↓
    MEMORY.md index
        ↓
    one memory_item concept file
    

    This proposal is inspired by Memoh rather than copying it directly: the index is grouped by semantic role instead of being only a flat chronological list. Existing Maka Markdown content will be imported during migration; after PR ③, the new memory bundle will become a projection generated from SQLite.

    中文翻译

    感谢审阅。我同意调整后的范围。下面是实现前更新后的设计方向。

    1. 对上一条评论的回答

    1. 是否保留 raw_memory

    会删除持久保存的 raw_memory。但是在提取记忆的过程中,raw_memory 仍会作为中间结果临时存在,用于生成 memory_item;处理完成后不会进入长期存储,也不会参与召回。

    2. 记忆提取放在哪里,什么时候触发

    记忆提取放在 packages/runtime,复用当前 Agent 已有的上下文,不再设置扫描闲置 Session 的独立后台提取任务。

    目前考虑以下三个触发时机:

    1. 触发上下文压缩时,在压缩上下文的同时,对本次压缩范围内尚未处理的 RuntimeEvent 进行记忆提取;
    2. 向 Agent 提供记忆提取工具。当 Agent 判断当前对话中出现了值得长期保留的信息时,主动调用工具,对上次记忆提取之后到当前 Turn 为止的内容进行提取;如果当前 Session 尚未提取过,则从对话开始处处理;
    3. 当用户明确要求修改长期记忆或记住某项信息时,Agent 调用工具,直接根据当前 Turn 的内容提取或更新记忆。

    三个入口最终使用同一套提取流程,并记录已经处理到的 RuntimeEvent 位置,避免重复提取。Phase 2 继续异步消费 memory_item 的变化。

    3. MEMORY.md 归谁所有

    这里计划参考 ChatGPT Memory 的交互方式:MEMORY.md 不允许用户直接编辑,但用户可以用自然语言描述希望记住、修改或删除的内容,由 Agent 调用 Memory Tool 修改对应的 memory_item,再更新 MEMORY.md。

    4. 反馈和遗忘是否属于当前 Issue

    反馈和遗忘在当前 Issue 内暂不考虑。

    5. 如何处理 agentReadEnabled 和 Incognito Session

    agentReadEnabled 继续控制记忆的使用,而不是提取:

    • 为 false 时,可以提取和保存记忆,但不能注入 Prompt 或自动召回;
    • 为 true 时,才允许注入和召回;
    • Incognito Session 不进行提取、保存、注入或召回。

    6. memory_item 添加时间语义

    这部分会按照建议,将记忆分为:

    • 永久有效的记忆;
    • 有期限的记忆。

    memory_item 会分别记录记忆的写入时间和事件的开始、结束时间。后台流程会定期检查有期限的记忆,并根据时间变化更新其当前状态。

    7. 如何定义确定性的验收标准

    评测分为两层。

    第一层从两个公开测试集中抽取固定子集,做端到端对比评测:

    • LongMemEval:测试信息提取、跨 Session 推理、偏好、知识更新、时间推理和拒答,记录 Recall@K 与问答准确率;
    • MSC:测试跨 Session 对话的连贯性和个性化,记录 METEOR 与 BERTScore。

    测试时为 Maka 和 Codex 使用相同的模型、测试数据和运行参数,比较双方的记忆召回率、最终回答正确率以及对话质量指标。由于模型生成和部分评分不完全确定,这组测试用于评估整体效果,不单独作为 CI 的通过条件。

    第二层从上述测试集覆盖的能力中选取少量场景,整理成固定 Session fixture,并使用 fake backend、fake clock、精确数据库断言、召回记录和 Markdown 快照,作为 CI 中的确定性验收标准。

    目标 固定场景 确定性通过条件
    跨 Session 承接有用上下文 Session A 提供长期项目事实,Session B 询问相关问题 生成并召回指定 memory_item_id,Session B 上下文包含正确内容,同时不包含无关记忆
    遵循偏好和约束 Session A 指定“使用 pnpm,不使用 npm”,Session B 请求安装依赖 模型请求包含适用的偏好记忆,fake backend 的固定结果使用 pnpm;另一条不适用场景验证该偏好不会被无条件注入
    随时间保持正确 fixture 记录未来行程,fake clock 推进到行程结束以后 原来的未来断言不再作为当前状态投影或召回,Phase 2 生成预期的历史状态

    公开测试集负责衡量真实语义效果,固定 fixture 负责确定性验收,两者分别报告,不能相互替代。

    2. MEMORY.md 格式选择

    目前我还不能确定 Codex 的 Task Group / Task 结构和 Memoh 的 memory bundle 哪一种更适合 Maka。下面先比较两种结构,并给出一种参考 Memoh 的候选方案。

    Codex 格式适合编程 Agent,因为它按照项目和任务整理操作知识。但它与 Maka 新方案存在一些不匹配:

    • memory_item 是原子记忆,而一个 Codex Task 可能混合多条结论和来源;
    • 偏好、身份和阶段性状态不一定属于某个 Task;
    • 修改单条记忆时,需要由 Agent 重写更大的 Task 段落;
    • Task 1、Task 2 等位置不是稳定标识。

    Memoh 的结构可以更直接地对应当前存储和召回粒度:

    MEMORY.md
    memory/
    ├── preference/
    ├── identity/
    ├── context/
    ├── knowledge/
    ├── failure/
    └── note/
    

    每个有效的 memory_item 对应一个自动生成的概念文件:

    ---
    id: <memory_item_id>
    kind: <记忆类型>
    scope: <global 或 workspace>
    applies_to: <适用边界>
    keywords: [<关键词>, ...]
    temporal_kind: <evergreen 或 bounded>
    event_time_start: <可选>
    event_time_end: <可选>
    recorded_at: <记录时间>
    updated_at: <更新时间>
    ---
    
    <记忆正文>

    完整来源、生命周期、使用次数等后端管理信息仍然只保存在 SQLite。

    MEMORY.md 变成按照语义分类的可读索引:

    # MEMORY
    
    ## User preferences and constraints
    
    - [<标题>](memory/preference/<slug>.md) — <简短摘要>
    
    ## Identity
    
    - [<标题>](memory/identity/<slug>.md) — <简短摘要>
    
    ## Current context and plans
    
    - [<标题>](memory/context/<slug>.md) — <简短摘要>
    
    ## Reusable knowledge and procedures
    
    - [<标题>](memory/knowledge/<slug>.md) — <简短摘要>
    
    ## Failures and recovery
    
    - [<标题>](memory/failure/<slug>.md) — <简短摘要>

    这样保留了 Codex 中有价值的语义分类,但删除了 Task 层级,并让索引中的每一条直接定位到一个 memory_item。正常召回流程为:

    memory_summary.md
        ↓
    MEMORY.md 索引
        ↓
    一个 memory_item 概念文件
    

    这个方案只是参考 Memoh,而不是完全照搬:索引按照语义作用分类,而不是只提供按时间排序的扁平列表。现有 Maka Markdown 会在迁移时导入;PR ③ 完成后,新 memory bundle 成为 SQLite 自动生成的投影。

  6. Astro-Han commented on Jul 30, 2026

    @Astro-Han
    Contributor

    Thanks, the updated direction looks good. The three triggers (compaction-time, agent-invoked tool, explicit user request) sharing one pipeline with a persisted event cursor is a clean design, and the two-layer evaluation plan answers the acceptance-criteria question directly. Both are accepted as proposed.

    Two remaining points:

    1. MEMORY.md format: drop the question instead of answering it.

    Agreed that users should not edit memory files directly. Taking that to its conclusion: drop the on-disk Markdown bundle entirely.

    Once SQLite is authoritative and the Markdown is non-editable, the files are a cache. A persisted cache costs a second write path, regeneration consistency between SQLite and disk, workspace file clutter, and the Codex-vs-Memoh format debate itself. Both things the bundle provides have more direct implementations:

    • Agent recall: the Memory Tool already handles writes (your point 3), so add search/get reading SQLite to the same tool. Recall becomes two hops (prompt summary, then tool fetch) instead of three (summary, index, concept file).
    • Human visibility: a memory management page in Desktop (via IPC) and a command in the TUI, both projecting from SQLite. ChatGPT Memory works the same way: the store is never exposed as user-facing files; users get a settings page and manage memory through conversation.

    memory_summary.md likewise becomes a generated string injected into the prompt, not a file on disk.

    Concretely: SQLite is the only persistence. MEMORY.md, the memory/ bundle, and memory_summary.md all leave the design. Existing MEMORY.md content is imported into SQLite during migration, after which the file is retired.

    2. agentReadEnabled default: gate the flip on the evaluation.

    Keep the default false at launch: extraction runs, injection doesn't. Flip it to true once the first evaluation layer (the LongMemEval/MSC comparison) shows memory injection improves answer quality, and the deterministic fixtures prove non-applicable memories are not injected unconditionally. The default then follows measured results rather than taste.

    With these two settled, the scope is agreed. PR ① can start.

    中文翻译

    感谢更新,调整后的方向很好。三个触发时机(上下文压缩时、Agent 主动调用工具、用户明确要求)共用一条管线并持久化事件游标,设计很干净;两层评测方案直接回答了验收标准的问题。这两部分按提案接受。

    剩下两个点:

    1. MEMORY.md 格式:这个问题可以直接取消,而不是回答它。

    同意用户不应直接编辑记忆文件,并把这个结论推到底:完全去掉落盘的 Markdown bundle。

    一旦 SQLite 成为权威、Markdown 不可编辑,这些文件就只是缓存。落盘的缓存要付出代价:第二条写入路径、SQLite 与磁盘之间的再生成一致性、workspace 里的文件杂物,还有 Codex 与 Memoh 的格式之争本身。bundle 提供的两样东西都有更直接的实现:

    • Agent 召回:Memory Tool 已经承担写入(你的第 3 条回答),给同一个工具加上读 SQLite 的 search/get 即可。召回从三跳(summary、索引、概念文件)变成两跳(prompt 中的 summary、工具取回)。
    • 人看记忆:Desktop 通过 IPC 提供记忆管理页,TUI 提供一个命令,都是对 SQLite 的前端投影。ChatGPT Memory 也是这么做的:存储本体从不以用户可见文件的形式暴露,用户看到设置页,通过对话管理记忆。

    memory_summary.md 同理:生成后作为字符串注入 prompt,不需要落盘。

    具体来说:SQLite 是唯一的持久化,MEMORY.md、memory/ bundle 和 memory_summary.md 全部从设计中移除。迁移时把现有 MEMORY.md 内容导入 SQLite,之后该文件退役。

    2. agentReadEnabled 默认值:由评测决定翻转时机。

    上线时默认保持 false:提取照常运行,但不注入。当第一层评测(LongMemEval/MSC 对比)表明注入记忆确实提升回答质量,且确定性 fixture 证明不适用的记忆不会被无条件注入时,再把默认值翻成 true。这样默认值跟着测量结果走,而不是口味之争。

    这两点定下来,范围就完全一致了。PR ① 可以开始。

  7. YayoiNanoka commented on Jul 30, 2026

    @YayoiNanoka
    ContributorAuthor

    I think removing MEMORY.md entirely may be too aggressive.

    Although memory_summary, MEMORY.md, and memory_item all represent memory conceptually, they serve different roles and operate at different levels of detail:

    • memory_summary is a highly compressed overview of the available memories. It does not necessarily need to be persisted, but it still needs to be generated at runtime and injected into the prompt so that the model can quickly understand what information may be available.
    • memory_item is an atomic memory unit representing a specific fact, event, preference, or other individual piece of information.
    • MEMORY.md acts as an organizational layer above memory_items. It groups related items into a more complete and coherent representation, preserves contextual relationships between them, and provides an entry point for locating the underlying items.

    Therefore, removing MEMORY.md would discard more than duplicated text. It could also remove the organization and relationships currently maintained between related memory_items.

    To remove MEMORY.md without losing this information, its responsibilities would need to move elsewhere, most likely into memory_summary. That replacement would need to represent at least:

    • relationships between related items;
    • the topic or context to which each item belongs;
    • a way to navigate from the summary to specific memory_items.

    Without those capabilities, retaining only memory_summary and memory_items may reduce retrieval efficiency and make it harder for the model to understand a related group of memories as a whole.

    For this reason, I think it would be better to first clarify the responsibility boundary between memory_summary and MEMORY.md, or simplify MEMORY.md into a lightweight index and organizational layer, rather than removing it entirely.

    中文翻译

    我感觉直接删除 MEMORY.md 可能有些激进。

    虽然 memory_summary、MEMORY.md 和 memory_item 在概念上都表示记忆,但三者承担的职责和信息粒度并不相同:

    • memory_summary 是对已有记忆的高度压缩描述。它不一定需要持久化保存,但仍然需要在运行时生成并注入 Prompt,帮助模型快速了解当前可能存在哪些可用信息。
    • memory_item 是原子化的记忆单元,表示某个具体事实、事件、偏好或其他独立信息点。
    • MEMORY.md 是位于 memory_item 之上的组织层。它将相关 Item 组合成更完整、连贯的记忆描述,保留它们之间的上下文关系,并提供定位底层 Item 的入口。

    因此,删除 MEMORY.md 丢失的不只是重复的文本内容,还可能包括相关 memory_item 之间的组织方式和关联信息。

    如果希望无损移除 MEMORY.md,就需要将它承担的职责转移到其他地方,最可能是 memory_summary。替代方案至少需要表达:

    • 相关 Item 之间的关联;
    • Item 所属的主题或上下文;
    • 从 Summary 定位到具体 memory_item 的方式。

    如果缺少这些能力,仅保留 memory_summary 和 memory_item 可能会降低检索效率,也会让模型更难从整体上理解一组相互关联的记忆。

    所以,我认为更合理的做法是先明确 memory_summary 和 MEMORY.md 的职责边界,或者将 MEMORY.md 简化成轻量的索引和组织层,而不是直接将其完全删除。

  8. Astro-Han commented on Jul 30, 2026

    @Astro-Han
    Contributor

    Thanks for pushing back on this, it points at a real gap in the last comment: calling the files "a cache" glossed over the fact that grouping, topics, and relationships between memory_items are real information produced by Phase 2. If MEMORY.md goes away, that information does need a proper home. Fully agreed there.

    So the only question left is where it lives, and here's a suggestion: keep it as structured data in SQLite rather than prose in a generated file. Prose is hard to query and update atomically, while the three capabilities you listed map quite naturally onto structure that's mostly already in the design:

    • Topic and context: the scope and kind fields on memory_item. The six categories from your Memoh proposal (preference, identity, context, knowledge, failure, note) would make a great kind enum, so that part of your design carries over as is.
    • Relationships between items: for a coding agent, related items usually share scope and kind, and keywords search covers the rest.
    • Summary-to-item navigation: build memory_summary by aggregating over scope × kind with item ids included, so recall is one Memory Tool call away.

    Will fields plus search be enough forever? Honestly, maybe not. If the LongMemEval/MSC comparison shows the model struggling to understand a group of related memories as a whole, that would be a clear signal to add a memory_group entity (title, synthesized description, member item ids), and it slots in as a purely additive change. Since neither evaluation layer currently tests group-level coherence, it feels safer to wait for that signal than to build it up front.

    The only hesitation about keeping even a lightweight MEMORY.md: once users can't edit it and the agent fetches the same content through the Memory Tool, the file mostly duplicates what SQLite already answers, and it still has to be kept in sync.

    Does this cover what you had in mind? If there's a scenario where fields plus search clearly falls short, happy to revisit. Otherwise the agreed scope stands and PR ① is good to go.

    中文翻译

    谢谢你提出这点,它确实戳中了上一条的一个漏洞:把文件叫"缓存",忽略了 item 之间的分组、主题和关联是 Phase 2 实打实的产出。如果 MEMORY.md 不在了,这些信息确实得有个正经去处,这点完全同意。

    所以剩下的问题只是放哪。这里有个建议:放 SQLite 里当结构化数据,而不是写在生成文件的行文里。行文不好查询、不好原子更新,而你列的三个能力,用设计里现有的结构基本都能接住:

    • 主题和上下文:memory_item 上的 scope 和 kind 字段。你 Memoh 方案里的六个分类(preference、identity、context、knowledge、failure、note)拿来当 kind 的取值正合适,这部分设计原样保留。
    • 相关 item 的关联:编码 Agent 场景下,相关的 item 通常就是同 scope 同 kind,剩下的靠 keywords 搜索补上。
    • 从 summary 定位 item:memory_summary 按 scope × kind 聚合生成、带上 item id,召回就是一次 Memory Tool 调用的事。

    字段加搜索是不是永远够用?说实话不一定。如果 LongMemEval/MSC 对比显示模型确实难以整体理解一组相关记忆,那就是加 memory_group(标题、合成描述、成员 item id)的明确信号,而且是纯增量的改动。目前两层评测都还没测组级连贯性,感觉等信号出现再加,比一开始就建更稳妥。

    对保留轻量 MEMORY.md 的唯一顾虑是:用户不能编辑它、Agent 又能从 Memory Tool 拿到同样内容之后,这个文件基本就是 SQLite 已有答案的一份副本,还得额外保证两边同步。

    这样有没有覆盖到你的想法?如果有字段加搜索明显接不住的场景,随时可以再讨论;没问题的话,之前定的范围不变,PR ① 可以开工了。

  9. Astro-Han commented on Jul 31, 2026

    @Astro-Han
    Contributor

    Continuing a discussion that happened outside this thread, recorded here so the design trail stays on the issue. The concern raised: with only memory_summary and atomic memory_items there is a large granularity gap (the summary is too compressed to answer questions, items are too fragmented to preserve context), and a simplified, auto-generated MEMORY.md could serve as the organization layer between them, with a knowledge-graph alternative considered and rejected for cost.

    The granularity-gap argument holds up, and the middle organization layer makes sense for V1. Accepted. The instinct matches what hierarchical-retrieval work like RAPTOR found: summary-level text plus atomic leaves genuinely helps on thematic queries, and settling the rest with a benchmark against direct item recall, as proposed, is the right way to do it.

    Before the carrier question, three corrections to arguments made earlier in this thread, since they change the picture:

    • "Grep and FTS are both lexical, so they tie" was wrong. Verified locally against node:sqlite (SQLite 3.53.4): the default unicode61 tokenizer does not segment CJK at all (searching 深色 in 用户偏好深色模式 returns nothing), and the trigram tokenizer cannot match queries shorter than three characters, which rules out very common two-character Chinese words like 偏好. Grep's substring matching handles CJK out of the box, so on raw text search the file approach is actually stronger. For the SQLite path this means: a normalized keyword table (B-tree exact/prefix matching; extraction stores bilingual keywords and aliases) as the primary lookup, trigram FTS as a secondary channel, and CJK two-character plus mixed-language queries included in the benchmark.
    • "The file has to be regenerated on every write" was a weak argument: the expensive part is LLM digest synthesis, which costs the same either way. The real file-specific concerns are narrower: a projection file has non-transactional staleness windows and a bad failure mode (a stale file that looks authoritative and keeps being read), and a workspace-visible MEMORY.md carries a real risk of being committed to git, while memory extracted from conversations is exactly the kind of content that must never land in a repo.
    • The token-saving claim is unproven. At V1 scale (hundreds of items), two-stage recall and direct top-K recall are roughly at parity once tool schema and summary overhead are counted. So the benchmark's primary metric should be answer accuracy, with tokens secondary, and it should separate two orthogonal comparisons: middle layer vs direct item recall (validates the layer), and Memory Tool vs generated MD plus Read/Grep (validates the carrier). The current plan covers the first but not the second.

    On the carrier, SQLite rows still look like the better home, for the reasons that survive the corrections above: the write path already goes through the Memory Tool, so reads reusing it keep one channel instead of two; structured filters (scope, lifecycle, time validity) compose with text search in one query; and tool-based retrieval produces structured logs the benchmark can assert on.

    If the middle layer goes in, four design conditions seem important:

    1. Filtering rows does not filter digest prose. A digest is natural language; WHERE active = 1 cannot remove an expired or out-of-scope fact already synthesized into the text. So: groups must not cross the global/workspace boundary; membership lives in a relation table with item revisions; each group carries source_fingerprint, dirty, generated_at, valid_until; member changes mark the group dirty in the same transaction; and a dirty or expired group falls back to direct item recall instead of being served anyway.
    2. One memory_search instead of agent-driven multi-hop. Rather than the agent deciding summary, then group search, then maybe item fetch, a single search tool resolves scope and time validity internally, searches groups and items in parallel, auto-falls back when a group is dirty, and returns within a budget: the digest, sentence-level item ids, and one to three evidence excerpts. memory_get stays for explicit drill-down. The digest organizes; items remain the evidence; the digest must not become a second fact layer.
    3. Groups are disposable projections. Phase 2's dedup clustering answers "which items are the same or conflicting fact"; topical grouping answers "which different facts belong together". Those are different clusterings, and an item can belong to several topics. So group membership is many-to-many, everything about a group is rebuildable from items, and group-generation failure must never block direct item recall.
    4. Wiring details that are easy to miss: incognito sessions get no read or write; headless benchmark runs use an isolated temporary database; and for weaker tool-calling models, keep the search tool to a single query parameter, consider auto-injecting top digests at session start or after compaction as a floor, and record tool-call traces as a benchmark metric.

    Human-readable output stays available as a Desktop/TUI view over SQLite plus an on-demand dump, just not on the recall path. Does this work as the resolution? If so, the middle layer is in scope for V1 with the conditions above, and PR ① is unblocked.

    中文翻译

    接着一段发生在 issue 之外的讨论,回到这里记录,保证设计脉络都留在 issue 上。当时提出的顾虑是:只有 memory_summary 和原子化的 memory_item 会存在较大的粒度差(summary 压缩过度答不了具体问题,item 太碎丢失上下文),可以用一个简化的、自动生成的 MEMORY.md 作为两者之间的组织层;另一个轻量知识图谱的替代方案因成本被否。

    粒度差这个论证是成立的,中间组织层进 V1 没问题,接受。这个直觉和 RAPTOR 这类分层检索工作的结论一致:摘要级文本加原子叶子,在主题式查询上确实有真实收益;剩下的问题按提议,用 benchmark 和"直接召回 item"做对比来定,是对的。

    谈载体之前,先纠正这个讨论里早前的三个论点,因为它们会改变判断:

    • "Grep 和 FTS 都是词面匹配所以打平"说错了。本地用 node:sqlite(SQLite 3.53.4)验证过:默认的 unicode61 分词器完全不切中文(在"用户偏好深色模式"里搜"深色"命中 0),trigram 分词器查询不足三个字符就无法命中,"偏好"这类最常见的两字词直接失效。Grep 的子串匹配对中文开箱即用,所以纯文本检索这一项,文件方案其实更强。SQLite 路线因此需要:规范化的 keyword 表(B-tree 精确/前缀匹配,提取时存中英文关键词和别名)作为主查询通道,trigram FTS 作辅助,并且 benchmark 里必须包含两字中文词和中英混合查询。
    • "文件每次写后要重新生成"是个弱论据:贵的是 LLM 合成 digest,这个成本两边一样。文件方案真正的问题更具体:投影文件存在非事务的陈旧窗口,失败模式很糟(一个看起来权威的旧文件被持续读取);而且工作区里可见的 MEMORY.md 有被 commit 进 git 的真实风险,从对话里提取的记忆内容恰恰是最不能进仓库的东西。
    • 省 token 的说法未经证实。V1 数百条的规模下,算上工具 schema 和 summary 的常驻开销,两级召回和直接 top-K 召回基本打平。所以 benchmark 的主指标应该是回答准确率,token 是次要指标;而且要拆成两个正交对比:中间层 vs 直接召回 item(验证组织层本身)、Memory Tool vs 生成 MD + Read/Grep(验证载体)。目前的计划覆盖了前者,没覆盖后者。

    载体上,SQLite 行仍然是中间层更好的去处,理由是纠正之后仍然站得住的那几条:写路径已经要走 Memory Tool,读复用同一个工具是一条通道而不是两条;结构化过滤(scope、生命周期、时间有效性)和文本检索能在一次查询里组合;工具化检索天然产出结构化日志,benchmark 可以直接断言。

    如果中间层进来,有四个设计条件比较重要:

    1. 过滤行不等于过滤 digest 文本。 digest 是自然语言,WHERE active = 1 拦不住已经被合成进文本里的过期或越界事实。所以:group 不得跨 global/workspace 边界;成员关系放带 item revision 的关联表;group 带 source_fingerprint、dirty、generated_at、valid_until;成员变更在同一事务里把 group 标脏;脏的或过期的 group 回退到直接 item 召回,而不是照常返回。
    2. 用一个 memory_search 取代 Agent 的多跳决策。 与其让 Agent 自己走"summary → 查 group → 不够再取 item",不如让一个检索工具在内部解析 scope 和时效、并行查 group 和 item、group 脏时自动降级,在预算内一次返回:digest、句子级对应的 item id、一到三条证据摘录。memory_get 留给明确的下钻。digest 负责组织,item 始终是证据,digest 不能变成第二个事实层。
    3. group 是可丢弃的投影。 Phase 2 的去重聚类回答"哪些 item 是同一个或冲突的事实",主题分组回答"哪些不同事实该一起出现",是两种不同的聚类,一个 item 可以属于多个主题。所以 group 成员是多对多、一切可从 item 重建,group 生成失败绝不能阻塞直接 item 召回。
    4. 容易漏掉的接线细节: incognito 会话不读不写;headless benchmark 用独立的临时数据库;对 tool-calling 较弱的模型,检索工具收成单个 query 参数、考虑在会话开始或压缩后自动注入 top digest 兜底,并把 tool-call trace 记为 benchmark 指标之一。

    人类可读的形态保留为 Desktop/TUI 对 SQLite 的视图加按需 dump,只是不在召回路径上。这样是否可以作为最终方案?可以的话,中间层带上述条件进入 V1 范围,PR ① 就没有阻塞了。

  10. YayoiNanoka commented on Jul 31, 2026

    @YayoiNanoka
    ContributorAuthor

    Yes, this works as the resolution.

    I agree with keeping the middle organization layer in V1 while storing it as structured data in SQLite rather than bringing MEMORY.md back into the recall path.

    The resulting hierarchy would be:

    memory_summary
        ↓
    memory_group
        ↓
    memory_item
    

    memory_item remains the source of truth and evidence. A memory_group is a disposable, rebuildable projection containing a topic-level digest and references to its member Item revisions. It must not become a second fact layer.

    I also agree with the proposed conditions:

    • Group membership is many-to-many and must not cross the global/workspace boundary.
    • Groups carry source_fingerprint, dirty, generated_at, and valid_until.
    • Item changes mark affected Groups dirty in the same transaction.
    • Dirty, expired, or failed Groups automatically fall back to direct Item recall.
    • A single memory_search searches Groups and Items internally, applies Scope and temporal filtering, and returns a bounded Digest, sentence-level Item references, and a small number of evidence excerpts.
    • memory_get remains available for explicit drill-down.
    • A normalized keyword table with bilingual aliases is the primary lexical lookup path, with trigram FTS as a secondary channel. CJK two-character and mixed-language queries will be included in the benchmark.
    • Incognito Sessions perform no memory reads or writes, and Headless benchmark runs use isolated temporary databases.
    • Human-readable output remains available through Desktop/TUI views and on-demand export, but it is not part of the recall path.

    The evaluation will also separate the two questions you identified:

    1. direct Item recall versus Group + Item recall, to validate the middle layer;
    2. Memory Tool retrieval versus generated Markdown with Read/Grep, to validate the carrier.

    Answer accuracy will be the primary metric, with Token usage, latency, and tool-call traces reported separately.

    With that, MEMORY.md is removed from the new recall architecture, memory_group is included in V1, and I’ll start working on PR ① based on this design.

    中文翻译

    可以,这个方案可以作为最终结论。

    我同意在 V1 中保留中间组织层,但将其作为结构化数据存入 SQLite,而不是重新让 MEMORY.md 进入召回链。

    最终层级为:

    memory_summary
        ↓
    memory_group
        ↓
    memory_item
    

    memory_item 仍然是事实和证据来源。memory_group 是可以删除并重建的投影,保存主题级摘要以及对应的成员 Item Revision,不能成为第二个事实层。

    我也同意以下设计条件:

    • Group 与 Item 是多对多关系,并且 Group 不能跨越 global/workspace 边界。
    • Group 保存 source_fingerprint、dirty、generated_at 和 valid_until。
    • Item 发生变化时,在同一个事务中将受影响的 Group 标记为 dirty。
    • Group 处于 dirty、过期或生成失败状态时,自动回退到直接 Item 召回。
    • 使用单一的 memory_search,在工具内部搜索 Group 和 Item,处理 Scope 与时间过滤,并在预算范围内返回 Digest、句子级 Item 引用和少量证据摘录。
    • 保留 memory_get,用于明确读取具体 Item。
    • 使用包含中英文别名的规范化关键词表作为主要词法查询方式,trigram FTS 作为辅助通道。Benchmark 会加入中文双字词和中英混合查询。
    • Incognito Session 不进行任何记忆读写,Headless Benchmark 使用隔离的临时数据库。
    • 人类可读内容继续通过 Desktop/TUI 视图和按需导出提供,但不进入召回链。

    评测也会拆分为你提到的两个独立问题:

    1. 直接 Item 召回与 Group + Item 召回,用于验证中间层;
    2. Memory Tool 与生成 Markdown + Read/Grep,用于验证载体。

    回答准确率作为主要指标,Token 消耗、延迟和工具调用轨迹分别记录。

    基于这个结论,新召回架构移除 MEMORY.md,memory_group 进入 V1,我将按照这套设计开始 PR ① 的工作。

  11. changed the title [-]Title: feat(memory): add an automatic long-term memory lifecycle[/-] [+]Title: feat(memory): add an automatic long-term memory lifecycle (memory pr2 1/4)[/+] on Aug 4, 2026
  12. changed the title [-]Title: feat(memory): add an automatic long-term memory lifecycle (memory pr2 1/4)[/-] [+]Title: feat(memory): add an automatic long-term memory lifecycle (memory PR② 1/4)[/+] on Aug 4, 2026
  13. changed the title [-]Title: feat(memory): add an automatic long-term memory lifecycle (memory PR② 1/4)[/-] [+]Title: feat(memory): add an automatic long-term memory lifecycle[/+] on Aug 4, 2026
  14. sunheyi6 commented on Aug 6, 2026

    @sunheyi6
    Contributor

    Hi @YayoiNanoka — cross-linking #2335: we just opened a complementary proposal focused on the read path (full injection → on-demand hybrid retrieval + layered injection) and the EverOS-inspired architecture (markdown as source of truth, rebuildable index, boundary-triggered extraction, offline consolidation).

    Your #1615 already covers the write path & lifecycle (extraction from sessions, consolidation, recall when MEMORY.md is insufficient, feedback, fine-grained correction/forgetting). The two overlap on several points and together form a complete design:

    • Your "recall more detailed memory when MEMORY.md is insufficient" ↔ our layered injection (constant digest + on-demand top-k);
    • Your "keyword-based recall" ↔ our SQLite FTS5 (BM25) first step (vector retrieval deferred, same as your "embedding can be considered separately");
    • Your "independently manageable memory points" ↔ our typed-memory table (profile / atomic facts / episode / skill);
    • Your consolidation & forgetting ↔ our offline-consolidation phase (weekly automation, analogous to EverOS OME reflect_episodes).

    A concrete file-level implementation plan is being posted on #2335 — happy to align the two proposals (e.g., reuse the same extraction prompt contract, entry metadata, and PENDING.md proposal flow).

    中文(点击展开)

    关联 #2335:我们刚提交了一份互补提案,侧重读路径(全量注入 → 按需混合检索 + 分层注入)和 EverOS 启发的架构(markdown 为真相、可重建索引、边界触发抽取、离线整合)。

    你的 #1615 已覆盖写路径与生命周期(会话抽取、跨会话整合、MEMORY.md 不足时的召回、反馈、细粒度修正/遗忘)。两边的重叠点与互补关系:

    • 你的「MEMORY.md 不足时读取更详细记忆」↔ 我们的分层注入(恒定 digest + 按需 top-k);
    • 你的「关键词召回」↔ 我们的 SQLite FTS5(BM25)第一步(向量检索后置,与你的「embedding 单独考虑」一致);
    • 你的「可独立管理的记忆点」↔ 我们的类型化记忆表(profile / atomic facts / episode / skill);
    • 你的「整合与遗忘」↔ 我们的离线整合阶段(每周自动化,对应 EverOS OME reflect_episodes)。

    具体的文件级实现方案将发布在 #2335 上——欢迎对齐两份提案(例如复用同一套抽取 prompt 契约、条目元数据与 PENDING.md 提案流程)。

  15. sunheyi6 commented on Aug 8, 2026

    @sunheyi6
    Contributor

    Full archive of #2335 (proposal + implementation plan)

    The complete content of #2335 is preserved below, per the consolidation decision. The merged contract (read-path requirements) is recorded in the previous comment; this comment archives the full proposal body and the file-level implementation plan so #1615 stands alone as the architecture authority.


    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


    Implementation plan comment by @sunheyi6 (2026-08-06)

    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 闸门始终是读取的唯一权威扼点。
  16. sunheyi6 commented on Aug 8, 2026

    @sunheyi6
    Contributor

    Contract addition: automatic merging of same-topic memories

    Suggestion for the combined contract. The current design covers two merge-adjacent operations, but a third is implicit and should be explicit:

    Operation Question it answers Result
    Dedup clustering (Phase 2) Which items are the same or conflicting fact? One surviving memory_item
    Topical grouping (memory_group) Which different facts belong together? Disposable projection; items stay as evidence
    Topic-level merge (this addition) Which different facts form one coherent topic and should be stored as one authoritative item? One merged memory_item, sources preserved via provenance

    The gap: three sessions each contribute a fragment about "project X's auth design". Without topic-level merge, recall surfaces three fragments (or a group digest) and the model must synthesize them each time. With it, one consolidated item is stored, and the fragments remain recoverable.

    Proposed contract item:

    1. Candidate scope: same scope, same kind, same topic cluster (keyword overlap + title similarity + existing memory_group membership); never cross-scope.
    2. Output: a merged memory_item (durable evidence, not a projection) that supersedes its sources — merged_from recorded in provenance; source items marked inactive, not deleted (consistent with the forgetting model).
    3. Trigger: Phase 2 consolidation (diff-driven), and/or when a new item joins a high-overlap topic cluster.
    4. Conflict handling: merging requires non-conflicting facts; conflicts resolve via the agreed newer-wins rule, with the losing fact recorded, not silently dropped.
    5. Decomposability: a merged item must remain splittable — if later evidence contradicts part of it, that part is split back into components (inverse operation), not rewritten wholesale.
    6. Fallback: low-confidence topic match or merge failure → items stay separate; the group digest still provides the topic view.
    7. Evaluation: add a deterministic fixture — two sessions contribute related facts about one topic; expect exactly one merged item, recall returns merged content, and both sources traceable via provenance.

    Open question: merged item vs. memory_group as the home for topic aggregation — a merged item is durable evidence, a group is disposable; a high-churn topic may be better served staying as a group until stable, then merging. Suggest the benchmark's "middle layer vs direct recall" comparison include a topic-merge variant.

    中文翻译 / Chinese

    契约补充:同一主题记忆的自动合并

    对合并契约的建议。当前设计覆盖了两种与合并相邻的操作,但第三种隐含存在、应当显式化:

    操作 回答的问题 结果
    去重聚类(Phase 2) 哪些 item 是同一个或冲突的事实? 一条存活的 memory_item
    主题分组(memory_group) 哪些不同事实该一起出现? 可丢弃投影;item 仍是证据
    主题级合并(本补充) 哪些不同事实构成同一主题、应作为一条权威条目存储? 一条合并后的 memory_item,来源经 provenance 保留

    空档在于:三个会话各贡献一条关于「项目 X 的 auth 设计」的碎片。没有主题级合并时,召回返回三条碎片(或一个 group digest),模型每次都要自行综合;有了它,存一条整合后的条目,碎片仍可追溯。

    建议的契约条目:

    1. 候选范围:同 scope、同 kind、同主题簇(关键词重叠 + 标题相似度 + 既有 memory_group 成员关系);绝不跨 scope。
    2. 产物:一条合并后的 memory_item(持久证据,而非投影),取代其来源——provenance 记录 merged_from;来源 item 标记 inactive 而非删除(与遗忘模型一致)。
    3. 触发:Phase 2 整合(diff 驱动),和/或新 item 加入高重叠主题簇时。
    4. 冲突处理:合并要求事实互不冲突;冲突按既定的 newer-wins 规则解决,败者事实被记录而非静默丢弃。
    5. 可分解性:合并后的 item 必须可拆分——若后续证据与其中一部分矛盾,只拆分该部分为组件(逆操作),而非整条重写。
    6. 回退:主题匹配置信度低或合并失败 → 各 item 保持独立;group digest 仍提供主题视图。
    7. 评测:新增一个确定性 fixture——两个会话贡献同一主题的相关事实;期望恰好产生一条合并 item,召回返回合并内容,且两个来源均可通过 provenance 追溯。

    开放问题:主题聚合的归宿是合并后的 item 还是 memory_group——合并 item 是持久证据,group 是可丢弃投影;高变动主题可能更适合先保持 group、稳定后再合并。建议 benchmark 的「中间层 vs 直接召回」对比中纳入一个主题合并变体。

  17. added
    enhancement
    on Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions