Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
docs(memory): consolidate the current design contract (#1691)
rkrkrkk36118911b874
diff --git a/README.md b/README.mdindex f08d3ead9..a5e60f2da 100644--- a/README.md+++ b/README.md@@ -349,7 +349,7 @@ Shipped recently: multi-window Apps, Show Page annotations, the Agent Harness, S- **[Official Docs](https://docs.avibe.bot)** — quickstart, concepts, platform & agent guides, troubleshooting- **[What is Avibe](https://docs.avibe.bot/concepts/agent-os)** — the Agent OS model- **[CLI Reference](docs/CLI.md)** · **[Commands](docs/COMMANDS.md)**-- **[Memory](docs/MEMORY.md)** · **[记忆](docs/MEMORY_ZH.md)** — processing timeline, diagnostic capture, retention, and recovery+- **[Memory](docs/MEMORY.md)** · **[记忆](docs/MEMORY_ZH.md)** — current architecture, best-effort data contract, native records, and recovery- **[Install via AI agent](docs/INSTALL_FOR_AI.md)** — hand this to Claude Code, Codex, or OpenCode for guided setup- **[Slack](docs/SLACK_SETUP.md)** · **[Discord](docs/DISCORD_SETUP.md)** · **[Telegram](docs/TELEGRAM_SETUP.md)** setup guidesdiff --git a/core/memory/admission.py b/core/memory/admission.pyindex 41e61510e..5897f83dd 100644--- a/core/memory/admission.py+++ b/core/memory/admission.py@@ -5,7 +5,7 @@ reaches the Memory store. It used to be spread over six `Controller` methodscarrying a nullable `is_ordinary_text` bool between layers, which meant therule could only be exercised through a `Controller`.-The contract in `docs/plans/memory-plugin-system.md` already says that+The contract in `docs/MEMORY.md` says that"platform adapters classify native events but do not own Memory businesslogic". This module is the other half of that sentence: surfaces normalizetheir native event into `InboundTurnFacts`, and `CaptureAdmission` alone turnsdiff --git a/core/memory/schema.sql b/core/memory/schema.sqlindex 2a29df2a7..37bbf269f 100644--- a/core/memory/schema.sql+++ b/core/memory/schema.sql@@ -1,4 +1,4 @@--- Identity-only Memory schema for new databases and v4 migration targets.+-- Metadata-only Memory schema for new databases and v4 migration targets.CREATE TABLE IF NOT EXISTS memory_meta (singleton INTEGER PRIMARY KEY CHECK (singleton = 1),epoch INTEGER NOT NULL,diff --git a/core/memory/store.py b/core/memory/store.pyindex 5fb80caeb..45b49a26a 100644--- a/core/memory/store.py+++ b/core/memory/store.py@@ -1,4 +1,4 @@-"""Identity-only SQLite state for best-effort Memory capture."""+"""Metadata-only SQLite state for best-effort Memory capture."""from __future__ import annotationsdiff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex c385eb06f..79a54d0df 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -1,8 +1,89 @@# Memory-Avibe Memory distills eligible Workbench and private-IM messages into a-per-user profile, episodes, and facts. Open **Settings > Memory** to inspect its-Processing Record, current profile, search results, and settings.+This is the canonical product and architecture contract for the current Memory+system. Superseded Memory design plans are available in Git history only; they+must not be treated as current behavior.++Avibe Memory distills eligible Workbench and private-IM messages into scoped+User and Agent profiles, episodes, and facts. Open **Settings > Memory** to+inspect its Processing Record, current profiles, search results, and settings.++## Design philosophy++The refactored Memory system follows one priority: **keep Avibe and its Agent+available, then preserve Memory data on a best-effort basis**. EverOS runs as an+isolated child service that Avibe can wake, stop, replace, or explicitly repair.+Memory intake may be lost when the process crashes, restarts, is replaced, or is+overloaded; the design aims to retain data in ordinary operation, not to provide+zero-loss or exactly-once delivery.++The following rules are architectural invariants:++1. **Memory is optional to the main product path.** Memory latency or failure+ must not make chat, the Agent, `/new`, archive, replacement, or shutdown+ unavailable. Lifecycle offers and barriers therefore stay bounded and+ non-blocking.+2. **Acceptance is not persistence.** An accepted capture has entered bounded,+ process-local work. It does not prove EverOS received or persisted it. Avibe+ keeps no durable outbox, replay ledger, or per-call delivery workflow.+3. **Resources and retries are bounded.** Admission, attachment preparation,+ provider calls, pending flushes, and restart attempts all have finite limits.+ At capacity, Memory may drop work while the primary product continues.+4. **EverOS native data is the only Memory content truth.** Search, profiles,+ episodes, facts, and the Processing Record are projections of retained+ native data. Avibe does not maintain a parallel Provider Call Log,+ correlation ledger, or reconstructed history to make incomplete evidence+ look complete.+5. **Each lifecycle responsibility has one owner.** Admission belongs to+ `CaptureAdmission` and `MemoryModule`; product policy belongs to+ `MemoryRuntime`; volatile delivery belongs to `BestEffortMemoryWriter`;+ child ownership and restart budgeting belong to `EverOSSupervisor`; one+ launch attempt belongs to `EverOSProcess`. Callers do not borrow their+ internals.+6. **Wake is the one non-destructive availability path.** Initial startup,+ manual retry, service restart, and crash recovery all reuse bounded Wake.+ Wake never deletes Memory data and never starts a replacement before the old+ owned process is proved stopped.+7. **Data loss requires explicit authority.** Repair, Delete data, and+ identity-invalidating configuration require exact `confirm_loss: true`,+ stop proof, and confined deletion. Ambiguity fails closed instead of widening+ the delete surface or silently falling back.+8. **Identity and diagnostic truth stay explicit.** User and Agent owners are+ server-derived and isolated. Partial or missing native evidence is reported+ as `partial` or `unavailable`; a possibly submitted provider result is never+ replayed.++## Current architecture++Platform adapters classify native events but do not own Memory business logic.+They normalize each event into `InboundTurnFacts`; `CaptureAdmission` treats+those facts as untrusted and rechecks identity, platform, event shape, and+settings before admitting a capture. `MemoryModule` owns the admitted product+operation and its scoped read behavior.++| Component | Single responsibility |+| --- | --- |+| Platform adapters | Classify native events and normalize transport-specific facts without deciding Memory business eligibility. |+| `CaptureAdmission` | Revalidate untrusted inbound facts and make the single capture-admission decision. |+| `MemoryModule` | Derive owner/project scope and expose admitted capture and read semantics without exposing storage internals. |+| `BestEffortMemoryWriter` | Owns bounded, ordered, volatile capture delivery and flush attempts. |+| `MemoryRuntime` | Owns public state, configuration policy, operation exclusion, and destructive-operation admission. |+| `EverOSSupervisor` | Exclusively owns the current child, readiness, bounded Wake/restart recovery, stop proof, and released-orphan reconciliation. |+| `EverOSProcess` | Adapts one private EverOS launch attempt, its process identity, UDS readiness, resource bounds, and termination. |+| Native readers | Read caller-authorized EverOS profiles, episodes, facts, runs, and indexing state without creating another source of truth. |++The data and lifecycle paths remain separate and short:++`eligible input -> CaptureAdmission -> MemoryModule -> bounded writer -> private EverOS UDS`++`MemoryRuntime -> EverOSSupervisor -> one EverOSProcess attempt`++Reads use the same private EverOS service and its active native root.+`memory.sqlite` retains stable Avibe identity and project-catalog facts plus a+bounded metadata row for timestamp, capture-outcome, and processing-fault+diagnostics. It contains no Memory payload and is not a delivery queue or+recovery state machine. The later sections define the product behavior at these+seams.## User and Agent memory ownership@@ -155,11 +236,18 @@ An Embedding identity change invalidates the native root. Saving such a changeuses the same explicit accepted-loss boundary and unified reset; there is nocandidate config, rebuild marker, retry stage, or fallback to old settings.-Released `recovery_intent`, `embedding_change_pending`, cloud transition, and-Clear-state shapes are compatibility input only. Their retired stages are not-serialized or resumed. Unsafe compatibility evidence collapses into an internal-`repair_required` fence that ordinary saves preserve until a successful-destructive Repair clears it.+When a working custom installation first receives organization-managed Memory+capability, Avibe persists `cloud.transition_notice_pending` as an+acknowledgement fence and keeps the current custom source selected until the+user explicitly confirms the identity-changing reset. This flag records a+pending user decision, not capture delivery or resumable recovery progress, and+does not promise to retain capture while the decision is pending.++Released `recovery_intent`, `embedding_change_pending`,+`transition_rebuild_owned`, and Clear-state shapes are compatibility input only.+Their retired execution stages are not serialized or resumed. Unsafe+compatibility evidence collapses into an internal `repair_required` fence that+ordinary saves preserve until a successful destructive Repair clears it.## Best-effort capture@@ -170,12 +258,16 @@ and a bounded pending-flush tracker (256 sessions, 100 message IDs per session).Idle, age, and count thresholds are fixed at five minutes, thirty minutes, and100 acknowledgements.-Admission writes only stable identity facts to `memory.sqlite`: the install-scope key, epoch, provider timestamp watermark, and project catalog. After v4-migration the only application tables are `memory_meta` and `memory_projects`;-released queue, lease, settlement, attachment-reference, and recovery tables-are discarded without provider I/O. Older v0-v3 shapes preserve identity and-project facts, deriving legacy project rows from their former capture data.+Persistence is metadata-only. `memory.sqlite` stores the install scope key,+epoch, provider-root id, provider timestamp watermark, project catalog, capture+summaries (`missed_count`, `last_success_at`, `last_error`, and their+timestamps), and bounded processing-fault diagnostics. These fields summarize+local state; they contain no message payload or per-call delivery workflow.+After v4 migration the only application tables are `memory_meta` and+`memory_projects`; released queue, lease, settlement, attachment-reference, and+recovery tables are discarded without provider I/O. Older v0-v3 shapes preserve+identity and project facts, deriving legacy project rows from their former+capture data.Lifecycle offers and barriers are non-blocking. `/new`, archive, runtimereplacement, and shutdown never wait for capture delivery. Work still preparingdiff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.mdindex ae222578d..16834e488 100644--- a/docs/MEMORY_ZH.md+++ b/docs/MEMORY_ZH.md@@ -1,7 +1,67 @@# 记忆-Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔离的画像、事件与事实。-在**设置 > 记忆**中可以查看状态、当前画像、搜索结果、设置和处理日志。+本文是当前 Memory 系统唯一有效的产品与架构契约。已被取代的 Memory 设计方案只保留在+Git 历史中,不再代表当前行为。++Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按范围隔离的用户与 Agent 画像、+事件和事实。在**设置 > 记忆**中可以查看状态、当前画像、搜索结果、设置和处理记录。++## 设计理念++重构后的 Memory 只有一个优先级:**先保证 Avibe 与 Agent 可用,再尽力保留 Memory+数据**。EverOS 作为隔离的子服务运行,Avibe 可以唤起、停止、替换,或在用户明确确认后+修复它。进程崩溃、重启、替换或过载时允许丢失尚未完成的 Memory 输入;系统追求大多数+正常场景不丢数据,而不承诺零丢失或 exactly-once 投递。++以下规则是架构不变量:++1. **Memory 不得拖垮主链路。** Memory 的延迟或故障不能让聊天、Agent、`/new`、归档、+ 运行时替换或关机不可用;生命周期 offer 与 barrier 必须有界且不阻塞。+2. **接受不等于持久化。** 捕获被接受,只表示进入了有界的进程内工作,不代表 EverOS+ 已经接收或持久化。Avibe 不维护持久 outbox、重放账本或逐调用投递工作流。+3. **资源与重试必须有界。** 准入、附件准备、提供方调用、待 flush 状态和重启尝试都有+ 固定上限。容量耗尽时可以丢弃 Memory 工作,但主产品必须继续运行。+4. **EverOS 原生数据是唯一 Memory 内容事实源。** 搜索、画像、事件、事实和处理记录都+ 投影已保留的原生数据。Avibe 不再维护平行的 Provider Call Log、关联账本或补造的+ 历史记录。+5. **每项生命周期职责只有一个 owner。** `CaptureAdmission` 与 `MemoryModule` 负责+ 准入;`MemoryRuntime` 负责产品策略;`BestEffortMemoryWriter` 负责易失投递;+ `EverOSSupervisor` 负责子进程归属和重启预算;`EverOSProcess` 只负责单次启动。+ 调用方不能借用这些组件的内部状态。+6. **Wake 是唯一非破坏性可用路径。** 初始启动、手动重试、服务重启和崩溃恢复都复用+ 有界 Wake。Wake 永不删除 Memory 数据,且在证明旧受管进程停止前不会启动替代进程。+7. **数据丢失必须得到明确授权。** 修复、删除数据和使身份失效的配置变更都要求精确的+ `confirm_loss: true`、停止证明和受限删除。遇到歧义时 fail closed,不扩大删除范围,+ 也不静默回退。+8. **身份与诊断必须诚实。** 用户和 Agent owner 由服务端派生并互相隔离。原生证据缺失+ 或不完整时明确报告 `partial` 或 `unavailable`;可能已经提交的结果绝不重放。++## 当前架构++平台适配器负责对原生事件分类,但不拥有 Memory 业务逻辑。它们把事件规范化为+`InboundTurnFacts`;`CaptureAdmission` 将这些事实视为不可信输入,在准入前重新校验身份、+平台、事件形状与设置。`MemoryModule` 负责已准入的产品操作及其范围化读取行为。++| 组件 | 唯一职责 |+| --- | --- |+| 平台适配器 | 分类原生事件并规范化 transport 事实,但不决定 Memory 业务准入。 |+| `CaptureAdmission` | 复核不可信的入站事实,并作出唯一的捕获准入决定。 |+| `MemoryModule` | 派生 owner/project 范围,提供已准入的捕获与读取语义,不暴露存储内部。 |+| `BestEffortMemoryWriter` | 负责有界、有序、易失的捕获投递和 flush 尝试。 |+| `MemoryRuntime` | 负责公开状态、配置策略、操作互斥和破坏性操作准入。 |+| `EverOSSupervisor` | 独占当前子进程、就绪状态、有界 Wake/重启恢复、停止证明和旧版本孤儿协调。 |+| `EverOSProcess` | 适配一次私有 EverOS 启动,包括进程身份、UDS 就绪、资源限制和终止。 |+| 原生读取器 | 在授权范围内投影 EverOS 画像、事件、事实、运行和索引状态,不创建第二事实源。 |++数据与生命周期路径保持分离且简短:++`符合条件的输入 -> CaptureAdmission -> MemoryModule -> 有界 writer -> 私有 EverOS UDS`++`MemoryRuntime -> EverOSSupervisor -> 一次 EverOSProcess 启动`++读取使用同一个私有 EverOS 服务及其当前原生数据根。`memory.sqlite` 保留稳定的 Avibe+身份与项目目录事实,以及一行有界的时间戳、捕获结果和处理故障诊断元数据;它不包含+Memory 消息载荷,也不承担投递队列或恢复状态机。后续章节定义这些边界上的具体产品行为。## 用户与 Agent 记忆归属@@ -54,10 +114,13 @@ LLM、Embedding 或重排序服务。## 可选重排序端点-**设置 > 记忆**中的第三个处理端点是可选项。要启用固定 Memory Runtime 的重排序能力,-必须同时填写 Base URL、模型和 API Key;添加或更改端点会在保存前执行同样的有界预检。-三个字段全部留空时会继续使用标准记忆搜索层级。移除已保存的重排序端点会清除这三个值,-但不会重建 Embedding 索引。+**设置 > 记忆**中的第三个处理端点是可选项。选择一个 EverOS 重排序提供方+(`deepinfra`、`vllm` 或 `dashscope`),并同时配置该提供方的 Base URL、模型与 API Key。+添加或更改端点会在保存前执行提供方对应的有界预检。旧配置若没有 `provider`,默认沿用+DeepInfra 协议;但省略 `provider` 且主机为 Bailian workspace(`*.maas.aliyuncs.com`)时,+会推断为 DashScope。所有字段留空时继续使用标准记忆搜索层级。移除端点会同时清除提供方+和端点字段,但不会重建 Embedding 索引。DashScope 当前只支持 `gte-rerank-v2`,Base URL+必须是 `https://dashscope.aliyuncs.com` 或 Bailian workspace 主机。## 处理记录@@ -79,10 +142,12 @@ Call Log,记录可以不完整或丢失。包含 `memory.diagnostics.log_provi有界的 PendingFlush 跟踪器(最多 256 个 session、每个 100 个消息 ID);空闲、年龄和数量阈值固定为 5 分钟、30 分钟和 100 次确认。-准入事务只写入稳定身份事实:安装 scope key、epoch、提供方时间戳水位线和项目目录。-v4 之后 `memory.sqlite` 只有 `memory_meta` 与 `memory_projects` 两张应用表。v0-v3-迁移会保留身份和项目事实,并从旧捕获数据推导项目行;队列、租约、结算、附件引用和-恢复表会在没有提供方 I/O 的情况下丢弃。+持久化仅包含元数据。`memory.sqlite` 保存安装 scope key、epoch、provider-root id、提供方+时间戳水位线、项目目录、捕获摘要(`missed_count`、`last_success_at`、`last_error` 及其+时间戳)和有界的处理故障诊断。这些字段只概括本地状态,不包含消息载荷或逐调用投递+工作流。v4 之后只有 `memory_meta` 与 `memory_projects` 两张应用表。v0-v3 迁移会保留身份+与项目事实,并从旧捕获数据推导项目行;队列、租约、结算、附件引用和恢复表会在没有+提供方 I/O 的情况下丢弃。生命周期 offer 和 barrier 都不会阻塞。`/new`、归档、运行时替换和关机不会等待捕获投递;仍在准备中或属于旧 authority generation 的捕获可能丢失或失效。替换和关机@@ -129,6 +194,26 @@ API、内部 API、客户端与 Controller 每一层都要求精确的 `confirm_Embedding 身份变更会使原生数据根失效,因此保存时使用同一个明确接受丢失的边界与统一重置。系统不再保留候选配置、重建标记、重试阶段,也不会静默回退到旧设置。-已发布的 `recovery_intent`、`embedding_change_pending`、cloud transition 与 Clear 状态仅作-兼容输入,其已退役阶段不会再次序列化或续跑。不安全的兼容证据会折叠为内部-`repair_required` 围栏;普通保存会保留该围栏,直到一次成功的破坏性修复将其清除。+当一个正常工作的 custom 安装首次获得组织托管的 Memory 能力时,Avibe 会持久化+`cloud.transition_notice_pending` 作为确认围栏,并在用户明确确认身份变更重置前继续选择+当前 custom 来源。该字段只记录待处理的用户决定,不表示捕获投递或可续跑的恢复进度,+也不承诺在等待确认期间保留捕获。++已发布的 `recovery_intent`、`embedding_change_pending`、`transition_rebuild_owned` 与 Clear+状态仅作兼容输入,其已退役执行阶段不会再次序列化或续跑。不安全的兼容证据会折叠为+内部 `repair_required` 围栏;普通保存会保留该围栏,直到一次成功的破坏性修复将其清除。++## 召回策略++召回使用一套封闭策略,模式只能是 `auto`、`keyword`、`vector`、`hybrid` 或+`agentic`。只有最近一次可信的 EverOS health 明确报告 Embedding 能力时,`auto` 才选择+hybrid,否则使用 keyword。显式请求 vector 或 hybrid 但能力缺失时 fail closed。一次+请求最多调用一次提供方搜索,不会换模式重试。++Agentic 召回只通过 CLI 提供,并且要求 health 明确报告 Embedding、LLM 与 rerank 能力,+且没有关闭 `agentic_search`。它只发起一次请求,由 sidecar 执行最长 30 秒的墙钟超时;+能力不可用时 fail closed。EverOS 1.2.3 尚不强制模型调用次数和 token 上限,因此这些策略+字段目前只是声明式边界,而不是 Avibe 独立执行的提供方预算。++当前 session overlay 只能使用运行时提供的可信调用者 session;调用者不能传入任意提供方+filter 或 session ID。diff --git a/docs/plans/2026-08-16-cloud-model-service-and-config-center.md b/docs/plans/2026-08-16-cloud-model-service-and-config-center.mdindex 476307d98..2734d58f4 100644--- a/docs/plans/2026-08-16-cloud-model-service-and-config-center.md+++ b/docs/plans/2026-08-16-cloud-model-service-and-config-center.md@@ -85,7 +85,7 @@ A **ModelServiceConfig** exists per scope owner and contains up to one slot per| Capability | Consumed by | Upstream wire shape || --- | --- | --- || `asr` | voice transcription + dictation (+ optional `realtime_model`) | DashScope-compatible `chat/completions` with `input_audio`; realtime WS |-| `chat` | memory LLM, voice transcript cleanup | OpenAI `chat/completions` (streaming supported) |+| `chat` | fallback memory LLM, voice transcript cleanup | OpenAI `chat/completions` (streaming supported) || `embedding` | memory embeddings | OpenAI `embeddings` || `multimodal` | memory IM-attachment/vision capture | OpenAI `chat/completions` |@@ -93,6 +93,10 @@ Each slot: `provider_label` (display), `base_url`, `model`, `api_key` (write-onl`realtime_model` + `realtime_url` (asr only, optional — realtime is available iff **both** areset; the realtime WS endpoint is a distinct URL, not derived from the HTTP `base_url`), `enabled`.+At the client boundary, status exposes the effective `memory_llm` capability and its source.+`chat_fallback` follows the Chat slot; a `dedicated` Memory LLM may remain available while Chat is+disabled.+**Unset multimodal**: there is no server-side fallback. The client leaves the sidecar's multimodalendpoint unset, so the engine itself falls back to its chat endpoint (everos's own behavior); the`/v1/model/mm/*` proxy path serves only a configured multimodal slot and returns@@ -376,53 +380,40 @@ shape is not extended for this.client-local and never appears in the server payload (§8.2).- **Memory**: in `organization`/`platform` modes, the runtime feeds the sidecar cloud endpoints +`mak_` key via the existing `EVEROS_*` env plumbing (`core/memory/process.py`); `custom` mode is- the unchanged current path. Mode changes route through the existing settings-change ladder.+ the unchanged current path. All Memory lifecycle and data-loss behavior is governed by the+ canonical [`docs/MEMORY.md`](../MEMORY.md) contract; this plan does not define a second queue,+ rebuild, or recovery protocol. Mode changes route through the existing settings-change ladder.Cloud mode injects **fixed model aliases** into `EVEROS_*__MODEL` (the proxy selects the realupstream model and ignores client-sent names); the embedding alias embeds `embedding_identity`- so provider-call diagnostics stay distinguishable across identity changes. Cloud memory mode- requires **both** `chat` and `embedding` enabled in the bound scope — anything less counts as- no memory capability (the no-transition rule below applies), since the engine cannot start- without a complete LLM + embedding pair. If an **active** cloud scope later disables either- slot, member instances pause memory processing (capture keeps queuing in the durable outbox),- surface the capability-off state, and resume automatically when the org re-enables the pair —- never a silent fallback to `custom` or platform. The resume passes through the standard identity- check: an embedding identity that changed while paused gates on the rebuild-confirmation flow- before processing restarts.-- **Embedding identity**: the cloud config's `embedding_identity` participates in the sidecar's- vector-space identity exactly like a local embedding config change — an org admin changing the- embedding slot triggers the existing rebuild flow on every member instance, with the admin UI- warning about exactly this blast radius before saving.-- **Rotation & key-change semantics (verified against code, 2026-08-16)**: an API-key change- (slot key or mak; base_url/model unchanged) is non-identity on both sides — Avibe's identity is- exactly `(embedding.base_url, embedding.model)` (`core/memory/runtime.py:3721-3735`, docstring:- "Non-identity fields (API keys, LLM settings) may change … without invalidating a completed- rebuild"), and everos 1.2.3 never persists any provider fingerprint (key lives only in process- env → `@functools.cache`d settings → singleton HTTP client; EVEROS_ROOT holds no config-derived- state; embedding dimension is the code constant 1024). A key change therefore applies through- the existing managed settings ladder: preflight probe child with candidate env → quiesce (30 s;- in-flight flushes awaited via `asyncio.shield`, durable outbox, no double-write) → graceful- sidecar restart. A failed probe leaves the old sidecar running and rolls the config back.+ so server-side usage remains distinguishable across identity changes. Cloud Memory requires an+ effective Memory LLM plus Embedding: current status uses `capabilities.memory_llm`; an older+ cache without that field falls back to `capabilities.chat`. `memory_llm_source` distinguishes a+ dedicated endpoint from Chat fallback. If an active cloud scope loses either effective+ capability, member instances surface `degraded` and new capture may be lost; there is no durable+ outbox. They retry through bounded non-destructive Wake when the capability returns and never+ silently fall back to `custom` or platform.+- **Embedding identity**: `MemoryConfig.runtime_embedding_identity()` returns+ `("custom", embedding.base_url, embedding.model)` for custom processing and+ `("cloud", applied_embedding_identity or embedding_identity, None)` for cloud processing.+ The source tag makes every `custom ↔ cloud` switch identity-changing even when endpoint text+ happens to match. A managed embedding identity change requires exact `confirm_loss` and the+ unified destructive reset on every member instance.+- **Rotation & key-change semantics**: API keys are excluded from the runtime embedding identity.+ A sidecar-held key change uses bounded preflight → bounded volatile-writer quiesce →+ non-destructive Wake. Pending capture can be lost during replacement, and no old configuration+ or delivery work is replayed after the new configuration is authoritative.These managed-restart semantics apply only to keys the sidecar itself holds (custom-mode slotkeys, the mak). **Org/platform slot keys live server-side only**: rotating them requires noclient action, restarts nothing, and changes nothing in the status payload.-- **Mode-switch semantics**: switching `custom ↔ cloud` changes the base_url the sidecar sees and- is an identity change by definition unless the upstream is identical — the existing- rebuild-confirmation flow governs it. In cloud modes the client's identity input is the status- payload's `embedding_identity` (upstream base_url+model), never the proxy URL — so org upstream- changes propagate as rebuilds, and mak rotation does not.- **Enterprise-attachment transition**: when an instance whose memory runs in `custom` mode becomes- enterprise-managed, the client pauses memory processing (capture keeps queuing in the durable- outbox; nothing is lost), surfaces a one-time transition notice, and performs the identity change- through the same rebuild-confirmation flow on the user's acknowledgment — forced management- changes the model source, but the rebuild is never silent. If the org provides no **cloud memory- capability** (the chat + embedding pair not both enabled — embedding-only and chat-only orgs- alike), no transition fires: an existing working `custom`- configuration keeps running unchanged (the org has not provided a replacement model source), and- the manual editor stays hidden only for *new* configuration; the transition applies when the org- later enables memory slots. **Custom preservation is grandfathering only**, not a new-configuration- entitlement: a fresh install attached to an organization without the memory pair renders the- managed read-only state with Memory unavailable until the organization enables both slots — it- never exposes manual setup and never falls back to the platform scope (PM ruling 2026-08-17).+ enterprise-managed and the organization has complete Memory capability, the client persists+ `cloud.transition_notice_pending`, exposes the acknowledgement UI, and keeps the current custom+ runtime selected until the user supplies exact `confirm_loss`. This is one durable confirmation+ fence, not a delivery or resumable recovery stage; capture remains accepted-loss while it is+ pending. Without effective Memory LLM + Embedding, no transition fires: an existing working+ custom configuration is grandfathered. A fresh managed install instead shows Memory unavailable+ until the organization supplies both effective capabilities; it never exposes manual setup or+ falls back to platform scope.- **Settings UI (Memory)**: three states per §5.3. Copy through `ui/src/i18n/{en,zh}.json`; showstate, not mechanism; the enterprise state is one sentence, not a tour.- **Voice**: no changes.@@ -464,7 +455,8 @@ required.```json{"mode": "organization",- "capabilities": { "asr": true, "chat": true, "embedding": true, "multimodal": false },+ "capabilities": { "asr": true, "chat": true, "embedding": true, "multimodal": false, "memory_llm": true },+ "memory_llm_source": "chat_fallback","embedding_identity": "emb-9f3ac2","quota": { "enforced": false },"revision": 12@@ -474,10 +466,13 @@ required.`mode` ∈ `organization | platform`. `embedding_identity` is an opaque hash of the embedding slot's(base_url, model) and changes iff vector-space identity changes. It is `null` exactly when`capabilities.embedding` is false because the embedding slot itself is missing, disabled, or-unavailable through the shared effectiveness predicate. A chat-only degradation leaves the healthy-embedding capability and identity intact; the released client pauses cloud memory through its-existing `chat && embedding` pair predicate. Before serializing a saved scope, the endpoint consumes-that predicate for every enabled slot and immediately discards any plaintext. It includes the+unavailable through the shared effectiveness predicate. `memory_llm_source` is `dedicated` or+`chat_fallback`; `capabilities.memory_llm` is the effective Memory LLM result, so a dedicated source+may remain true while `capabilities.chat` is false, whereas Chat fallback requires both values to+match. The client admits cloud Memory only when the effective Memory LLM, Embedding, nonempty+`embedding_identity`, proxy URL, and model key are available. Before serializing a saved scope, the+endpoint consumes the shared effectiveness predicate for every enabled slot and immediately+discards any plaintext. It includes theplatform scope's approved legacy-env recovery only when the normalized saved and env provideraddresses match; organization scope never receives that recovery. A slot with neither decryptablesaved custody nor eligible recovery is reported unavailable and the response adds a per-slot reasondiff --git a/docs/plans/everos-1.2.1-upgrade.md b/docs/plans/everos-1.2.1-upgrade.mddeleted file mode 100644index a544f5195..000000000--- a/docs/plans/everos-1.2.1-upgrade.md+++ /dev/null@@ -1,170 +0,0 @@-# EverOS 1.2.1 Upgrade + project_id Integration--Status: implemented-Date: 2026-07-29--## Background--Memory currently pins `everos==1.1.3` (upstream EverMind-AI/EverMemOS). Upstream-has since shipped 1.1.4 (reliability/security fixes on paths we use: `/flush`-LLM-output retries, cascade index reliability, empty-embedding poisoning fix),-1.2.0 (`/api/v2` prefix, opt-in OpenTelemetry), and 1.2.1 (optional-embedding/rerank tiers, LanceDB schema v2, `ProviderNotConfiguredError` -> HTTP-422 `PROVIDER_NOT_CONFIGURED`).--The adapter also hardcodes `project_id="personal"`, so EverOS's-`(app_id, project_id, user_id)` isolation triple is collapsed to a single-project for all memories.--## Decisions (confirmed with owner)--- Memory launches on EverOS 1.2.1 as its initial state. The implementation- assumes a new database and defines one initial schema; there is no data- migration or cross-version provider-root compatibility work in scope.-- Target `everos==1.2.1` directly (skip 1.1.4 stopover).-- Move the adapter and sidecar guard to `/api/v2` routes.-- Wire `project_id` for real this version: **project = the Agent Session's- working directory**, reported to the provider as an HMAC digest (same- keyed-digest scheme as `derive_principal_id`), never as a raw path.-- Project identity is **fixed per Agent Session**: a Session owns its cwd and- the stored `agent_sessions.workdir` is effectively write-once- (`storage/agent_session_rows.py`); scope cwd changes only seed new sessions.- Memory must read the session's stored workdir, never re-resolve from Scope.-- Not adopted this version: capability tiers (optional embedding), OpenTelemetry- tracing, `cascade backfill` CLI. Avibe keeps requiring full LLM + embedding- configuration.--## Phase 1 — Version bump--1. `scripts/memory_runtime/pyproject.toml`: `everos==1.2.1`; regenerate- `uv.lock` with uv 0.9.18 (1.2.1 adds a direct `click>=8.1` dependency).-2. Centralize the version: `core/memory/artifact.py` `EVEROS_VERSION` becomes- the single behavioral source; other modules import or interpolate it instead- of embedding their own copy. Update every remaining pin to 1.2.1 and the new- lock SHA256:- - `core/memory/artifact.py` `EVEROS_VERSION` (drives- `provider_root_format="everos-1.2.1"`, the dev fingerprint, and the- embedded smoke script)- - `core/memory/sidecar.py` startup version check- - `core/memory/runtime.py` — the two `"everos-1.1.3"` fallback literals- (lines 147 and 569) must use the canonical constant- - `scripts/build_memory_runtime.py` `EVEROS_VERSION` / `LOCK_SHA256`- - `scripts/generate_memory_runtime_manifest.py`- - `scripts/memory_runtime_release_guard.py` (hardcoded `"1.1.3"`)- - `vibe/memory_runtime_manifest.json` (version strings; `release_state`- stays `unavailable` with placeholder hashes until a runtime release is- actually published — none exists today, verified against GitHub)- - Close-out gate: `rg -n '1\.1\.3'` over the repo must show no remaining- behavioral reference (docs/changelog mentions excepted).-3. Adapter behavior review for 1.2.1:- - `_deterministic_client_rejection` in `core/memory/everos.py`: upstream- v1.2.1 maps `ProviderNotConfiguredError` to **422 with error code- `PROVIDER_NOT_CONFIGURED`** (the changelog's `CAPABILITY_UNAVAILABLE` is a- different, 503-mapped code — the tagged code and tests agree on- `PROVIDER_NOT_CONFIGURED`). That rejection is configuration-dependent, not- a function of the request bytes: classify it retryable by inspecting the- error envelope code on 422, not just the status, and rewrite the docstring- that anchors the 4xx taxonomy to the 1.1.3 build. Test against the shipped- envelope shape.- - 503 `CAPABILITY_UNAVAILABLE` / `EXTERNAL_SERVICE_UNAVAILABLE` land in the- existing 5xx handling (retryable) — confirm in tests, no adapter change.- - `/health` typed response and search score-field renames need no adapter- change (body ignored / scores unread) — confirm in tests.-4. Comments referencing "EverOS 1.1.3" in `core/memory/process.py`,- `modality.py`, `artifact.py` updated where behavior-relevant.--## Phase 2 — /api/v2--- `core/memory/everos.py`: `add/flush/search` routes move to- `/api/v2/memory/*` (`/health` stays unversioned).-- `core/memory/sidecar.py` guard: route allowlist and per-route validator- dispatch move to `/api/v2/*`; v1 routes are no longer forwarded (brutal cut,- no alias support in the guard).--## Phase 3 — project_id = Agent Session working directory--Derivation:--- New `derive_project_id(scope_key, workdir) -> "p-" + digest[:32]` in- `core/memory/store.py`, plus `is_project_id` shape check, mirroring the- principal scheme. Raw paths are never persisted or sent to the provider.-- Define the project-aware store in `core/memory/schema.sql`, with non-null- `project_ref` on queue rows. This is the only schema, not a migration, and the- store does not carry a schema-version upgrade mechanism.--Write path (capture -> add/flush):--- `InboundTurnFacts` gains the session workdir; `Controller` fills it from the- resolved Agent Session row's stored `workdir` (the same value the agent turn- ran under — not re-resolved from Scope).-- `CaptureAdmission` validates it and the store persists `project_ref` on each- queue row as part of the initial schema.-- `ProviderCapture` gains `project_ref`; `EverOSPort.add` sends it as- `project_id` instead of the `_PROJECT_ID` constant.-- Because project is fixed per session, flush stays keyed by `session_id` and- `_provider_session_ref` is unchanged; the store enforces the invariant that- all rows of one session carry one `project_ref` (defensive check, not a- grouping dimension).--`vibe memory remember` (agent-initiated capture):--- `/internal/memory/remember` in `core/internal_server.py` builds a- `CaptureRequest` directly; it must resolve the caller session's project the- same way reads do (below) and carry it on the request.-- The idempotency key becomes- `agent:{principal}:{project}:{session}:{digest}` so the same remembered text- in two projects cannot collide on one digest row.--Read path (search/profile):--- `MemoryModule.search/profile` and `MemoryProviderPort` take `project_id`.-- CLI reads (`/internal/memory/search|profile|remember`): the caller-session- map in `core/controller.py` (`configure_memory_cli_session`) stores- `(principal_id, project_id)` — project derived from the admitted session's- stored workdir — so an admitted agent session reads and writes its own- project's memories.-- UI reads (`vibe/ui_memory_routes.py` via `internal_client`): the trusted- Controller-side internal route derives the default-cwd project- (`derive_project_id` over the default working directory) before calling the- provider. Resolve that directory with the same shared- `expanduser` / `abspath` / configured-default / process-cwd fallback used by- Agent Session creation; never hash the raw config string independently.- Upstream 1.2.1 pins an omitted- `project_id` to the literal string `"default"` in the query filter — it is- not a cross-project view, and the sidecar guard would reject that literal- anyway. Test both that UI profile/search payloads carry a `p-<32 hex>` value- and that it exactly equals the project ID used by a default Agent Session.- A UI project selector is follow-up work.-- Sidecar guard `_valid_scope`: `app_id == "avibe"` unchanged; `project_id`- must match the `p-<32 hex>` shape instead of `== "personal"`.--## Phase 4 — Tests and validation--- Update version-pinned tests: `test_memory_everos.py`, `test_memory_sidecar.py`,- `test_memory_runtime*.py`, `test_local_deps.py`,- `test_memory_runtime_release_guard.py`.-- New coverage: project-aware store schema, project derivation/shape, guard- scope acceptance/rejection, capture->add payload- carrying the derived project, one-project-per-session invariant, remember- idempotency key with project, CLI-session (principal, project) mapping, UI- reads sending the same project as a default Agent Session, and 422- `PROVIDER_NOT_CONFIGURED` retry classification against the shipped envelope.-- `ruff check` on changed files; focused pytest first, then the full local- suite and CI.-- Incus regression (`回归测试` flow) for user-facing verification: capture,- search and profile from agent sessions in two different working directories- must be isolated.--## Phase 5 — Runtime packaging (when publishing)--- `scripts/build_memory_runtime.py` for darwin-arm64 / linux-arm64 / linux-x64;- publish `memory-runtime-v1.2.1-1` release assets **before** flipping the- manifest to `release_state: published` with real hashes (release-guard- ordering rule).--## Out of scope / follow-ups--- Capability tiers (embedding-optional operation) — separate product task.-- OpenTelemetry tracing — future observability task.-- UI project selector for the memory browser (this version fixes UI reads to- the default-cwd project).diff --git a/docs/plans/everos-memory-adjustment.md b/docs/plans/everos-memory-adjustment.mddeleted file mode 100644index bca72a07f..000000000--- a/docs/plans/everos-memory-adjustment.md+++ /dev/null@@ -1,480 +0,0 @@-# EverOS Memory Integration Adjustment--> Status: historical; superseded by `memory-best-effort-capture.md` and-> `memory-processing-log-page.md`->-> Date: 2026-08-08->-> Target branch: Avibe `dev`->-> This document records the original implementation and review. It preserves the-> owner-approved scope, the two capabilities already merged into `dev`, and the one remaining-> implementation PR. This umbrella plan is tracked with that implementation.->-> The implementation must start from the latest `origin/dev`, not from any deleted staging branch-> or abandoned worktree. The owner will review the resulting Processing Record UI after it is built;-> a separate mockup approval round is not required.--## 1. Delivery status and objective--### 1.1 Already implemented--#### PR #1224 — EverOS runtime 1.2.3--Merged into `dev`:--- merge commit: `b7350bdcb834edc1b7ea1bfabb492cc08461d412`;-- EverOS runtime pin and lock/provenance updates for 1.2.3;-- release/manifest guard that refuses to claim availability without real immutable assets.--The manifest may remain `release_state: unavailable` until the release process publishes and verifies-real immutable artifacts. Do not fabricate assets, URLs, or checksums.--#### PR #1230 — durable Memory foundation--Merged into `dev`:--- PR: <https://github.com/avibe-bot/avibe/pull/1230>;-- merge commit: `a104df57ef7debf7f2782e360e475282d9e136d8`;-- clean new Memory schema;-- canonical `ProviderSessionRef` identity:- `(principal_id, epoch, project_ref, session_id)`;-- deterministic identity serialization and validation;-- durable capture enqueue, idempotency, claim, success settlement, and boot recovery;-- strict structural validation of successful `/add` receipts;-- malformed, timeout, disconnect, and otherwise ambiguous `/add` outcomes become terminal- `manual_required` and are never silently replayed;-- conservative transport classification for `ReadError`, `RemoteProtocolError`, `WriteError`, and- `CloseError`;-- deterministic non-retryable provider rejection remains terminal even when a health probe fails;-- failure-log and status-foundation visibility for terminal failures.--PR #1230 deliberately does **not** contain flush coordination, generation routing, natural-boundary-projection, attachment pinning, clear journaling, Processing Record changes, or search-policy-expansion. Those belong to the one remaining implementation PR below.--### 1.2 Objective of the remaining PR--Deliver the remaining approved Memory behavior as one coherent PR into `dev`:--1. authoritative session flush coordination;-2. durable attachment handling and crash-safe clear;-3. Processing Record backend and UI;-4. single-run search policy and capability gating;-5. focused contract/scenario tests and UI build validation;-6. release-manifest completion only when the real immutable runtime artifacts are available.--This is one delivery unit, not a sequence of artificial PR1–PR9 stages. The Agent may split the work-internally, but the final PR must have one coherent contract and one review loop.--## 2. Non-negotiable product decisions--Memory is a new, unused feature. There are no existing users or production Memory data to preserve.-Therefore:--- do not inspect, detect, or infer an old schema;-- do not write migrations, compatibility conversion, legacy import, or `migrated_legacy` rows;-- do not preserve or rebuild historical user data;-- start from the clean schema already merged by PR #1230;-- do not implement a broad user-data rebuild workflow or rebuild button in this delivery;- the later, narrowly scoped embedding-identity recovery in issue #1314 is defined by- `docs/plans/memory-embedding-rebuild-recovery.md`;-- do not implement an audited manual-resolution `operate` API, decision rows, fence-release UI, or- manual-resolution workflow;-- keep `manual_required` as a durable, visible, terminal safety state with no automatic replay;-- keep search single-run only; no multi-declaration or fan-out request body;-- defer cross-platform IM alias pairing;-- defer a caller-facing bounded-freshness action/API in the first version; internal bounded waits may- still be used by coordination logic;-- do not add assistant/tool/agent capture;-- do not modify EverOS source code;-- do not add a private EverOS status protocol, business-metrics API, or deep provider-root scan;-- do not make `/metrics` a core Processing Record dependency;-- do not fabricate release assets or checksums.--The existing `restart` and `clear` lifecycle operations may remain where already supported. `clear`-is destructive and must not be treated as a resolution of `manual_required`; it must use the-crash-safe journal described in §7.--## 3. Architecture and boundaries--Continue using the Avibe-managed EverOS child process over private UDS HTTP. Do not import EverOS-in-process and do not expose the UDS as a TCP/public service.--```text-Avibe controller- -> Memory runtime/lifecycle- -> durable capture outbox + session flush coordinator- -> EverOS UDS HTTP adapter- -> managed EverOS child-```--The public Avibe Memory seam remains provider-neutral:--- `capture` accepts a capture and returns only durable-local acceptance/duplicate semantics;-- `recall` accepts an Avibe-owned single-run search policy and returns Avibe-owned results;-- existing maintenance operations retain their current narrow behavior, but no new manual-resolution- operation is introduced.--The outbox and lifecycle remain reliability mechanisms, not a second product status system.--### 3.1 Canonical identity contract--The exact serialized `ProviderSessionRef` from PR #1230 is the sole provider-session identity:--```text-(principal_id, epoch, project_ref, session_id)-```--Every session-scoped capture, `/add`, generation, fence, `/flush`, settlement, retry, recovery,-attachment reference, and processing record must use this identity. Never key coordination by bare-`session_id`, `(session_id, project_ref)`, or `app`.--A different logical session may progress concurrently. The same canonical provider session must be-serialized for `/add` and `/flush`; the existing global provider concurrency cap still applies.--### 3.2 Provider-write outcome contract--For every provider write:--- confirmed success requires a structurally complete, supported response and valid receipt/request ID;-- a failure proven before submission may use bounded retry when explicitly retryable;-- timeout, disconnect, malformed/unsupported 2xx, or any outcome that may follow submission is- ambiguous and becomes terminal `manual_required` with evidence retained;-- ambiguous writes are never silently auto-replayed;-- deterministic non-retryable provider rejection is terminal and must not be rewritten as a temporary- outage merely because a health probe is unhealthy.--No implementation may claim exactly-once provider extraction without an EverOS receipt/reconciliation-capability that the current public interface does not provide.--## 4. Remaining PR: implementation contract--The implementation worktree tracks one concrete implementation spec under `docs/plans/`. It cites this-document and freezes the concrete schema, state transitions, operation-token CAS rules, file scope,-source contract for the Processing Record, and test matrix.--### 4.1 Authoritative session flush coordinator--Remove flush-after-every-successful-add. Implement these triggers only:--- idle timeout (initial default recommendation: five minutes);-- maximum unflushed age and/or message bound to prevent starvation (initial max-age recommendation:- thirty minutes);-- internal explicit final flush for `/new`, archive, and centralized explicit session close hooks,- only where the canonical identity is available;-- durable boot recovery of `due` and interrupted flush state.--The coordinator owns the smallest durable state needed for recovery and settlement:--- canonical provider session reference;-- current/open generation;-- `first_unflushed_at` that is not reset by every continuous message;-- latest confirmed add watermark and `last_add_ack_at`;-- `due_at` and bounded retry `next_attempt_at`;-- flush state (`idle`, `due`, `in_flight`, and terminal `manual_required`, or an equivalent minimal- set that makes recovery unambiguous);-- monotonically increasing `fence_epoch` / operation token;-- exact settlement evidence for the acquired generation.--#### Fence-first ordering--Final flush is ordered strictly:--1. acquire and persist the session fence and operation token;-2. while holding the fence, drain or short-wait for rows belonging to the fenced generation;-3. call EverOS `/flush` with the exact canonical provider session reference;-4. settle by compare-and-set against the exact session, generation, and fence token;-5. release next-generation delivery only after safe settlement.--Checking that the queue is drained before acquiring the fence is forbidden. A capture arriving during-an in-flight flush is accepted and persisted into the next generation. A same-session worker may not-claim/send `/add` while that flush fence is in flight. A different canonical session may continue.-Shutdown persists `due`/incomplete state rather than blocking indefinitely on an LLM flush.--#### Add acknowledgements and natural boundaries--- `status=accumulated` advances the add watermark and updates idle due time while preserving the- generation's original `first_unflushed_at`; continuous traffic must not starve max-age.-- `status=extracted` is an authoritative natural-boundary settlement for the exact current generation;- it advances the watermark and opens/recomputes the next generation from remaining rows. Do not issue- a redundant explicit `/flush` for a naturally settled generation.-- Settlement evidence records operation kind (`add` natural boundary or explicit `flush`), exact- provider session/generation/token, observation (`settled`, `rejected`, or `manual_required`), receipt- ID when valid, confirmed watermark, observed time, and error code where applicable.-- Stale settlement cannot clear or overwrite a newer fence.--#### Flush retry and recovery--- Proven pre-submission, explicitly retryable failures use bounded exponential backoff and a cap.-- Confirmed non-retryable provider rejection settles terminally.-- Exhausted retry and repeated uncertain outcomes become terminal `manual_required` and remain visible.-- Structurally invalid 2xx, timeout, disconnect, and post-submission-capable transport failure become- `manual_required`, retain the fence/evidence, and are not retried automatically.-- An `in_flight` flush found after process death is `manual_required` unless durable evidence proves it- was never submitted.--Do not grow `MemoryWorker` or `MemoryStore` into an unbounded state machine. Prefer a cohesive-`SessionFlushCoordinator` seam with narrow transactional/CAS store methods. Keep lifecycle wiring-limited to centralized hooks that can pass canonical identity; do not fan out into speculative changes-across every platform adapter.--### 4.2 Durable attachments--An attachment is recoverable only after its bytes are copied or pinned into Avibe-owned private durable-storage before the capture is reported as recoverably accepted.--Required behavior:--- enforce attachment-root confinement and symlink/privacy checks;-- keep the durable attachment reference in the capture row;-- clean payload/attachment data only after confirmed provider settlement according to PR #1230 rules;-- include attachment bytes and metadata in the runtime backup/restore consistency scope;-- never put attachment bytes or secrets into logs, Processing Record responses, or provider diagnostics;-- define bounded size/retention behavior and explicit failure when bytes cannot be pinned.--### 4.3 Crash-safe clear journal--`clear` is destructive and is not a manual resolution mechanism. Because the live queue, any replay-state, and provider-owned data may live in separate durable surfaces, clear must use a two-phase journal:--1. under the maintenance fence, write an idempotent open journal containing operator identity, start- time, pre-clear digests, and restorable snapshots/paths before destructive work;-2. delete the explicitly owned local Memory surfaces and record each substep completion;-3. mark completion only after all substeps succeed, retaining an immutable completion/audit record;-4. after a crash, surface `recovery_needed` and require an explicit resume or abort path; never silently- replay quarantined rows, silently delete more data, or treat `manual_required` as resolved.--If rollback/abort is supported, restore every surface covered by the journal, not only one SQLite file.-Open journal state must be included or explicitly block a backup candidate so restore cannot combine-incompatible queue/provider/journal states.--### 4.4 Processing Record backend--Fold the useful Memory runtime summary into the existing Processing Record page. Do not create a-separate status model or a composite global `ready/syncing/degraded` claim.--The backend contract has four read-only areas:--1. **EverOS runtime summary** — latest successfully read public `GET /health`, including version,- declared capabilities, Cascade fields, and `observed_at` when present;-2. **Recent pipeline** — bounded native EverOS memcells, runs, linked semantic files,- profile state, and index state;-3. **Anomalies and recovery** — confirmed add/flush failures, boot recovery, clear-journal recovery,- and terminal `manual_required` evidence;-4. **Diagnostic detail** — bounded, scrubbed native processing detail with current- permission, pagination, and response-size limits.--Source rules:--- every summary carries `observed_at` or is marked unknown/unavailable;-- missing, stale, locked, corrupt, or schema-incompatible sources degrade only that local source;-- `/health` success never means the entire Memory pipeline is ready;-- ordinary page reads do not invoke active processing probes or deep provider-root scans;-- `/metrics` is optional and not a core dependency;-- no new EverOS business-metrics API;-- no new private EverOS SQLite reader or private EverOS status protocol;-- do not implement profile/data rebuild or an index rebuild workflow as part of this page;-- `manual_required` is visible read-only; no resolution button, decision form, or fence-release action.--Reuse the native Processing Record adapter and UI data shapes where possible. If an existing-adapter cannot read a source safely, return `unknown`/`unavailable` rather than inventing a complete-status. Do not expand a pinned-runtime adapter into a new global state machine.--### 4.5 Processing Record UI--Implement the UI directly in the same PR; no separate mockup gate. The owner will inspect the actual-page and request follow-up visual changes if needed.--The page should clearly separate:--- EverOS runtime/capability summary and observation time;-- source availability;-- recent processing timeline/list and detail;-- anomalies, recovery notices, and read-only `manual_required` records.--Use existing UI primitives, existing layout conventions, and frontend i18n files. Never hardcode-user-facing strings in React components. Keep bodies, secrets, raw attachment bytes, vectors, and-unrelated high-cardinality IDs out of the rendered page. Validate with `cd ui && npm run build`.--### 4.6 Single-run search policy--Ship one Avibe-owned `RecallPolicy` per request with these modes:--- `keyword` — precise names, IDs, error codes, and terms;-- `vector` — semantic similarity;-- `hybrid` — general default;-- `agentic` — explicit opt-in only.--No `declarations` list, duplicate-key trick, multi-run execution, or fan-out ceiling is needed in this-first delivery.--Policy requirements:--- `auto` may choose only among non-agentic modes and never implicitly escalates to `agentic`;-- `agentic` requires explicitly declared non-zero `timeout_seconds`, `max_model_calls`,- `max_results`, and `cost_budget_tokens`; missing capability or budget fails closed with an explicit- `capability_unavailable`/validation result and never silently falls back to `hybrid`;-- `keyword` remains usable when embedding is unavailable;-- profile reads follow the decided user-global owner-keyed path;-- session overlays accept only the trusted current canonical session and reject arbitrary caller- `session_id` filters;-- freshness/source/watermark markers remain explicit, but caller-facing bounded-freshness controls are- deferred from the first UI/API surface;-- cross-platform IM alias pairing is deferred.--## 5. Explicit non-goals and deferred work--The one remaining PR must not absorb the following:--- old schema inspection, migration, compatibility, legacy preservation, or historical-data rebuild;-- broad user-data/index/profile rebuild workflows or generic rebuild actions; issue #1314 adds only- the confirmed embedding-identity recovery defined in `memory-embedding-rebuild-recovery.md`;-- audited manual operation, manual decision rows, or manual-resolution UI;-- multi-run/fan-out search;-- cross-platform IM alias pairing;-- private EverOS SQLite/status protocol;-- deep provider-root scans on ordinary page reads;-- new EverOS business-metrics APIs;-- assistant/tool/agent capture;-- exactly-once claims that require unavailable EverOS receipts/reconciliation;-- release artifacts or checksums that have not been published and verified.--Automatic or generic semantic embedding rotation remains future/gated work. Issue #1314 is a narrower-follow-up: an explicit confirmed settings change persists one recovery intent and runs the already-supported pinned-child rebuild without adding background jobs, automatic repair, or a general operations-framework. Its contract lives in `memory-embedding-rebuild-recovery.md`.--## 6. File and ownership boundaries--Expected implementation files include:--- `core/memory/schema.sql`, `types.py`, `store.py`, `worker.py`, and one cohesive coordinator module;-- `core/memory/module.py` / `runtime.py` only for centralized final-flush, clear-journal, and lifecycle- interfaces;-- attachment storage/backup modules where an existing seam exists;-- Processing Record backend/read contracts and existing Memory log handlers;-- `ui/` Processing Record page/components, styles, and i18n files;-- `docs/MEMORY.md` and one tracked implementation spec under `docs/plans/`;-- focused Memory and UI tests.--Do not touch platform adapters, agent backends, generic controller routing, or release files unless a-concrete end-to-end contract requires it and the implementation spec records the reason. Do not modify-or commit this umbrella plan from the implementation worktree.--## 7. Required validation and review--Before opening the PR:--- run focused store/coordinator/worker/module/runtime tests;-- run broader Memory tests;-- run attachment and clear-journal crash/fault tests;-- run Processing Record source-degradation and redaction tests;-- run single-run search policy and mode-capability tests;-- run `ruff check` on every changed Python file;-- run `cd ui && npm run build` when UI changes;-- run relevant scenario/contract tests and name scenario IDs in the PR description when a catalog- exists;-- perform an independent quality review of the complete diff for correctness, simplicity, scope, and- test quality before merge.--Delivery rules:--- branch from latest `origin/dev` and open one real non-draft PR targeting `dev`;-- automatic Codex review only; do not manually comment `@codex review`;-- poll the automatic review and CI state at one-minute intervals; do not create a managed background- watch for this delivery;-- if the same architectural review theme repeats twice, stop and revisit the contract instead of adding- another patch layer;-- merge only when CI is green, the latest-head Codex review is clean, zero unresolved review threads- remain, `mergeStateStatus == CLEAN`, and the implementation Session is quiescent. The orchestrator- may merge directly once those mechanical gates pass.--## 8. End-state acceptance checklist--### Flush and durability--- Continuous successful adds do not trigger one flush each.-- Idle, max-age/message-bound, explicit final flush, and boot recovery work durably.-- Final flush acquires the fence before checking drain and holds it through `/flush`.-- Captures during a flush persist in the next generation; same-session delivery waits; unrelated- sessions continue.-- Settlement is CAS-protected by exact canonical session, generation, and fence token.-- Natural `status=extracted` settles the exact generation without redundant `/flush`.-- `first_unflushed_at` does not move on every message; max-age cannot starve.-- Ambiguous flush outcomes become terminal `manual_required`, retain evidence, and never auto-replay.-- Shutdown does not block indefinitely on an LLM flush.--### Attachments and clear--- An accepted recoverable attachment is pinned in Avibe-owned private durable storage.-- Attachment paths are confined, privacy-safe, backed up, and never logged/rendered as raw bytes.-- Clear writes its journal before destructive work, records substeps, and retains completion evidence.-- Crash recovery cannot silently delete data, replay cleared data, or convert `manual_required` into a- successful resolution.--### Processing Record--- The page contains runtime summary, source availability, recent pipeline, anomalies/recovery, and- diagnostic detail without a separate Memory status console.-- Runtime summary is sourced from public EverOS `/health` and includes `observed_at`.-- Pipeline history reads bounded native EverOS provenance.-- Missing/stale/locked/unreadable sources show local `unknown`/`unavailable` states.-- `/health` success is not presented as global pipeline readiness.-- `manual_required` is visible but has no resolution control.-- No private EverOS SQLite dependency, deep scan, new metrics API, or data-rebuild action is required.-- Bodies, secrets, attachments, vectors, and unrelated identifiers are not exposed.-- UI i18n and `npm run build` pass.--### Search--- `keyword`, `vector`, `hybrid`, and explicit `agentic` have provider-neutral adapter tests.-- `hybrid` is the default; `keyword` works without embedding.-- Agentic missing capabilities/budgets fail closed without fallback.-- Search is single-run only; no fan-out or IM alias pairing ships in this PR.-- Profile follows user-global scope and overlays use only the trusted current session.--## 9. Product decision table--| Decision | Final choice |-|---|---|-| Memory data compatibility | New feature; no old-schema inspection, migration, or legacy preservation |-| Delivery shape | One remaining implementation PR into `dev` |-| Provider session identity | Exact `(principal_id, epoch, project_ref, session_id)` `ProviderSessionRef` |-| Flush trigger | Natural add boundary, idle, max-age/message bound, centralized final close, durable boot recovery |-| Flush ordering | Fence first, then drain, flush, exact-token CAS settlement, release next generation |-| Ambiguous provider write | Terminal `manual_required`; retain evidence; no automatic replay |-| Manual resolution | No `operate`, decision rows, or resolution UI in this scope |-| Attachments | Pin/copy before recoverable acceptance; include in backup scope |-| Clear | Destructive, journaled two-phase operation; never a manual-resolution shortcut |-| Processing Record source | Public EverOS `/health` plus bounded native EverOS memcells, runs, semantic files, profile state, and index state |-| Processing Record UI | Implement directly; no separate mockup approval round |-| Global readiness | Not derived or claimed from partial sources |-| Search | Single-run `keyword/vector/hybrid/agentic`; hybrid default; agentic explicit and fail-closed |-| Fan-out | Deferred; no multi-declaration request body |-| IM alias pairing | Deferred |-| Broad user-data rebuild | Out of scope; #1314 separately permits only confirmed embedding-identity recovery |-| EverOS changes | None; no private status or business-metrics API |-| Runtime manifest | Publish/update only with real immutable artifacts and checksums |-| Automatic/generic semantic embedding rotation | Future/gated; #1314 is limited to explicit confirmed identity recovery |--## 10. Primary source references--### Avibe--- `CLAUDE.md` — repository workflow, testing, safety, and PR rules;-- `core/memory/types.py` — canonical provider session and foundation outcome types;-- `core/memory/schema.sql` — clean durable schema merged by PR #1230;-- `core/memory/store.py` — enqueue, claim, settle, recovery, and terminal visibility;-- `core/memory/worker.py` — current durable `/add` delivery path;-- `core/memory/everos.py` — public UDS `/add`, `/flush`, `/health`, `/search`, and `/get` adapter;-- `core/memory/module.py` and `core/memory/runtime.py` — Memory interface and managed lifecycle;-- `core/memory/everos_insight/` — native Processing Record adapter;-- `ui/` — existing Processing Record UI, primitives, layout, and i18n;-- `docs/MEMORY.md` — user-facing Memory behavior and recovery notes.--### EverOS--Use the pinned runtime contract and public interfaces already consumed by Avibe. The remaining PR must-not assume new EverOS source changes or private database semantics beyond what the native adapter-can safely confirm.diff --git a/docs/plans/everos-memory-remaining-implementation.md b/docs/plans/everos-memory-remaining-implementation.mddeleted file mode 100644index f69f768b0..000000000--- a/docs/plans/everos-memory-remaining-implementation.md+++ /dev/null@@ -1,318 +0,0 @@-# EverOS Memory Remaining Implementation Spec--Status: historical; superseded by `memory-best-effort-capture.md` and-`memory-processing-log-page.md`--This specification implements the remaining PR defined by-[`everos-memory-adjustment.md`](./everos-memory-adjustment.md). The umbrella plan is the product-decision record; this file freezes the concrete Avibe schema, state transitions, CAS rules, source-contracts, file ownership, and validation for the implementation branch.--## 1. Module boundaries--The public Memory seam remains provider-neutral:--- `MemoryModule.capture()` validates and durably admits one user capture.-- `MemoryModule.recall()` executes exactly one `RecallPolicy` decision and at most one provider search.-- `SessionFlushCoordinator` exclusively owns session generations, fences, explicit flushes, and flush- recovery. `MemoryWorker` only claims and delivers add rows through the coordinator.-- `AttachmentPinStore` owns private durable attachment bundles and crash-safe release.-- `MemoryMaintenance` owns the durable clear-intent marker and four idempotent deletion primitives.- Runtime lifecycle code only establishes the maintenance fence, stops/starts owned processes, and- invokes this seam.-- Processing Record directly projects public EverOS `/health` and bounded native EverOS- memcells, runs, semantic files, profile state, and index state.--No platform adapter, agent backend, release manifest, private EverOS database, or EverOS source is in-scope.--## 2. Canonical session identity--`ProviderSessionRef(principal_id, epoch, project_ref, session_id)` is the only coordination key. Its-deterministic JSON serialization is stored in every session-scoped SQLite row and is the key passed-between Avibe modules. Store methods accept `ProviderSessionRef` or a typed lease, never a bare session-ID or `(session_id, project_ref)` pair.--The EverOS 1.2.3 public request caps `session_id` at 128 bytes. The adapter therefore accepts the full-typed reference and performs the only wire projection: `session_id=ref.session_id` and-`project_id=ref.project_ref`. The bounded `ref.session_id` is already derived from the principal,-project, original session anchor, and epoch. `/add` and `/flush` must receive the same typed reference;-callers cannot construct either wire field independently.--## 3. Durable schema--This is a clean-schema change. Migration, inspection, or preservation of pre-implementation Memory-databases is explicitly out of scope.--### 3.1 Capture outbox--`memory_capture_queue` retains capture delivery only. Remove every `flush_*` column. Add:--- `generation INTEGER NOT NULL CHECK (generation >= 1)`;-- `lease_token INTEGER NOT NULL DEFAULT 0 CHECK (lease_token >= 0)`;-- `add_status TEXT NULL CHECK (add_status IN ('accumulated', 'extracted'))`;-- `attachment_bundle_id TEXT NULL` referencing the attachment bundle table.--The queue continues to retain the canonical serialized reference and the closed states `pending`,-`processing`, `delivered`, `dead`, and `manual_required`. Claim increments `lease_token`; every settle-CAS includes digest, epoch, lease owner, and lease token. `manual_required` retains payload and pinned-attachments. Confirmed delivered/dead outcomes scrub text and mark an attachment bundle for release.--### 3.2 Attachment bundles--`memory_attachment_bundle` contains:--```text-bundle_id TEXT PRIMARY KEY # random 128-bit hex-relative_path TEXT UNIQUE NOT NULL-state TEXT NOT NULL # pinned | releasing-file_count INTEGER NOT NULL-total_bytes INTEGER NOT NULL-created_at TEXT NOT NULL-updated_at TEXT NOT NULL-```--Versioned attachment JSON stores only `kind`, display `name`, `ext`, bundle-relative `storage_key`,-`size_bytes`, and SHA-256. Absolute paths and source URIs are never persisted in the queue payload.--### 3.3 Flush authority and evidence--`memory_session_flush_state` contains one row per serialized provider reference:--```text-provider_session_ref TEXT PRIMARY KEY-epoch INTEGER NOT NULL-open_generation INTEGER NOT NULL-target_generation INTEGER NULL-state TEXT NOT NULL # idle | due | in_flight | manual_required-first_unflushed_at TEXT NULL-last_add_ack_at TEXT NULL-confirmed_add_watermark_ms INTEGER NULL-unflushed_count INTEGER NOT NULL-due_at TEXT NULL-next_attempt_at TEXT NULL-retry_count INTEGER NOT NULL-operation_epoch INTEGER NOT NULL-fence_token TEXT NULL-submission_started_at TEXT NULL-updated_at TEXT NOT NULL-```--`memory_flush_settlements` is append-only and records:--```text-settlement_id INTEGER PRIMARY KEY AUTOINCREMENT-provider_session_ref TEXT NOT NULL-epoch INTEGER NOT NULL-generation INTEGER NOT NULL-operation_kind TEXT NOT NULL # add | flush-operation_token TEXT NOT NULL-observation TEXT NOT NULL # settled | rejected | manual_required-request_id TEXT NULL-confirmed_watermark_ms INTEGER NULL-observed_at TEXT NOT NULL-error_code TEXT NULL-UNIQUE(provider_session_ref, epoch, generation, operation_kind, operation_token)-```--Terminal settlement rows cannot be updated or deleted. Public anomaly projections omit the canonical-reference and operation/fence token.--## 4. Flush state machine and CAS--Defaults are five minutes idle, thirty minutes maximum age, 100 acknowledged messages, three proven-pre-submission attempts, and bounded exponential retry of 1, 2, then 4 seconds.--1. Enqueue ensures a session state row and assigns its current `open_generation`. If a fence exists,- the capture is still accepted into the already advanced next generation.-2. Normal worker claims exclude sessions in `due`, `in_flight`, or `manual_required`. Delivery and- fencing are serialized by the coordinator per exact provider reference; unrelated references may- progress under the existing global provider concurrency bound.-3. An `accumulated` add ack atomically settles the exact row lease, advances the watermark and count,- sets `first_unflushed_at` only for the first ack in the generation, and computes- `due_at=min(last_add_ack+idle, first_unflushed+max_age)`. The message bound makes it immediately due.-4. An `extracted` add ack writes an `add/settled` record for the exact generation and lease token,- advances the generation, reassigns still-pending rows to the new generation, and releases an exact- matching fence without calling `/flush`.-5. A due or explicit final flush first CAS-acquires a fence. It freezes `target_generation`, advances- `open_generation`, increments `operation_epoch`, creates a fresh `fence_token`, and sets `due`.-6. While holding the per-session fence, the coordinator drains target-generation rows. A worker row- claimed immediately before the fence is returned to pending and then drained by the fence owner.-7. Immediately before the HTTP call, CAS on exact ref/generation/token changes `due` to `in_flight`- and persists `submission_started_at`. Only then may the adapter call `/flush`.-8. Settlement CAS includes exact ref, epoch, target generation, fence token, state, and submission- marker. A stale result changes nothing. Confirmed success or rejection writes immutable evidence and- releases the next generation. Ambiguous outcomes write `manual_required`, retain the fence, and- never replay.-9. A proven pre-submission failure leaves `submission_started_at` null and schedules bounded retry.- Exhaustion becomes `manual_required`. On boot, a durable `due` row with no submission marker is- retryable; `in_flight` or any marker-bearing interrupted operation becomes `manual_required`.--Malformed/unsupported 2xx, missing receipt/request ID, timeout, disconnect, and response loss are-ambiguous. A received non-2xx response is a confirmed rejection. Provider health never rewrites one-outcome into another. Runtime shutdown cancels tasks after a short bound and persists unsubmitted work-as due; it never starts a final provider call.--Central lifecycle hooks may request `final_flush(ref, deadline)` only when they already hold a trusted-canonical reference. The initial hooks are `/new`, Workbench archive when the full reference is-available, and the central explicit session-close seam. No IM adapter receives flush logic.--## 5. Durable attachments--Attachment storage is `<effective_home>/memory/attachments/{staging,bundles}`. Directories are mode-0700 and files mode 0600. A bundle contains at most eight files, each at most 25 MiB, with a 100 MiB-capture total.--Pinning uses a no-follow file descriptor, verifies root confinement, owner, parent/file type and mode,-streams copy plus SHA-256 under the size bound, verifies source `fstat` did not change, fsyncs files and-directories, and atomically renames staging to the bundle path. Unsafe/missing/mutated input returns-`memory_invalid_input`; size excess returns `memory_input_too_large`; insufficient space returns-`memory_low_disk_space`; copy/fsync/rename failure returns `memory_store_unavailable`. Capture cannot-return `accepted` until pinning and the enqueue transaction both commit.--Duplicate/rejected admission deletes the unreferenced new bundle. Confirmed add delivery or dead-rejection marks the bundle `releasing` in the same settle transaction, then idempotently removes its-files and finalizes the bundle row. Boot reconciliation completes `releasing` bundles and removes only-unreferenced staging/orphan bundles inside the private root. Pending and `manual_required` bundles are-never removed.--## 6. Durable clear intent--Clear Memory Data uses `<effective_home>/state/memory/clear-intent.json` as its single-source of truth. Every marker contains a new UUID4 operation id. The marker also contains operator reference,-pre/target epochs, `deleting|failed` state, error code, and creation/update timestamps. It-is atomically written through a same-directory temporary file, file fsync, replace, and-parent-directory fsync.--The operation fences claims and runs exactly four idempotent deletion primitives: queue-reset, provider-root recreation, confined legacy-file cleanup, and attachment clear. Completion clears-the in-progress flag and removes the marker. An interrupted or failed marker is retried-automatically on the next reconcile; corrupt or unreadable marker state fails closed for-Memory projection while service startup continues. An explicit Clear request can replace-a corrupt marker. A legacy Clear journal is not semantically migrated: one bounded open-row-probe either permits best-effort deletion or creates a fresh failed marker with-`memory_clear_legacy_state_requires_rerun`. Legacy backup/restore and Clear snapshot residue-is best-effort cleanup only. There is no backup/restore journal or user-facing resume/abort API.-The complete contract and three-tier fault model live in-`docs/plans/memory-clear-durable-intent.md`.--## 7. Recall policy--Each request carries exactly one closed `RecallPolicy`:--```text-mode: auto | keyword | vector | hybrid | agentic # default hybrid-max_results: integer # default 8, range 1..20-include_profile: boolean # default true-include_current_session: boolean # default false-timeout_seconds: positive number | null-max_model_calls: positive integer | null-cost_budget_tokens: positive integer | null-```--Agentic limits are `timeout_seconds <= 30`, `max_model_calls <= 4`, `max_results <= 20`, and-`cost_budget_tokens <= 32000`; all four must be explicitly non-zero. Non-agentic policies reject-agentic-only budget fields. Unknown keys, `declarations`, arbitrary filters, and caller-supplied session-IDs are rejected.--`keyword` requires no embedding. Explicit `vector`/`hybrid` require a latest trustworthy health-observation declaring embedding capability. `auto` chooses hybrid only when embedding is explicitly-available, otherwise keyword, and never agentic. Missing/unknown required capability returns-`memory_capability_unavailable` with zero provider calls and no fallback.--EverOS 1.2.3 neither accepts nor declares enforcement for model-call or token ceilings. Its adapter-therefore declares `agentic_budget_enforced=false`: even a valid complete agentic policy returns-`memory_capability_unavailable` and performs zero searches. This changes only when a future public-EverOS contract both declares and enforces those ceilings; a local timeout is not sufficient.--`include_current_session` accepts only the trusted caller-session header, resolves it through the-current principal/project/epoch to a canonical reference, and emits the sole provider session filter.-Missing or mismatched trusted context fails closed. Profile remains user-global and owner-keyed.-Results publish requested/effective mode, source, overlay use, `watermark_ms` (null when unavailable),-and freshness (`unknown` when the provider gives no marker). One recall performs at most one `/search`;-a provider rejection never triggers another mode.--## 8. Processing Record contract--Keep the existing route family but remove `MemoryModule.status()` and the global-`ready|syncing|degraded|down` projection. `/api/memory/status` becomes a bounded direct projection:--```json-{- "status": "ok",- "source": {- "status": "available",- "observed_at": "2026-08-08T12:00:00Z",- "reason": null- },- "health": {- "status": "ok",- "version": "1.2.3",- "capabilities": {},- "disabled_features": [],- "cascade": {}- }-}-```--The provider port performs one typed `/health` read. Only allowlisted fields are returned; reason lists-are closed/scrubbed, item-limited, and length-limited. A successful read is `available` with the local-observation time. A later read failure returns the last successful snapshot as `stale` with its original-time; no prior snapshot is `unavailable` with `health=null`. Cascade health is a source fact, not a-global readiness claim. Page reads do not invoke processing probes or provider-root scans.--Processing Record has independently degradable runtime, native source, anomaly, maintenance,-and bounded detail projections. Native pagination, authorization, redaction, response-size,-and detail limits remain. Each source section carries `observed_at` or explicit-unknown/unavailable; no queue state is used as fallback evidence.--Anomalies expose only kind, state, operation, time, closed error, attempts, generation, and bounded-request ID. They include confirmed provider rejection, `manual_required`, boot recovery, clear-and recovery. They never expose canonical refs, fence/lease tokens, payloads,-absolute paths, attachment metadata/hashes, vectors, or raw exceptions. `manual_required` is read-only.--The UI merges status and processing views into one Processing Record view with explicit Refresh,-runtime/capabilities, native source availability, anomalies/recovery, and native detail.-It does not poll the composite status every four seconds. Disabled Memory still renders retained local-recovery/anomaly evidence. Clear recovery is marker-owned and has no user-facing resume/abort-commands; `manual_required` has no command. Embedding configuration lock reads a separate cheap local-`data_exists` maintenance fact rather than health or a deep provider-root scan. All copy uses i18n.--## 9. File scope--Expected backend changes are confined to `core/memory/` (schema, types, store, worker, coordinator,-attachments, snapshot, clear journal, EverOS port, runtime/module, and insight projection), existing-internal Memory routes/client, and centralized session lifecycle handlers that can provide the full-reference. Frontend changes are confined to the existing Memory settings/Processing Record components,-API types, and English/Chinese i18n. Update `docs/MEMORY.md`.--Do not update `vibe/memory_runtime_manifest.json` without real published immutable artifacts. Do not-add an EverOS API, private DB reader, metrics dependency, manual-resolution operation, data rebuild,-multi-run search, platform aliasing, or assistant/tool/agent capture.--## 10. Validation matrix--- Store/coordinator: schema, generation assignment, idle/max-age/message triggers, fence-first capture- race, same-ref serialization, unrelated-ref progress, natural extraction without flush, exact stale- CAS, retry cap, malformed/timeout/disconnect terminal behavior, boot before/after submission, and- shutdown with no provider write.-- Adapter: typed ref body, strict add/flush receipts, pre-submission versus ambiguous transport,- complete/scrubbed single-call health, four non-agentic method payloads, keyword without embedding,- and agentic capability fail-closed.-- Attachments: confinement/symlink/special-file/owner/mode checks; byte limits; mutation detection;- fault injection at copy/fsync/rename/DB boundaries; original deletion after accepted pin; duplicate- cleanup; confirmed release; manual/stale retention; boot release/orphan convergence; no leakage.-- Clear intent: crash after marker creation, each deletion primitive, queue-fence clearing, and marker- removal; automatic boot retry; one marker-owned operation; idempotent four-surface deletion; corrupt- marker fail-closed projection; operation fences; legacy journal migration.-- Processing Record: available/stale/unavailable health; Cascade unhealthy as a valid observation;- independently locked/corrupt/schema-incompatible sources; confirmed-only timeline; anomalies and- clear recovery; authorization, pagination, bounds, and redaction; no active probes/root scans.-- Recall: validation for every mode/budget, auto selection limited to keyword/hybrid, zero-call missing- capability, exactly one provider search, no rejection fallback, trusted-only session overlay,- user-global profile, and explicit source/watermark/freshness serialization.-- UI: merged tab, source-independent failures, disabled recovery visibility, read-only- `manual_required`, clear recovery actions, separate maintenance data fact, responsive rendering, and- `npm run build`.-- Run focused Memory/UI tests, changed-Python `ruff check`, broader relevant pytest coverage, and the UI- production build before push.diff --git a/docs/plans/issue-1574-memory-provider-root-ownership.md b/docs/plans/issue-1574-memory-provider-root-ownership.mddeleted file mode 100644index ecf8954ba..000000000--- a/docs/plans/issue-1574-memory-provider-root-ownership.md+++ /dev/null@@ -1,56 +0,0 @@-# Issue 1574: Memory Provider Root Ownership--## Background--A released Memory sidecar/rebuild path can create `memory/everos-root` and write-Avibe-generated control files without first proving the root is owned by the-current Memory store. Clear correctly refuses to delete a root without-`.avibe-memory-root.json`, so a failed durable Clear intent can remain open and-fence every later Memory operation.--## Goal--1. No sidecar or rebuild launch may create or write the provider root unless a- current `ProviderRoot` ownership guard succeeds.-2. Durable Clear recovery must repair the narrow released first-start shape- created by Avibe itself, then finish idempotently.-3. Unknown or unsafe unsentinelled roots must remain fail-closed.--## Solution--- Add a public `ProviderRoot.require_owned()` guard and pass it through the- runtime, sidecar lifecycle, and rebuild process. Run it under the provider- root process lock before directory preparation, generated root config writes,- or subprocess spawn.-- Stop process directory preparation from creating the provider root. It may- create only Avibe child-home/generated directories; the root must already be- a private directory claimed by `ProviderRoot`.-- Add a Clear-only `ProviderRoot.recreate_empty_for_clear()` recovery path. An- unsentinelled root is recoverable only when its top-level shape is a bounded- EverOS first-start state. Complete root TOMLs must exactly match the private- copies in `memory/generated`; interrupted `.toml.tmp` writes must be byte- prefixes of those generated controls; provider data is accepted only after- both final controls exist. The method writes and verifies the sentinel before- reusing the existing destructive primitive.-- Keep ordinary `ProviderRoot.ensure()` strict so normal startup never adopts a- non-empty root.--## Evidence--- Unit: sidecar and rebuild refuse an unclaimed root without writing or spawn;- unsafe/mismatched recovery evidence remains rejected.-- Contract: released first-start root recovery is crash-idempotent through the- existing sentinel and `recreate_empty()` sequence.-- Scenario: `MEMORY-CLEAR-203` retries a failed durable Clear marker against the- released unsentinelled root shape, releases the fence, and allows normal- reconciliation to continue.-- Residual manual: Incus Memory enable -> Clear -> restart remains part of the- integration regression pass.--## Todo--- [x] Add failing ownership and Clear-recovery tests.-- [x] Enforce the provider-root guard in sidecar/rebuild launch paths.-- [x] Add narrow released-shape recovery to durable Clear.-- [x] Update scenario catalog and dependency observation.-- [x] Run focused Memory tests and Ruff.diff --git a/docs/plans/memory-agent-owner-split.md b/docs/plans/memory-agent-owner-split.mddeleted file mode 100644index 0deb872e2..000000000--- a/docs/plans/memory-agent-owner-split.md+++ /dev/null@@ -1,474 +0,0 @@-# Memory: agent-initiated memories as a separate EverOS user owner--## Background--Avibe has two Memory write sources:--1. automatic capture of user messages (`provenance="user_input"`);-2. agent-initiated `vibe memory remember` (`provenance="agent"`,- `core/internal_server.py` `/internal/memory/remember`).--Both currently reach EverOS as the same owner: `EverOSPort.add()` always sends-`sender_id=<user principal>, role="user"` (`core/memory/everos.py`), so an-agent-recorded fact ("the user plans to release on the 23rd") is-indistinguishable from something the user said themselves. `provenance` is-stored locally but never crosses the provider boundary.--Product requirements:--- do not modify EverOS;-- user memories and agent-initiated records are both searchable;-- separate profiles: the real user's profile and the agent's private profile;-- an agent-initiated record is the agent's own memory, even when its content- describes the user;-- no cross-user leakage when different users use the same agent.--Two schemes were reviewed against EverOS code (pinned integration, reviewed at-EverOS `560fb80`):--- **Scheme 1 (rejected): send agent records as `role="assistant"`.**- Structurally unworkable for single-fact records, not merely a poor fit:- - the boundary stage requires a `role="user"` anchor before it cuts cells- (`EverOS/src/everos/service/_boundary.py`, "Need a role=user anchor"- guard) — assistant-only sessions accumulate in the buffer until a forced- flush;- - Episode fan-out only covers `role="user"` senders- (`user_memory.py::_unique_user_senders`) — assistant messages never- produce Episode / AtomicFact / Profile;- - the only possible product is an AgentCase, and `AgentCaseExtractor` is- built for task-execution trajectories, not standalone facts — a single- fact is dropped or distorted into a nonsensical TaskIntent.- Scheme 1 remains the right shape for a future feature that captures real- assistant/tool execution trajectories. It is out of scope here.-- **Scheme 2 (adopted): agent records become a second EverOS *user* owner.**- Both write sources use `role="user"`, but under different `sender_id`s. The- assistant owner flows through the normal UserMemoryPipeline and gets its own- Episodes, AtomicFacts, and Profile. EverOS never knows the owner represents- an agent; the mapping is an Avibe-side convention.--This plan is the implementation contract for Scheme 2. It incorporates the-three blockers found in the design review (owner-aware session derivation,-owner ID shape gates, `ProviderSessionRef` persisted-shape compatibility).--## Verified provider contract (EverOS, no modification)--Load-bearing behaviors confirmed in EverOS source:--- `memorize.mode` defaults to `"agent"`; both pipelines run on the same cells- (`service/memorize.py`).-- The unprocessed buffer and MemCells are keyed by- `(session_id, track, app_id, project_id)` (`service/_boundary.py`- `list_for_track`). **Distinct session IDs can never share a MemCell.** This- is the isolation primitive the whole design rests on.-- Within one MemCell, the Episode is written once per distinct `role="user"`- sender ("every user sender owns a copy of the same narrative",- `pipeline/user_memory.py`). This is why the user owner and the assistant- owner must never share an EverOS session: a mixed cell would fan the same- Episode out to both owners.-- AtomicFacts follow `EpisodeExtracted.owner_id`- (`strategies/extract_atomic_facts.py`); Profile extraction follows- `event.owner_id` (`strategies/extract_user_profile.py`). A single-sender- session therefore yields Episodes, Facts, and a Profile for exactly that- owner.-- `extract_agent_case` returns early with `agent_case_skipped_no_assistant`- when a cell has no assistant senders. Assistant-owner sessions (all- `role="user"`) never produce AgentCases. The per-cell warning log this emits- is a known, accepted side effect.-- Search is owner-exclusive: `user_id` XOR `agent_id`- (`memory/search/dto.py::SearchRequest`). Assistant-owner data is user-memory- and must be queried with `user_id=<assistant owner>`, never `agent_id`.-- `sender_id` is a `PathSafeId`: charset `^[a-zA-Z0-9_.@+-]+$`, length 1..128- (`entrypoints/api/routes/memorize.py`). It becomes an on-disk directory- segment.--## Design--### 1. Memory owner model (Avibe-side)--New vocabulary, kept strictly separate from the authenticated caller:--- `caller principal` — unchanged; the `u-`-prefixed ID resolved by- `_memory_cli_scope` / capture admission. All access-control gates keep- validating this with `is_principal_id`.-- `memory_owner_kind: Literal["user", "assistant"]` — derived, never- caller-supplied.-- `memory_owner_id` — the EverOS-facing owner:- - `user` captures: the caller principal itself (byte-identical to today);- - `assistant` captures: a derived assistant owner ID (below).--Derivation rule (no new caller inputs):--- `provenance="user_input"` → `memory_owner_kind="user"`;-- `provenance="agent"` → `memory_owner_kind="assistant"`.--The mapping lives in `core/memory/module.py` (`MemoryModule.capture`), the-first layer that owns both the trusted principal and the provenance. Callers-of `/internal/memory/remember` cannot specify an owner; the endpoint contract-is unchanged.--### 2. Assistant owner ID--Shape: `<principal>-agent`, i.e. `u-<32 hex>-agent` — 40 characters, a pure-suffix on the caller principal.--Why a suffix instead of a derived hash:--- collision-free by construction: principals are exactly 34 characters- (`is_principal_id`), so the 40-character suffixed form can never be a real- principal, and distinct users trivially get distinct assistant owners;-- no new information leaves the host: the principal is already sent to EverOS- as `sender_id` today, so suffixing it exposes nothing new;-- no dependency on local store state: a keyed hash would bind the owner ID to- the store's scope key, coupling EverOS-side data to Avibe-local state; the- suffix form is stable regardless of store lifecycle;-- debuggable: `users/<principal>/` and `users/<principal>-agent/` sit side by- side in the EverOS tree;-- future per-agent split extends naturally to `u-<hex>-agent-<agent-key>`- without a schema change. This plan uses the single `-agent` owner: the- remember path (`_memory_cli_scope`) has no per-agent identity today, and one- private owner per user satisfies every stated requirement.--The form satisfies EverOS `PathSafeId` (`-` is allowed, length ≤ 128). It is-always constructed server-side from the trusted principal; callers can never-supply it.--A new shape predicate (e.g. `is_memory_owner_id`) accepts the principal shape-and the `-agent`-suffixed shape. It is used only where the *owner* flows;-caller-facing access-control gates keep the strict `is_principal_id`.--**Gate-closure property** (stated once, not maintained as a site list): every-shape validator on the owner flow — from module through store minting,-the sidecar boundary (`_valid_principal` at `_validate_add` /-`_validate_search` / `_validate_get`), provider payload mapping, response-validation, and insight matching — accepts memory owner IDs. The closure is-proven behaviorally, not by enumeration: PR A adds a contract test that-drives an assistant-owner value through each public provider operation-(add, search, get/profile) end-to-end against the stubbed sidecar and-asserts acceptance, so a validator missed today or added later fails the-test instead of costing a review round.--### 3. Owner-scoped provider sessions (Blocker 1)--Avibe never sends raw session IDs; it sends-`src--<keyed digest of principal:project:session>--e<epoch>`-(`core/memory/store.py::_provider_session_ref`).--Change: the digest input's first component becomes `memory_owner_id` instead-of `principal_id`.--- User captures: `memory_owner_id == principal_id`, so every existing user- session digest is **byte-identical to today**. No migration, no orphaned- provider sessions.-- Assistant captures: a different owner ID yields a different digest, so the- assistant owner automatically gets its own EverOS session per- (raw session, project, epoch). Combined with EverOS's session-keyed buffer,- cross-owner MemCell contamination is structurally impossible.--Every derivation and re-derivation site must move together, or assistant rows-get quarantined on recovery:--- `store.provider_session_ref` (minting; gains owner parameters);-- `store.enqueue_request` (mints its own ref inline via- `_provider_session_ref` when persisting a capture row — it never goes- through `provider_session_ref`, so it must take the derived owner- explicitly while continuing to persist the separate caller-principal- column);-- `store.resolve_current_session_scopes` (recomputes expected digests to trust- recovery — must try both owner derivations per scope);-- `_legacy_provider_ref` (v0 migration re-derivation — v0 rows are all- user-owned by definition; derive with owner = principal).--Queue-driven flush *scheduling* needs no changes: `SessionFlushCoordinator`-keys everything by the serialized `ProviderSessionRef`, so the assistant-session gets its own retry/flush lifecycle once its rows exist.--**Terminal flush is not free and is in scope.** The session-end path-(`MemoryModule._final_flush_under_admission`) mints exactly one session ref-from the caller principal today. It must fan out: on a terminal boundary,-final-flush every owner-scoped session that has capture state, so an agent-capture followed immediately by session end is distilled rather than left in-the assistant session's buffer.--**The admission fence stays caller-keyed.** `MemoryModule.capture` keys its-admission lock by the caller principal's scope; if lifecycle resolution-returned owner-qualified scopes, the terminal path would acquire an-assistant-owner lock that does not exclude a racing capture holding the-caller-keyed lock, and the final flush could complete before the capture-commits. Therefore the lifecycle fence (scope resolution and admission-locking) remains keyed by the caller principal exactly as today, and the-owner fan-out happens *beneath* that fence: inside the held admission, the-terminal path derives both owner session refs for the caller's scope and-flushes each; both flush tasks are scheduled concurrently under the shared-terminal deadline, so a stalled first leg cannot starve the second-(`SessionFlushCoordinator.final_flush` handles one session today), and the-terminal-boundary test covers a slow first leg. Owner-aware validation-applies only where an owner (not a-caller) flows — fence keys and access-control gates keep `is_principal_id`.--### 4. `ProviderSessionRef` compatibility (Blocker 3)--`ProviderSessionRef.deserialize` (`core/memory/types.py`) rejects any payload-whose key set is not exactly `{principal_id, epoch, project_ref, session_id}`,-and the serialized form is persisted in the `memory_capture_queue` table-(`provider_session_ref` column). Adding a field would break rollback: rows-written by the new version would fail to load in the old one.--Decision: **keep the four-field shape unchanged.** The `principal_id` field's-semantics widen to "memory owner ID" (its validation was already only-non-empty-string). For user rows the value is unchanged; for assistant rows it-carries the `-agent`-suffixed owner. The queue row's separate `principal_id` column keeps-the caller principal for audit and scope checks, and `provenance` already-distinguishes the two row classes durably.--Consequences:--- old rows load in new code unchanged (they are all user-owned, and owner ==- principal for those);-- new *user* rows are byte-identical to old ones — rollback-safe;-- new *assistant* rows under rollback split into two cases. **Delivered**- rows are preserved: their memories live under `u-…-agent` on EverOS,- invisible to the old read path until re-upgrade restores the fan-out.- **Pending** rows are not deliverable by old code: the old sidecar guard- rejects the suffixed owner with 403 (`sidecar.py:36,88-98`), `EverOSPort.add`- maps that to a non-retryable `AddRejected`, and terminal settlement- dead-letters the row and scrubs its payload (`store.py:2684-2692`). Rows- still queued at rollback time are therefore lost, not parked. This is the- accepted degradation: downgrade compatibility cannot be added to- already-released code, the exposure is bounded to the undelivered queue at- the rollback instant, and nothing crashes;-- Load fixtures: keep a fixture of the released four-field shape plus a- pre-owner-split queue row and assert both load and deliver (persisted-shape- rule).--### 5. Write path--`EverOSPort.add()` keeps sending `role="user"`; the `sender_id` becomes the-capture's `memory_owner_id` (carried by `ProviderSessionRef.principal_id` per-§4). Attachment handling, timestamps, and the add/flush protocol are-unchanged.--Result for an agent `remember` of "用户准备在 23 号做发布":--- lands in the assistant owner's own EverOS session;-- boundary cuts a cell (role=user anchor present);-- Episode + AtomicFacts + Profile update under the assistant owner;-- no AgentCase (no assistant senders in the cell);-- the user owner's Episodes and Profile are untouched.--### 6. Read path: dual-owner fan-out (in `MemoryModule`, not the port)--`EverOSPort` stays single-owner-per-request. `MemoryModule.recall` /-`search` / `profile` fan out:--- run the same query against `user_id=<principal>` and- `user_id=<assistant owner>` concurrently (same method, project, bounded- `top_k` each);-- tag every result with its owner kind; `MemoryItem` gains an optional- `origin: Literal["user", "agent", "both"]` field, serialized only when- present so legacy payload shapes stay stable (same pattern as `project`);-- ranking metadata crosses the port boundary: today `_map_search_items`- discards provider scores and episode IDs, and `MemoryItem` cannot carry- them, so the promised merge cannot be built on `MemoryItem` alone. The port- returns an internal scored result type (provider score, stable episode ID,- timestamp, owner) to the module; the module merges on that type and only- then projects to `MemoryItem`. Score and episode ID stay *optional*: the- accepted provider contract allows search responses without either- (`tests/test_memory_everos.py:692-710`), so requiring them would reject- valid responses. When absent, ordering falls back deterministically to- provider rank, then timestamp, then normalized text; metadata-free- response coverage is retained. The public payload shape is unchanged;-- merge: when both legs ran the same method, merge by EverOS score- (comparable LR-calibrated values), tie-break by timestamp then stable ID.- When the legs ran different methods (agentic recall: user leg agentic,- assistant leg hybrid), raw scores are not comparable, so merge by per-leg- rank interleave instead — deterministic, no cross-method score comparison.- Trim to the caller's limit after merging;-- dedupe: normalized exact-match only. When both owners hold the same- normalized text, the merged item keeps the better hit (higher score for- same-method legs, better per-leg rank otherwise) and carries- `origin="both"` — collapsing must never erase one side's provenance.- Paraphrase duplicates ("我 23 号准备做发布" vs "用户准备在 23 号做发布") are- *not* merged; they coexist and are distinguished by origin labels.- Deterministic near-duplicate detection over paraphrases is explicitly out- of scope;-- partial failure: one failed leg degrades to the other leg's results plus the- existing `memory_search_partial` warning. The all-projects aggregator- (`MemoryRuntime._recall_all_projects`) currently drops `result.warnings`- from successful per-project recalls; it must propagate them so a- single-leg degradation stays visible on the `all` surface;-- `include_current_session` overlays: each leg carries its **own** derived- session filter (the assistant leg filters on the assistant session), since- `filters.session_id` is also what returns that leg's unprocessed buffer- rows;-- response validation in `everos.py` (`_map_search_items`, `_map_profile_item`- and list mapping) compares `user_id` against the owner that was queried, not- against the caller principal.--`profile` returns both owners' profiles as two separately labeled blocks; they-never merge into one ranked list. `list_episodes` stays user-owner-only in-this plan (documented limitation; fan-out is a follow-up).--Cost: recall goes from one provider search to two concurrent ones with-bounded per-leg `top_k`. For `mode="agentic"` the budgets do **not** cover-the fan-out for free, and a split cannot be enforced provider-side: only a-wall-clock timeout crosses the provider boundary, and splitting-`max_model_calls=1` across two legs with per-leg floors is arithmetically-impossible. The design is therefore **at most one agentic leg per recall**:-the user-owner leg runs the caller's agentic policy with the caller's-budgets, and the assistant-owner leg always runs `hybrid` (no agentic LLM-loop, rerank off per the current port defaults). Both legs share one-wall-clock deadline. This keeps budget semantics exactly as today: the-wall-clock deadline is the Avibe-enforced bound, while `max_model_calls` /-`cost_budget_tokens` remain declared policy that does not cross the provider-boundary — a pre-existing limitation of single-owner agentic recall that the-fan-out neither fixes nor worsens, because it still issues at most one-agentic provider run. The assistant leg's slightly weaker retrieval is-acceptable for short factual records.--### 6a. Diagnostics (Settings Memory log)--`core/memory/everos_insight/reader.py` recognizes only the 34-character-principal shape (`_PRINCIPAL_RE` / `_PRINCIPAL_GLOB`) and scopes MemCells by-exact caller principal, so assistant-owned processing would silently vanish-from scoped and admin diagnostics. The insight reader gains the same trusted-caller→owner expansion as the read path, stated as a property over the whole-reader rather than a predicate list: a caller's scoped view covers its-principal owner and its derived assistant owner wherever the reader matches,-scopes, or correlates by owner — list, capture↔MemCell correlation, and-detail queries alike (queue rows stay keyed by the caller principal, so-correlation joins translate caller→owner rather than comparing raw IDs).-Insight tests cover assistant-owned entries at list and detail level. This-ships in the same PR as the write-path switch — the processing log must never-have a window where accepted captures are invisible to diagnostics.--### 7. Injection and surfaces--Wherever recalled memory or profile text is injected into agent context or-shown to users, the two origins stay visibly separated (user-direct memory vs-agent-recorded memory). This covers every user-visible surface: injected-agent context, Web UI panels, and the human-readable CLI output-(`vibe memory search` / `profile` without `--json`). All display strings go-through `vibe/i18n/` (backend) and `ui/src/i18n/*.json` (frontend); no-hardcoded labels. The system-prompt-guidance in `core/system_prompt_injection.py` is updated in the same PR that-changes recall output, since its CLI examples are live contract surface.--### 8. Historical data--- No migration of existing memories: EverOS output carries no provenance, so- old agent-recorded facts cannot be reliably identified inside the user- owner. They stay where they are.-- The same stance covers the upgrade window's queue: a pre-split pending row- with `provenance="agent"` carries a user-owned ref and delivers to the- user owner — exactly where pre-split semantics put every agent memory, so- this cannot leak anything the old contract did not already share. No- rederivation of legacy rows.-- The dual-owner search reads both owners, so pre-split agent records remain- findable (labeled as user-owner since that is where they physically live).-- No text-similarity-based guessing migration, ever.--## Non-goals--- No EverOS changes.-- No `role="assistant"` / AgentCase writes (future trajectory capture only).-- No per-agent assistant owners in this iteration (derivation is ready; the- identity plumbing is not).-- No paraphrase-level semantic dedupe.-- No UI management pages for the assistant owner beyond labeled search/profile- output.--## Acceptance criteria (invariants)--1. **Ownership routing.** For every capture accepted at or after the split,- the provider-visible owner is a pure function of `provenance`:- `user_input` → caller principal, `agent` → that caller's derived assistant- owner. Pre-split queue rows deliver under the contract they were enqueued- with (user owner) — consistent with the no-migration stance in §8. No code path sends an assistant- capture under the principal or vice versa (assert by seeding one capture- of each provenance and inspecting the provider payloads).-2. **Session disjointness.** For any (raw session, project, epoch), the two- derived provider session IDs differ, and every provider payload's- `sender_id` matches its session's owner. Existing user-capture session- digests are byte-identical before and after the change.-3. **Recovery closure.** Every queue row shape that could exist on disk- (v0 rows, released four-field refs, new assistant rows) loads, revalidates- through the owner-aware re-derivation, and delivers — seeded as one row per- shape, asserted unchanged after recovery, not enumerated as skip-lists.-4. **Search fan-out.** One Avibe search returns both owners' hits, each- tagged with its origin; an exact-duplicate collapse carries both origins;- a single-leg provider failure yields the other leg's results plus a- partial warning; profiles render as two labeled blocks and never- interleave.-5. **Budget closure.** A recall executes at most one agentic provider run- regardless of fan-out, under one shared Avibe-enforced wall-clock- deadline; declared model-call/token budgets keep their current- single-search semantics (the fan-out adds no second agentic spender).-6. **Terminal flush closure.** A session reaching a terminal boundary- final-flushes every owner session that holds capture state for it; an- agent capture immediately before session end is distilled and searchable- afterwards.-7. **Diagnostics closure.** Every accepted capture remains visible in the- Settings Memory processing log under its trusted caller's scoped view,- regardless of owner.-8. **Cross-user isolation.** Distinct principals derive distinct assistant- owners; no search, profile, or clear path accepts a caller-supplied owner- ID.-9. **End-to-end (scenario).** An agent `remember` of a user fact yields, in- the assistant owner only: an Episode, at least the possibility of Facts and- a Profile update; no AgentCase; the user owner's profile unchanged; and a- subsequent search on the fact's keyword recalls it with the agent-origin- label.--## Testing--- Unit: owner derivation (shape, stability, per-user distinctness), session- digest disjointness and user-digest byte-stability, `ProviderSessionRef`- round-trip with released fixtures.-- Contract: provider payload assertions for both provenance classes against a- stubbed sidecar; fan-out merge/dedupe/partial-failure semantics; response- validation against queried-owner identity.-- Scenario: extend `tests/scenarios/memory_search/catalog.yaml` with- agent-owner scenarios (write isolation, dual-owner recall with labels,- cross-user isolation) and wire IDs into the tests and PR descriptions.-- Residual manual: one Incus regression pass exercising `vibe memory- remember` plus Settings search, verifying labels and profile blocks.--## Delivery plan--Three PRs, in dependency order. **Reads land before writes**: shipping the-writer first would make every `remember` between the two PRs invisible to-recall, search, and profile; shipping the reader first is a safe no-op (the-assistant owner is empty until the writer lands, and the empty leg returns-nothing).--1. **PR A — read fan-out + labeled surfaces.** Owner-ID derivation and the- owner-aware shape predicate, plus read-side owner-aware session-ref- support (`_provider_session_ref` owner parameter and a- `provider_session_ref` entry point that accepts the derived owner —- without it the assistant leg's `include_current_session` filter cannot be- minted past the `is_principal_id` gate). Dual-owner recall/search/profile- in `MemoryModule`, the internal scored result type at the port boundary,- origin tags (including `both`), merge/dedupe/partial semantics,- single-agentic-leg budget rule, per-leg session filters, queried-owner- response validation, backend i18n labels, Web UI labeled rendering- (`MemorySearchPanel` / `MemoryProfilePanel`), frontend i18n, localized- origin labels in the human-readable CLI output- (`vibe/cli.py::_print_memory_cli_human` for `search` / `profile`),- system-prompt guidance update, scenario catalog entries. Deploys dark by- data (assistant owner empty) but complete by capability — no user-visible- surface renders dual-owner data unlabeled.-2. **PR B — write path.** Write routing to the assistant owner:- `store.enqueue_request` owner-aware minting, remaining re-derivation- sites (`resolve_current_session_scopes`, `_legacy_provider_ref`),- terminal-flush fan-out beneath the caller-keyed fence (§3),- `ProviderSessionRef` semantics per §4, `EverOSPort.add` sender change,- everos_insight owner expansion (§6a), fixtures and unit + contract +- scenario tests. The moment this lands, new agent captures are immediately- searchable and labeled through PR A's reader.- User documentation for the changed Memory semantics ships in this PR,- since this is the PR that activates the user-visible behavior.-3. **PR C — regression close-out.** The Incus regression checklist and any- residual scenario catalog updates.--This document is the plan of record; material scope changes update it in the-same PR that implements them.diff --git a/docs/plans/memory-architecture-deepening.md b/docs/plans/memory-architecture-deepening.mddeleted file mode 100644index 8e3c98a70..000000000--- a/docs/plans/memory-architecture-deepening.md+++ /dev/null@@ -1,348 +0,0 @@-# Memory Architecture Deepening--> Status: complete->-> Follow-up architecture work on the Memory system delivered by-> [PR #1006](https://github.com/avibe-bot/avibe/pull/1006). Product behavior is-> unchanged throughout: every item here is a structural change behind existing-> interfaces, verified by the existing Memory test suite.--## Background--The Memory system landed with one declared port — `MemoryProviderPort` in-`core/memory/everos.py`, published alongside `FakeMemoryProvider`. That single-seam is why `tests/test_memory_module.py` needs one `monkeypatch` across 1,612-lines.--The two dependencies that did not get a port cost the opposite:-`tests/test_memory_runtime.py` spends 2,151 lines on 58 `monkeypatch.setattr`-calls and 43 distinct private-attribute pokes, and re-declares the same-`_Process` and `_Artifact` fakes ten times each.--Three things are already deep and are explicitly out of scope:--- `core/managed_runtime.py` — a real seam with three adapters- (`GitRuntimeManager`, `MemoryArtifactManager`, `EngineRuntimeManager`).- Manifest parsing, arch selection, checksum verification and safe extraction- are shared, and Memory reuses them correctly.-- `MemoryModule` — six methods over 1,046 lines.-- `modules/im/message_facts.py` — the five per-platform ordinary-text predicates,- consolidated in `2a504b9e`.--## Goal--Raise the depth of the Memory modules that callers and tests actually cross,-without changing product behavior:--- the interface becomes the test surface, so tests stop reaching past it;-- rules that exist in more than one place collapse into one;-- adding a platform, a status counter, or a runtime method stops requiring- edits in N files.--## Solution--Six changes, each its own commit, in order. Each keeps-`tests/test_memory_*.py` and `tests/test_ui_memory_routes.py` green.--### 1. Ports for the process and artifact dependencies--`MemoryRuntime` constructs `EverOSProcess` and `EverOSPort` internally, so tests-substitute them by patching module globals and private attributes.--The interfaces `MemoryRuntime` actually needs are small:--| Port | Members | Implementation behind it |-|---|---|---|-| `EverOSProcessPort` | `running`, `starting`, `start()`, `stop()`, `processing_healthy()` | `EverOSProcess`, 990 lines |-| `MemoryArtifactPort` | `resolve_python()`, `status()`, `ensure()`, `provider_root_format()`, `artifact_fingerprint()`, `compatible_provider_root_formats()`, `set_provider_root()`, `set_activation_coordinator()` | `MemoryArtifactManager`, 668 lines |--Declare both as `Protocol`s next to their implementations, publish a fake with-each, and let `MemoryRuntime` accept a process factory plus a typed artifact-port. The defensive `getattr(self._artifact_manager, "...", None)` checks in-`runtime.py` exist only because the interface was undeclared; a port removes-them.--### 2. Collapse `UnavailableMemoryRuntime`--`UnavailableMemoryRuntime` mirrors ten methods of `MemoryRuntime` by hand and-answers one condition — "the store could not be opened" — three ways: raising-`MemoryStoreUnavailableError`, returning `{"status": "failed"}`, and returning-`{"ok": False}`. It is returned as a bare union with no `Protocol`.--Make store acquisition lazy inside `MemoryRuntime`, make "unavailable" one of its-internal states, and report it through the existing `OperationFailed` result.--### 3. Queue lifecycle behind `MemoryStore`--`MemoryStore` exposes 30 public methods to exactly two callers. Fourteen of them-form the delivery and fault-breaker state machine, whose rules live in-`worker.py`: the store does not enforce that a claimed row is settled, or that a-flush marked in flight reaches a verdict.--Collapse those primitives into transition methods that take an outcome.--`compact_terminal_tombstones` has no caller outside the store, but its retention-rule has no other direct test, so it stays public rather than losing coverage.--### 4. One status bucket contract--`memory_status_buckets` (`core/memory/presentation.py`) and-`memoryStatusBuckets` (`ui/src/lib/memoryStatus.ts`) implement the same-six-bucket rule once per language, each with its own dedicated test, while-nothing verifies that the backend emits those six counter names.--Emit the buckets from `MemoryModule.status`, delete the TypeScript copy, and-replace the four ad-hoc result type guards in `SettingsMemoryPage.tsx` with the-discriminated result the backend already returns. `vibe/cli.py` already consumes-the Python one.--### 5. `core/memory/admission.py`--Capture admission is decided across `Controller` (six methods, ~130 lines),-`session_turns`, `ui_server` and the adapters, carried by a nullable-`is_ordinary_text` bool on `MessageContext` that nothing enforces. The Workbench-predicate sits in `vibe/ui_server.py` while its five siblings live in-`modules/im/message_facts.py`.--Move the admission methods into `core/memory/admission.py` taking a facts record-and returning the existing `CaptureRequest | CaptureSkipped`, and move the-Workbench predicate next to the others.--This finishes an intent the Memory contract already states — "platform adapters-classify native events but do not own Memory business logic" — rather than-revising it.--### 6. Memory read module in the UI--`SettingsMemoryPage.tsx` is 1,122 lines with 32 `useState` calls, where five-panels each re-implement fetch, loading, error-code mapping and result-discrimination. The six memory routes plus seventeen helpers are inline in-`vibe/ui_server.py`.--Extract one read module the panels call, split the panels into their own files,-and lift the routes into a module of their own.--## Todo--- [x] 1. Ports for `EverOSProcess` and `MemoryArtifactManager` — `d13fef20`-- [x] 2. Collapse `UnavailableMemoryRuntime` — `a2afdadb`-- [x] 3. Queue lifecycle behind `MemoryStore` — `3989a8e8`-- [x] 4. One status bucket contract — `f170ddb3`-- [x] 5. `core/memory/admission.py` — `3546c638`-- [x] 6. Memory read module in the UI — `a515f053`--## Validation--Per commit:--- `uv run pytest tests/test_memory_*.py tests/test_ui_memory_routes.py`-- `ruff check` on changed Python files-- `cd ui && npm run build` for commits touching `ui/`--Full-suite gates stay on GitHub CI.--## The activation flake, root-caused and fixed--`tests/test_memory_runtime.py -k activation` failed about 1 run in 30 with-`FileNotFoundError` on `memory.sqlite-shm` surfacing as `memory_clear_failed`.-Measured at the same rate before this work, so it was not caused by the-refactors — but `MemoryStore._enforce_private_database_modes` guarded only its-first `lstat`, leaving `chmod` and the verifying `lstat` exposed when WAL-checkpointing removed a sidecar between calls. That method runs on every-`_connection()` entry and exit, so any concurrent connection could trigger it.-Fixed in `654c55de`; 0 failures in 40 runs after.--## Follow-ups this work deliberately left open--- **`modules/im/slack.py` hardcodes `is_ordinary_text=True`** on the native- slash-command context. Reads as drift from `2a504b9e` rather than intent, and- the Memory contract treats a slash command as a control event. Latent, not- live: slash commands never reach `MessageHandler.handle_message`. Changing it- is a product-behavior decision.-- **Three failure conventions for an unavailable store** remain- (`MemoryStoreUnavailableError`, `{"status": "failed"}`, `{"ok": False}`).- Unifying them onto `OperationFailed` would turn the 503s in- `core/internal_server.py` into 200s, so it needs a product decision.-- **Profile and search still repeat the item-list markup.** Second occurrence,- not third; extract on the next repeat.-- **`isMemoryForbidden` is a shape probe, not a discriminant.** It matches the- loopback-403 body (`status: "failed"` with `error: "memory_disabled"`) because- `getJson({handleError: false})` discards the HTTP status. Replacing it properly- means exposing the status code from the API layer.--## One behavior nuance worth recording--`failureRetentionDays` used to be sticky: the page updated it only when a-response carried a numeric `retention_days`, otherwise it kept the previous-value. It is now `failuresRead.data?.retention_days ?? 90`. The two differ only-for a response that carries items but omits `retention_days`, which-`core/memory/runtime.py` never sends and `MemoryFailureLogResult` types as-required — equivalent under the declared contract, but not literally identical-code.--## Review round on the pushed range--Two independent reviews ran against `ab9dbb4d`: a local Codex pass-(`gpt-5.6-sol`, max effort) over the nine-commit range, and the GitHub Codex bot-over the whole PR. Eleven findings, all fixed in `654c55de..d8bfd0bb`.--Three were introduced by this work:--- `4bfe5318` — admission fail-open on malformed booleans. Extracting the policy- into `core/memory/admission.py` left strict boolean normalization behind in- `Controller`, so the new security boundary was not self-contained.-- `6dd7f9df` — boot recovery sampled its clock before reclaiming leases instead- of after, because three ordered store calls collapsed into one.-- `6988a7ca` — the extracted read hook stopped clearing a stale error on retry.--Eight were pre-existing in PR 1006 and are fixed here because they ship in the-same PR:--- `654c55de` — SQLite sidecar removal races (the flake above).-- `7f518b43` — **Slack Memory capture was inoperative against real payloads.**- Every message from a modern Slack client carries a `rich_text` block, and the- predicate rejected any event with truthy `blocks`. The only existing test used- a bare `{"text": "hello"}` event, a shape production never delivers.-- `eb4ab1fa` — status polls could stack and land out of order.-- `3f8df6ea` — pre-upgrade IM dedup rows were ignored on redelivery.-- `854529f7` — CLI capabilities never expired.-- `8c955c85` — overlapping settings saves could roll back over a newer write.-- `ac4bdecb` — generated control files made an empty provider root look occupied.-- `d8bfd0bb` — the UI proof secret desynchronized after a partial restart.--### Second review round on `03c4c2cd`--The GitHub Codex bot found six more, all verified against the code and fixed.-Two are consequences of the first round rather than new ground:--- `3eed43e5` — **`doctor repair` did not carry the proof-secret fix.** It stops- the old service and starts a replacement beside a surviving UI, which is the- case `cmd_start` handles by restarting the UI; a bare CLI holds no process- secret, so the new controller verified with `None`. Not the accepted- degradation below — that one is service-*reused*.-- `879c29b6` — the release guard skipped its backup upload on the six-hourly- schedule whenever the probe passed, so a newly published manifest hash had no- artifact to recover from until the weekly Sunday run. Fixed by uploading when- no live backup exists for the hash, and by resolving the backup's run from the- artifact listing rather than a 50-run window that covered ~12 of its 90 days.--Four are independent defects in PR 1006:--- `8bd655f3` identified that Codex and OpenCode persist caller context while- Claude passes it in the child environment. Its backend-specific `0600`/`0700`- hardening was subsequently removed by product decision: Avibe does not treat- arbitrary code running as the same OS account as a Memory isolation boundary,- and will not introduce a partial, POSIX-specific permission contract for two- backends. A future system-wide Agent sandbox must cover all local private- files and every backend rather than special-case Memory storage or one- credential transport.-- `420bc7fc` — the empty-profile warning lived on the shared `EverOSPort`, which- one instance serves every principal from. `profile_payload` sampled it after- its own await, so a concurrent read for another principal decided what a- caller was told; `status_payload` exposed it with no principal at all. Derived- from each request's own result now, and dropped from status.-- `4a199786` — the `engine` fault's Repair button called- `installDependency('memory-runtime')`, which returns- `memory_runtime_install_requires_disabled_memory` whenever the supervisor is- running — exactly the state an engine fault describes, since the worker- classifies it after a *successful* processing-health probe. It now reconciles- the live sidecar through a new `POST /api/memory/runtime/restart`.-- `9db312af` — `cleanup_sync` never settled `_internal_server_task`, so the done- callback that records `stopped` never ran and `internal-server.json` kept- `ready`. Shutdown now cancels and records it directly, and `vibe status`- treats a live state with no service owner as stale — which also covers a- SIGKILL, where no shutdown path runs at all.--Residual limit worth stating plainly: Agent backends run as the local user with-arbitrary local file access. The session-to-principal association scopes-supported Memory API calls; it is not a sandbox against an Agent that-deliberately explores the user's files. Avibe does not inject internal Memory-storage locations into Agent-facing prompts or errors. Enforced local-file-isolation is a system-wide follow-up, not a Memory-specific file-layout promise.--### Third review round on `03c4c2cd`--The bot re-reviewed the same commit before the second round's fixes landed, so-its `core/memory/runtime.py` profile-warning finding is the one already closed-by `420bc7fc`. Four were new:--- `4589e020` — **Memory settings leaked through the generic config response.**- `/api/sessions/<id>/bootstrap` is reachable by an authenticated remote user- over the tunnel and returned `config_to_payload()` whole, including Memory- enablement, both processing endpoint URLs and model names, and- API-key-presence flags — data otherwise served only by the- direct-loopback-only `/api/memory/*` routes. `/api/config` and the config-save- response already popped it; bootstrap did not. Fixed at the projection rather- than the third call site: responses now go through `api.client_config_payload`,- so a new endpoint inherits the exclusion. `config_to_payload` still emits- `memory` because the save path deep-merges from it, and an omitted block- resets the stored one.-- `c7ac506c` — two transport deadlines were shorter than the work they waited- on. `memory_status` gave up at 10s while `MemoryModule.status` bounds its- provider health probe at `PROVIDER_READ_TIMEOUT_SECONDS` (20s), so the- Settings page got a generic transport failure exactly during the outage it- exists to diagnose; the runtime install gave up at 120s while the Dependencies- UI polls for 310s, turning a slow download into a false failure the user could- retry into. Both are now named constants, with- `tests/test_internal_client_timeouts.py` asserting the ordering against the- real sources so raising one bound without the other fails there.-- `2e1f1203` — the active-runtime pointer was accepted when `platform` and- `runtime_version` were merely well-formed strings. Installation rejects a- manifest whose version is not `EVEROS_VERSION`, but the pointer outlives that- check, so a `~/.avibe` moved between architectures kept resolving an- unusable executable. Now compared against `runtime_platform_tag()` and- `EVEROS_VERSION`. Three existing pointer fixtures hardcoded `1.0` /- `darwin-arm64` and were updated to real values so they still test what they- claim.--### Fourth review round on `9601de75cb`--Four new findings were verified and fixed:--- Memory Clear now uses a 150-second transport deadline, beyond its bounded- drain/cleanup plus an enabled reconciliation, so the UI cannot report a false- failure while the destructive request keeps running.-- Settings reconciliation now uses a 120-second transport deadline, beyond its- processing probe, active-add drain, child stop, and replacement readiness- sequence. Tests derive both deadline relationships from the lifecycle's real- constants.-- Artifact activation no longer treats `concurrent.futures.Future.cancel()` as- proof that the controller coroutine settled. The installer waits on a result- bridge completed by the actual `asyncio.Task` done callback, after cancellation- rollback and reconciliation cleanup finish.-- Slack capture now rejects every nonempty message subtype. Ordinary composer- events carry no subtype, so decorated, system, and future subtype forms fail- closed instead of depending on an incomplete denylist.--The remaining caller-context thread was resolved as a product threat-model-decision. Avibe scopes supported Memory API calls through the current Agent-session and its controller-side principal association, but does not claim that-Agent backends with arbitrary access as the same OS user are isolated from that-user's local files. The backend-specific POSIX mode change from `8bd655f3` was-removed; comprehensive local-file isolation belongs in a shared sandbox-covering Claude, Codex, OpenCode, and their child processes.--### The proof-secret gap, decided--`d8bfd0bb` fixes only the half it can without weakening the secret's-stdin-only, never-persisted property. When the service is reused and the UI is-started fresh, the pair stays desynchronized; the gap is logged and the-`vibe stop` recovery step is printed.--**Decision: accept the degradation.** Closing it would mean either persisting-the secret — which would let any same-user process, including an agent backend,-forge local-owner Memory reads — or restarting a live service on a bare `vibe`-re-run, which turns an apparently harmless command into a service interruption.-Neither cost is worth removing a state the CLI already detects, logs, and gives-a one-line recovery for. Documented as a known limitation under `vibe start` in-`docs/CLI.md` and `docs/CLI_ZH.md`.--Scope note: the affected surface is the Web UI Memory Settings page. Direct-loopback reads use the `avibe:local` principal; authenticated Avibe Cloud reads-use the remote Workbench account's `avibe:remote:<subject>` principal behind the-same process-private proof. `vibe memory ...` uses the Agent session's-controller-side principal association and is unaffected.--`d8bfd0bb` also introduces one new behavior, reviewed and kept: when the service-is freshly started and a UI is already running, the UI is restarted so the pair-shares the new secret.diff --git a/docs/plans/memory-best-effort-capture.md b/docs/plans/memory-best-effort-capture.mddeleted file mode 100644index 203f84854..000000000--- a/docs/plans/memory-best-effort-capture.md+++ /dev/null@@ -1,358 +0,0 @@-# Memory best-effort capture (Phase 1)--> Recovery operations in this document are historical. The current lifecycle-> and destructive-operation contract is-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md).--> Status: implementation contract->-> Scope: replace Avibe's durable Memory outbox with a bounded process-local writer.-> Capture loss is intentional; the design optimizes for healthy, unsaturated use-> instead of preserving every item across failures and restarts.->-> This PR implements the contract below in the same change. The implementation and-> focused scenario rewrites are part of this PR; the contract is not a planning-only-> follow-up.--## Decision--> **Reliable control plane, best-effort capture data plane.**--Keep EverOS supervision, provider-root confinement, identity, authorization, and-destructive-operation fencing reliable. Treat capture payloads, retries, flush-schedules, per-call provenance, and failure history as disposable.--Most eligible captures should reach EverOS while Avibe and EverOS are healthy and-the writer is not saturated. There is no zero-loss guarantee, delivery SLO,-cross-restart replay, or complete diagnostic history.--## Product contract--### Optimized path--When the Memory runtime and identity store are ready, the request is authorized,-the writer has capacity, and EverOS is reachable:--1. Avibe reserves bounded process-local capacity.-2. It performs bounded local admission work and enqueues the item.-3. One ordered worker calls EverOS.-4. An acknowledgement updates volatile flush state and small summary fields on a- best-effort basis.--`CaptureAccepted` means only that Avibe accepted volatile work. It does not mean-EverOS stored or processed the content.--### Required guarantees--- Chat, `/new`, archive, configuration replacement, and shutdown never wait for- queued Memory delivery.-- Attachment preparation, queued items, and in-flight items share an explicit- process-wide bound.-- A provider operation that may have executed is not replayed.-- Existing authorization, project limits, and path confinement remain fail closed.-- Stable identity and catalog data survive every recognized store upgrade.-- Clear and Factory Reset retain durable authority; malformed or missing markers- never grant destructive permission.-- Destructive and maintenance operations never race an old provider owner against- a replaced provider root.-- Logs never contain credentials, provider URLs, captured text, attachment paths,- or identity digests.--### Accepted loss--An accepted item may be lost when the process exits, the runtime is replaced, the-writer is full, EverOS fails or returns an ambiguous result, attachment handling-fails, a session barrier is missed, or an upgrade discards old outbox work.-Diagnostics may also omit calls, failures, and correlations.--Record bounded content-free counters or logs when practical, but never make that-record a prerequisite for dropping work or accepting later captures. Do not add a-persistent state machine to distinguish every loss window.--Review guardrail: a finding that only exposes one of these loss windows is covered-by this contract. Fix it only if it also breaks the healthy path, a resource bound,-authorization/confinement, stable identity, or control-plane exclusion.--### Out of scope--- EverOS source, API, data format, or identity derivation changes-- exactly-once, at-least-once, durable replay, or complete diagnostics-- durable per-call provenance, anomaly, gap, correlation, retry, pending-flush, or- attachment-cleanup state-- a new attachment lease design-- automatic Rebuild, Repair, Clear, or Factory Reset-- user-configurable queue, retry, or flush tuning--### `vibe memory remember`--Keep `memory.cli.remembered` as an explicit best-effort acknowledgement and JSON-`ok: true` with `result.status` in `{accepted, duplicate}`. This copy describes-volatile admission, not storage.--## Writer design--### Remove durable delivery state--Delete durable enqueue, claim, lease, retry, settlement, flush FSM,-`manual_required`, tombstone, bundle-ownership, recovery, and drain behavior from:--- `core/memory/store.py`-- `core/memory/coordinator.py` / `SessionFlushCoordinator`-- `core/memory/worker.py` / `MemoryWorker`-- `memory_capture_queue`, `memory_session_flush_state`,- `memory_flush_settlements`, and `memory_attachment_bundle`-- `MemoryRuntime` recovery loops and `MemoryModule.final_flush` waits--### One bounded path--```text-CaptureAdmission- validate + authorize + reject duplicates- |- v-BestEffortMemoryWriter.try_reserve()- one of 256 process-local permits- |- v-optional attachment pin + short identity transaction- |- v-offer_reserved() -> asyncio.Queue -> one ordered worker- |- v-EverOSPort.add / flush -> best-effort summary-```--Fixed implementation defaults:--| Bound | Value |-|---|---:|-| writer permits across preparation, queue, and in-flight work | 256 |-| duplicate source-message LRU | 256 |-| provider attempts per queue item | 3 |-| pending provider sessions | 256 |-| retained message ids per pending session | 100 |-| flush thresholds | 5 min idle / 30 min age / 100 acknowledgements |--These values are not durability promises or user settings.--### Admission--Admission performs no EverOS I/O and no unbounded wait:--1. Run existing authorization, size, scope, and request overflow checks.-2. Under one process-local lock, reserve a permit and claim the source digest as a- non-evictable pending entry; existing digests return `CaptureDuplicate`.-3. Pin optional attachments under that permit. Pin failure must prove confined- cleanup or latch attachment intake off before releasing the permit; admit a- non-empty caption as text-only, while attachment-only input drops.-4. In one short admission critical section and bounded SQLite transaction, compute- candidate catalog and timestamp state. Reject a 17th project or a value above- `MAX_PROVIDER_TIMESTAMP_MS` before mutating either durable field.-5. Remove a failed pending entry. Otherwise convert the reservation to a queue item- and mark it admitted/evictable in the 256-entry LRU under the same lock.--Every reservation stays generation-visible through pinning, its bounded transaction,-and terminal queue conversion or failure. A cancelled generation returns immediately,-but old work keeps its permit until joined or reaped; no late catalog or watermark-commit may cross a transition. Rejected candidates leave state unchanged and create-no recovery item; existing projects remain usable at the limit.--Every queue entry, including a session barrier, owns one permit until its local-operation is terminal; attachment cleanup follows the bounded rule below.--### Ordered worker and retries--One worker preserves ready-queue order. Concurrent attachment preparation may-reorder caller arrival; arrival-order FIFO is not a contract.--Each add or flush has at most three attempts, only after proven pre-execution failure.-A possibly submitted timeout/cancel/transport loss is not retried: the worker starts-the existing bounded owned-sidecar stop/reap and holds its permit until termination-is proved; failure leaves Memory unavailable. Malformed/unclassified responses end.--The sole post-call modality fallback is an attachment rejection for which existing-`attachment_add_rejection_proves_no_write()` positively proves no write. Under the-same permit, the worker may make exactly one caption-only call, still within the-three-attempt total. Empty captions and ambiguous or unclassified outcomes drop.--An acknowledged add updates `last_success_at` and volatile flush state. Summary-write failure never creates a retry or blocks later capture.--### Session flush--`PendingFlush` stores only refs, timestamps, count, up to 100 message ids, and one-scheduled bit. At most 256 sessions are tracked; state disappears on extraction,-runtime replacement, or process exit.--One process-local scheduler drives idle/age/count thresholds without per-session-tasks. An offer failure defers five minutes; success marks it scheduled but-barrier-visible until dequeue. An earlier barrier may extract it; the offer then no-ops.--If the tracker is full, keep the successful add but leave its session untracked.-`/new` and archive make one non-blocking attempt to enqueue a session barrier and-return. At queue head, the barrier flushes currently tracked scopes for that raw-session. It may miss an untracked scope, a capture still preparing attachments, or-state lost during a transition.--A flush uses the same three-attempt cap. Once submitted, it is consumed regardless-of result and never restored to the tracker.--### Runtime transitions--Shutdown stops intake, cancels the generation, and drops queued/tracked work without-draining; process teardown reaps owned work.--Disable or any transition that changes provider authority or its root -- runtime-configuration replacement, Restart Engine, Rebuild, Repair, Clear, or Factory Reset--- drops volatile work; one bounded barrier stops/reaps old RPCs and joins every-old-generation reservation through pinning, transaction, and terminal conversion-before authority publication, provider replacement, maintenance, or deletion.-Cancellation alone is insufficient; failed exclusion keeps old authority/root and fails closed.--## Persistent state and migration--After migration, `state/memory/memory.sqlite` contains only:--- `memory_meta`: epoch, Clear fence, scope/root identity, timestamp watermark,- bounded summary fields, and timestamps-- `memory_projects`: caller principal, project id, and catalog timestamps--Summary fields are not an event log and never gate startup, submission, or later-capture. Stop writing processing-fault/alert/recovery fields. Do not add-`memory_call_provenance`, `memory_processing_anomaly`,-`memory_flush_correlation_guard`, `memory_observation_gap`, or equivalents.--Keep current provider-session derivation:--```text-src--<hmac-sha256(scope_key, "{memory_owner_id}:{project_ref}:{session_id}")>--e{epoch}-```--Keep #1642 ownership: user input uses the 34-character caller principal; agent-provenance uses that caller's derived `-agent` owner; project rows stay keyed by-the caller principal.--Recognize every released v0-v3 shape accepted by the current migrator. Migration:--1. Reconcile readable Factory Reset/Clear intent. An unreadable marker or orphaned- Clear fence stays blocked until an explicit Clear supplies fresh authority.-2. Recognize the confined SQLite shape without writing.-3. In one transaction, preserve identity, catalog, timestamp watermark, and- `last_success_at` exactly from each released shape, deriving v0-v2 catalog rows- from queue data; no helper commits independently. Discard delivery state; install v4.-4. Commit, then checkpoint, close owned connections, and reopen through SQLite's- normal WAL lifecycle. Never unlink WAL, SHM, or journal files directly.-5. Best-effort scrub the confined attachment root, then enable text capture.--Any failure before commit rolls back and leaves the prior logical store intact.-Commit is the migration completion point: a later checkpoint, close, or reopen-problem does not roll back v4. A busy checkpoint is not a migration failure; keep-the committed store and retry normal open/startup handling. Unknown nonempty stores-remain untouched and Memory stays unavailable. Downgrade is unsupported.--## Retained surfaces--### Control plane--Keep artifact installation, sidecar ownership, root confinement,-`MemoryOperationLease`, Restart Engine, Rebuild (`cascade rebuild --yes`), Repair-(`cascade sync`), Clear authority, Factory Reset, and root recreation.--All authority-changing operations use the barrier; none drains or adds delivery-state. Clear retains four confined deletion surfaces: identity/catalog/watermark/summary state,-provider root, legacy call-log files, and attachments; it completes only after all four succeed.--### Diagnostics--- Processing Record shows only caller-authorized data derived from native EverOS- memcells, runs, semantic files, profile state, and index state.-- Missing, malformed, or retained-away evidence makes the relevant source `partial`- or `unavailable`; it never broadens scope or falls back to a legacy call log.-- Migration, restart, pruning, and ambiguous results may leave history incomplete.-- Diagnostic read/write failure never blocks writer startup or provider calls.--Remove delivery-table joins rather than replacing them with durable gap, guard, or-anomaly ledgers. UI/API responses must distinguish an unavailable source from a-complete empty result.--### Attachments--Use the shared permit before pinning and attempt confined bundle release once at a-terminal outcome. If release fails, atomically latch attachment intake off for that-runtime before returning the permit; only already-reserved work may add a bounded-number of orphans. Log without paths.--Run existing confined cleanup before enabling attachment capture. If confinement-or cleanup safety cannot be proved, disable attachment capture for that runtime and-continue text capture. Never reconstruct delivery from leftover bundles or touch-original chat attachments.--### Receipts and callers--| Writer outcome | Receipt |-|---|---|-| admitted to volatile writer | `CaptureAccepted` |-| duplicate in local LRU | `CaptureDuplicate` |-| disabled, invalid, busy, over limit, not ready, or full | `CaptureSkipped` with existing closed code |--Automatic capture logs the receipt without content. `/internal/memory/remember`-continues returning `receipt.status`; callers never see delivery-state primitives.--## Delivery plan--Implementation order:--1. Add identity-only v4 migration.-2. Add the bounded writer, one worker, and volatile flush tracker.-3. Switch capture and session lifecycle callers to non-blocking offers/barriers.-4. Simplify diagnostics without weakening authorization.-5. Delete the durable delivery/observer protocol and obsolete tests.-6. Update scenario catalogs, focused tests, and `docs/MEMORY.md` /- `docs/MEMORY_ZH.md` with the accepted-loss contract.--Prefer one implementation PR. Never ship durable and volatile delivery active at-the same time merely to split the diff.--### Scenario changes--| Scenario | Contract |-|---|---|-| `MEMORY-INDEP-001`, `-002`, `-012` | retain non-blocking lifecycle, accepted loss, and content-free logs |-| `MEMORY-INDEP-003`, `-007`, `-008` | rewrite shutdown to drop; archive offers one barrier then releases authorization without settlement waits |-| `MEMORY-INDEP-010` | rewrite lifecycle snapshots around a non-blocking barrier offer; a capture still preparing or belonging to a stale generation may be missed or invalidated |-| `MEMORY-SEARCH-005`, `-006`, `-012`, `-013`, `-014`, `-017` | rewrite v4 migration/diagnostics; remove reopen recovery; bound flush |-| `MEMORY-SEARCH-016`, `MEMORY-IM-ATTACH-001`, `-003`, `-010` | retain healthy/fallback semantics; replace drain/final flush with test-only worker/barrier sync |-| `MEMORY-REBUILD-202`, `MEMORY-REPAIR-006` | rewrite claim/sidecar assertions around the transition barrier |-| `MEMORY-CLEAR-201`, `MEMORY-FACTORY-003`, `-004`, `-201` | barrier covers post-pin admission; Clear resets stable identity and drops volatile work without replay |-| `MEMORY-IM-ATTACH-004`, `-009`, `-011`, `-013` | retain cleanup/fallback; bound cleanup failure |--Remove only scenarios whose product contract requires replay, exact history, or drain.--### Validation--- Every fixture preserves identity/catalog, exact watermark, and exact `last_success_at`;- v0-v2 catalog derives from queue rows and delivery rows vanish without provider I/O.-- Pre-commit failures leave the old store unchanged with no helper commit;- post-commit checkpoint/reopen failures retain v4 for normal recovery.-- Unknown schemas, unsafe paths, and ambiguous Clear authority fail closed without- writes.-- The 256 permits bound preparation plus queued/in-flight work; rejected project or- timestamp candidates leave catalog and watermark unchanged.-- Ready items preserve queue order; queued flushes remain barrier-visible, concurrent- preparation may reorder arrivals, and queue/flush trackers stay within bounds.-- Offers, barriers, replacement, and shutdown never wait for delivery; transitions- intentionally discard volatile state.-- Adds/flushes stop after three attempts; ambiguous calls initiate bounded reaping;- pin failures and proven-unwritten rejection preserve non-empty captions.-- Diagnostics failure cannot reject capture, missing evidence never widens access,- and unavailable sources are reported truthfully.-- Authority changes quiesce old RPCs and every admission through queue conversion;- no drain occurs, and cleanup failure disables further pinning.-- Logs, summaries, and receipts remain content-free.--Tests must prove the healthy path, bounds, non-blocking behavior, security, and-intentional drops. They must not assert that every capture survives.--If stronger delivery or diagnostic guarantees become necessary, approve them as a-separate measured capability. Do not silently grow this writer back into an outbox.diff --git a/docs/plans/memory-chat-probe-thinking-models.md b/docs/plans/memory-chat-probe-thinking-models.mddeleted file mode 100644index 0cd90abb2..000000000--- a/docs/plans/memory-chat-probe-thinking-models.md+++ /dev/null@@ -1,106 +0,0 @@-# Memory chat probes for reasoning models--Status: approved by owner. This document is the implementation contract for-one small PR. Update it only if scope changes materially.--## Background--Gemini's OpenAI-compat endpoint-(`https://generativelanguage.googleapis.com/v1beta/openai`) with current-gen-thinking models (`gemini-3.5` / `3.6` / `3.7-flash`, and-`gemini-3-flash-preview`, EverOS's official multimodal default) answers Avibe's-chat probe (`max_tokens=8`, `temperature=0`) with a 2xx body that has no-`content` key at all:--```json-{- "choices": [- {- "finish_reason": "length",- "index": 0,- "message": {"role": "assistant"}- }- ],- "usage": {"completion_tokens": 0}-}-```--Probe latency jitters 0.85–4.78s and occasionally exceeds 5s.--Two Avibe-side failures follow:--1. `_chat_probe_response_issue` in `core/memory/everos.py` rejected a missing- `content` key as `provider_response_missing_content`, even though a- present-but-empty `content` is already accepted when `role == "assistant"`- and `finish_reason` is terminal (`stop`, `length`, `content_filter`,- `tool_calls`, `function_call`).-2. `_PREFLIGHT_TIMEOUT_SECONDS = 5.0` produced intermittent- `provider_request_timed_out` on save.--EverOS itself has no such probe. This is Avibe's admission layer only.-Preflight and periodic health share the same chat-response validator for both-`llm` and `multimodal` endpoints.--## Goal--Admit reasoning-model OpenAI-compat chat probes that omit `content` when the-rest of the existing empty-content contract holds, and give save-path preflight-enough wall-clock budget for observed Gemini jitter.--## Changes--1. **Validator tolerance.** In `_chat_probe_response_issue`, a missing- `content` key is treated exactly like `content: null` and falls through to- the existing empty-content branch: `role` must be `"assistant"` and- `finish_reason` must be a terminal string. All other rejections stay- unchanged (missing `choices` / `message`, invalid types, non-terminal or- missing `finish_reason`).-2. **Preflight budget.** `_PREFLIGHT_TIMEOUT_SECONDS` is `30.0` (owner- decision). It still bounds both `asyncio.wait_for` per endpoint and- `httpx.Timeout(..., connect=2.0)`. `vibe/internal_client.py`- `memory_preflight` uses `timeout=None`, so the IPC hop does not cap this.- Worst-case save-path preflight is 4 endpoints × 30s.-3. **Periodic health budget is unchanged.**- `PROCESSING_PROBE_REQUEST_TIMEOUT_SECONDS` stays `8.0`.--## Non-goals--- Do not raise `_CHAT_PROBE_MAX_TOKENS` (stays 8).-- Do not add `reasoning_effort` or any provider-specific request params to- probe payloads. Probes stay lowest-common-denominator OpenAI-compat.-- No config schema change, no UI change, no i18n change, no sidecar / EverOS- change.-- Do not touch `enable_llm_rerank`, agentic recall, or rebuild / recovery- behavior.--## Known notes--- **30s preflight is an owner decision**, not a measured minimum. Observed- Gemini jitter only needed slightly more than 5s; 30s is the granted- headroom, not a claim that probes take that long.-- **Preflight (30s) / health (8s) asymmetry.** A provider that only answers- after more than 8s will pass save preflight and may still flap periodic- health. That split is intentional in this PR: health remains a short- liveness check.-- **Admission risk.** A provider that responds but never produces text now- passes admission when `role` is `assistant` and `finish_reason` is terminal.- Real generation failures surface later in the Processing Record, not at- save-path preflight.--## Diagnostic-code shift--A payload that used to fail as `provider_response_missing_content` because the-`content` key was absent now continues into the empty-content branch. When-`role == "assistant"` and `finish_reason` is also absent, the reported code is-now `provider_response_missing_finish_reason`.--## Tests--- Validator unit fixtures for the Gemini thinking shape, the missing-content- diagnostic shift, a non-assistant role, and the existing OpenAI- `content` / `""` / `null` shapes.-- Preflight contract tests: stubbed `llm` and `multimodal` endpoints returning- the thinking shape pass `EverOSPort.preflight()`.-- Health: `processing_healthy()` judges the same stub healthy.-- The preflight constant is pinned at `30.0`; the health probe budget stays- `8.0`.diff --git a/docs/plans/memory-clear-durable-intent.md b/docs/plans/memory-clear-durable-intent.mddeleted file mode 100644index b5b7bb0df..000000000--- a/docs/plans/memory-clear-durable-intent.md+++ /dev/null@@ -1,179 +0,0 @@-# Memory Clear Durable Intent--> Historical design. Superseded by-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md); no active-> Clear intent is written or resumed.--This document consolidates issue #1392 Rev 2 and the owner-approved Rev 2.1-amendment. It is the implementation contract for Memory Clear.--## Decision--Clear Memory Data is an irreversible, idempotent re-run. The backup/restore and-Clear snapshot stacks are removed. There is no user-facing Resume or Abort-choice: a Clear written by this implementation continues automatically until it-finishes.--The implementation keeps and orchestrates these four high-level deletion-primitives; it does not replace them with raw directory deletion:--1. queue: clear queue tables and call `store.reset_for_clear(target_epoch=...)`-2. provider: call `ProviderRootOwner.recreate_empty()`-3. legacy files: remove the retired `memory/call-log` directory with the confined- filesystem helper, without opening or interpreting its SQLite files-4. attachments: call `MemoryModule.clear_attachments()`--The confined filesystem primitives remain shared infrastructure for Clear,-Reset, and artifact installation.--## Durable marker--The single authority is `<effective_home>/state/memory/clear-intent.json`. It is-written before the first surface deletion and removed only after all four-surfaces complete.--Schema version 1 contains:--- `operation_id`: a new UUIDv4-- `operator_ref`: the initiating operator provenance-- `pre_epoch` and `target_epoch`-- `state`: `deleting` or `failed`-- nullable `error_code`-- `created_at` and `updated_at`--`target_epoch` is fixed at marker creation and never recomputed. Replays pass-that value to the queue reset, whose two-state acceptance allows either-`pre_epoch` or `target_epoch` and prevents a crash from advancing the epoch-twice.--Every create or update uses a same-directory temporary file, file fsync,-atomic replace, and parent-directory fsync. Marker operations run under the-existing maintenance lifecycle lock and `MemoryOperationLease`; there is no-cross-process protocol beyond same-host lease mutual exclusion.--The marker is the source of truth for an open Clear. The queue's-`memory_meta.clear_in_progress` flag is set after the marker is durable. On-completion the four surfaces finish, the queue fence is released, and the-marker is removed. A crash in a terminal step remains recognizable and is-settled on the next reconcile.--## Boot and admission--Boot reconcile keeps Memory fenced whenever a readable marker exists. A marker-written by this implementation is changed from `failed` to `deleting`, the four-idempotent primitives run again, and Memory is unfenced only after terminal-settlement. A failed sweep persists a failed marker and leaves Memory fenced;-service startup continues.--An explicit user Clear may replace an unreadable marker or the failed marker-created for legacy state. It derives a fresh epoch pair from the current store,-writes a new UUIDv4 operation, and converges through the normal four-surface-sweep.--## Fault model--### Tier 1: exact recovery required--- Process crash or power loss at any instruction boundary, assuming POSIX- same-directory rename atomicity and the marker fsync order above.-- Marker durability failures, including fsync, rename, unlink, and parent- directory sync failures. Memory fails closed through a persisted failed- marker when writable, or an in-memory authority error otherwise; service- startup proceeds.-- Same-host mutual exclusion through the maintenance lifecycle lock and- `MemoryOperationLease`. A lease loser defers and does not mutate shared state.--### Tier 2: fail-closed is sufficient--- Any corrupted, truncated, oversized, type-invalid, or otherwise- uninterpretable marker or legacy journal content is refused. Memory is- fenced, the failed projection is surfaced, and an explicit Clear replaces- the state. The implementation does not distinguish corruption causes,- preserve corrupt fields, or enumerate malformed shapes beyond one bounded- read and schema check.-- Filesystem anomalies under `state/memory/`, including dangling symlinks,- permission errors, and files disappearing during a read, follow the same- unreadable-state rule.--### Tier 3: out of scope or best effort--- Legacy backup/restore residue and Clear snapshot cleanup is best effort:- warn and continue without blocking Memory or service startup.-- Adversarial local tampering beyond Tier 2 refusal is out of scope because the- local user owns these files.-- Behavior of foreign or older processes beyond lease mutual exclusion is out- of scope.-- Byte-perfect semantic migration of the legacy Clear journal is not provided.--## Legacy Clear journal--There is no semantic migration and no preservation of legacy `operation_id`,-`operator_ref`, or `target_epoch`. The implementation does not validate legacy-state or resolution vocabularies, row cardinality, surface receipts, or field-types beyond this bounded probe:--1. Detect `clear-journal.sqlite` with `lexists`, so dangling symlinks count.-2. Attempt one bounded query asking whether any row has a non-null open slot.-3. If the query succeeds with no open row, best-effort confined-delete the- journal and do not fence.-4. If the query fails for any reason or finds any open row, write a fresh failed- marker with a new UUIDv4, epochs derived from current `memory_meta`, and- `memory_clear_legacy_state_requires_rerun`; then best-effort delete the- journal. Boot does not replay this marker. An explicit Clear replaces it.-5. If a marker and journal both exist, the marker wins and the journal is- best-effort deleted.--`memory_clear_legacy_abort_unsupported` and all abort-specific handling are-removed.--## API, UI, and projection--The Resume and Abort methods and routes are removed across runtime,-maintenance, internal server/client, UI routes, authorization, API context, and-frontend types. A stale page receives 404 and refreshes into the current shape.--Processing Record replaces `clear_recovery` with:--```json-{- "clear_in_progress": {- "operation_id": "uuid",- "state": "deleting",- "occurred_at": "2026-08-13T00:00:00Z",- "error_code": null- }-}-```--`state` may be `deleting` or `failed`. Marker read failure projects `failed`-with `memory_clear_marker_unreadable`. A row appears in the failures projection-only when its state is `failed`. Backend, UI, and tests consume this one shape.--English and Chinese copy must include-`memory_clear_legacy_state_requires_rerun` and must not retain the abort-specific-error.--## Persisted residue--The retired backup/restore journal, backup directory, and Clear snapshot-directory are removed on boot with confined best-effort deletion. Failure logs-a warning and does not fence Memory or fail service startup.--## Required evidence--- `MEMORY-CLEAR-201`: Clear discards retained ambiguous local evidence through- the four deletion primitives and permits later delivery.-- `MEMORY-CLEAR-202`: a marker written by this implementation is retried- automatically on boot.-- The marker is durable before the first delete and survives interruption after- any surface.-- Re-run does not advance the epoch twice, each primitive is repeatable, and- marker removal occurs only after all surfaces.-- Terminal marker-removal failure stays recognizable and converges.-- Corrupt markers fail closed without stopping service startup.-- The legacy probe distinguishes only open versus no-open; probe failure and an- open row create the fresh rerun-required marker, while terminal residue does- not fence.-- Lease losers defer without mutation and legacy cleanup remains best effort.--Four-platform Incus verification is a residual post-merge check.diff --git a/docs/plans/memory-coupling-followup.md b/docs/plans/memory-coupling-followup.mddeleted file mode 100644index 4cf12d8c9..000000000--- a/docs/plans/memory-coupling-followup.md+++ /dev/null@@ -1,69 +0,0 @@-# Memory coupling follow-up audit--## Background--PRs #1582, #1588, #1589, and #1590 removed four concrete ways in which-Memory could block session archive, overwrite transport identity, leak its-metadata vocabulary into the durable queue, or fence dispatch and `/new`.-Those fixes establish a broader invariant: failure or latency in optional-Memory work must not fail, delay without a product-owned bound, or mutate a-non-Memory workflow.--## Goal--Scan every Memory touchpoint outside `core/memory/` and close remaining-violations of that invariant. Keep Memory-owned operations fail-closed where-required for authorization or data integrity, while keeping messaging,-session lifecycle, startup, and shutdown independent.--## Approach--1. Inventory imports, awaits, locks, callbacks, shared identities, and mutable- state crossing the Memory boundary.-2. Add fast hermetic tests for each credible coupling path before changing it.-3. Fix the highest shared layer and keep provider/platform policy out of core- delivery code.-4. Run focused tests, the Memory independence scenario guardrails, Ruff, and- the broader affected suites.--## Findings and resolution--- Metadata leaf imports previously executed eager `core.memory` package exports- and loaded the full store/worker/provider stack. Public exports are now lazy,- and subprocess contracts prove storage sees only the metadata leaf.-- Lifecycle snapshots previously crossed dispatch through the JSON-oriented- `platform_specific` payload, and reading that key made `MessageHandler` import- the SQLite-backed session FSM. Snapshots now use an explicit transient dispatch- argument, are released after capture admission, and keep lightweight handler- imports storage-free.-- IM attachment filtering previously reached back through `core.handlers`,- creating a handler/session-turn import cycle. The opaque lease and descriptor- validation primitives now live in a dependency-free core leaf.-- Session capture locks, operation locks, and generation integers retained one- entry for every historical session. A weak lifecycle state now stays alive- only while an operation or capture snapshot can still use it.-- Synchronous text-capture setup exceptions could escape into message dispatch.- The scheduling boundary now logs and drops optional work.-- Archived Workbench sessions retained process-local Memory authorization, and- archive flush tasks could outlive Memory runtime shutdown. Archive completion- now forgets the cache, and shutdown closes registration then settles tracked- flush tasks before closing the runtime.--## Residual boundaries--- A user-initiated factory reset remains settlement-first during shutdown. Its- durable recovery intent and provider-root ownership make abandoning it less- safe than waiting; this is explicit Memory maintenance, not an ordinary- messaging dependency.-- No live provider or IM regression is required for these process-local- contracts. Existing five-platform behavior remains covered by unchanged- admission and adapter tests.--## Todo--- [x] Audit controller construction, startup reconciliation, and shutdown.-- [x] Audit capture scheduling, cancellation, and lifecycle generations.-- [x] Audit `/new`, archive, and multi-scope lifecycle paths.-- [x] Audit routing/admission identity and leaf-module dependency direction.-- [x] Add regression coverage and fix confirmed violations.-- [x] Record residual risks and verification evidence.diff --git a/docs/plans/memory-default-project-1393.md b/docs/plans/memory-default-project-1393.mddeleted file mode 100644index 74e710c1c..000000000--- a/docs/plans/memory-default-project-1393.md+++ /dev/null@@ -1,492 +0,0 @@-# Memory default project and explicit project IDs--> Status: accepted-> Issue: #1393-> Branch / worktree: `plan/memory-default-project` at-> `/Users/rk/work/chainbot/avibe-bot/worktrees/memory-default-project`-> Base: `origin/master` @ `b6c4393f`--This revision absorbs the plan review: schema v3, split project-id-predicates, a durable project catalog, a bounded UI-only `all`-contract, multi-project final flush, and a closed ID input matrix.--## Background--#1393 is not a lost-index bug. User conversations are captured under an-EverOS `project_id` derived from the Agent Session workdir-(`p-<32 hex>`). Settings Search then hashes the **default Agent cwd**-and queries that space. A Workbench project whose folder is not the-default cwd returns HTTP 200 with `items: []`.--EverOS treats `project_id` as a hard partition. Search always pins-`project_id = ?`. The literal `"default"` is EverOS's reserved default-space (on disk: `default_project`), not a cross-project view. Avibe's-sidecar currently rejects `"default"` on add/search and only allows-`p-[0-9a-f]{32}`. Profile `/get` already uses `"default"`.--The current store CHECK (`core/memory/schema.sql` `project_ref`, schema-version 2) also only accepts `p-<32 hex>`. Python-only relaxation of-`is_project_id` cannot persist `"default"` or named slugs.--Upstream EverOS 1.2.3 has no global search. Episode LanceDB ids omit-`project_id` (EverOS #320). Multiple EverOS projects for one owner-remain a residual index-collision risk; this iteration reduces how-often that happens, it does not change EverOS key shape.--## Goal--Close #1393 by putting all user conversation capture on EverOS-`"default"`, and by making extra projects **opt-in named slugs**.--- User conversations always write `project_id = "default"`.-- Agent `remember` may pass a named slug. Omitted → `"default"`.-- Settings and Agent search this principal only. No `u-…` fan-out.-- Agent search: `"default"` or a named slug. No `all`.-- Settings Search: picker default `"default"`; may choose a named slug- or **all of this user's catalogued projects**.-- Legacy `p-<32 hex>` is not a product id. It is only a persisted- recovery/drain shape.--## Non-goals--- Cross-user admin search.-- Mapping Workbench `proj_…` or workdir onto EverOS `project_id`.-- EverOS upstream global search.-- Migrating historical `p-…` markdown into `"default"`.-- Changing profile ownership. Profile stays per principal.-- Patching EverOS row ids this iteration.--## Project ID contract--Single module: `core/memory/project_ids.py`. No second charset.--Wire values must already be lowercase. **Do not `casefold()`.** Mixed-case is invalid.--| Token | Shape | New write | Agent search | UI search | Persist / drain |-|---|---|---|---|---|---|-| `default` | exact | yes | yes (CLI default) | yes (picker default) | yes |-| named slug | `^[a-z][a-z0-9_-]{0,62}$`, not reserved, not `p-` prefix | yes | yes | yes | yes |-| `all` | exact | no | no | yes | no |-| `p-[0-9a-f]{32}` | exact legacy | no | no | no | yes |-| `personal` | reserved | no | no | no | no |--Reserved: `default`, `all`, `personal`. Named slugs must not start with-`p-`.--### Input matrix--| Input | remember / user capture | Agent search | UI search |-|---|---|---|---|-| key omitted / JSON `null` | `default` | `default` | `default` |-| `""` / whitespace | invalid | invalid | invalid |-| `default` | `default` | `default` | `default` |-| `Default` / `BILLING` | invalid | invalid | invalid |-| `billing` | create/use `billing` | `billing` if catalogued, else invalid | same |-| `all` | invalid | invalid | UI `all` fan-out |-| `personal` | invalid | invalid | invalid |-| `p-` + 32 hex | invalid | invalid | invalid |-| `p-deadbeef` (short) | invalid | invalid | invalid |-| `u-…` | invalid | invalid | invalid |--Helpers:--- `is_legacy_memory_project_id` — exact `p-[0-9a-f]{32}`-- `is_new_stored_memory_project_id` — `default` or named slug-- `is_persisted_memory_project_id` — legacy **or** new stored-- `is_writable_memory_project_id` — new stored only-- `parse_writable_memory_project`-- `parse_agent_search_project` — new stored only-- `parse_ui_search_project` — new stored or `all`--Callsites must pick a predicate. **Do not** make `store.is_project_id`-a drop-in alias for persisted and keep using it on new write/read-paths.--| Callsite | Predicate |-|---|---|-| New capture (`CaptureRequest` / `module.capture`) | `is_writable_memory_project_id` |-| `enqueue_request` | `is_writable_memory_project_id` |-| `module.recall` / `module.profile` | `is_new_stored_memory_project_id` |-| `provider_session_ref`, `resolve_current_session_scopes`, worker drain, session lifecycle | `is_persisted_memory_project_id` |-| Sidecar add/flush | persisted |-| Sidecar search | new-stored |--If `store.is_project_id` remains as a compatibility name, it may only-wrap persisted and **must not** be called from capture, enqueue,-recall, or profile. Grep those four sites in the implementation PR.--`derive_project_id(scope_key, workdir)` stays for old tests. New-capture and remember must not call it.--## Schema v3 (P0)--Current `MEMORY_STORE_SCHEMA_VERSION = 2`. Fresh `schema.sql` and-existing v2 files must both accept the new project shapes.--### Fresh schema--- Bump `PRAGMA user_version` to 3.-- Widen `memory_capture_queue.project_ref` CHECK to- `is_persisted_memory_project_id` (SQL equivalent of `default` OR- exact `p-<32 hex>` OR named slug).-- Add catalog:--```text-memory_projects (- principal_id TEXT NOT NULL, -- same u- CHECK as the queue- project_id TEXT NOT NULL, -- new-stored CHECK only (no legacy)- created_at TEXT NOT NULL,- last_written_at TEXT NOT NULL,- PRIMARY KEY (principal_id, project_id)-)-```--- Include `memory_projects` in `_MEMORY_STORE_TABLES` /- `_verify_current_schema`.--### v2 → v3 migration--Invariant: **no data loss and the final schema object set matches-v3**. Temporary drop/recreate of queue indexes during the rebuild is-required (SQLite keeps the old index names on the renamed table).-Do not drop settlements, attachments, or their triggers.--One transaction:--1. Drop `ix_memory_capture_due` and- `ix_memory_capture_session_generation`.-2. `ALTER TABLE memory_capture_queue RENAME TO memory_capture_queue_v2`.-3. `CREATE TABLE memory_capture_queue` with the v3 `project_ref` CHECK- and the same columns otherwise.-4. `INSERT INTO memory_capture_queue SELECT * FROM memory_capture_queue_v2`- (every row, including `p-…`).-5. `DROP TABLE memory_capture_queue_v2`.-6. Recreate `ix_memory_capture_due` and- `ix_memory_capture_session_generation`.-7. `CREATE TABLE memory_projects` if missing.-8. Backfill catalog from distinct `(principal_id, project_ref)` **only- where `project_ref` is new-stored**. Never insert `p-…`.-9. Execute `PRAGMA foreign_key_check` and require zero returned rows;- then `_verify_current_schema`; then `PRAGMA user_version = 3`.--Settlement triggers (`trg_memory_flush_settlements_*`) must still-exist after the transaction.--Open path (each step is a real snapshot, not a rename of-`schema.sql`):--| On-disk `user_version` | Action |-|---|---|-| 0, empty | Install current `schema.sql` (v3) |-| 0, recognized non-empty v0 | Keep a frozen v2 `schema.sql` snapshot in-repo. `_migrate_v0_to_v2` applies **that snapshot only**, then `_migrate_v2_to_v3`. Do not point v0→v2 at live `schema.sql` after it becomes v3. |-| 1 | existing `_migrate_v1_to_v2`, then `_migrate_v2_to_v3` |-| 2 | `_migrate_v2_to_v3` |-| 3 | verify only |-| other | fail closed |--Check in `tests/fixtures/memory_foundation_v2.sql` (released v2-shape). Do not generate it from post-change `schema.sql`.--### Legacy non-terminal rows--`pending` / `processing` / `manual_required` rows with `p-…` stay-drivable:--- Worker add/flush still sends that legacy `project_id` to EverOS.-- Sidecar add/flush therefore **accepts persisted ids** (legacy +- new stored) so drain can finish.-- Sidecar search accepts **new stored only**.-- New public remember/search/UI never accept `p-…`.-- After drain, terminal `p-…` tombstones may remain until ordinary- compaction. They are invisible to picker and `all`.--### Tests--- Released v2 fixture (check in a v2-shaped file, or generate from- the current v2 `schema.sql` snapshot) loads, migrates, keeps a- `p-…` queue row, and then accepts a `"default"` enqueue.-- Fresh install is user_version 3 and can enqueue `"default"` and- `billing`.-- A v2 file with a non-terminal `p-…` row still recovers scopes and- can be claimed.--## Durable project catalog--Source of truth for picker, `all`, and “unknown slug”.--- Created/updated in the **same enqueue transaction** as an accepted- capture or remember of a new-stored project. Duplicate remember- upserts `last_written_at`.-- `"default"` is always implicitly searchable. Upsert it on first- user capture or default remember; picker always shows it even if- the row is missing.-- Named slug remember of a not-yet-catalogued id **creates** the- row (that is how a project is created).-- Named slug **search** of a not-yet-catalogued id is- `memory_invalid_input` (unknown).-- Cap: 16 named projects per principal, plus `"default"`. A 17th- distinct named remember is `memory_invalid_input`.-- Clear / factory reset deletes `memory_projects` with the other- Memory tables.-- Picker order: `default`, named by `last_written_at` desc, then- UI-only `all`.-- `all` = implicit `default` + catalogued named slugs (see Read path).--## Write path--### User conversations--`CaptureAdmission.project_for` returns `"default"` and does not-require a workdir. Human Workbench and bound IM turns enqueue-`"default"` and upsert the catalog.--### Agent remember--`POST /internal/memory/remember`: `{text}` or `{text, project}`.--- Missing / JSON `null` → `"default"`.-- Present → `parse_writable_memory_project` (rejects `all`,- `personal`, `p-…`, mixed case, empty).-- Principal and session come from the admitted CLI session, not- from the workdir hash.--```bash-vibe memory remember "<text>" [--project <slug>] [--json]-```--Idempotency:-`agent:{principal}:{project}:{session}:{digest}`.--### Final flush (P1)--`final_flush_memory_cli_session` must flush **every** current-epoch-scope of that raw session, not only live `(principal, "default")`.--- Union live CLI scope with `resolve_current_session_scopes()`.-- Order: `"default"` first, then remaining project ids sorted.-- **One shared deadline** (controller default 5s, same as today's- single-scope budget). Compute an absolute deadline at entry.- Each scope gets only remaining time. After the deadline, do not- start another provider call; mark leftover scopes unfinished.-- Prefer a `final_flush_scopes(...)` helper that reuses the- multi-scope admission-lock pattern from archive.-- If any visited scope with unflushed work fails, or any scope was- skipped because the budget expired, the overall result is failure.-- `archive_memory_cli_session` uses the same union + shared deadline.-- Tests: (1) remember `--project billing` then final-flush visits- `billing` and `default` if in the union; (2) several slow scopes- still finish (or abort) within ~5s wall time, not 5s × N.--### System prompt--- `remember` / `search` without `--project` use `"default"`.-- `remember --project <slug>` only when the fact is explicitly for- that named space.-- `search --project <slug>` only that space.-- Never `--project all` (Settings only).-- Never hashes, never Workbench `proj_`, never `personal`.--## Read path--Principal is always server-side:--- Settings: verified UI user key → one principal.-- Agent CLI: admitted session → that principal.--Callers never submit `u-…`.--### Search request--```text-{ query, policy } # → default-{ query, policy, project }-```--- UI user key: `parse_ui_search_project`.-- CLI session: `parse_agent_search_project` (`all` → 400).--```bash-vibe memory search "<query>" [--project <slug>] [--limit 1..20] [--json]-```--### Universes--| Selector | Who | EverOS queries |-|---|---|---|-| omitted / `default` | UI and Agent | one `(principal, default)` |-| named slug | UI and Agent | one `(principal, slug)` if catalogued |-| `all` | Settings UI only | implicit `default` + catalogued named slugs |--### `all` membership--```text-all = implicit default + catalogued named projects-```--Always search `"default"` first, even if that principal has no-`memory_projects` row for `default` (user created only named slugs).-Then named slugs by `last_written_at` desc. Never include `p-…`.--### `all` recall contract--Applies only to Settings `project=all`.--1. **Modes.** `keyword`, `vector`, `hybrid`, `auto`. Reject `agentic`- and reject `include_current_session=true`.-2. Force `include_current_session=false`.-3. Probe provider health / embed capability **once**.-4. `include_profile` is sent on **at most one** project query (the- `default` query). Every other fan-out call sets- `include_profile=false`.-5. Fan-out sequentially under the existing lifecycle lock. Overall- deadline 20s (must finish inside the 45s search transport).-6. Per-project provider failure: skip, continue. If every project- fails, return the first error. If any succeed, return merged- items plus `warnings` including `memory_search_partial`.-7. Deadline hit: return merged items so far plus- `memory_search_truncated`.-8. Merge: collect items, attach `project`, sort by `date` desc- (missing last), then `kind`, then `text`; dedupe- `(kind, text, date, project)`; bound to `max_results`.-9. UI shows the project badge on each hit when the selector is not- the single default space. Partial/truncated banners must render.--### Search warning codes--`memory_search_partial` and `memory_search_truncated` are-**transport-only** warnings, not persisted queue errors.--- Add a closed `MemoryWarningCode` (preferred) or a transport-only- extension of the public warning union. Do **not** add them to- SQLite `last_error` CHECKs.-- `RecallItems.warnings` / public search JSON use that warning- union, not `MemoryErrorCode`.-- TypeScript `MemoryRecallResult` narrows the same two strings.-- `MemorySearchPanel` renders a banner for each present warning- (EN/ZH i18n + `memoryCopyContract`).-- Tests: API returns the codes on injected per-project failure and- on an injected deadline; UI contract asserts the banner.--`MemoryItem` / search JSON gain an optional `project` field. Single--project searches set it to that project.--Do not fan-out other principals.--### Settings UI--`MemorySearchPanel` `<Select>`: Default, named slugs, All my-projects. Default selected.--`GET /api/memory/projects` returns this principal's catalog rows-plus the implicit `default` and the UI-only `all` option. No host-paths. No other principals.--i18n: `ui/src/i18n/en.json` + `zh.json`,-`memoryCopyContract.test.ts`, `vibe/i18n/en.json` + `zh.json`.--## Sidecar and insight--- Add/flush: `is_persisted_memory_project_id` (drain legacy + new- stored). Reject `all`, `personal`, malformed.-- Search: `is_new_stored_memory_project_id` only.-- Profile `/get` stays `project_id="default"`.--Insight split (admin list currently filters with `_memcell_scope`):--- `_memcell_scope` accepts **persisted** ids (legacy + new stored)- so admin log can still show historical `p-…` memcells.-- User-scoped `_validated_scope` / scoped list+detail accept only- **new-stored** (`default` or named). A scoped read of a `p-…`- project is invalid input, not an empty page.-- Admin SQL/GLOB and the post-filter use persisted.-- Picker / `all` still read **only** `memory_projects` (new-stored),- never insight legacy ids.--## Residual risk: EverOS project collision--Named slugs still share EverOS owner-keyed Lance ids (EverOS #320).-Opt-in + 16-named cap reduces how often two spaces share-`{owner}_{ep_<date>_00000001}`. Markdown paths stay isolated.-**Index isolation is not guaranteed** this iteration.--Accepted residual: two named projects for one principal on the same-UTC day may clobber one Lance episode/profile row. Follow-up is an-EverOS-side key change or a later Avibe rebuild.--Required regression: same principal, two named remembers with the-same text/timestamp class produce distinct Avibe-`(principal, project)` queue identities and distinct EverOS add-`project_id`s. Do not claim Lance-level isolation in that test.--## Residual data--`p-<hash(workdir)>` markdown and tombstones stay on disk. They are-not listed, not in `all`, not searchable, not writable. Drain-only-until compaction. No rebuild in this iteration.--#1393 closes for **new** captures: user turns → `"default"`;-Settings default search → `"default"`.--## Tests and catalog--New capability `memory_search`. IDs in the executable test and PR.--- `MEMORY-SEARCH-001` — Workbench turn whose workdir ≠ default cwd- captures as `"default"` and Settings default search returns it.-- `MEMORY-SEARCH-002` — `remember --project billing` is absent from- default search and present in `--project billing`.-- `MEMORY-SEARCH-003` — Settings `project=all` returns this- principal's `default` + named hits, never another principal,- never a `p-` space.-- `MEMORY-SEARCH-004` — Agent `search --project all`,- `remember --project all` / `personal` / `p-…` / mixed case /- unknown slug search are rejected.-- `MEMORY-SEARCH-005` — v2 store fixture migrates to v3; a- non-terminal `p-…` row still drains; a new `"default"` enqueue- succeeds.-- `MEMORY-SEARCH-006` — `remember --project billing` then- final-flush visits `billing` (and `default` if in the union).--Also:--- Admission: human capture `"default"`; missing workdir still- admits.-- Sidecar: add `"default"` allowed; add `all` / `personal`- rejected; add legacy `p-…` allowed (drain); search legacy- rejected.-- UI route: search forwards only `{query, policy}` or- `{query, policy, project}`.-- Catalog upsert on accepted remember; 17th named project- rejected.-- Insight: `"default"` memcells appear in scoped/admin lists.-- Prompt / CLI-example tests if they pin the old search sentence.--`ruff check` on changed Python. `npm run build` if `ui/` changes.--## Close-out--- Implement on a non-draft PR from this worktree (new implementation- commits, not plan-only).-- PR names the capability, lists `MEMORY-SEARCH-00x`, and states- unit / contract / scenario / residual manual layers.-- After merge (or when the owner says): close #1393.--In this worktree use-`GH_CONFIG_DIR=$HOME/.config/gh-avibe-bot` (`rkrkrkk`).--## Implementation order--1. `project_ids.py` + input-matrix unit tests.-2. Schema v3 + v2 fixture migration + catalog table.-3. Split project-id validation by callsite: writable for- capture/enqueue, new-stored for recall/profile, persisted for- recovery/drain/lifecycle. Admission +- `default_memory_project_id()` → `"default"`.-4. Sidecar persisted-vs-search split; insight new-stored ids.-5. Remember/search payloads, catalog upsert, CLI `--project`.-6. Final-flush union of all session scopes.-7. UI-only `all` with the recall contract above.-8. Settings picker + i18n.-9. Scenario catalog and remaining tests.-10. Prompt + `docs/CLI.md` / `docs/CLI_ZH.md`.diff --git a/docs/plans/memory-embedding-rebuild-recovery.md b/docs/plans/memory-embedding-rebuild-recovery.mddeleted file mode 100644index daf771fdc..000000000--- a/docs/plans/memory-embedding-rebuild-recovery.md+++ /dev/null@@ -1,60 +0,0 @@-# Memory Embedding Rebuild Recovery--> Historical design. Superseded by-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md); an-> identity-changing save now uses the confirmed unified reset without a rebuild-> marker or retry workflow.--> Status: implementation review->-> Issue: #1314->-> Target: `dev`--## Problem and goal--Changing an established embedding base URL or model can leave Memory fenced forever when vector-bearing-data already exists. The confirmed candidate must remain durable, existing Markdown must remain intact,-and the user must have one truthful Retry path.--This plan defines only that recovery path. It supersedes the older blanket deferment of embedding rebuild-in `everos-memory-adjustment.md`; it does not authorize a generic operation system or broad data repair.--## Contract--1. Any unconfirmed embedding identity write returns `memory_embedding_rebuild_required` and writes- nothing. This includes the first non-empty `base_url` or `model`: it must follow the same confirmation,- durable-intent, and rebuild path as a later identity change. API-key-only writes do not change identity.-2. A confirmed change atomically persists the candidate and `recovery_intent: rebuild` before destructive- work. Memory config writes use one cross-process transaction so stale UI or Controller snapshots cannot- overwrite a newer candidate or marker.-3. `MemoryRuntime` owns one retained, shielded rebuild task. Duplicate requests join it, concurrent Memory- mutations return `memory_operation_in_progress`, and callers wait for a closed result rather than poll a- job.-4. Artifact, endpoint, data-state, and quiesce checks complete before the existing sidecar is stopped.- Empty data settles as `completed_empty`; non-empty data runs the pinned role-aware rebuild child.-5. Only `completed` and `completed_empty` clear the marker. `root_busy`, interruption, timeout, and other- failures retain the candidate and marker so Retry is honest. Boot with a marker keeps claims fenced and- never starts destructive work automatically.-6. The browser route accepts exactly `{"confirm": true}` through the existing CSRF and signed-user chain.- Settings expose only `rebuild_required`, confirmation, Retry, and restart admission state; secrets,- progress, job IDs, and operation history remain private or nonexistent.--## Boundaries--- Preserve Markdown and never mix old and new vector spaces.-- Do not fall back to Clear or factory reset.-- Do not add manual rebuild without a pending marker, automatic repair, `cascade sync`, `fix --apply`,- generic operation records, polling, or EverOS source changes.-- Keep the implementation in the Memory config/runtime and existing UI/internal route boundaries.--## Evidence--- Scenario: `MEMORY-REBUILD-101`, `MEMORY-REBUILD-001`, and `MEMORY-REBUILD-201` cover the browser settings- journey at the service boundary.-- Unit: config transaction, runtime fencing/preflight/settlement, retained-task concurrency, and UI state- tests cover local invariants.-- Contract: internal client/server tests prove the exact signed rebuild request and closed response shape;- child tests prove admitted argv and result mapping.-- Residual manual check: inspect the Settings confirmation, pending warning, Retry action, and disabled- Restart state in the packaged UI. No live Memory service or network call is required for automated tests.diff --git a/docs/plans/memory-factory-reset-1315.md b/docs/plans/memory-factory-reset-1315.mddeleted file mode 100644index 2d170c26c..000000000--- a/docs/plans/memory-factory-reset-1315.md+++ /dev/null@@ -1,41 +0,0 @@-# Memory Factory Reset (#1315)--> Historical design. Superseded by-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md); Factory-> Reset was replaced by Repair and the distinct Delete data intent.--## Background--Rebuild can recreate projections from Markdown but cannot recover a corrupt-Memory tree, queue database, or durable state. Factory reset is the supported-replacement path for that corruption floor.--## Frontend contract--- Settings > Memory exposes Factory reset beside Clear all.-- The shared destructive confirmation waits five seconds and names exactly- `memory` and `state/memory` as deleted while retaining settings and the- installed pinned artifact.-- The request is awaited at `POST /api/memory/runtime/factory-reset` with- `{"confirm": true}`; there is no polling or generic operation projection.-- The final payload's `roots` entries are rendered independently so partial- deletion remains truthful.-- A projected `recovery_intent: factory_reset` changes the action to Retry;- invalid or unknown `memory-runtime` artifact state disables it and links to- Dependencies Repair.--## Evidence--- Vitest coverage for confirmation, awaited request, pending Retry, and the- existing Memory settings/recovery controls.-- Scenario catalog IDs `MEMORY-FACTORY-001`, `002`, `003`, `101`, `201`, `202`,- and `301` with executable test docstrings carrying each ID. The backend- service-boundary scenarios exercise the Controller replacement gate, old- runtime worker/process quiescence, stale old-module rejection, fresh runtime- claim resumption, truthful two-root deletion, and durable- `recovery_intent: factory_reset` after post-delete activation failure.-- Focused route contract coverage proves the public adapter preserves the- exact internal `memory_operation_in_progress` closed envelope as HTTP 409- while rejecting malformed envelopes and omitting backend-only fields.-- English and Chinese Memory docs describe deletion scope, retained state,- partial outcomes, and crash recovery.diff --git a/docs/plans/memory-host-architecture-review.md b/docs/plans/memory-host-architecture-review.mddeleted file mode 100644index e26ce464a..000000000--- a/docs/plans/memory-host-architecture-review.md+++ /dev/null@@ -1,30 +0,0 @@-# Memory Host Architecture Review--Issue 1392 Rev 2 removes the backup/snapshot state machines and makes Clear Memory-Data a marker-owned, idempotent operation.--## Verified ownership--- `MemoryRuntime` owns lifecycle admission, fences, and boot reconciliation.-- `MemoryMaintenance` owns the clear-intent marker and calls exactly four deletion- primitives: queue reset, provider-root recreation, confined legacy-file cleanup,- and attachment clear.-- `MemoryProcessingRecord` projects the marker as `clear_in_progress`; failures expose- only the failed marker state and error code.-- UI routes and the Web UI only forward Clear and display read-only marker state.--## Persistence contract--`state/memory/clear-intent.json` is atomically written with a same-directory temporary-file, file fsync, replace, and parent-directory fsync. The marker is the source of truth;-the legacy clear journal is migrated at boot when it contains an open operation and then-removed. Corrupt marker/journal state fences Memory projection without blocking service-startup. Legacy backup journals, backup directories, and snapshot directories are-best-effort boot cleanup only.--## Safety properties--The runtime holds the exclusive maintenance fence while deleting, sets the queue clear-fence before the first surface, and removes the marker only after every surface succeeds.-An interrupted or failed marker is retried on the next reconcile, so no restore path or-operator action can accidentally resurrect partially deleted data.diff --git a/docs/plans/memory-im-attachment-followups-1470-1471.md b/docs/plans/memory-im-attachment-followups-1470-1471.mddeleted file mode 100644index a0d854b21..000000000--- a/docs/plans/memory-im-attachment-followups-1470-1471.md+++ /dev/null@@ -1,186 +0,0 @@-# Memory IM attachment follow-ups (#1470 / #1471)--## Fixed contracts--Ingress attachment eligibility is the conjunction of:--1. the platform belongs to `IM_ATTACHMENT_CAPTURE_PLATFORMS`;-2. an explicit multimodal configuration is complete; and-3. its configuration generation is a valid non-negative integer.--Platform rollout changes only the first term. The #1470 ingress fix changes only-the latter two terms by removing live provider health from eligibility. Workbench-keeps its one-cycle implicit provider compatibility outside this IM call site.--The call-site invariants remain:--- **Bounded-wait invariant.** No deadline-bound provider or subprocess read may- occur in a span that blocks any bounded waiter.-- **Text independence.** Eligible text remains independently best effort, and- that invariant holds at every attachment-path failure or early return.-- Facts sampled before an indeterminate await are revalidated in the O(1),- no-`await` segment that consumes them; mismatch fails closed.--## PR-D: local IM eligibility (#1470 item 1)--**Selected model.** For IM ingress, a valid explicit configuration generation is-the complete local eligibility proof. Project `ready` without calling-`attachment_capture_status()`, then keep the existing replacement-gate generation-comparison immediately before capture. Provider failure remains downstream and is-absorbed by the existing fail-closed queue/provider outcomes.--**Rejected models.** Moving the health read before or after ticket acquisition is-a position rule: one placement blocks Agent dispatch and the other blocks `/new`.-A cached health value is also rejected as an eligibility input because freshness-cannot be proved without coupling admission correctness to refresh timing.--**Blast radius.** `core/controller.py`, the authoritative generation normalizer in-`core/memory/admission.py`, and focused controller tests only. No persistent shape-changes. This PR does not touch platform allowlists, Workbench readiness, or-Processing Record.--Workbench does not enter the bounded span changed here. The outer-`admits_attachment_turn()` check requires membership in the IM platform allowlist,-while Workbench attachments are converted directly by `CaptureAdmission.decide()`.-It therefore never awaits `attachment_capture_status()` while holding this IM-exact-session ticket, and its `/new` lifecycle budget is not exposed to the probe-removed by PR-D. The one-cycle implicit provider compatibility remains unchanged-in the Workbench/provider path.--**Tests.** A permanently blocked health stub is never called and an eligible-attachment reaches the request; `/new` completes inside its lifecycle budget while-that stub remains blocked; a generation change after selection strips attachments-but preserves caption text; and downstream unavailability does not change ingress-eligibility. Scenarios: `MEMORY-IM-ATTACH-001`, `MEMORY-IM-ATTACH-003`.--## PR-E: lock-free processing action execution (#1470 item 2)--**Selected model.** Producers atomically persist the existing durable processing-action and do nothing else. The existing `MemoryWorker` pass is the single driver:-each active pass asks the coordinator to schedule exactly one background processing-action task before any session-due lookup or early return based on session work.-The pass never awaits that task, so a deadline-bound probe cannot hold the-exact-session delivery lock or serialize another session. Deliver, session flush,-boot recovery, and future producers never call the runner. Boot recovery preserves-the durable action for the next active tick. Failed actions retain the existing-retry deadline; the worker's one-second tick bounds classification latency, which-is not a prerequisite for user-path correctness. The coordinator cancels and joins-an active action task before lifecycle quiescence reports success and during-shutdown; cancellation leaves the durable action for a later active tick. The-provider health await runs outside the processing-fault lock, with only the local-action read and generation/`occurred_at` compare-and-set commit inside short lock-segments. Those compare-and-set checks continue to reject stale probe results.--**Rejected models.** Having every producer call a shared drain entry is a-coordination rule that a new producer can omit. Commit-triggered scheduling avoids-that omission but introduces task/lifecycle wake-up machinery when the existing-single periodic owner already supplies a one-second bound. Leaving the probe inside-the exact-session delivery lock violates the bounded-wait invariant.--**Blast radius.** `core/memory/coordinator.py` and focused tests. It reuses the-existing worker tick and durable action representation and does not add a table,-component, migration, or worker call-site rule.--**Tests.** With zero due sessions and one durable processing action, one worker-tick executes the action. A blocked probe never holds an exact-session delivery-lock, delays `/new`, or serializes another session. Recovery after a crash between-settlement and probing leaves the action for the next tick. Retry deadlines-suppress only retry attempts, never the initial durable action; a stale probe-completion cannot commit across a newer fault generation.--## PR-A: materializer-wide failure preserves caption (#1471 item 1)--**Selected model.** After PR5 merges, keep the shared materializer's Agent-facing-failure semantics unchanged. At the message-handler boundary, a batch-wide-materializer exception schedules the already-authorized caption through the-text-only Memory path, then preserves the original Agent-path error behavior. The-text-only handoff uses the canonical session anchor and the existing best-effort-capture ownership rules.--**Rejected models.** Converting every materializer exception into per-file failures-would hide infrastructure defects from ordinary Agent attachment handling. Moving-all Memory capture ahead of materialization is a position rule and would duplicate-capture when materialization later succeeds.--**Blast radius.** `core/handlers/inbound_attachments.py`,-`core/handlers/message_handler.py`, and focused tests. These files overlap PR5, so-this work starts only after PR5 merges and rebases; it never runs in parallel with-PR5. As part of that already-owned edit, PR-A replaces the existing inline-non-negative-generation predicate in `message_handler.py` with-`normalize_attachment_config_generation()`; PR-D deliberately does not widen into-that file. No persistent shape changes.--**Tests.** Root initialization, lease initialization, and gather-level failures-each preserve exactly one caption capture while the Agent path retains its existing-error/result. Cancellation is not converted into degradation, and attachment-only-turns do not create empty captures.--## PR-B: atomic claimed-row text downgrade (#1471 item 2)--**Selected model.** On deterministic bundle decode or revalidation failure before-the provider is called, use one existing-store transaction to change the claimed-row to text-only, clear its bundle reference, return the bundle release id, and make-the same row retryable. The transaction is conditional on the current lease owner,-a non-empty caption, and a still-present bundle. It does not increment attempts;-after downgrade the missing bundle makes a second downgrade impossible. The-coordinator releases the returned bundle outside the transaction.--**Rejected models.** Settling the row and enqueuing a replacement creates a crash-gap and can break ordering/deduplication. Creating a second row duplicates identity.-Keeping text while terminally settling the original row never retries it.--**Blast radius.** `core/memory/store.py`, `core/memory/coordinator.py`, attachment-release handling, and focused transaction/coordinator tests. The default design-changes no persisted schema. If an in-row downgrade cannot be expressed without a-shape change, implementation stops for a persisted-shape decision and legacy-load-fixtures before any code is pushed.--**Tests.** Decode and descriptor revalidation failures atomically retain caption,-release the bundle once, preserve row identity/order and attempt count, and deliver-text on the next claim. Cancellation/crash boundaries leave either the original-claimed row or the committed downgraded row, never a caption-less intermediate.--## PR-C: deterministic provider rejection downgrade (#1471 item 3)--**Selected model.** Reuse PR-B's row downgrade only when pinned EverOS 1.2.3 returns one-of the closed upstream `/add` envelope codes `UNSUPPORTED_FORMAT` or-`CAPABILITY_UNAVAILABLE`. These are raw provider codes, not Avibe's closed-`MemoryErrorCode` values. In the pinned provider they can arise only during-attachment ingest/parser work, before boundary preparation or any durable provider-write, so they prove no attachment write was accepted and the row may safely retry-as text-only. Timeouts, transport failures, unknown errors,-`PROVIDER_NOT_CONFIGURED`, and every other 4xx/5xx retain their existing-terminal/retry semantics; they are never replayed as text-only because the remote-write may already exist or the failure does not prove that dropping attachments-would make the request acceptable.--**Rejected models.** Treating every 4xx as deterministic guesses provider semantics.-Routing all provider exceptions through one degradation path can duplicate memory-after an ambiguous success. Adapter-side immediate text resubmission bypasses the-durable row's ordering and idempotency.--**Blast radius.** `core/memory/everos.py`, `core/memory/coordinator.py`, the PR-B-store operation, and focused provider/coordinator tests. No new table, component,-or migration.--**Tests.** Parameterize the two allowed capability codes and the full rejected-boundary. Allowed codes produce one attachment call followed by the durable-text-only retry. Timeout, transport error, unknown error, and all other 4xx keep a-single provider invocation and never enqueue or invoke a text-only replay. The-closed-loop provider-rejection degradation is `MEMORY-IM-ATTACH-011`.--## Delivery order and lane boundaries--1. PR-D ships first from `063aebd2`, in parallel with PR5.-2. PR-E follows PR-D in this lane; it is not bundled with the cheapest fix or run- concurrently in this lane.-3. PR-A starts immediately after PR5 merges and is the first #1471 implementation.-4. PR-B lands alone because it owns the claimed-row transaction model.-5. PR-C follows PR-B and reuses only its proven deterministic downgrade operation.--PR5 exclusively owns the four remaining IM adapters plus-`core/memory/attachments.py` and `core/memory/im_attachments.py`. PR-D exclusively-owns `core/controller.py`. Any change to the frozen eligibility conjunction routes-through the orchestrator rather than lane-to-lane coordination. Five-platform-Incus acceptance remains incomplete until PR-A closes the multiplied caption-loss-exposure after PR5.diff --git a/docs/plans/memory-im-attachments-1425.md b/docs/plans/memory-im-attachments-1425.mddeleted file mode 100644index 32fd39629..000000000--- a/docs/plans/memory-im-attachments-1425.md+++ /dev/null@@ -1,451 +0,0 @@-# IM attachment capture via EverOS multimodal ingest--Issue: [#1425](https://github.com/avibe-bot/avibe/issues/1425)--## Goal--Let an eligible attachment sent in a bound one-to-one IM conversation enter the-existing durable Memory capture pipeline without changing ordinary Agent file-delivery. Avibe acquires each native attachment once, pins only admitted content-inside the existing private Memory bundle root, and sends the same closed-`ContentItem` kinds that the Workbench path already uses to EverOS.--This is a multi-platform, provider-neutral capability. Platform adapters expose-bounded acquisition primitives; shared core owns admission, lifetime, limits,-redaction, and capture behavior.--## Locked product decisions--- IM attachment capture requires an explicit, complete- `memory.processing.multimodal` endpoint. Workbench keeps the released implicit- main-LLM inheritance for one compatibility cycle; loading an old config must- not copy or persist that inherited API key.-- A complete multimodal endpoint is the opt-in. There is no second attachment- toggle.-- A mixed turn degrades per attachment. Eligible text and every valid attachment- survive independently; one unsupported, oversized, or failed download never- rejects the turn. If a selected attachment later fails descriptor/hash- verification during durable pinning, the same capture is retried once as- text-only; an attachment-only turn retains the closed pin failure.-- The live allowlist in `core/memory/modality.py` follows the pinned EverOS- parser except for SVG and video. Office/iWork/ODF/RTF files are admitted only- when the host can resolve LibreOffice `soffice`; otherwise they are skipped- per file so a missing converter cannot abort the rest of the `/add` batch.-- The Memory consumer alone applies the limit of 8 files, 25 MiB per file, and- 100 MiB per bundle. Ordinary Agent attachment behavior is unchanged.-- Multimodal preflight sends a tiny generated image containing no user or- conversation data.--## Admission contract--Adapters add a literal-true native fact for an ordinary human attachment turn,-separate from `is_ordinary_text`. `core/memory/admission.py` remains the only-authority. Memory may retain an IM file only after all of these properties hold:--- Memory is enabled and explicit multimodal configuration is complete;-- platform, stable native message id, and stable session id are recognized;-- the event is a one-to-one DM from a human and is positively classified as an- ordinary attachment shape;-- the user is bound and enabled; and-- the principal and the default v3 Memory project resolve successfully.--Missing or non-boolean facts fail closed. Groups, channels, edited, forwarded,-shared, rich, system, bot, and self-authored events remain ineligible. Admission-must complete before Memory retains a lease or performs Memory-only acquisition.-The Agent path may still use the same materialized file under its existing rules.--An attachment-only turn with no surviving attachment is skipped. A mixed turn-with no surviving attachment may still capture eligible text. Admission and-attachment failure never annotate or fail the chat turn.--## Acquisition and lifetime contract--`core/handlers/inbound_attachments.py` owns shared native-file materialization.-It calls the platform's `BaseIMClient.download_file_to_path` implementation,-uses sanitized names, removes partial files, and publishes only an opaque,-reference-counted local lease. Consumers never receive a native URL, token,-encryption material, or mutable `MessageContext` as their durable contract.-Lease files live below the fixed private-`<effective-home>/attachments/im/<opaque-lease-id>/` root. A rejected or-unclaimed batch is removed after its final reference; ordinary Agent delivery-adopts its existing local-file lifetime, while a retained Memory reference can-finish pinning first. Empty and failed batches are never preserved by adoption.-The materializer keeps no-follow root and lease descriptors open for the lease-lifetime. It pre-creates each partial file with descriptor-relative-`O_EXCL | O_NOFOLLOW`, passes a duplicate file descriptor to bounded platform-writers, and performs normalization, publication, and cleanup relative to the-verified lease descriptor. Replacing the directory entry during materialization-fails closed and cannot redirect writes outside the private lease.-Each published record binds its original device/inode. Memory selection and-durable pinning reopen that record relative to a duplicated retained lease-descriptor and reject inode mismatches. The record also binds a materialization-SHA-256 that durable pinning verifies while copying, so neither public pathname-replacement nor same-inode modification can substitute bytes after acquisition.--The message handler materializes before scheduling Memory capture. Agent delivery-and Memory retain independent lease references, so Agent cleanup, retry, or-Memory capture failure cannot race the Memory pin. Downloads are sequential or-at most two concurrent and keep the existing 30-second per-file timeout.--Slack, Discord, and Feishu/Lark use their existing authenticated streaming path-downloads with declared, response-header, and streamed-byte limits. Telegram is-changed to a bounded-to-disk Bot API download; it must not buffer the entire file-before checking the limit. WeChat checks declared size before acquisition and-bounds ciphertext/decrypted output while writing; a post-download-only check is-not sufficient. The shared materializer normalizes non-negative integer declared-sizes and rejects an over-limit item before creating a partial or invoking any-platform adapter.--`core/memory/im_attachments.py` accepts only shared-materializer leases. It checks-declared size before retaining a Memory consumer and checks final size, MIME,-extension, and magic after acquisition through the closed modality table. It-produces immutable `CaptureAttachment` values for surviving files. Missing or-non-string native MIME metadata normalizes to `application/octet-stream` at this-shared boundary. Text-like formats stream their complete bounded file through-incremental UTF-8 and NUL validation; checking only the leading magic sample is-insufficient. M4A admission parses brands only from the declared,-four-byte-aligned `ftyp` brand table; brand-like bytes in later ISO-BMFF boxes do-not admit excluded video.--`core/memory/attachments.py` accepts either the fixed Workbench upload root or a-fixed leased-IM source handle. Both paths keep no-follow opens, owner and mode-checks, copy-time size enforcement, hashing, atomic bundle publication, existing-free-disk checks, and crash reconciliation. Source kind is not persisted; bundle-manifest v1 and the store schema do not change.--## Provider and degradation contract--Prepared captures use the existing path:--```text-MemoryModule -> bounded writer -> EverOSPort.add(ContentItem[]) -> flush-```--Writer inputs and logs may contain only sanitized display name, closed content kind-and extension, byte count, bundle-relative metadata, keyed source digests, and-closed skip reasons. They must not contain native URLs, credentials, encryption-material, raw attachment bytes, absolute source paths, filenames supplied for-telemetry, or adapter exception text.--Absent multimodal configuration or parser capability skips IM attachments before-pinning, enqueueing, or calling `/add`. Each rejected item degrades independently.-Avibe emits one scrub-safe `memory_attachment_capture` event per capture attempt-with platform, total, captured, and dropped counts only.--Configured adds retain the existing retry and ambiguity semantics. Deterministic-EverOS `UNSUPPORTED_FORMAT` and `CAPABILITY_UNAVAILABLE` attachment outcomes are-terminal, release their bundle, and cannot open an endless processing fault.-Transient and ambiguous outcomes retain the bundle exactly as the current capture-coordinator does.--The sidecar gains no route. Its existing exact `POST /api/v2/memory/add` envelope-remains unchanged; `_valid_workbench_attachment` becomes pinned-attachment-validation without accepting platform URLs or widening the confined provider root.--## Configuration, preflight, and status--Add optional all-or-none values at:--```text-memory.processing.multimodal.base_url-memory.processing.multimodal.model-memory.processing.multimodal.api_key-```--The block follows the released rerank behavior: an absent old key loads and saves-without shape churn, an empty block normalizes to absent, partial API input is-rejected, and a malformed persisted optional block disables only multimodal with a-warning so startup continues. API keys remain write-only.--Only allowlisted child environment variables carry-`EVEROS_MULTIMODAL__BASE_URL`, `EVEROS_MULTIMODAL__MODEL`, and-`EVEROS_MULTIMODAL__API_KEY`. Generated TOML contains the confined attachment root-and `file_uri_max_bytes = 26214400`, but no credential. Saving a changed endpoint-runs bounded preflight and rolling sidecar reconciliation; it does not rebuild-embeddings or restart Avibe.--`MemoryPreflightDiagnostic.side` adds `multimodal`. Its real compatibility probe is-a generated 64x64 PNG request with no user data. Missing optional configuration does-not block Memory enablement. Insight-reader and preflight redaction include the-independent multimodal URL and key; an unconfigured skip produces no provider add.--The settings API carries the optional Multimodal endpoint with the same write-only-key-and clear semantics as rerank. Either optional endpoint can be cleared while Memory-remains enabled; required LLM and embedding keys retain the enabled-state clear gate.-The Slack closed-loop slice flips the implementation stage gate and reveals the-visible card. Status continues to project EverOS-`multimodal_llm`, `parser`, and `disabled_features` and adds a concise attachment-capture availability line. Configuration remains UI-only; no CLI config flags are-added.--### Review-loop closure decision--After review of head `cf66a808`, the orchestrator approved one whole-model closure-for the repeated multimodal health-probe root-cause class. The recurrence came from-environment provenance ambiguity: the same `EVEROS_MULTIMODAL__*` values can mean-either an explicit IM opt-in or the one-cycle Workbench compatibility fallback.--- An Avibe-private marker is present only for a complete explicit multimodal- triple. The probe child checks multimodal only when that marker is present;- the normal sidecar keeps the fallback variables for Workbench compatibility.-- Fixed synthetic provider health checks initially ran fully concurrently under a- fixed 20-second child deadline. The complete model below supersedes that boundary:- endpoints sharing provider credentials must not overlap, so the child deadline is- derived from the largest serialized group instead of assuming one concurrent wave.-- Attachment capture reports ready only from a current available runtime health- observation. Cached stale health and unavailable health report unavailable;- absent explicit configuration still reports not configured.--This closure adds no persistent field, sidecar route, or provider payload shape.--### Processing health probe model--This is the complete contract for settings compatibility checks, child processing-health, and attachment readiness. It closes root-cause classes A-E, which were all-gaps in the probe model rather than independent endpoint bugs.--- **Endpoints and gating.** Saving processing settings runs the existing bounded- compatibility preflight for LLM and embedding plus each complete optional rerank- or multimodal endpoint. Runtime processing health runs fixed authenticated probes- for LLM and embedding, complete rerank, and multimodal only when the private- `AVIBE_MEMORY_MULTIMODAL_EXPLICIT=1` marker proves the persisted multimodal triple- was explicit. The normal sidecar may still receive inherited- `EVEROS_MULTIMODAL__*` values for the one-cycle Workbench fallback, but those values- alone never admit a multimodal health probe.-- **Grouping and concurrency.** Runtime health groups endpoints by the exact resolved- `(base_url, credential identity)` pair. Requests within one group run serially so a- shared provider or key is not subjected to overlapping health traffic. Different- groups run concurrently. The credential identity is compared only in private- process memory and is never logged or projected.-- **Deadlines.** Each runtime provider request remains bounded at 8 seconds. The- parent child deadline is `8 seconds * largest provider group size + 2 seconds`,- structurally capped by the four endpoint model at 34 seconds. Independent groups- therefore receive 10 seconds; the worst case with all four endpoints in one group- receives 34 seconds. This bounded derived deadline supersedes the earlier fixed- 20-second composition because serialization is now required to avoid provider- concurrency and rate-limit failures. Settings compatibility preflight remains a- separate sequential flow with its existing 5-second per-endpoint bound.-- **Synthetic payload.** Text, embedding, and rerank probes use fixed literals only.- Multimodal checks use the same generated opaque 64x64 RGBA PNG (153 bytes, no user- data) in a PNG data URI plus the fixed `Reply with OK.` prompt. Tests pin its PNG- dimensions and exact byte digest.-- **Readiness and freshness.** Attachment capture can report `ready` only when an- explicit multimodal config exists, the current runtime source status is- `available`, and the projected `multimodal_llm` and parser capabilities are- enabled. An absent config reports `not_configured`; stale or unavailable runtime- health reports `unavailable` even when cached capability values were previously- healthy.--### Slack activation contract--Delivery slice 4 makes Slack the reference platform. The settings availability-projection is derived from the intersection of the installation's enabled IM-platforms and `IM_ATTACHMENT_CAPTURE_PLATFORMS`; that allowlist remains closed to-Slack until slice 5 adds contract evidence for the other four adapters.--- Slack `message` and `app_mention` events publish a separate literal-true- `is_ordinary_attachment` fact only for a native, human `file_share` shape with- plain composer blocks. The fact does not reuse or weaken ordinary-text- classification, and edited, forwarded, bot, rich, system, and shared shapes- still fail closed.-- The message handler performs the existing shared Agent materialization first.- It asks admission whether Memory may retain that materialized batch, then gives- Memory an independent lease reference. A retain or scheduling failure is- best-effort and cannot reject the Agent turn.-- The retained reference lives until the asynchronous Memory capture finishes.- The Memory module pins through the descriptor-backed lease before enqueueing;- the ordinary Agent consumer independently adopts its source files. This keeps- one native download while preventing Agent cleanup or Memory capture failure- from racing the Memory pin.-- Capture reads current attachment readiness only after the closed DM admission- gates pass. `not_configured` and `unavailable` retain eligible text but produce- no attachment pin or provider attachment. Attachment-only turns- with no surviving item are skipped.-- Per-attachment selection uses the closed format and limit table. A rejected- sibling does not remove eligible text or valid siblings. Attachment telemetry- reports only the attempt's total, captured, and dropped counts; it does not- attribute reasons to individual files.-- The hermetic Slack scenario drives the shared materializer, admission, volatile- pin/writer, fake EverOS add/flush, a test-only invocation observation, and- `vibe memory search`. It proves a single adapter download and zero temp or- Memory-bundle residue after successful processing.--### Capture call-site contract--Memory capture stays best effort and must not become part of user-visible Agent-dispatch latency. The call site therefore branches by turn shape instead of moving-all capture work to one late stage.--- Text-only human turns use the original early capture path immediately after the- stable base session is resolved and before Agent routing. Attachment turns alone- use the delayed path, and the only legal reason for that delay is waiting for the- shared materializer to produce its immutable descriptor-backed lease.-- The canonical Memory session anchor is copied from `base_session_id` immediately- after session resolution, before any subagent or routing-agent namespace can- rewrite the Agent session id. Both the early capture and the delayed lifecycle- fence/capture request receive that saved canonical value.-- **Cross-await revalidation invariant.** Any local fact resolved before an- indeterminate await is revalidated inside the O(1), no-`await` atomic segment- that consumes it; a mismatch fails closed, and no bounded waiter waits for the- indeterminate span. Attachment turns snapshot the canonical session lifecycle- epoch before materialization, then revalidate it while holding `SessionTurn`- immediately before reservation. `/new` advances that local epoch only after its- destructive operation succeeds and before releasing `SessionTurn`; a failed- operation leaves the epoch unchanged. Therefore a reset never waits for a- download, while an attachment that finishes after a successful reset is dropped- as `stale_session` and eligible caption text is still captured independently.-- **Bounded-wait invariant.** No deadline-bound provider or subprocess read may- occur in a span that blocks any bounded waiter. The bounded waiters here include- both the user-visible Agent dispatch path and `/new`'s five-second lifecycle- budget. Attachment eligibility must therefore be decided from local facts before- any health read: platform and message shape, binding/config completeness, and the- explicit multimodal configuration generation. Moving a remote read to a different- call site does not satisfy this invariant if either bounded waiter still depends- on its completion.-- Multimodal opt-in is an authoritative, generation-bound fact. The synchronous- segment snapshots the stable Runtime configuration generation that proves an- explicit endpoint and carries it on the immutable capture request. Immediately- before enqueue, the replacement gate compares that generation with the current- Runtime generation; absence or mismatch fails closed for attachments, including- an opt-out or endpoint replacement that completed while readiness was being read.- A missing IM generation projects `not_configured` immediately and retains eligible- text without performing a live health read. Workbench alone keeps its one-cycle- implicit compatibility path. Eligible text remains independently best effort, and- that invariant must hold at every attachment-path failure or early return rather- than only for failures with an existing closed classification.-- **Attachment capture logging (best-effort observability, not a ledger).**- When a capture attempt reaches `MemoryModule.capture()` and returns a result,- the controller emits one `memory_attachment_capture` record with- `platform` / `total` / `captured` / `dropped`, where `captured` comes from- `CaptureAccepted.captured_attachment_count` (the bundle actually enqueued;- every other result type is zero) and `dropped = total - captured` is computed- at that one site. This record set is deliberately **not** a complete census of- turns: paths that terminate before a capture attempt is made — admission- skips, runtime replacement, retirement, factory reset — emit nothing, by- design. Do not add emission points to make it complete; completeness was tried- and is what produced the cross-call-site accounting defects this section- replaced. No per-attachment reason attribution is retained.-- **Reservation boundary.** While holding per-session `SessionTurn` lifecycle- admission, the handler performs only an O(1), non-blocking, local registration of- an exact-session Memory capture ticket. Registration records FIFO order but never- waits for an earlier capture and never reads a provider or subprocess. Once the- ticket and task ownership are established, the handler releases `SessionTurn`- immediately and continues durable Agent admission.-- **Concurrent captures.** Tickets for the same canonical session execute in- registration order. A background task waits for its predecessor only after- `SessionTurn` has been released, then performs readiness, attachment selection,- bundle pin/copy, and queue commit under the existing exact-session execution- fence. Tickets for different canonical sessions have independent tails and remain- concurrent. Order is represented by ticket data, never by holding the dispatch- lock while slow work runs.-- **Lifecycle barrier.** `/new` first acquires `SessionTurn`, then registers a- lifecycle barrier behind the current exact-session ticket tail and waits for that- snapshot with the existing bounded lifecycle deadline. Holding `SessionTurn`- prevents later turns from registering while the barrier drains, so every ticket- before the reset is included and the wait converges; captures admitted after the- reset queue behind the barrier. The reset and final flush therefore cannot pass an- older registered capture, while Agent dispatch never waits for capture execution.-- **Single ownership, in process.** Before task tracking, the handler owns the- reservation and any retained materializer lease. Successful scheduling transfers- both to the background task; every exception, cancellation, or scheduling failure- completes the reservation and releases the retained lease together. Once tracked,- the task completes its ticket in `finally` and its done callback releases the- lease. At shutdown, Controller closes the loop-owned capture-registration gate and- then cancels and joins every tracked capture in the same event-loop coroutine,- without the generic five-second cleanup cutoff. The handler rechecks the gate- after any `SessionTurn` wait and immediately before the no-`await` reservation,- retain, and task-registration segment. Once closed, that atomic segment cannot- produce another reservation, lease, or task, so the sweep operates on a closed set- and converges independently of every IM client's shutdown order. This- process-local cleanup is best effort: no exit path may have two owners, but an- abrupt process termination can bypass all callbacks.-- **Authoritative durable cleanup.** Startup recovery is the final correctness- guarantee for every termination path, including crashes and `SIGKILL`.- `MemoryCoordinator.recover_after_boot()` takes the database attachment-reference- snapshot inside the admission fence and `_reconcile_attachments()` invokes the- idempotent `AttachmentStore.reconcile(referenced, releasing)` operation. It removes- all staging remnants and every bundle not referenced by the database. Therefore an- attachment lease or bundle abandoned before queue adoption is bounded to the- process lifetime plus the next Memory startup recovery, rather than permanently- retained.--## Scenario contract--The canonical capability is `memory_im_attachment_capture` under-`tests/scenarios/memory_im_attachment_capture/`:--- `MEMORY-IM-ATTACH-001`: a bound Slack DM image/PDF is downloaded once, pinned,- added, flushed, extracted, and retrievable through `vibe memory search`;-- `MEMORY-IM-ATTACH-002`: group and unbound denial performs no Memory acquisition;-- `MEMORY-IM-ATTACH-003`: absent multimodal configuration captures eligible text- only and creates no attachment provider activity; and-- `MEMORY-IM-ATTACH-004`: count, per-file, total-size, unsupported-type, and partial- download failures preserve valid siblings and leave no temp or bundle leak;-- `MEMORY-IM-ATTACH-005`: a native human Discord file share reaches attachment- admission while rich, bot, webhook, sticker, forwarded, and snapshot shapes- remain closed;-- `MEMORY-IM-ATTACH-006`: Telegram document, largest-photo, voice, and audio- shapes reach admission independently, including separate album messages;-- `MEMORY-IM-ATTACH-007`: Lark file and image messages with non-empty native keys- reach admission while `media` and malformed events remain closed; and-- `MEMORY-IM-ATTACH-008`: direct WeChat image, voice, file, and video items reach- admission while reference and malformed media items remain closed.--The closed-loop harness uses a stub platform client, a real test-owned bundle path,-and local fake OpenAI-compatible providers. It must not use live credentials,-running Avibe services, real user paths, or production state.--## Delivery slices--1. Contract and scenario catalog, including the stale Workbench-copy and IM- non-goal corrections in `memory-plugin-system.md`.-2. Optional multimodal config, child environment, preflight/redaction, UI, and- status. IM capture stays gated: the platform allowlist remains empty, the- settings response hides the card, and configured capture cannot report `ready`;- absent configuration retains the locked `not_configured` projection.-3. Shared leased materializer, bounded Telegram/WeChat acquisition, and pin-source- generalization. IM capture stays gated.-4. Attachment classification/admission and the Slack closed loop with test-only- provider-invocation proof. This slice adds Slack to the platform allowlist only after the capture path- and its closed-loop evidence land, revealing the endpoint card when Slack is- enabled and enabling health-derived readiness without a user-facing toggle.-5. Discord, Telegram, Feishu/Lark, and WeChat enablement and contract tests, plus- final user documentation and manual verification matrix.--Each PR is based on the latest merged `master`; there are no stacked PRs. Shared-files with the #1424 lane receive only additive, narrowly scoped changes. If that-lane lands first, this work rebases and re-runs the complete review loop before the-next slice.--## Residual manual checks--Hermetic tests prove the product contracts without live platform credentials.-After all five slices merge, the orchestrator's integration pass should run the-following matrix in the local Incus regression environment while preserving-accumulated product state:--- Slack: one eligible image and one rejected file;-- Discord: one ordinary upload and captured fixtures for ordinary-upload embeds,- authored embeds, components, stickers, webhooks, forwards, and snapshots. The- repository has no fixture proving whether an ordinary upload receives an embed,- so PR5 conservatively rejects every embed-bearing message until this check;-- Telegram: document, largest photo variant, voice, audio, separate messages in- one album, and non-published video, animation, and sticker shapes;-- Lark: file, image, malformed/empty native keys, and a captured real `media`- event for a later admission decision. Runtime tracing confirms the adapter sends- the literal platform name `lark`; the separate `IM_PLATFORMS` set still carrying- both `lark` and `feishu` is a future namespace-cleanup item; and-- WeChat: direct image, voice, file, and video items plus quoted/reference and- source-identity cases. Video must reach the shared modality policy and produce- its existing skip accounting rather than being prefiltered in the adapter.--The final PR4 invariant audit also found five pre-existing paths outside this-slice's implementation files. The two bounded-wait spans are tracked by #1470;-the materializer-wide failure, post-enqueue bundle failure, and deterministic-provider attachment rejection paths are tracked by #1471. They remain outside-PR4 so its Slack activation does not expand into coordinator, provider, store, or-shared materializer changes.--A future observability improvement may add a non-identifying per-turn correlation-marker so operators can group multiple disjoint skip records from the same turn.-That marker is an operational convenience, not part of drop-accounting correctness.diff --git a/docs/plans/memory-independence-c2-c3.md b/docs/plans/memory-independence-c2-c3.mddeleted file mode 100644index d3250173e..000000000--- a/docs/plans/memory-independence-c2-c3.md+++ /dev/null@@ -1,262 +0,0 @@-# Memory independence: capture must not fence dispatch or destructive ops--Context: issue #1584 Memory-independence audit items C2 and C3.-This plan does **not** claim to close #1584 (C1 / WeChat identity is a sibling PR).--## Background--PR #1357 and the later Memory capture fence made Avibe's per-session-lifecycle lock a mutual-exclusion gate between:--1. durable turn start-2. in-flight Memory capture-3. destructive session transitions (`/new`, archive)--That gate keeps a reset or archive from racing a capture that would-attribute content to the wrong session generation. It also made Memory-latency a user-visible dependency: a slow sidecar add (30s) delays the-session's next turn, and a capture wedged past its timeout blocks the-session indefinitely. `/new` and archive wait 5s on the same lock and-then fail the user with `memory_session_lifecycle_busy`.--The product rule for this change: a hung or failed Memory capture must-never block message turns, `/new`, or archive. Losing at most one-turn's capture is acceptable; failing the user's action is not.--## Current fence semantics--### Layer A — Avibe session lifecycle lock (`core/session_turns.py`)--- `_session_lifecycle_locks[session_id]` is an unbounded `asyncio.Lock`.-- `_start_persisted_turn` awaits `acquire_lifecycle_admission` with- **no timeout**, then parks the lease on- `context.platform_specific["_turn_lifecycle_admission"]`.-- Text-only capture (`MessageHandler._schedule_text_only_memory_capture`)- takes that lease (or acquires its own) and holds it until the capture- task completes.-- Attachment capture acquires the same lock on the **turn path** after- materialization, then releases it as soon as the capture task is- scheduled. Generation safety for the download gap uses- `session_lifecycle_epoch` / `session_lifecycle_epoch_matches`.-- `run_session_lifecycle` waits up to 5s for the lock. On timeout it- raises `SessionTurnLifecycleBusyError` (`memory_session_lifecycle_busy`).- On success it runs the operation, then increments- `_session_lifecycle_epochs[session_id]`. A failed operation leaves- the epoch unchanged.--Callers:--- `/new` wraps the reset in `SessionTurnManager.run_session_lifecycle`- (`core/handlers/command_handlers.py`), then nests Memory's own- `run_session_lifecycle` (flush + capture-admission lock).-- Workbench archive still wraps the terminal session write in- `SessionTurnManager.run_session_lifecycle`. PR #1582 already made the- Memory final flush best-effort *after* that write: a busy or failed- Memory runtime cannot roll archive back. The remaining archive risk is- only the shared turn-lifecycle lock raiser, not a second Memory fence.--C3 in this PR is therefore `/new` plus every remaining-`memory_session_lifecycle_busy` raiser. It does not re-work #1582's-archive flush. Fail-opening `SessionTurnManager.run_session_lifecycle`-clears the last archive raiser as a side effect of the shared lock.--### Layer B — Memory capture-admission lock (`core/memory/module.py`)--`MemoryModule.run_session_lifecycle` waits for in-flight-`capture_admission` tickets, then final-flushes, then runs the-operation. On timeout it raises `MemorySessionLifecycleBusyError`-(same code string). `/new` nests this **inside** layer A via-`controller.run_memory_session_lifecycle`. So a hung sidecar can-make `/new` wait 5s + 5s and still fail the user.--`run_session_scopes_lifecycle` has the same timeout raise. Archive-flush already swallows that exception (PR #1582). Maintenance-open-still raises; that path is not a hung-capture case and stays as-is.--### Why the fence exists (invariant we must keep)--A capture admitted against session generation **G** must not be written-as if it belonged to generation **G+1**. `/new` reuses the same raw-session anchor on IM surfaces, so a late add after reset mixes the old-conversation into the new one.--The epoch counter already exists for this (`session_lifecycle_epoch`,-consumed by attachment capture). Mutual exclusion was a stronger-implementation of the same invariant, not a second invariant.--## Chosen design--**Generation token replaces mutual exclusion as the correctness-mechanism.** The per-session lock remains only as a *best-effort-quiesce* so a nearly-finished capture can flush before reset. It is-never a dispatch fence, and it is never a reason to fail the user.--Rejected alternative: bound the turn-start wait at ~5s and proceed.-That still makes Memory latency a message-turn delay. The audit allows-dropping the turn-start acquire entirely; we do that.--### C2 — invert the turn-start dependency--1. `_start_persisted_turn` snapshots- `session_lifecycle_epoch(anchor)` onto the context- (`_turn_lifecycle_epoch`) and does **not** acquire the lifecycle- lock. Dispatch never waits on Memory.-2. `MessageHandler` uses that snapshot when present; otherwise it- samples the epoch when the session id is known (legacy / non-durable- path). The snapshot is taken **before** any await a concurrent- `/new` could win.-3. Capture tasks — text and attachments — acquire the lifecycle lock- **inside the capture task**, never on the turn/`_handle_turn` await- path. The next turn can start and reply while a previous capture- still holds the lock.-4. After the capture task acquires the lock, it revalidates the- snapshotted epoch. Mismatch logs and returns without calling- `capture_user_memory`.-5. `drain_memory_capture_tasks` / `cancel_memory_capture_tasks` /- `quiesce_memory_capture_tasks` stay as they are: shutdown still- settles or cancels accepted captures.--### C3 — destructive ops fail open--`SessionTurnManager.run_session_lifecycle`:--- Still waits up to 5s for the lock (best-effort flush of an in-flight- capture).-- On timeout: log a warning, advance the epoch (abandon in-flight- captures for that session), **do not raise**, run the operation- without holding the lock.-- On acquire: run the operation while holding the lock; on success- advance the epoch (same as today). A failed operation still leaves- the epoch unchanged so an in-flight turn is not abandoned by a- failed `/new`.--`MemoryModule.run_session_lifecycle` and-`run_session_scopes_lifecycle` timeout paths: log a warning, skip the-final flush, run the operation. They no longer raise-`MemorySessionLifecycleBusyError` on quiesce timeout.--`/new` therefore always reaches `_reset_session`. Archive always-reaches the terminal session write. Nested fences cannot stack a-user-visible busy error.--### Abandonment--Advancing a session's epoch is the abandonment signal. Capture tasks-for that session are also cancelled so a hung sidecar await does not-resume into a write after `/new`. The epoch check after lock acquire-covers the case where a waiting capture wakes after the bump and was-not cancelled.--Residual: a sidecar `add` that already left the process may still-complete in EverOS after cancel. That write carries the pre-transition-`session_id` and is the one-turn loss the audit accepts. Tests assert-the Avibe-side decision (no `capture_user_memory` attribution after-the bump).--Epoch keys and capture buckets share one canonical session id when the-session handler is present: `/new` passes `memory_session_anchor` from-`get_base_session_id`, and capture uses `get_session_info`, which-returns that same `get_base_session_id`. When the fallback path yields-`memory_session_anchor=None`, `/new` skips the turn-lifecycle fence-entirely (pre-existing fail-open). Telegram's new-topic branch returns-before a mismatched pair is used.--Cancellation of in-flight captures happens only on the 5s timeout-path, and only after that path's destructive operation succeeds. A-failed `/new`/archive leaves both the epoch and in-flight captures-unchanged. A successful `/new`/archive that acquired the lock only-advances the epoch. The capture task's epoch check discards stale-work without killing a capture admitted for the new generation.--Destructive ops serialize on a dedicated per-session op lock, independent-of the capture lock. `/new` may wait for another `/new`; it never waits-unboundedly on Memory. A hung capture only costs the bounded capture-quiesce, then the op proceeds.--### Dead error surfaces--- `SessionTurnLifecycleBusyError` is no longer raised. The class is- removed.-- `MemorySessionLifecycleBusyError` remains for the maintenance-open- case on `run_session_scopes_lifecycle` (not a user `/new`/`archive`- failure). Quiesce-timeout raisers are removed.-- `/new` no longer maps `memory_session_lifecycle_busy` to i18n.- `error.memorySessionLifecycleBusy` is removed from `vibe/i18n`.-- Internal archive HTTP no longer special-cases the busy code; a- leftover raise would surface as `session_archive_unavailable`.--## Correctness argument--Let `E(s)` be the in-memory generation for session `s`.--1. A turn admitted at generation `G` stores `G` on its context before- any later await. Capture uses that `G`, not a later sample.-2. A successful `/new`/archive increments `E(s)` only after the- destructive operation commits (acquired path). A timed-out- `/new`/archive increments `E(s)` before the operation, because the- operation will run anyway and in-flight captures must not land on- the post-transition generation.-3. Capture writes only if `E(s) == G` after it holds the lifecycle- lock. Therefore:- - If `/new` acquired the lock, every lock-holding capture has- already finished (or been cancelled on the bump). Attachment- captures that had released the lock see the new epoch or a- cancellation.- - If `/new` timed out, `E(s)` is already `G+1` before reset, so a- capture admitted at `G` cannot pass the check.-4. Turn start never waits on the lock, so a capture that never- resolves cannot prevent the next `_start_persisted_turn` or the- handler's agent dispatch. Capture admission acquire lives only- inside the fire-and-forget task.-5. Shutdown still drains the same `_memory_capture_tasks` set. Moving- the lock acquire into the task does not change membership or- `drain_memory_capture_tasks` / `cancel_memory_capture_tasks`.--The replaced guarantee is exactly the original fence's purpose: no-cross-generation attribution. The dropped guarantee is "destructive-ops and the next turn wait until Memory is quiet." That wait is what-made Memory a messaging dependency.--## Hard boundaries--Do not touch (sibling PRs):--- `core/session_turns.py` `_hydrate_delivery_context`-- `_memory_admission_merge_identity` / `_collect_delivery_segment`-- `core/controller.py` `_memory_turn_facts`-- `modules/im/wechat.py`--Do not change `core/memory/admission.py` admission policy. Fencing-and serialization only.--## Tests--Scenario IDs (capability `memory_independence`):--- `MEMORY-INDEP-001` — hung capture does not block the next turn,- `/new`, or archive (`memory_session_lifecycle_busy` never surfaces).-- `MEMORY-INDEP-002` — a capture admitted before `/new`/archive and- completed after the transition is discarded.-- `MEMORY-INDEP-003` — idle-session capture still attributes; shutdown- still drains accepted captures.--Executable evidence lives next to the existing lifecycle tests-(`tests/test_session_delivery_fsm.py`, handler/command/runtime-modules). Catalog: `tests/scenarios/memory_independence/`.--## Todo--- [x] Write this plan.-- [x] Drop turn-start lock acquire; snapshot epoch onto the context.-- [x] Move capture lock acquire into the capture task; epoch-check- after acquire; cancel captures on epoch advance.-- [x] Fail-open `run_session_lifecycle` (session_turns + Memory- module) on the 5s deadline; skip flush; proceed. Remaining C3- surfaces after #1582: `/new` and the shared busy raisers, not- archive flush.-- [x] Remove dead busy error surfaces (raise sites, `/new` i18n,- archive HTTP special case) coherently.-- [x] Add MEMORY-INDEP-001/002/003 and update tests that encoded the- old "busy fails the user" contract.-- [x] `ruff check` on changed Python files; run the touched test- modules.diff --git a/docs/plans/memory-list-1427.md b/docs/plans/memory-list-1427.mddeleted file mode 100644index 8a1de6fba..000000000--- a/docs/plans/memory-list-1427.md+++ /dev/null@@ -1,103 +0,0 @@-# Memory episode listing via EverOS `/memory/get`--Issue: [#1427](https://github.com/avibe-bot/avibe/issues/1427)--## Goal--Add a closed, principal-scoped listing path for processed EverOS episodes, then-expose it through `vibe memory list`. The provider boundary must not leak raw-EverOS dictionaries or broaden the existing profile lookup.--## Locked decisions--- v1 lists only active processed `episode` memories. Profiles remain on the- existing profile surface; atomic facts, unprocessed messages, agent cases,- and agent skills are excluded.-- Single-project listing uses EverOS's 1-based `page` and `page_size` contract.- CLI rejects `--project all`; only the verified UI/controller path may request- an Avibe-aggregated `all` listing.-- The `all` result uses a versioned, bounded Avibe cursor that records per-project- timestamp/opaque-id boundaries, provider-page hints, observed-total hints, and- a principal-bound project-catalog fingerprint. Continuations locate the current- boundary timestamp with revalidated provider-page probes, so inserts and deletes- do not turn page offsets into replay or skip positions. It is not an EverOS cursor.-- `vibe memory list` is not added to the injected Personal Memory prompt. Parser- contracts must prove the injected CLI surface remains unchanged.-- JSON output includes the provider-neutral opaque episode `id` for future item- management. The id has no management semantics in this change.-- No config key, persisted schema, or EverOS source changes are required.--## Contract--The provider port accepts only an Avibe-derived principal, one stored project id,-`page >= 1`, and `1 <= page_size <= 20`. It sends the exact EverOS episode shape-to `POST /api/v2/memory/get` and returns a provider-neutral page:--- item: `id`, `kind=episode`, `subject`, `summary`, `body`, RFC3339 `timestamp`,- and `project`-- page: `items`, `page`, `page_size`, current-page `count`, pre-page- `total_count`, and closed warnings--The adapter validates the complete EverOS envelope, all four kind arrays, owner,-app/project scope, counts, and bounded item fields. Any malformed or cross-scope-response fails closed as `memory_provider_response_invalid`. A provider-`total_count` above EverOS's 20,000-row exact-ordering window adds the-transport-only `memory_list_truncated` warning.--The sidecar keeps the existing profile request as an independent exact shape.-Episode requests additionally allow only the exact eight fields used by Avibe:-`user_id`, `app_id`, `project_id`, `memory_type`, `page`, `page_size`, and the-fixed `sort_order=desc`/`sort_by=timestamp` pair. Unknown keys, filters,-`agent_id`, legacy/reserved projects, and values outside the bounds are rejected.--## CLI and aggregation--`vibe memory list [--project <slug>] [--page N] [--limit 1..20] [--json]`-defaults to `default`, page 1, and limit 20. The internal route derives the-principal from the caller-session binding exactly like search; no owner id is-accepted on the wire.--Single-project ordering is fixed to `timestamp desc`. This is the smallest-closed v1 contract because the EverOS episode response exposes `timestamp` but-not `updated_at`, so Avibe cannot correctly merge an `updated_at`-sorted `all`-result. Sorting controls can be added later only when the provider response has-the corresponding merge key.--For UI-only `all`, the runtime enumerates the same principal's current Memory-project catalog as search, fetches bounded provider pages under one 20-second-deadline, and performs a deterministic merge by timestamp then project/id.-Failures produce `memory_list_partial`; deadline/provider-window limits produce-`memory_list_truncated`. `total_count` is null if any project failed.--## Delivery and evidence--1. PR1: value types, EverOS port/fake, exact sidecar expansion, module/runtime- single-project listing, and focused unit/contract tests.-2. PR2 (after PR1 review pass): scoped internal route/client, CLI/i18n/docs,- UI-only aggregate cursor, parser contracts, and closed-loop scenarios.-3. PR3 (after PR2 review pass): extend the existing Search tab with the approved- browse state, UI API types, i18n, and component contracts.--## Search tab browse state--The owner-approved UI keeps the existing Processing Record / Profile / Search /-Settings tabs. `MemorySearchPanel` switches by trimmed query value:--- empty query: browse processed episodes in timestamp-descending order-- non-empty query: retain the existing relevance-ordered search behavior--Browse uses the same project catalog as search, including the UI-only `all`-aggregate. Single-project pages use EverOS page numbers. For `all`, the client-keeps the opaque cursor returned for each visited page so Previous, known page-numbers, and Next remain navigable without interpreting the token. Project-changes reset browse pagination.--Each browse row shows its project, timestamp, and a bounded excerpt. Selecting a-row opens a detail view with the episode body and a copy affordance for the-opaque entry id. Loading, empty, partial/truncated, disabled, and closed-error-states remain explicit. The sort control is fixed to Newest first because v1's-provider-neutral contract exposes only timestamp ordering.--Scenario IDs are catalogued under `tests/scenarios/memory_list/`; the closed-loop-evidence captures processed episodes in one scoped project, lists them through-the product boundary, and verifies an exact pagination boundary.diff --git a/docs/plans/memory-plugin-system.md b/docs/plans/memory-plugin-system.mddeleted file mode 100644index c05fcf324..000000000--- a/docs/plans/memory-plugin-system.md+++ /dev/null@@ -1,409 +0,0 @@-# Memory Plugin System--> Status: implemented beta->-> This is the canonical product and architecture contract for the complete-> Memory plugin system, including the final behavior from-> [issue #983](https://github.com/avibe-bot/avibe/issues/983). Earlier product,-> technical, POC, and follow-up documents are retained in Git history only.--Memory is an optional built-in Avibe capability backed by an independently-packaged EverOS runtime. It captures eligible human input into a local queue,-processes that queue outside the chat response path, and exposes user-scoped-profile, search, status, and explicit Agent writes.--The core product invariants are:--- normal chat never waits for Memory processing and continues when Memory fails;-- installing the runtime never enables Memory, and startup never downloads it;-- every captured or recalled item is scoped to one derived user principal;-- automatic capture accepts human input only, never assistant or tool output;-- Agents recall only through an explicit, capability-gated CLI call; there is no- automatic prompt injection;-- configuration and destructive operations remain in the local Settings UI;-- provider output is bounded, rendered as inert data, and never trusted as- instructions; and-- runtime code, Avibe queue state, and provider data have separate ownership and- deletion boundaries.--## Product Surface--### Setup and navigation--The setup flow is deliberately staged:--1. **Settings -> Dependencies** shows the optional `memory-runtime` dependency.- Install or Repair is the only production download path.-2. Once installed, the dependency row links to- `/admin/settings/memory` (`/settings/memory` redirects there).-3. The owner configures separate OpenAI-compatible LLM and embedding endpoints,- reviews the data disclosure, and explicitly enables Memory.-4. After the runtime is installed and Memory is enabled, **Memory - Beta** is- visible in Settings navigation. Before then, the route still exists but is- reached from Dependencies.--Enablement requires complete endpoint blocks, bounded authenticated probes, a-verified runtime, an owned provider root, and a healthy sidecar. A failed enable-rolls the persisted setting back to disabled. API keys are write-only: responses-expose only `has_api_key`, omission preserves an existing key, and explicit key-clearing is allowed only while the resulting configuration is disabled.--The Settings page provides:--- runtime and processing status, queue counters, provider disk use, and a- sanitized failure history;-- the current local owner's profile and bounded search;-- endpoint configuration and enable/disable controls; and-- a held-confirmation Clear all action.--There is no Workbench Memory page and no `/memory` command. Text such as-`/memory status` is an ordinary user message: it may be captured and is sent to-the selected Agent like any other eligible text.--### Capture admission--All automatic capture passes through the shared `MessageHandler` boundary after-session resolution. Platform adapters classify native events but do not own-Memory business logic.--| Source | Captured | Not captured |-|---|---|---|-| Workbench | An attributed human text turn; an attachment-only turn; up to eight validated local Workbench attachments | Unresolved fallback identities, quick replies, forwarded metadata, assistant/tool output |-| Slack, Discord, Telegram, Feishu/Lark, WeChat | Ordinary text from a bound, enabled user in a one-to-one DM | Groups/channels, unbound or disabled users, attachments, rich/forwarded/edited events, bot/self events |-| Automation | None | Scheduled tasks, Harness turns such as `vibe agent run`, and agent-to-agent turns |--Memory must also be enabled, the event must carry a stable native message id,-and the adapter must positively mark it as ordinary human text. Missing identity-or platform facts fail closed. Every enabled bound DM user is eligible; Memory-does not require the user to be an administrator.--Busy Workbench sessions preserve the same rule. Consecutive queued messages are-merged only within one user segment, the flushed segment keeps that user's-identity and final message id, and the segment is captured once.--Workbench attachments are accepted only when their existing local files are-inside Avibe's controlled attachment root. Memory validates and copies admitted-files into a private pinned bundle before enqueueing; provider access remains-confined to that bundle root. IM attachments are currently excluded pending the-bounded acquisition and admission contract in #1425.--### User isolation--Memory derives an opaque principal from the existing install-local scope key:--```text-user_key = "<platform>:<resolved-user-id>"-principal_id = "u-" + HMAC_SHA256(scope_key, user_key).hex()[:32]-```--The queue, provider writes, profile reads, and searches all carry that principal.-Raw Workbench, IM user, message, chat, thread, and session ids are not stored in-the Memory database or provider paths. Source ids are reduced to keyed digests,-and provider session references include the principal and current clear epoch.--This is isolation, not identity linking. The same person on two platforms has-two principals unless a future product explicitly introduces account linking.-There is no shared install-wide pool, workspace memory, or group memory.--The local Settings page always reads `avibe:local`. Authenticated remote-Workbench users and IM users access only their own principal through an eligible-Agent session; the browser API accepts no user selector.--### Agent and CLI access--An eligible interactive human turn receives scoped guidance for:--```text-vibe memory status [--json]-vibe memory profile [--json]-vibe memory search <query> [--limit 1..20] [--json]-vibe memory remember <text> [--json]-```--`profile`, `search`, and `remember` require an Avibe-injected Agent session id.-For each eligible human Workbench or bound-DM turn, the controller associates-that session with the derived Memory principal; denied turns clear the-association. Missing or unassociated sessions return `memory_access_denied`.-The session id is routing context, not a security boundary against arbitrary-processes running as the same OS user. `status` contains install-level-operational data and is not a content read.--`vibe agent run` is a Harness/CLI automation source. Supplying an existing-session id does not turn it into a human Workbench or IM turn, so it receives no-Memory guidance or a live principal association. This prevents ordinary-background jobs and scripts from reading personal Memory merely by naming a-session through supported Avibe flows.--`remember` is the Agent's own write channel. With Memory enabled, the injected-guidance asks the Agent to call it proactively when a turn yields a durable signal —-a preference that emerged across several turns, a correction of Agent behavior, a-decision the conversation reached, or a durable user- or machine-specific-environment fact. Project conventions, architecture, and workflows stay on the-`AGENTS.md` surface and never enter personal Memory. The same guidance bounds the-noise: one self-contained distilled fact per call, nothing that paraphrases a-plain text message automatic capture already holds, no secrets or transient-state, and at most one or two calls per turn. The no-paraphrase rule is scoped to-plain text on purpose: automatic capture drops IM turns carrying files while the-prompt gate does not, so a durable fact stated only alongside an attachment is-still the Agent's to record.--`remember` accepts at most 4,000 characters and records-`provenance="agent"`; automatic capture records `provenance="user_input"`.-Identical text in one Agent session is idempotent. Exit code 0 means `accepted`-or `duplicate` in the local queue, not that provider distillation has completed.-All other outcomes are nonzero and Agents must not invent an unbounded retry-loop.--There are no CLI operations for clear, configuration, export, deletion, or item-editing. Memory results are untrusted data and must never be followed as-instructions.--## Architecture--```text-Workbench or eligible IM message- -> shared MessageHandler capture seam- -> MemoryModule.capture()- -> dedicated SQLite queue- -> controller-owned worker- -> EverOS adapter over a private UDS- -> configured LLM/embedding endpoints + owned provider root--Settings UI or scoped Agent CLI- -> UI/controller mode-0600 UDS- -> MemoryRuntime / MemoryModule- -> bounded status, profile, search, remember, or clear operation-```--The `core/memory/` package is the ownership boundary:--| Component | Responsibility |-|---|---|-| `module.py` | Provider-independent capture, search, profile, status, failure log, and idempotent clear |-| `store.py` | Dedicated SQLite metadata, principal derivation, queue state, deduplication, tombstones, and recovery markers |-| `worker.py` | Health-gated add/flush delivery, retry classification, flush observations, and processing health event reconciliation |-| `everos.py` | Bounded mapping between the module contract and EverOS public HTTP operations |-| `runtime.py` | Enable/disable/reconcile lifecycle and composition of the module, worker, and sidecar |-| `process.py` / `sidecar.py` | Owned child process, private UDS, request allowlist, environment, restart, and shutdown |-| `artifact.py` | Thin specialization of Avibe's shared managed-runtime installer and activation protocol |-| `attachments.py`, `http_headers.py`, `ui_access.py` | Attachment confinement and internal read-scope headers/proofs |--Callers never receive a provider object, database connection, filesystem root,-epoch, or principal selector. `MemoryModule` remains the deep product interface;-the provider and process types are internal implementation details.--### Local state--State is split under the effective `AVIBE_HOME` (normally `~/.avibe`):--```text-state/memory/memory.sqlite # Avibe queue and operational metadata-memory/everos-root/ # sentinel-owned provider data-memory/.rt/everos.sock # private sidecar socket-memory/generated/ # generated non-secret provider config-runtime/memory/ # downloaded immutable runtimes and active pointer-```--The SQLite store has only `memory_meta` and `memory_capture_queue`. The initial-schema is edited in place because Memory has not shipped; old development state-from an earlier branch revision must be reset explicitly rather than through a-silent startup migration.--The root sentinel binds a random `provider_root_id`, provider id, root format,-and artifact fingerprint. Clear and runtime activation refuse missing,-mismatched, symlinked, or unowned roots.--### Queue and delivery semantics--Capture normalizes and validates input, checks capacity and disk space, and-performs one local idempotent insert. It never calls EverOS or either model-endpoint on the chat path.--The worker uses these durable states:--```text-pending -> processing -> delivered- \-> dead-```--Each accepted row gets one stable provider timestamp. Retries and restarts reuse-it. The worker first adds the row, scrubs the source payload when add succeeds,-then flushes the provider session and records the public flush verdict. This-distinguishes queued work, delivered-but-awaiting receipt, successful-distillation, rejected distillation, and an unknown result without inspecting-EverOS private files.--Delivery is at least once. A crash or timeout can produce duplicate derived-memory. Infrastructure outages pause claims without consuming a row's retry-budget; a failure isolated to one message retries at fixed backoff and becomes-dead after three failed attempts. Terminal rows contain no source payload. A-sanitized failure history reports abandoned delivery, rejected distillation,-and unknown results without provider bodies or user text.--Important fixed guards are:--| Guard | Limit |-|---|---|-| Automatic capture text | 32 KiB UTF-8 |-| Memory attachment bundle | 8 files; 25 MiB/file; 100 MiB total; 16 KiB descriptor metadata |-| Nonterminal queue | 500 rows |-| Minimum free disk for capture | 512 MiB |-| Terminal idempotency tombstones | 90 days, newest 100,000 rows |-| Search query/results | 8 KiB query; 1-20 items; 64 KiB/item; 256 KiB total; 20 s |--At a queue or disk guard, capture is skipped and an aggregate missed counter is-updated; normal chat still proceeds.--### Status and failure behavior--Status uses the closed states `disabled`, `starting`, `ready`, `syncing`,-`degraded`, `down`, `clearing`, and `error`. It includes pending, processing,-awaiting-receipt, succeeded, unknown, distillation-failed, dead, and missed-counters plus the latest sanitized processing observation.--Sidecar or endpoint outages pause new claims and trigger bounded-supervision/backoff. Work not yet added remains pending; an ambiguous flush is-recorded as an unknown result instead of restoring already-scrubbed payload.-A sidecar exit is never allowed to take down normal Avibe chat. The process-manager stops only the child tree it started, verifies process identity before-signaling, removes only its owned socket, and participates in the normal service-shutdown lifecycle.--All public errors use Avibe-owned closed categories such as-`memory_disabled`, `memory_access_denied`, `memory_runtime_missing`,-`memory_sidecar_unavailable`, and `memory_processing_failed`. Raw exceptions,-provider responses, credentials, captured text, queries, and returned memory are-never logged or serialized as errors.--## Lifecycle--### Disable and re-enable--Disable closes capture and content reads, pauses the worker, and stops the-sidecar. It preserves queued rows, tombstones, provider data, and stored endpoint-credentials. Status and Clear all remain available. Re-enable starts the same-verified runtime and resumes pending work.--Changing only an API key is allowed without replacing the vector space.-Changing the embedding endpoint or model while provider data exists is rejected.-The supported replacement flow is: disable Memory, Clear all, change the-embedding configuration, then re-enable.--### Clear all--Clear all is local-Settings-only, CSRF-protected, explicitly confirmed, and-idempotent. Under the shared lifecycle lock it:--1. records `clear_in_progress` and advances the epoch;-2. pauses claims and stops the owned sidecar;-3. validates and removes children of the exact sentinel-owned provider root- without following links;-4. removes every queue row and recreates an empty owned root; and-5. clears the recovery marker and restarts Memory only if it remains enabled.--Startup resumes an interrupted clear before opening Memory. A restart failure-after deletion does not undo a completed clear.--Clear removes local provider data, hidden provider indexes/buffers, pending-payloads, terminal tombstones, and Memory-only operational history. It does not-remove original Avibe conversations, logs/backups, model-provider retention,-user copies or filesystem snapshots, or physical storage remnants. It also does-not remove the installed `memory-runtime`.--## Managed Runtime and Release--The production provider is official EverOS 1.1.3 behind the internal adapter.-The independently built `memory-runtime` pins:--- EverOS 1.1.3;-- Python 3.12.12;-- uv 0.9.18; and-- the reviewed `scripts/memory_runtime/uv.lock` digest.--Release workflows build deterministic archives for Darwin and Linux on x64 and-arm64. Archives contain only regular files/directories, are capped at 1 GiB,-and are verified for target, hashes, embedded Python, exact lock, required-imports, relocation, production child startup, and UDS health.--The Avibe wheel contains only `vibe/memory_runtime_manifest.json`, never the-large archives. Release jobs generate a `published` manifest from the exact-archive bytes and publish immutable archives before the wheel depends on them.-The repository manifest intentionally remains `release_state: unavailable` with-placeholder digests because a source checkout has no published assets.-`AVIBE_MEMORY_DEV_RUNTIME` is an explicit development-only bypass.--The runtime is strictly lazy: controller startup and ordinary reconciliation-resolve an already installed runtime but perform no download. Only the explicit-Dependencies install/repair job calls the installer, and installation does not-toggle `memory.enabled`.--Each runtime declares its provider-root format and compatible older formats. A-compatible nonempty root is retained. An incompatible nonempty root leaves the-previous runtime active and requires Clear all. A verified empty owned root may-switch formats. Activation coordinates worker/sidecar shutdown and atomically-updates the root sentinel and active pointer; failure rolls both back and-restarts the previous runtime when possible.--The scheduled release guard resolves the latest published wheel manifest,-verifies every immutable asset against it, maintains a manifest-qualified-backup, and restores only missing bytes. It never replaces an existing asset-with different content.--## Security and Data Disclosure--- Memory Settings and browser content routes require either a direct loopback- connection or an authenticated Avibe Cloud session. Every request requires a- same-origin Origin/Referer, and mutations also require CSRF. LAN, arbitrary- proxy, and Docker bridge routes remain unable to read Memory state or content.-- Authenticated Avibe Cloud browser reads use the same stable per-user principal- as that account's remote Workbench messages. The install-wide settings,- diagnostics, runtime restart, and Clear all controls remain owner operations- protected by the signed Cloud session and same-origin/CSRF checks.-- The controller socket and EverOS socket are owner-only Unix-domain sockets in- mode `0600`; the sidecar has no TCP listener and is not exposed through remote- access.-- The sidecar accepts only health plus the exact add, flush, search, and get- shapes used by Avibe. Principals must match `u-[0-9a-f]{32}`, and file URIs- must stay inside the Workbench attachment root.-- Child environment variables are allowlisted. Outside Avibe's owner-only- config, API keys reach the provider only through the sidecar environment;- generated files contain no secrets, and proxy/TLS override variables are not- inherited.-- Captured text, attachment content, and search queries may be sent to the- configured Memory endpoints and retained under those providers' policies.- Disable retains local data; only Clear all removes Avibe-owned Memory data.--These controls enforce the supported product surfaces. They are not a sandbox-against arbitrary code running as the same OS account and do not prove that two-platform identities belong to the same human.--## Deliberate Non-goals--The beta does not include automatic recall, assistant-message capture,-group/workspace/shared memory, cross-platform identity linking,-registered backend-specific Memory tools, item-level edit/delete, export/import,-provider migration, editable provider Markdown, exactly-once provider delivery,-or agent-driven configuration and Clear all. Each requires a separate product-and migration contract rather than placeholder interfaces in this system.--## Verification Contract--The implementation is covered at four layers:--- module/store/worker contracts for validation, deduplication, principal- isolation, retries, observations, payload scrubbing, status, clear, and crash- recovery;-- real sidecar and artifact contracts for multi-principal add/search/get,- attachment confinement, UDS/process lifecycle, runtime compatibility,- activation rollback, packaging, and release-asset verification;-- UI, controller, CLI, Workbench, and five-platform adapter tests for admission,- capability scope, lazy install, secret masking, CSRF/origin checks, inert- rendering, and the absence of `/memory` interception; and-- end-to-end verification of install/download, configure/enable, Workbench text- and attachment capture, Agent search/profile/status/remember, disable and- re-enable, Clear all, restart persistence, and IM admission simulation.--Real network IM delivery still requires configured platform credentials and is-the residual manual check. Provider-selection experiments and the removed POC-harness are historical evidence; production inputs are the pinned runtime lock,-manifest, implementation tests, and release workflows.diff --git a/docs/plans/memory-processing-log-page.md b/docs/plans/memory-processing-log-page.mddeleted file mode 100644index 34093d57f..000000000--- a/docs/plans/memory-processing-log-page.md+++ /dev/null@@ -1,20 +0,0 @@-# Native Memory Processing Record (superseded plan)--Status: superseded by the native Processing Record cutover--This plan originally specified a durable, installation-wide Provider Call Log.-That observer, its routes, and its UI are no longer part of the product contract.--The current contract is intentionally smaller:--- Processing Record reads caller-authorized EverOS native memcells, runs, linked- semantic files, profile state, and index state.-- Native evidence is retention-bounded and best-effort. Missing or malformed- evidence is reported as `partial` or `unavailable`; accepted loss is not replayed.-- There is no durable per-call observer, cross-request correlation ledger, gap or- anomaly ledger, installation-admin projection, or fallback to a legacy log.-- Clear may delete legacy call-log files while that storage still exists, but no- reader or recorder may depend on them.--See `docs/MEMORY.md`, `docs/MEMORY_ZH.md`, and-`docs/plans/memory-best-effort-capture.md` for the active behavior.diff --git a/docs/plans/memory-repair-factory-reset-integration.md b/docs/plans/memory-repair-factory-reset-integration.mddeleted file mode 100644index 10f5d0bb9..000000000--- a/docs/plans/memory-repair-factory-reset-integration.md+++ /dev/null@@ -1,64 +0,0 @@-# Memory Repair / Factory Reset Integration--> Historical design. Superseded by-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md); the live-> Repair and Factory Reset integration described below was removed.--Do not apply these edits until PR #1332 lands with its current review fixes.-The final integration worker must preserve both operations' retained-task and-closed-response contracts while adding the gates below.--Reference inspected: PR #1332 head `9d20ce6b` on 2026-08-11. Re-read the merged-head before applying this map because the six open P1 fixes may move these-locations. This branch intentionally does not integrate any #1332 commit.--## Bidirectional Admission Gate--The gate must cover both request orders, not only the shared operation lease:--1. In `vibe/ui_memory_routes.py`, include the loop-local Repair task in the- mutation-running predicate. The Repair route must reject a running factory- reset both before and inside `_memory_settings_write_lock()`. The factory- reset route must symmetrically reject a running Repair at those same two- points. Keep each existing retained task shielded and preserve the exact- `{ok, error, result}` conflict envelope.-2. In `core/internal_server.py`, make `/internal/memory/repair` reject while- `controller._memory_factory_reset_task` is live. Make- `/internal/memory/factory-reset` reject when the selected Runtime reports- either `_rebuild_running()` or `_repair_running()`. Keep the signed Memory UI- proof check and exact confirmation body ahead of all mutation work.-3. In `core/memory/runtime.py`, carry Repair into PR #1332's retirement model:- `repair()` must reject `_retired`, `_closing`, and a `factory_reset` recovery- intent. Preserve Repair in all existing Runtime mutation conflict predicates.- Repair's `MemoryOperationLease` and factory reset's lease acquisition before- `runtime.retire()` are the cross-controller/process serialization boundary;- neither operation may wait through the other's lease.-4. Add race tests for both directions: a retained Repair makes factory reset- return `memory_operation_in_progress` without retiring the Runtime, and a- retained factory reset makes Repair return the same closed conflict without- launching `EverOSSyncProcess`. Also cover the checks immediately before and- after the UI settings lock is acquired.--## Controller Shutdown Order--PR #1332 adds `_join_memory_factory_reset_task()`, because reset can replace-`controller.memory_runtime`. Preserve this exact shutdown order in-`Controller.stop()`:--1. Stop the internal dispatch server so no new Repair or reset can enter.-2. Settle startup Memory reconciliation.-3. Join `_memory_factory_reset_task` with no reporting timeout.-4. Drain Memory capture tasks.-5. Only then read the current `self.memory_runtime` and close that aggregate.--Within `MemoryRuntime.close()`, cancel and join `_repair_task` before the rebuild-join and before `_close_after_rebuild()` starts ordinary worker, retention, and-sidecar shutdown. Never cache the Runtime before the Controller joins factory-reset: the task may publish a fresh aggregate, and closing the old value would-leave the fresh sidecar and worker alive after Controller shutdown.--Required close-order tests should hold a reset immediately before fresh Runtime-publication and hold a Repair in its owned-child cleanup. Controller shutdown-must wait for reset publication, then close the published Runtime; Runtime close-must not release its operation lease until the Repair child and ownership record-are fully retired.diff --git a/docs/plans/memory-rerank-agentic-enablement.md b/docs/plans/memory-rerank-agentic-enablement.mddeleted file mode 100644index b6e304d51..000000000--- a/docs/plans/memory-rerank-agentic-enablement.md+++ /dev/null@@ -1,187 +0,0 @@-# Memory: enable EverOS rerank (Tier 3) and agentic search--Status: approved by owner 2026-08-14. This document is the source of truth for-the two delivery PRs below. Update it when scope changes materially.--Evidence baseline: Avibe `master @ 7fe4d19f`; pinned EverOS `1.2.3`-(`core/memory/artifact.py:55`). Related decision record:-`docs/memory-everos-reuse-audit.md` (recovery workstream — separate scope).--## Background--Avibe currently pins EverOS at capability **Tier 2** (`[llm]` + `[embedding]`)-and deliberately fails closed on everything above it:--- Every search request hardcodes `enable_llm_rerank: False`- (`core/memory/everos.py`), and the in-sidecar guard rejects any other value- (`core/memory/sidecar.py::_validate_search`).-- The generated `everos.toml` blanks `[rerank].model` / `[rerank].base_url`,- and `_validate_generated_config` asserts they stay blank- (`core/memory/process.py`). No rerank credentials exist in `MemoryConfig`.-- `method: "agentic"` is unreachable through three independent gates:- `EverOSPort.agentic_budget_enforced` is a constant `False`- (`core/memory/everos.py`), `MemoryModule.recall` /- `resolve_recall_mode` return `memory_capability_unavailable`- (`core/memory/module.py`), and the sidecar `method` allowlist is- `{keyword, vector, hybrid}` (`core/memory/sidecar.py`).--EverOS official guidance (docs verified in the EverOS 1.2.3 source tree,-`docs/api.md`, `EVEROS_INTEGRATION_zh.md`, `CHANGELOG.md`):--- Configuring `[rerank]` upgrades the sidecar to **Tier 3**, which unlocks- `method=agentic`. Tier upgrades require a sidecar restart. `GET /health`- reports `capabilities.rerank` and a `disabled_features` list- (`agentic_search` appears there when rerank is absent).-- Recommended usage ladder: hybrid defaults first; `agentic` is reserved for- complex, decomposable queries (slow/expensive: 1 LLM sufficiency call always,- +1 LLM multi-query call and 3 parallel retrievals when round 1 is judged- insufficient, plus 1–2 cross-encoder rerank batches; the episode path also- reads the cluster snapshot and fetches the full owner corpus).-- **Key nuance:** Avibe's searches are all `user_id`-owned episode/profile- lookups. For that owner kind, `enable_llm_rerank` is a documented no-op- (agent_case/agent_skill fusion only) and the automatic cross-encoder hybrid- lane applies only to agent skills. Therefore the only rerank-quality payoff- for Avibe's current usage is **`method=agentic`** (which runs its own- internal cross-encoder rerank loop).-- Agent-side agentic was broken before 1.2.2 and stabilized exactly at 1.2.3- (skill-shaped rerank passage fix) — the pinned version is the first safe one.--## Goal--1. Add an optional third memory endpoint (**rerank**) to product config and- plumb it into the EverOS sidecar so it starts at Tier 3 when configured.-2. Open a bounded, opt-in **agentic** recall path for agent callers via the- `vibe memory search` CLI, keeping `hybrid` the default everywhere.--## Owner decisions (2026-08-14)--1. **Provider-neutral rerank config.** Three user-filled fields- (`base_url`, `model`, `api_key`) exactly like the existing `llm` /- `embedding` endpoints. No provider preset, no default vendor.-2. **Agentic exposure = CLI only.** Agents choose the mode per query, guided- by system-prompt wording ("complex multi-hop recall only"). The Web UI- memory search stays hybrid-only for now.-3. **Budget gate resolved Avibe-side.** No upstream budget contract exists in- EverOS 1.2.3. Avibe enforces a wall-clock timeout (≤ 30 s, matching the- existing `RecallPolicy` budget validation in `core/memory/types.py`) on- agentic requests and records round telemetry (EverOS logs- `agentic_search_decision round=round1|round2`). `agentic_budget_enforced`- becomes true once that enforcement is real.--## Out of scope--- `enable_llm_rerank: true` (no-op for user-owned memories; revisit only if- agent_id-owned memories are adopted). The sidecar guard keeps rejecting it.-- The EverOS knowledge subsystem.-- UI-initiated agentic search.-- Any change to memorize/flush/rebuild/recovery behavior- (`docs/plans/memory-rebuild-and-recovery-ladder.md` owns that).--## Delivery plan — two sequential PRs--PR2 starts only after PR1 merges (both touch `core/memory/everos.py` and-`core/memory/runtime.py`; sequencing avoids contract drift and merge risk).--### PR1 — rerank endpoint config + Tier 3 unlock--Scope (indicative files):--- `config/v2_config.py`: `MemoryProcessingConfig` gains an **optional**- `rerank: MemoryEndpointConfig` (same field names/limits as `llm` /- `embedding`). Memory may be enabled without it (stays Tier 2). A partially- filled rerank endpoint is a validation error. Persisted-shape rule applies:- config files written by released versions (no `rerank` key) must load- unchanged; add load fixtures.-- `core/memory/runtime.py` (`_provider_kwargs` / `_process_settings`) and- `core/memory/process.py`: pass rerank settings through- `EverOSProcessSettings`; inject `EVEROS_RERANK__BASE_URL`,- `EVEROS_RERANK__MODEL`, `EVEROS_RERANK__API_KEY` into the child env only- when configured (mirror the llm/embedding pattern; api_key never touches- disk).-- `core/memory/process.py` generated-config: when rerank is **not**- configured, keep the current blanked `[rerank]` section (explicit Tier 2).- When configured, the generated toml + env must deterministically yield a- constructable reranker — verify EverOS toml/env precedence in the pinned- wheel and, if toml wins over env for non-secret keys, write the configured- `model`/`base_url` into the generated `[rerank]` section (api_key stays- env-only). Update `_validate_generated_config` to assert consistency with- the persisted product config instead of asserting always-blank.-- `core/memory/everos.py` health parsing: the current strict equality on the- 5-key capability set must tolerate EverOS's typed- `capabilities`/`disabled_features` health shape without flipping healthy- sidecars to `memory_provider_response_invalid`. Surface `rerank` capability- and `agentic_search` disabled/enabled state to the existing UI status- labels (`ui/.../memoryStatusPresentation.ts` already has both labels).-- UI: memory settings page gains the third (optional) endpoint form,- reusing the existing endpoint form pattern; all strings via- `ui/src/i18n/en.json` + `zh.json`.-- Preflight: if a rerank endpoint is configured, extend the existing- endpoint preflight pattern with a rerank probe consistent with how- llm/embedding are probed; a missing rerank endpoint must not degrade any- existing Tier 2 behavior.--Acceptance (PR1):--- With no rerank config: byte-identical generated toml/env versus master- (regression fixture), all existing memory flows unchanged, health shows- rerank capability false / agentic_search disabled without erroring.-- With rerank configured (fake/stub endpoint in tests): child env carries the- three `EVEROS_RERANK__*` vars; generated-config validation passes; health- snapshot reports `rerank: true`.-- Older persisted config without the `rerank` key loads and saves cleanly.-- `agents.*`-style config save reconciliation still applies (rolling refresh- path; no second restart requirement).--### PR2 — bounded agentic recall path (after PR1 merges)--Scope (indicative files):--- `core/memory/everos.py`: `_search_data` accepts `method="agentic"`; apply a- per-request wall-clock timeout (≤ 30 s) for agentic calls;- `agentic_budget_enforced` returns true iff timeout enforcement is active.- `enable_llm_rerank` stays `False` in every request body.-- `core/memory/sidecar.py` `_validate_search`: add `"agentic"` to the method- allowlist; keep every other guard (including `enable_llm_rerank is False`).-- `core/memory/module.py` / `core/memory/types.py`: `resolve_recall_mode`- routes `agentic` → available only when health reports the capability- (rerank + llm + embed present, `agentic_search` not disabled); otherwise- fail closed with `memory_capability_unavailable` exactly as today.-- `core/memory/runtime.py`: keep `_recall_all_projects` rejecting agentic- (`--project all` + agentic stays unsupported).-- `vibe/internal_client.py` + `core/internal_server.py` + `vibe/cli.py`:- `vibe memory search --mode {hybrid|keyword|vector|agentic}` (default- `hybrid`). Parser-backed contract tests required — injected system-prompt- CLI examples are live callers (see AGENTS.md §7).-- `core/system_prompt_injection.py`: extend the memory CLI guidance with one- sentence: agentic mode is for complex, multi-hop recall only; default stays- hybrid.-- Telemetry: log/record agentic usage and result (at minimum: mode, duration,- success/timeout) so the round-2 rate and latency can be measured from logs.--Acceptance (PR2):--- Rerank unconfigured → `--mode agentic` returns the existing- `memory_capability_unavailable` error surface (never an EverOS 422 leaking- through, never a hang).-- Rerank configured (stubbed sidecar in tests) → agentic request reaches the- sidecar with `method="agentic"`, `enable_llm_rerank=False`, and times out- cleanly at the budget with a typed error.-- Default CLI behavior byte-identical to master (`hybrid`, limit 8).-- Behavioral deltas documented in user docs: agentic episodes return empty- `atomic_facts`; with unlimited `top_k` EverOS caps agent kinds at 10.-- `--project all --mode agentic` rejected with a clear error.--## Contracts frozen for both lanes--- Config field names: `memory.processing.rerank.{base_url,model,api_key}`- (optional section), identical semantics/limits to the existing- `MemoryEndpointConfig`.-- Child env names: `EVEROS_RERANK__BASE_URL`, `EVEROS_RERANK__MODEL`,- `EVEROS_RERANK__API_KEY`.-- Recall mode vocabulary: `auto | keyword | vector | hybrid | agentic`- (existing `RecallMode`); CLI flag `--mode`, default `hybrid`.-- Sidecar request shape: unchanged key set; `method` allowlist grows by- `"agentic"` in PR2 only; `enable_llm_rerank` remains hard-`False`.-- Agentic budget: wall-clock ≤ 30 s, enforced in `EverOSPort`.--Deviations from these contracts route through the PM, never lane-to-lane.diff --git a/docs/plans/memory-sidecar-force-restart-button.md b/docs/plans/memory-sidecar-force-restart-button.mddeleted file mode 100644index 59f16ae4e..000000000--- a/docs/plans/memory-sidecar-force-restart-button.md+++ /dev/null@@ -1,472 +0,0 @@-# Add a forced Memory sidecar restart action (rev21)--> Historical design. Superseded by-> [`memory-unified-recovery-pr3.md`](./memory-unified-recovery-pr3.md); Wake is-> now the sole non-destructive availability operation.--> Rev21 keeps one public recovery action and one linear Runtime lifecycle while-> closing the replay-marker, delayed-readiness, and UI timeout races. The Runtime,-> Module, Worker, and Process interfaces stay deep: callers see-> `MemoryRuntime.restart()`, while worker lease handoff and process ownership-> remain private implementation details.--## Decision--When Memory is enabled, the settings page will expose one "Restart engine"-action. The action replaces an alive-but-unreachable sidecar with a new child-using the Runtime's replay configuration: the startup configuration until the-first successful reconcile, then the latest configuration applied successfully.-An independently successful `embedding_change_pending` settlement is reflected-in that snapshot without adopting the rest of a subsequently failed candidate.--This plan deliberately does not repair configuration persistence. In-particular, restart does not:--- load its target configuration from disk;-- rewrite a failed persisted candidate back to the last-good configuration;-- migrate or serialize every V2 config writer;-- update `Controller.config` or force the UI to reload settings; or-- settle `embedding_change_pending`.--If the replay snapshot still has `embedding_change_pending=true`, restart fails-closed with `memory_clear_failed` before pausing the worker or touching the-sidecar. The existing Settings/Clear lifecycle remains responsible for checking-the provider root and settling that persisted marker. Once settlement succeeds,-the Runtime mirrors only the cleared marker into its replay snapshot. Keeping-the settlement itself and all other configuration repair out of restart is what-removes the global config transaction and Controller rebasing work from this-feature.--## Goals--1. Whenever saved Memory settings are known to be enabled, show one restart- action even when status is loading, unavailable, or reports `down`.-2. Stop the old supervised sidecar, start a replacement from the in-memory- replay configuration, and report success only after the replacement process- is ready.-3. Preserve the queue's existing at-least-once behavior without leaving rows- stranded under the old worker lease.-4. Never launch a second child until the old supervisor has confirmed its child- tree is stopped.--## Non-goals--- automatic health-based restart;-- persisted/live/Controller config repair after a failed settings rollback;-- a general Memory lifecycle coordinator or explicit state machine beyond the- narrow ready-callback generation described below;-- new provider, store, or process interfaces;-- retrying historical `unknown` flushes;-- disabled/no-store cleanup recovery UX;-- global ownership tracking for every `asyncio.to_thread()` call; and-- a full four-platform regression.--## Why reconcile is not the restart operation--The current UI route calls persisted reconciliation. That is the wrong-interface for a process-only recovery action:--- reconcile loads the persisted settings instead of replaying the last working- Runtime configuration;-- it may wait 30 seconds for a worker drain and then run a processing preflight;-- an active flush can last up to 300 seconds; and-- `MemoryRuntime._config` is assigned before every later root/start step has- succeeded, so a failed candidate is not necessarily safe to replay.--Keep the existing public route, but route it to a dedicated operation:--```text-UI- -> POST /api/memory/runtime/restart- -> internal_client.memory_restart()- -> POST /internal/memory/restart- -> MemoryRuntime.restart()-```--## Observable contract--`MemoryRuntime.restart()` returns one of:--```text-{ok: true, state: "ready"}-{ok: false, error: <Memory error code>}-```--The contract is:--- concurrent callers join the same in-progress restart task; they do not queue- a second stop/start sequence;-- success means the replacement `EverOSProcess.start()` returned `True`, which- already includes the sidecar health/readiness check;-- restart does not run the processing preflight probe;-- restart does not modify persisted settings; an earlier reconcile that settled- the durable embedding marker also clears only that marker in the replay copy;-- disabled replay returns `memory_disabled` without constructing a process;-- unavailable store/module returns `memory_store_unavailable`;-- a pending embedding change or failed clear recovery returns- `memory_clear_failed` without launching a replacement;-- ordinary orchestration failures return `memory_restart_failed`;-- a replacement that fails readiness returns- `memory_sidecar_unavailable`; and-- no failure may leave two sidecars owned by the Runtime.--The five-second requirement applies only to graceful worker drain. It is not a-five-second HTTP or whole-operation deadline. Process stop and startup keep-their existing bounded behavior. A synchronous SQLite store call that was-already executing must finish before the worker task is considered stopped;-the SQLite connection's existing busy timeout bounds ordinary lock contention,-but the plan does not pretend Python can preempt an arbitrary running thread.--## Backend design--### 1. Replay configuration--Add one private `_restart_config` to `MemoryRuntime`:--- initialize it as a deep copy of the startup `MemoryConfig`;-- update it with a deep copy only after enabled or disabled reconciliation has- returned success while `_reconcile_lock` is held;-- immediately after `_settle_embedding_change_pending()` succeeds, clear only- `_restart_config.embedding_change_pending` while `_reconcile_lock` is held,- even if a later reconciliation step fails;-- never copy any other field from a failed candidate; and-- copy it again at the start of the locked restart sequence.--The deep copies are required because `MemoryConfig`, its nested settings, and-`embedding_change_pending` are mutable.--The startup value is intentionally a retry candidate, not proof that the-configuration has run successfully. A new Runtime has no durable last-good-record. After its first successful reconcile, `_restart_config` becomes the-latest successfully applied configuration for the remainder of that Runtime-instance. This plan does not add persistence for replay history across an Avibe-restart.--Marker settlement is a separate successful fact from candidate activation. The-existing guard has already proved the provider root safe and persisted-`embedding_change_pending=false`, so leaving `true` in the startup or last-good-replay copy would permanently disable restart after a later readiness or root-failure. Mutating only that boolean preserves the last-good settings while-making the replay snapshot agree with the durable marker.--Immediately before replacement, restore `self._config` from the replay copy so-the worker's `enabled` callback and the new child settings use the same value.-Restart does not compare this snapshot with disk and does not-claim to repair a pre-existing disk/live split. A failed C1 settings transaction-therefore remains a Settings concern: restart may run live C0, but the persisted-file is unchanged and the UI must not report that configuration was repaired.--### 2. One retained restart task--Add one private `_restart_task` to `MemoryRuntime`.--`restart()` creates `_restart_once()` as a task when none is active, otherwise-it awaits the existing task. Every caller awaits it through `asyncio.shield()`.-Caller cancellation or an HTTP disconnect therefore detaches that caller but-does not abandon a half-completed process handoff. A later caller joins the same-task and receives the same terminal result.--The task converts ordinary exceptions to the structured failure result and is-cleared by a done callback only after it is terminal. `close()` joins an active-restart task before running its existing worker/process shutdown. Do not add a-restart-specific shutdown budget or a registry of lifecycle owners.--### 3. Existing lock order and Clear serialization--The restart task uses the existing lock order:--```text-MemoryRuntime._reconcile_lock- -> MemoryModule._lifecycle_lock- -> provider-root lifecycle lock, only inside Clear recovery-```--No pending counters, waiter inspection, retained-owner gate, or new coordinator-is added. A concurrent reconcile, Clear, artifact activation, or restart finishes-in this lock order; it is acceptable for restart to wait for the current-lifecycle operation rather than implement fail-fast admission. The narrow-generation below only invalidates readiness notifications; it does not grant-ownership or replace these locks.--Make two focused fixes to keep that order real:--1. Extract `MemoryModule._recover_interrupted_clear_locked()` from the current- wrapper. It requires `_lifecycle_lock`, takes the existing root lock, rereads- the durable marker, and performs the existing bounded recovery. The public- wrapper keeps its current read-path behavior. Reconcile, artifact activation,- and restart call the locked helper only after both Runtime and Module locks- are held. This removes the current recovery/check gap.-2. Make `MemoryRuntime.clear()` hold `_reconcile_lock` across `module.clear()`- and its optional post-Clear reconcile. `module.clear()` continues to own its- own Module/root locks; the post-Clear step reacquires the Module lock and calls- the existing locked reconcile helper. Do not pre-acquire the Module lock and- then call `module.clear()`, which would self-deadlock.--Capture and status do not need a new lifecycle gate. Capture only enqueues store-work, and status metadata writes do not carry a worker lease. Search/profile and-Clear already serialize through the Module lifecycle lock.--### 4. Ready-callback serialization--Add one private monotonic `_lifecycle_generation`, one retained-`_ready_activation_task`, and one latest-event slot to `MemoryRuntime`. Each-outer Runtime lifecycle owner advances the generation in `finally`: reconcile,-Clear, restart, and the full artifact-install span. Locked helpers reuse their-owner's generation rather than marking a nested lifecycle. The artifact-install-span continues to use its existing active flag while its blocking thread runs-outside `_reconcile_lock`.--Bind each supervisor's `on_ready` callback to that exact supervisor. The callback-must synchronously schedule or coalesce a Runtime-owned activation task and-return; it must not await Runtime locks while `EverOSProcess` is still holding-its own lifecycle lock. Scheduling overwrites the latest-event slot with the-notifying supervisor and captured generation, then ensures one activation task-is running. That task drains the slot and acquires `_reconcile_lock` followed by-`module._lifecycle_lock` for each event. Its done callback clears only the exact-task that became terminal, so a newer task cannot be lost. Before resuming claims-it revalidates all of the following:--- the captured generation is unchanged;-- the notifying supervisor is still `self._process` and reports `running`;-- replay/live configuration is enabled with no pending embedding marker; and-- artifact installation is not active.--A callback emitted by a lifecycle-owned `start()` is therefore stale after that-lifecycle advances the generation in `finally`; the explicit success path resumes-claims and starts the worker itself. A delayed automatic retry in a quiescent-generation is serialized behind any later lifecycle and activates the worker-only if its process identity and captured generation still match. A callback-during the unlocked artifact-install span fails the active-install revalidation.-`close()` advances the generation, clears the latest-event slot, and joins the-retained ready-activation task before process shutdown. This prevents both lock-inversion with the Process supervisor and unowned callback work.--### 5. Worker stop and lease handoff--Only worker store calls need cancellation settlement because they may write a-row using the old lease owner.--Change `MemoryWorker._store_call()` to create one task for the current-`asyncio.to_thread()` call and await it through `shield()`. If the drain task is-cancelled, wait for that exact store task to finish before propagating-`CancelledError`. The worker drain lock already makes these calls serial, so no-registry or Module-wide store tracking is needed.--Change `MemoryRuntime._stop_worker()` so `_worker_task` is cleared only after-the exact task is terminal. It must distinguish the drain task's expected-`CancelledError` from cancellation of the lifecycle caller.--Add a private Worker helper such as `begin_new_lease_activation()` that generates-a new lease UUID and then reuses `begin_activation()`. Its interface is expressed-only in Worker lease terms; it does not know about process replacement. Call it-only after the old worker task and its active store call have ended, and only-after the old supervisor has stopped successfully. The next drain activation-then uses the existing `recover_after_boot()` path before making a new claim.--Queue semantics remain unchanged:--- an add claimed under the old lease is recovered for the new lease and may be- delivered again under the existing at-least-once contract; and-- an interrupted in-flight flush becomes `unknown` and opens the existing- processing fault. Restart does not retry or erase that historical result.--### 6. Keep artifact installation truthful--`install_artifact()` currently clears `_artifact_installing` in `finally` even-though cancellation of `asyncio.to_thread(ensure)` does not stop its thread.-Use one local shielded task and wait for it to finish before clearing the flag-or propagating cancellation. Restart checks the flag while holding-`_reconcile_lock` and returns `memory_restart_failed` before handoff if an-installation is still active.--This is a local ownership fix. Do not add an installer registry or a general-`to_thread()` framework.--### 7. Linear replacement sequence--Inside `_restart_once()`:--1. Acquire `_reconcile_lock`, copy the replay configuration, and validate- store/module availability, artifact installation state, enabled replay, and- `embedding_change_pending=false`. Resolve the installed Python runtime here,- before handoff, but do not run a processing preflight.-2. Acquire `module._lifecycle_lock`.-3. Run locked interrupted-Clear recovery. If it fails, return without creating- a process. On success, call `pause_claims()` again with no intervening await;- the existing recovery helper may resume claims before returning, but no worker- can run between its return and this synchronous fence.-4. Allow the current drain tick five seconds to finish with new claims paused.- Whether it finishes gracefully or times out, cancel and await the exact old- worker task. The shielded Worker store call must settle before this step ends.-5. Call the old supervisor's existing `stop()` interface. Clear `_process` only- after `stop()` succeeds. If it fails, retain the supervisor reference, keep- claims paused, and return `memory_restart_failed` without constructing a new- process.-6. Restore `self._config` from the replay copy, replace the provider, apply the- existing artifact/root metadata checks, and construct the replacement.- Bind its ready callback to that exact supervisor and assign it to `_process`- before awaiting `start()` so ownership is never lost.-7. After old ownership is gone, rotate the Worker lease and then call the- replacement's `start()`. Rotating before `start()` ensures that both immediate- success and a later automatic ready callback use the new lease. If `start()`- returns `False`, keep the replacement supervisor for its existing automatic- retry, keep claims paused, and return `memory_sidecar_unavailable`.-8. On success, resume claims, start the drain task, clear the visible runtime- error, and return `{ok: true, state: "ready"}`.-9. Advance `_lifecycle_generation` in `finally`, making any callback emitted- during the lifecycle stale before releasing `_reconcile_lock`.--Failures before the old process is touched may restore the previous worker and-claims when its supervisor is still running. Failures after old ownership is-released remain fail closed: retain any replacement supervisor, keep claims-paused, and leave the same restart action available. These two phase-based-postconditions replace rev19's per-owner failure matrix.--`EverOSProcessPort` remains unchanged. Runtime calls only `running`, `starting`,-`start()`, `stop()`, and `processing_healthy()`; it never reads watcher,-monitor, restart-task, process-tree, or cleanup-phase internals. The Process-implementation remains responsible for the successful `stop()` postcondition.--## Transport and UI--### Backend transport--1. `core/internal_server.py`: add `POST /internal/memory/restart`, which calls- `MemoryRuntime.restart()`. Missing Runtime returns `memory_runtime_missing`;- unhandled exceptions map to `memory_restart_failed`.-2. `vibe/internal_client.py`: add `memory_restart()` without a client-side- reporting timeout. The Runtime may be waiting for an already-running SQLite- thread that Python cannot preempt, so only the internal response is proof that- its retained restart task reached a terminal result.-3. `vibe/ui_memory_routes.py`: keep `/api/memory/runtime/restart`, preserve its- same-origin/user checks, and call `memory_restart()` instead of reconcile.- Create or join one loop-scoped, retained UI-process restart request task using- the same loop-rebinding discipline as `_memory_settings_write_lock()`. That- task acquires the settings lock and holds it until the no-timeout internal- request returns; route callers await it through `asyncio.shield()`. A browser- disconnect or cancelled route waiter therefore does not release the settings- lock while the controller restart continues, and a normal Memory PATCH cannot- save/reconcile concurrently. Clear the retained task only after it is terminal.- Do not add a pending counter or a cross-process config lock.-4. `core/memory/types.py` and frontend translations: add transport-only- `memory_restart_failed`. Reuse existing error codes for disabled, unavailable,- clear-marker, and sidecar-readiness failures. Do not add a SQLite schema value.--### Frontend--1. `SettingsMemoryPage.tsx`: render one page-level secondary `xs` action with- `RotateCw` whenever `settings?.enabled === true` and Memory access is- authorized. This preserves both trusted loopback and authenticated Avibe- Cloud access; the frontend does not invent a separate locality test. Put the- action outside the status/loading/runtime-required branches so a missing- status or runtime dependency does not hide it.-2. Keep one `restarting` boolean. Disable the action and show `Loader2` while the- request is pending.-3. Reuse the existing `MemoryRuntimeRestartResult` union. Success shows a- completed-restart toast and reloads status/failures. Failure uses- `memoryErrorMessage()` and the returned literal error code. Do not invalidate- or reload settings because restart did not change them.-4. Remove the engine-fault banner's duplicate restart action. Keep the- credential-fault "Open settings" action.-5. Update English and Chinese translations together. Do not add- `restartRetryEligible`, `config_committed`, config-recovery state, or a new- frontend test framework.--## Focused tests--Test observable behavior through the existing module interfaces. Do not assert-private counters, task registries, generations, or callback phases.--### Python--- `tests/test_memory_runtime.py`- - alive-but-unreachable process: one old `stop()`, one new `start()`, then- `ready`; no processing preflight;- - two concurrent callers share one restart and one result;- - before any successful reconcile, restart uses the startup retry candidate;- after successful C0, a failed C1 is not committed and restart uses C0 while- the persisted config remains byte-for-byte unchanged;- - successful marker settlement followed by a later reconcile failure clears- only the marker in the replay snapshot, so restart remains available without- adopting the failed candidate's settings;- - pending embedding marker and failed Clear recovery launch no child;- - restart and Clear/reconcile serialize without a marker/start race;- - a delayed ready callback racing Clear, reconcile, or artifact activation- cannot start a worker inside that lifecycle; stale process/generation- callbacks are ignored and a surviving quiescent retry activates normally;- - drain completion inside the grace window preserves its result;- - cancellation during a Worker store call does not start replacement until- the synchronous write has ended, after which the new lease recovers old- claimed work;- - old `stop()` failure retains the old supervisor and creates no replacement;- - new readiness failure keeps claims paused and allows later automatic ready- recovery or another explicit restart; and- - caller cancellation leaves the retained operation owned, and a second- caller joins it without another replacement.-- `tests/test_memory_worker.py`: new-lease activation rotates the lease and runs- durable activation recovery before the next claim. Do not duplicate the- existing Store tests for add recovery and interrupted-flush `unknown` rules.-- Artifact activation coverage: inject a blocking artifact manager, run its- `ensure()` through the real `asyncio.to_thread` path, and cancel the install- caller. Through `MemoryRuntime.restart()` results, prove restart remains- excluded until that exact thread settles and is admitted afterward; do not- assert the private `_artifact_installing` flag.-- `tests/test_internal_server.py`: success, missing Runtime, and exception- mapping for the new endpoint.-- `tests/test_internal_client.py` and timeout tests: method/path, response- passthrough, and the explicit absence of a restart reporting timeout.-- `tests/test_ui_memory_routes.py`: new client call, settings-lock serialization,- retained-task sharing, caller-cancellation behavior, internal unavailability,- and existing cross-origin rejection. Prove a PATCH remains blocked after its- restart route waiter is cancelled and proceeds only after the internal restart- reaches a terminal response.--### TypeScript--- Extend the existing static-render Memory tests to cover an enabled page-level- action when status is absent/error, disabled spinner state, and exactly one- restart action for an engine fault.-- Keep response-shape coverage on the existing- `MemoryRuntimeRestartResult`; do not add a separate normalizer module unless- implementation reveals an actual malformed-response bug.-- Cover click/toast behavior with the single manual scenario rather than adding- a DOM test framework.--## Validation--1. Run focused Memory Runtime, Worker, internal transport, and UI route tests.-2. Run `ruff check` on changed Python files.-3. Run the relevant Vitest files and `cd ui && npm run build`.-4. Update only the local Incus `master` environment with- `./scripts/run_regression.sh`; preserve its configuration and verify service- health.-5. In the container, send `SIGSTOP` to the managed sidecar to create an- alive-but-unreachable process. Verify the page-level action remains visible,- the old PID is replaced, the action shows progress, and status returns to- `ready`. Send `SIGCONT` to the original PID only if cleanup needs it.-6. Verify Avibe service health again. Do not restart the local `vibe` service and- do not use `kill -9` for this scenario.--## Deferred work--Track these as separate proposals only when their own product requirement-exists:--- a cross-process transaction for every V2 config writer;-- failed settings rollback repair across disk, Runtime, Controller, and UI;-- generic async-thread ownership and cancellation infrastructure;-- a general Memory lifecycle coordinator or process generation model beyond the- narrow ready-callback generation;-- disabled/no-store durable orphan recovery UX; and-- global process-budget or shutdown-lifecycle redesign.--## Todo--- [x] Replay `_restart_config`, single-flight task, and focused Runtime tests-- [x] Locked Clear recovery and serialized Runtime Clear-- [x] Five-second worker drain, store-call settlement, and lease rotation-- [x] Linear old-stop/new-start flow and failure postconditions-- [x] Internal transport and existing UI route switch-- [x] One page-level action, toast/i18n, and engine-banner deduplication-- [x] Focused Python/TypeScript validation-- [ ] Local Incus `SIGSTOP` scenariodiff --git a/docs/plans/memory-symlinked-home-confinement.md b/docs/plans/memory-symlinked-home-confinement.mddeleted file mode 100644index 519134722..000000000--- a/docs/plans/memory-symlinked-home-confinement.md+++ /dev/null@@ -1,39 +0,0 @@-# Memory symlinked-home confinement--Issue: [#1520](https://github.com/avibe-bot/avibe/issues/1520)--## Background--Memory currently derives several mutable paths from the logical Avibe home, but-its attachment store, SQLite store, provider-root guard, and process supervisor-do not share one trust-anchor decision. A supported home reached through a-symlink can therefore fail an absolute no-follow walk before the walk reaches-anything Avibe owns.--## Goal--Resolve the operator-controlled effective home once to a physical trust anchor,-derive Memory-owned paths lexically below it, and preserve no-follow rejection-for every Avibe-owned descendant.--## First implementation slice--- add one confined-root value in `core/memory/confined_filesystem.py` that maps- logical and already-physical child spellings to the same physical root without- resolving child components;-- make `MemoryRuntime`, `MemoryStore`, `AttachmentPinStore`, `ProviderRoot`,- `EverOSProcess`, and `EverOSRebuildProcess` consume that physical identity;-- route attachment storage layout and Memory-store directory preparation through- the existing confined-filesystem interface while retaining domain error types;-- add contract tests for a symlinked parent, the legacy final-home symlink shape,- one physical provider/lock identity, and rejection of symlinks below the home.--## Non-goals--- no changes to attachment limits, modality, hashing, bundle lifetime, SQLite- transaction semantics, provider sentinel semantics, or child lifecycle;-- no change to explicitly configured provider roots or socket paths outside the- effective home;-- the remaining caller audit (`operation_lock`, retired provider-call storage cleanup, artifacts,- clear intent, and factory reset) stays tracked by #1520 and is not declared- complete by this first slice.diff --git a/docs/plans/memory-sync-foundation.md b/docs/plans/memory-sync-foundation.mddeleted file mode 100644index 332e48ad4..000000000--- a/docs/plans/memory-sync-foundation.md+++ /dev/null@@ -1,37 +0,0 @@-# Memory Sync Foundation--This change establishes the process and artifact contract for the future-Repair index action. The only child command admitted by the contract is:--```text-<artifact-python> -I -m everos.entrypoints.cli.main cascade sync-```--The embedded runtime carries an inert `.pth` bootstrap and a minimal persistence-scrubber module. The bootstrap is enabled only for the exact `cascade sync`-argv, validates the parent/role/nonce envelope, installs scrubbers, and stops-before EverOS imports. The parent writes `memory/.rt/everos.sync.json` ahead of-spawn, validates the stopped child, atomically finalizes the record, releases-it, and cleans only the recorded process group. The sync record is independent-of `everos.sidecar.json` and rebuild ownership.--The current published Memory Runtime artifacts predate this contract. A release-must build all supported `linux-x64`, `linux-arm64`, and `darwin-arm64` bundles,-generate a manifest containing the sync bootstrap and scrubber digests, pass the-release guard, and publish those assets before a product Repair action can be-enabled. This branch intentionally does not publish artifacts, tags, or releases.--The bootstrap acceptance test uses a versionless behavioral fake only to prove-Avibe's launch, stop-before-import, scrubber-ordering, and argv-rejection-boundary. A separate required CI contract provisions the hash-locked EverOS-wheel from `scripts/memory_runtime/uv.lock`, invokes the real module entrypoint-against an isolated root, and proves that pathless sync scans one Markdown file-and drains its queue. Neither test downloads or contacts a provider while it is-running.--`cascade fix --apply` remains deliberately absent. The pinned upstream contract-only establishes that pathless `cascade sync` may coexist with the live server;-similar-looking implementation code is not an online-safety guarantee. The same-executable acceptance test proves the artifact bootstrap rejects `fix --apply`-before its CLI can mutate state. Adding that operation requires a separate issue-and an explicit upstream live-safety contract.diff --git a/docs/plans/memory-unified-recovery-pr3.md b/docs/plans/memory-unified-recovery-pr3.mddeleted file mode 100644index e3fe482a3..000000000--- a/docs/plans/memory-unified-recovery-pr3.md+++ /dev/null@@ -1,87 +0,0 @@-# Memory unified recovery PR 3--Status: implemented locally from `origin/dev` at-`f020c38b0d0199134e2910c91c01f27836ffb6c7`.--This plan replaces the active Memory recovery ladder with one non-destructive-availability operation and two explicitly authorized destructive intents. It is-the current contract for the PR 3 `recovery` and `fsm` workstreams.--## Product surface--- `Wake` validates or reinstalls the admitted artifact, stops the old owned- process, starts the same EverOS root, and verifies native readiness with- bounded backoff. Startup and unexpected exit use this path. It never deletes- data.-- `Repair(confirm_loss)` exists only for `needs_repair`. It proves the old- process tree stopped, preserves stable identity/config, performs the confined- data reset, then calls Wake and requires native readiness.-- `Delete data(confirm_loss)` is a distinct explicit user intent using the same- stop-before-delete and confined reset primitive.-- An Embedding identity change uses the same accepted-loss reset instead of a- candidate plus rebuild marker.-- Status is one state in `disabled`, `starting`, `running`, `degraded`, or- `needs_repair`, plus one sanitized reason across API, CLI, and UI.--Provider, credential, disk, and permission failures are `degraded`; they do not-authorize Repair. Failed or interrupted destructive operations retain no stage-or replay instruction. Startup reevaluates local state.--## Destructive boundary--Every route and client uses the exact `confirm_loss` field. The Controller also-checks it, acquires the process-level Memory operation lease, proves the old-owned sidecar and runtime stopped, then invokes a pathless deletion primitive.--That primitive can remove only:--- `<effective_home>/memory`, the native EverOS root and Memory attachment area;-- fixed, retired Clear journal/backup names under `state/memory`.--It cannot accept a caller path, follow symlinks, recursively erase an unproved-root, or remove `state/memory/memory.sqlite`. The identity store rotates its data-generation atomically while preserving scope identity, provider-root identity,-and the project catalog. Unsafe or foreign content fails closed and remains-visible in the operation response.--## Removed protocol--New code no longer writes or executes `MemoryConfig.recovery_intent`,-`MemoryRecoveryIntent`, `embedding_change_pending`,-`cloud.transition_rebuild_owned`, rebuild/factory-reset retry flags, retained-request owners, or cascade sync/rebuild children. Standalone Restart, Rebuild,-Clear, and Factory Reset routes, clients, controls, types, and scenario harnesses-are removed.--Released workflow fields collapse on load into the durable `repair_required`-compatibility fence. Ordinary saves preserve that fence until a successful-destructive reset clears it. Released Clear state is only classified; it never-authorizes deletion or resumes a workflow. No workflow journal, pending stage,-or fallback executor is introduced.--## Scenario contract--- `MEMORY-WAKE-001`, `MEMORY-WAKE-002`, and `MEMORY-WAKE-201`: Wake is- non-destructive and bounded; unexpected exits re-enter Wake and external faults- remain degraded.-- `MEMORY-REPAIR-201` through `MEMORY-REPAIR-206`: exact loss confirmation,- eligibility, stop-before-delete, native readiness, no stage resume, and- identity preservation.-- `MEMORY-DELETE-DATA-001` and `MEMORY-DELETE-DATA-002`: distinct user intent, exact- confirmation, shared confinement, and truthful partial failure.--The `memory_rebuild_recovery`, `memory_factory_reset`, and-`memory_clear_recovery` catalogs are retired. Their process identity,-authorization, exclusion, and confinement assertions move to the unified-Repair/Delete-data coverage; stage continuation assertions are deleted.--## Validation--Focused unit and contract suites cover config compatibility, runtime Wake,-process ownership/reaping, Controller reset, internal/UI routes and clients, CLI-status, and native Processing Record. UI tests cover status, controls, exact-confirmation, copy, and settings identity changes. Ruff, compileall, Vitest,-UI lint/build, and `git diff --check` are required before the local commit.--Incus and full-repository regression remain residual checks for PR delivery and-are not required for this local preparation.diff --git a/docs/plans/proactive-memory-capture.md b/docs/plans/proactive-memory-capture.mddeleted file mode 100644index 18902a6f5..000000000--- a/docs/plans/proactive-memory-capture.md+++ /dev/null@@ -1,356 +0,0 @@-# Proactive Memory Capture--## Background--Avibe Memory already has both write paths it needs:--- **Automatic capture.** Every eligible human turn sends the user's message- verbatim into the Memory queue through the shared handler seam- (`core/handlers/message_handler.py` -> `Controller.capture_user_memory`).-- **Agent-initiated writes.** `vibe memory remember "<text>"` reaches the- internal server, records `provenance="agent"`, is idempotent for identical- text inside one Agent session, and accepts at most 4,000 characters.--What is missing is the habit. Agents almost never call `remember` on their own,-and the direct cause is the injected prompt rather than the runtime. In-`core/system_prompt_injection.py`, the Memory section `_MEMORY_CLI_PROMPT`-describes `remember` as queuing "durable context explicitly requested by the-user" — an explicit instruction not to record anything the user did not ask for.-The highest-value material for a personal memory system is exactly what the user-never thinks to request: corrections of agent behavior, preferences revealed in-passing, and conclusions the conversation reached over several turns.--A second problem sits next to it. `_USER_PREFERENCES_PROMPT` is a parallel set of-memory instructions (the shared preferences file plus `AGENTS.md`) whose wording-is equally passive ("You may also update it when explicitly asked") and whose-scope overlaps the Memory section without either one saying which surface owns-what. An agent reading both sections has two passive memory instructions and no-routing rule.--## Goal--> This section describes the shipped end state. An interim release (#1092)-> gated the behavior behind a `memory.proactive_capture` opt-in; that design-> was removed after a product re-evaluation and survives only as history in-> the review-round sections and the removal follow-up at the end of this-> document. Read this section when changing the behavior.--Give the Agent a proactive Memory-write habit with enough noise control that-what it records stays useful.--1. With Memory enabled, the injected guidance tells the Agent to call- `vibe memory remember` on its own initiative when a turn produces a durable- signal. There is no separate opt-in: the Memory enable disclosure states- Agent-recorded durable facts as part of what enabling Memory means.-2. Name the signals worth recording: a preference or identity detail that- emerged across several turns, a correction of Agent behavior, a decision the- conversation reached, and a durable user- or machine-specific environment- fact. Project conventions, architecture, and workflows stay on the- `AGENTS.md` surface.-3. Give explicit noise controls so proactive capture does not degrade into- logging: one self-contained distilled fact per call, no paraphrase of a plain- text message automatic capture already holds, no one-off task detail, nothing- derivable from code or git, no secrets, a small per-turn budget, and silence- when in doubt.-4. On Memory-admitted turns, route eligible explicit requests for durable,- non-secret personal facts and stable habits to `vibe memory remember` unless- the user names another permitted destination. The shared preferences file- remains writable only when the user names that file itself; project knowledge,- transient details, and secrets keep their existing exclusions and surfaces.--## Non-goals--- No change to the capture contract: admission, queue, schema, CLI surface, and- internal server stay exactly as they are.-- No change to the injection gate. `memory_cli_prompt_admitted` keeps requiring- `memory.enabled`, a human turn, and an admitted principal; the new flag can- only narrow what that gate advertises, never widen who receives it.-- No proactive writes to the shared preferences file. Everything the Agent- records on its own initiative stays inside Memory's managed lifecycle, which- is disclosed before enabling and clearable through Clear all.-- No assistant-message capture and no automatic recall injection; both remain- non-goals of the Memory plugin system.--## Solution--The behavior lives entirely in the injection layer plus the enable disclosure;-there is no new persisted config.--### Config and settings surface--`memory.enabled` is the only Memory switch. A config written by the interim-opt-in release still loads: the stored `proactive_capture` flag is dropped on-read and no longer serialized. The settings PATCH whitelist is-`{enabled, processing}`, so a stale client sending the retired field gets-`memory_invalid_input` instead of a silent merge. `Controller.reconcile_memory`-has no prompt-only classification: every accepted save runs the full runtime-reconciliation.--The Settings -> Memory disclosure, subtitle, and enable hint state-unconditionally that durable facts the Agent records while working for the user-are part of Memory.--### Injected prompt--`_MEMORY_CLI_PROMPT` is the single Memory section: the four `vibe memory` CLI-examples and the read guidance, plus a trigger list, a signal-quality block, a-silent-recording posture, and a surface-routing paragraph. Its no-paraphrase-rule is scoped to plain text messages on purpose: automatic capture drops IM-turns carrying files while the prompt gate does not, so a durable fact stated-only alongside an attachment is still the Agent's to record. The exception is-phrased in terms the Agent can observe — whether the message arrived with a-file — rather than internal admission state. An explicit request overrides only-that no-paraphrase rule: the existing durability, secret, task-detail, and-surface filters still apply. The Agent confirms a requested write only after-`remember` returns `accepted` or `duplicate`; any nonzero outcome is reported as-a failure without an unbounded retry.--`build_system_prompt_injection` injects it whenever `include_memory_cli` is-true. The three backends resolve `memory_cli_prompt_admitted` once per turn —-it associates or clears the Memory CLI session scope as a side effect — and-pass the result straight through.--### `_USER_PREFERENCES_PROMPT`--Without Memory admission, the file keeps its historical explicit-request role.-When Memory is admitted, eligible general remember requests and proactive writes-route to `vibe memory remember`; the file becomes read-only unless the user names-it as the destination. This named-file exception is explicit because the file-lives under the Avibe state directory, while Memory's SQLite and runtime-owned-state files remain prohibited write targets.--### Test coverage--Prompt assertions anchor on semantic keywords rather than whole-paragraph-equality. The injected-command contract test keeps every `vibe memory` example-in the single prompt under the parser-backed live-caller check. Config-load-tolerance and settings-PATCH rejection of the retired flag each have their own-cases.--## Todo--- [x] Inject the proactive contract whenever Memory is admitted, as the single- Memory prompt.-- [x] Route eligible explicit remember requests to Memory on admitted turns,- while preserving the named preferences-file destination and all existing- eligibility and safety filters.-- [x] Drop the retired `proactive_capture` flag on config load and reject it in- the settings PATCH whitelist.-- [x] Describe Agent-recorded facts unconditionally in the Settings disclosure,- subtitle, and enable hint (en/zh).-- [x] Update the prompt, live-caller CLI contract, config, and settings-route- tests to the single-prompt contract.-- [x] Update `docs/plans/memory-plugin-system.md` and the CLI references.-- [x] Run the focused tests and `ruff check` on changed Python files.--The review-round sections below record the interim opt-in design (#1092) as-history; they are not normative.--## Review follow-ups (Codex review of 72a09153)--- [x] Gate proactive preference-file writes on Memory admission: the proactive- update sentence in `_USER_PREFERENCES_PROMPT` is now selected per turn- (`memory_cli_admitted`), falling back to the original explicit-request- wording when Memory is disabled or the turn is not admitted.-- [x] Narrow the fourth `remember` trigger to user/machine-specific environment- facts and route project conventions, architecture, and workflows to the- nearest `AGENTS.md`, which future Agents load early.-- [x] Disclose the broadened outbound data flow: `ui/src/i18n/en.json` and- `zh.json` (Memory subtitle, enable hint, and a new pre-enable disclosure- bullet) plus `docs/CLI.md` and `docs/COMMANDS.md` now state that Agents- proactively record distilled conclusions, not only user-requested context.--## Review follow-ups, round 2 (Codex review of e4d3f994)--- [x] Keep proactive capture on a single surface: the preferences file is now an- explicit-request surface on every turn; the memory-admitted variant of its- guidance adds only a routing rule pointing proactive capture at- `vibe memory remember`, so all proactive writes stay inside Memory's- managed, disclosed, clearable lifecycle.-- [x] Reword "Choosing the surface" to state that everything recorded- proactively — including working preferences — belongs in Memory.-- [x] Sync the Chinese CLI references (`docs/CLI_ZH.md`, `docs/COMMANDS_ZH.md`)- with the Agent-distilled capture wording.-- [x] Align the `remember` contract in `docs/plans/memory-plugin-system.md` with- the injected prompt: durable user- or machine-specific environment facts- only; project knowledge stays on the `AGENTS.md` surface.--## Review follow-ups, round 3 (Codex review of 84c64be0)--- [x] Disclose non-conversation capture sources: the Memory subtitle, enable- hint, and disclosure bullet (en/zh) now cover durable conclusions the- Agent distills from work on the machine — including environment or- account facts found in files or tool output — not only conversations.-- [x] Keep cross-project preferences reachable across projects: Memory is- project-scoped, so "Choosing the surface" now tells the Agent to offer- saving a clearly cross-project preference to the user-global preferences- file and write it there only once the user agrees, keeping that file an- explicit-request surface. This was the round-3 behavior; the later- admitted explicit-request routing contract below supersedes the automatic- cross-project offer while retaining writes when the user names the file.--## Review follow-ups, round 4 (Codex review of a9994cf6)--- [x] Make proactive capture an explicit opt-in so an existing consent is never- silently widened. `MemoryConfig.proactive_capture` (default false,- validated as a bool, persisted through `memory_config_to_payload` /- `V2Config.from_payload`) now gates the behavior; the Memory settings route- accepts and returns it, and Settings → Memory exposes a "Proactive- capture" switch that requires Memory to be enabled. An install upgraded- from a Memory-enabled release therefore keeps requested-only behavior.- The injected guidance is split into two variants selected per turn:- `_MEMORY_CLI_PROMPT` restores the pre-PR requested-only wording, and- `_MEMORY_CLI_PROACTIVE_PROMPT` carries the proactive contract. The- preferences-file routing rule is likewise limited to proactive turns, so a- Memory-admitted turn without the opt-in never points the Agent at a- proactive channel it does not have. All three backends resolve- `memory_cli_prompt_admitted` once per turn (it has a session-scope side- effect) and combine it with the fail-closed- `memory_proactive_capture_enabled`.-- [x] Stop the proactive guidance from re-queuing what automatic capture already- holds. The first trigger now covers preferences that emerged across several- turns rather than ones stated outright in a single message, matching the- "no single user message states in full" qualifier on the decision trigger,- and the section states plainly that a paraphrase of a single user message- must never be queued. The no-echo rule is strengthened to say a proactive- write exists only for a conclusion automatic capture cannot reach.-- [x] Attribute Agent-recorded content in the reader-facing surfaces:- `memory.profile.sourceNote` and `memory.search.sourceNote` (en/zh) now- cover notes the Agent records, not only conversation history. The- pre-enable disclosure bullet is restated as conditional on the new toggle.--## Review follow-ups, round 5 (Codex review of 1bcfc687)--- [x] Enforce "disabling Memory revokes the opt-in" in the API, not just the UI.- Settings PATCH is a merge, so a client sending only `{"enabled": false}`- left the stored `proactive_capture: true` in place, and the next- `{"enabled": true}` silently restored Agent-initiated writes.- `_memory_settings_patch` now clears the flag whenever the merged result is- disabled, so an older client, a cached page, or a direct call cannot skip- the revoke that `proactiveCaptureFor` already applies in the browser.-- [x] Stop the proactive guidance from over-claiming what automatic capture- holds. `CaptureAdmission.decide` drops IM turns carrying files, but the- prompt gate (`memory_capture_admitted` → `admits`) does not apply that- check, so an IM turn with an attachment and a caption still receives the- proactive prompt. The unconditional "anything you stated is already in- Memory, never restate it" would have stranded a durable fact that appears- only in such a caption. The claim is now scoped to plain text messages,- with the exception stated in terms the Agent can observe — whether the- message arrived alongside a file — rather than internal admission state.- Admission, queue, and schema are untouched.-- [x] Stop binding a prompt-only flag to provider health.- `_apply_memory_settings_patch` always reconciles, and reconciliation- probes the provider and swaps the sidecar, rolling the save back on- failure — so an owner could not turn proactive capture off while their- endpoint was down. `Controller.reconcile_memory` now compares the- runtime-relevant projection of the two configs (`enabled`, both processing- endpoints, `embedding_change_pending`; deliberately not- `proactive_capture`) and, when only the flag differs, adopts the new- config and returns without touching `memory_runtime`. The comparison is- fail-safe: any runtime-relevant difference, and any config that cannot be- projected, runs the full reconciliation.--## Review follow-ups, round 6 (Codex review of c95b07ca)--- [x] Close a race that could resurrect a revoked opt-in for the life of the- process. `Controller.run` starts a background reconciliation carrying the- config as it was at boot; while it awaits the sidecar, a prompt-only save- can publish a revoked `proactive_capture`, and the boot reconciliation- then republished its stale candidate on success — disk and UI showed the- flag off while the live controller kept injecting proactive guidance until- the next restart. `reconcile_memory` now claims a monotonic sequence- number before its first await, and a completed reconciliation whose number- has been overtaken publishes its own runtime fields but takes the- prompt-only fields from the newest request. A lock spanning the- reconciliation was rejected deliberately: it would queue the prompt-only- path behind a provider probe, which is exactly the round-5 failure of an- owner unable to revoke while their endpoint is down. The prompt-only- branch has no await between classification and publication, so it is- already atomic on the loop.-- [x] Rewrite Goal, Non-goals, and Solution to describe the opt-in design that- shipped. They still described the first draft — proactive capture as- unconditional default behavior, no new switch, changes confined to the- prompt — which would have led a later reader to reintroduce the consent- problem these rounds removed. The follow-up sections below are kept as- evolution history, and the rewritten body says so.-- [x] Disclose machine-derived capture in the CLI references. `docs/CLI.md`,- `docs/CLI_ZH.md`, `docs/COMMANDS.md`, and `docs/COMMANDS_ZH.md` now match- the Settings disclosure: conclusions distilled from conversations *and*- from work on this machine, gated on the proactive-capture opt-in.--## Review follow-ups, round 7 (Codex review of 3fb1a549)--- [x] Generalize the automatic-capture exception in- `_MEMORY_CLI_PROACTIVE_PROMPT`. Round 6 excepted only messages arriving- with a file, but the exclusion is much wider: adapters mark forwarded or- shared content non-ordinary (for example Slack's `not has_shared_content`),- and `_is_ordinary_human_text` drops every non-ordinary turn, so the prompt- still told the Agent that text was already stored and must not be- restated. The wording now says coverage stops at plain text and names the- shape rather than any platform's internal rule — a turn carrying a file,- forwarded or shared content, or any other non-plain form. The- "record it rather than assume" failure direction and the no-paraphrase- rule for plain text are both unchanged, and the no-echo bullet already- carried the same plain-text qualifier from round 5.-- [x] Stop the Memory enable copy from promising a data flow that is off by- default. `memory.subtitle`, `memory.settings.enableHint`, and both- `sourceNote` strings asserted unconditionally that Agent-recorded facts- are included, while `proactive_capture` defaults to false. All four are- now conditional in en and zh: the subtitle and enable hint name the- separate switch, and the source notes hedge with "any notes your Agent- recorded" so they read accurately in either state. Copy-only, no- conditional rendering — the strings are honest without one, and the- pre-enable disclosure bullet keeps its existing conditional form.--## Review follow-ups, round 8 (Codex review of 6b13a0f2)--- [x] Exclude `proactive_capture` from settlement equality:- `_same_memory_configuration` normalized only the pending marker, so an- owner toggling the prompt-only flag while a pending embedding change was- settling made the candidate look like a different configuration, failing- the settlement with `memory_runtime_install_failed` and leaving both the- marker and the runtime unreconciled. The comparison now normalizes both- settlement-irrelevant fields, mirroring the controller's runtime identity.--## Follow-up: the opt-in switch is removed (2026-07-30)--The `memory.proactive_capture` opt-in shipped in #1092 as a response to the-round-4 consent finding, but it was never part of the approved product design,-and it carried most of the PR's accidental complexity: the flag lived inside-`MemoryConfig`, whose changes otherwise drive sidecar reconciliation, so every-config path had to learn to classify prompt-only versus runtime-relevant-changes (runtime identity projection, a prompt-only fast path, a-sequence-numbered publication merge against a reconcile race, and a-settlement-equality exclusion).--After re-evaluation the owner decided proactive capture is part of what-enabling Memory means. The switch, its UI toggle, and the whole prompt-only-machinery are removed:--- `MemoryConfig` no longer carries `proactive_capture`; a stored flag from the- interim release is dropped on load and no longer serialized.-- `build_system_prompt_injection` has a single Memory prompt: enabling Memory- injects the proactive contract (When to remember / noise controls / surface- routing) directly. The requested-only variant is gone.-- `reconcile_memory` is back to its pre-#1092 shape; the settlement comparison- normalizes only `embedding_change_pending` again.-- The settings PATCH whitelist is `{enabled, processing}`; a stale client- sending the retired field gets `memory_invalid_input`.-- Settings UI and disclosure describe Agent-recorded facts unconditionally.--Consent posture: the Memory enable disclosure now states Agent-recorded-durable facts as part of what enabling Memory means, instead of gating them-behind a second toggle.--## Follow-up: admitted explicit-request routing (2026-08-12)--General requests to remember durable, non-secret personal facts and stable-habits now use Memory whenever the CLI is admitted for the turn. This does not-broaden eligibility: project knowledge still goes to `AGENTS.md`, transient and-one-off task details remain out, and secrets are never queued. A user who names-the shared preferences file can still select it directly, despite its location-under Avibe state; runtime-owned Memory files and SQLite remain off-limits.--The acknowledgement contract follows the CLI outcome: `accepted` and-`duplicate` permit a short success confirmation, while every nonzero outcome is-reported as a failure and must not be described as saved.diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 28ad91d45..aee5d3fee 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1888,7 +1888,7 @@ export type DependencyItem = {export type DependenciesResult = { ok: boolean; deps: DependencyItem[] };-// Memory plugin contract: docs/plans/memory-plugin-system.md.+// Current Memory contract: docs/MEMORY.md.// Keys are write-only: GET never returns a usable `api_key`, only `has_api_key`.export type MemoryRerankProvider = 'deepinfra' | 'vllm' | 'dashscope';