Repository navigation
Description
Track the migration of memory logic from main to rust-preview. Replace the separate MEMORY.md mechanism with a unified memory store to reduce the complexity of maintaining two storage systems. Provide an interface for users to inspect and edit automatically collected memories, making it easier to understand what has been remembered, correct mistakes, and maintain useful long-term information.
1. Delivery goals and migration boundaries
| Area | Current main behavior | Rust target for this work |
|---|---|---|
| User management | Settings primarily manage legacy MEMORY.md, separately from automatic atomic memory |
Sessions, automatic extraction, and UI share the same items, versions, sources, and service |
| Always-provided content | Markdown bodies enter context | A small set of user_always items in the same store, loaded automatically for each applicable new session/Run and modified only with user authorization |
| Explicit remember | Evidence from a frozen conversation; synchronous return of actual saved content | Preserve evidence checks and receipts; explicitly authorized items receive user protection |
| Model-requested extraction | memory_extract marks a turn for extraction after completion |
Preserve the explicit model trigger; extracting after every Run is not an equivalent migration |
| Compaction extraction | Background work after a durable automatic compaction checkpoint | Migrate in its own PR, sharing coverage cursors and write rules with requested extraction |
| Deduplication and conflicts | Extraction appends assertions; only operation idempotency, no semantic deduplication | An exact-match fast path, bounded candidate retrieval, and batched semantic judgment for duplicates, additions, explicit replacements, and unresolved conflicts |
| User correction | Atomic storage supports CAS, but the automatic lifecycle/UI is incomplete | Users can edit automatic memories; protect the new version and record correction relationships to old assertions so a new ID cannot bypass protection |
| Deletion | No productized per-item deletion lifecycle in the atomic path | One Delete operation: retain the original content as a suppression record, exclude it from normal use, and prevent equivalent content from automatically becoming effective again |
| Recall | Atomic facts plus original conversation search | Extend existing Rust Recall, consistently enforcing permissions and suppression across facts, historical evidence, caches, and continuation reads |
Preserve AGENTS.md, global instructions, and their existing precedence. Retire the product's MEMORY.md/PENDING.md memory protocol; do not delete arbitrary user files with those names. Memory bodies are data and do not automatically gain system/developer instruction authority.
Do not migrate Assistant Memory Network, DiscoveryMemory, investigation scheduling, or notification feedback as substitutes for ordinary memory. They may share existing authorization, source-location, and transaction facilities, but not business records or authorization boundaries. Do not introduce a vector database, generic memory platform, second background scheduler, cross-Host synchronization, or automatic decay.
2. Product and data contracts to settle first
2.1 One store, three management modes
Use closed enums to express valid combinations. Source type, write authority, and current use must not be collapsed into one origin field.
| Management mode | Normal reads | What automation may do |
|---|---|---|
auto_recall |
On-demand recall | Create, supplement, or explicitly replace within evidence, version, and conflict rules |
user_recall |
On-demand recall | Add evidence that genuinely supports the current assertion and maintain rebuildable indexes; cannot change the body, scope, validity period, or effective state |
user_always |
Automatically provided for every new Run in scope; sources remain available on demand | Same as user_recall; cannot automatically pin, unpin, edit, or delete |
Editing an automatic item makes it user_recall; pinning confirms its current content and makes it user_always. Unpinning returns it to user_recall without automatically restoring automation's editing authority. Viewing alone does not change its mode. Automatic evidence additions must not change user-authored content, validity, or protection flags, nor quietly change user-selected priority by modifying sort fields.
Authority for the four entrypoints is defined as follows:
- UI edits and explicit “remember/correct/use this from now on” commands targeting specific content carry equal user authority.
- Model-requested and compaction-triggered extraction carry automatic authority and cannot overwrite, retire, or restore protected items.
- “Organize this conversation” authorizes extraction, not blanket replacement of user-owned items. Explicitly requested items and incidental extractions receive separate authority.
- “Use English this time,” quoted commands, tool output, and assistant inference do not authorize lasting changes.
A trusted entrypoint binds the capability to the actual user operation or immutable user message, authorization scope, and operation identity. The model cannot upgrade its own authority by emitting actor=user or origin=user_requested. Natural-language intent parsing can still fail and requires targeted acceptance examples; the existence of a matching source quote does not prove authorization intent.
Protected items must participate in duplicate detection; excluding them because updates are forbidden would create a bypass. If an automatic candidate conflicts with a protected item, it must not become an effective new item under another ID. Save it as an unresolved candidate linked to the target and exclude it from answers by default. Replacement requires new user authorization explicitly targeting that subject and scope. Determine ordering from the user's expression time or the fact's effective time, not background-job completion time.
2.2 Separate items, assertion versions, and sources
The minimum persisted data comprises:
- Items: typed
MemoryId, current version, management mode, scope,active / unresolved / suppressedstate, and creation/modification times. - Immutable assertion versions: body, kind, statement/temporal types and validity, generation method, and relationships to replaced or corrected versions. Ordinary edits keep the item ID and increment its version; changes of subject or scope cannot automatically reuse the same fact identity.
- Evidence links: bind to a specific assertion version; reuse immutable source addresses, message versions/fingerprints, and verified source-span locations, with separate source-observation times. Direct UI entry uses a real user-operation record as its source.
- Matching records: normalized body hashes, keywords/aliases, and scope/time, covering current facts and restricted matching content retained after deletion or user correction.
- Operation receipts and coverage cursors: operation identity, actual outcome, target IDs/versions, and source range. Keep explicitly selected evidence ranges separate from continuous coverage for automatic incremental work. Receipts must not retain a separate readable body that bypasses deletion filtering.
- Relevant-scope generations: detect newly added items, user corrections, and suppression changes during model judgment, rather than checking only the selected target's version.
After identifying a duplicate, reuse one current fact and incrementally link new sources; differing sources do not justify another effective body. A preference replacement creates a new assertion version while retaining the old body and evidence: evidence for the old “Chinese” assertion must not become supporting evidence for the new “English” body. A user-edited body must be labeled as user-modified, without claiming that old chat text supports it verbatim.
Page evidence and history on demand and append incrementally; do not place all sources in an array on every read/write. Main's per-item source limit and full-replacement interface cannot support unlimited evidence accumulation unchanged. Source references provide provenance, not semantic uniqueness: one source may support several facts, and different sources may express the same fact.
2.3 Delete means suppression with retained content, not physical erasure
Users perform one Delete action; no separate “never record this again” action is required. The deletion transaction sets the item to suppressed, unpins it, and retains the assertion body, necessary scope/time, source links, and matching keys. Follow confirmed relationships to handle related old versions, merged equivalents, and unresolved candidates together. Discover unknown equivalents through later matching; do not claim that one deletion has scanned and understood the entire store.
- Ordinary lists, Recall, always-provided projections, default exports, and model tool results must not return suppressed bodies.
- The dedicated write adjudicator may read relevant suppressed bodies for comparison. The main Agent receives only a result that does not disclose the body, such as “not added: matches a user deletion record.”
- New sources, different wording, restarts, retries, and old-backup imports cannot automatically lift suppression.
- Only an explicit user request to remember that deleted information again can lift suppression for that fact and write it. Merely mentioning it again or requesting bulk organization is not restoration authority.
- Do not expire suppression content by TTL, which would allow old information to return. Retention grows and requires disk/index size metrics, pagination, and maintenance; silently discarding suppression records is not an acceptable capacity policy.
This is an explicit retention policy. The UI should briefly explain: “Deleted memories are no longer used; matching records are retained to prevent automatic re-creation.” It must not promise complete erasure or add several similar action buttons to explain the distinction. Deleting a memory does not physically erase original chats, already-sent model requests, or independent backups.
User corrections likewise retain the old assertion body and a corrected_by relationship to prevent old wording from returning under a new ID. Correction suppression applies to the old assertion, not the entire topic. Deleted content and corrected old versions cannot serve as evidence for new facts.
2.4 One write-adjudication flow for duplicates, conflicts, protection, and suppression
Trusted entrypoint / source range / authorization
→ safely normalize the body and look up its exact hash
→ check subject, scope, statement type, time, authority, and lifecycle
→ retrieve keyword-index candidates for unresolved proposals
→ judge new/old relationships in batches (ordinary, protected, suppressed)
→ trusted code validates actions, versions, evidence, and authorization
→ commit assertions / sources / relationships / suppression / cursor / receipt atomically
The exact-match path normalizes formatting only; it must not remove negation, quantities, conditions, or effective dates. A matching hash still requires semantic-field checks and is not a globally unique fact key. Queries must cover both effective items and the restricted suppression index; duplicate checking cannot end at an active-only query.
Use keyword/entity/alias indexes for semantic candidates, not model scans of the entire store. Allocate separate count and total-token budgets for ordinary, protected, and suppressed candidates so normal results cannot crowd out deletion records. The small always-provided set may be compared in full within the authorized scope. New candidates within a batch must also be compared with one another before forming one commit plan.
| Relationship | Write action |
|---|---|
| Equivalent | Reuse the fact and append supporting evidence; block creation if equivalent to a suppression record |
| Compatible addition | Save the added fact or an evidence-backed new version; retain conditions and do not discard content merely because topics are similar |
| Explicit replacement | For the same subject, matter, and scope, create a new version based on explicit change and actual time; retain the old assertion in history |
| Independent or different scope/time | Store separately; do not merge across scopes |
| Conflict without a reliable resolution | Save a sourced unresolved candidate linked to its conflicting target; exclude it from default recall and always-provided context |
Automatic authority may replace only automatically managed items. For protected items, deletion suppression, or corrected old versions, code limits the available actions before the model decides. User authority must also match the current target, scope, and operation; an ordinary “remember X” request does not authorize deleting unrelated facts.
“Likes Chinese” and “likes English” may coexist; “use English by default from now on, replacing Chinese” expresses replacement. Preserve conditions such as “English for work email, Chinese for other communication.” Delayed extraction of older source material must not replace newer facts. Unknown fact time cannot be resolved by blindly choosing the later database write.
If a protection/suppression match is uncertain, defer activation. A model timeout, invalid output, or candidate-search failure must not fall back to direct creation. When retrieval finds no candidate, creation may proceed, but that is a miss under bounded retrieval, not proof of global semantic uniqueness. Exact checks, CAS, permissions, and idempotency have deterministic acceptance criteria; retrieval misses, false merges, and incorrect suppression require semantic evaluation.
Run model calls outside database transactions. Capture memory/policy generations for every relevant scope when reading candidates; at commit, check scope generations, target versions, source identities, and current authorization together. If a relevant scope changes, retrieve again and perform bounded rejudgment rather than checking only the old target ID. This covers two Sessions both finding no candidate, and deletion between judgment and commit. Unrelated scopes must not share a lock held across a model call.
2.5 Loading, budgeting, and recovering always-provided content
Always-provided content is neither another summary nor an automatically maintained file; the UI edits the same item's current version. For the first Run of each new session and every subsequently admitted Run, read all applicable user_always items and generate a stable, budgeted projection. Later model steps within that Run use the same admitted projection. Compaction must neither remove it nor append duplicate copies as chat messages.
- Check the aggregate budget when the user pins an item or edits pinned content; check again against the actual model window at request admission.
- Reject an over-budget mutation or admission explicitly and provide an adjustment entrypoint. Do not silently truncate, automatically unpin some items, or claim that everything loaded. Reuse existing context-budget mechanisms without adding many configurable knobs.
- Persist actual IDs/versions, scopes, policy versions, order, and projection content/fingerprint. Cache keys include these identities, not just the Session.
- Ordinary edits affect later new Runs; do not promise that the next step of an already admitted Run automatically reads the latest body. Normal recovery reuses the frozen projection without silently changing its content.
- Record every controlled memory dependency entering model input, including IDs/versions for pinned blocks, Recall facts, source spans, and memory tool results. After deletion, permission revocation, Incognito activation, or disablement, recheck revocation before the next Provider send or native continuation. If affected content cannot be safely excluded, use existing abort/readmission paths. Frozen recovery or previous-response continuation must not keep sending/reusing prohibited memories. Preserve records of requests already sent.
This is the explicit boundary required by Rust's frozen-input model, replacing the earlier promise to read the latest store on every model step. Verify actual input paths for both native execution and existing external executors. Report unavailable capabilities rather than silently falling back to MEMORY.md.
2.6 Read and retention boundaries
Normal memory reads expose only current effective versions. Suppressed and unresolved content must not enter model facts. Report fact failures/incompleteness explicitly; do not reintroduce a deleted fact through historical fallback that skips suppression checks.
Reuse source-span relationships to filter known deleted/corrected evidence from historical candidates, neighbor expansion, continuation reads, material expansion, and caches. Do not suppress an entire message and damage its other facts. Equivalent wording in unknown sources remains limited by semantic recognition. A user explicitly opening an original chat is viewing history, not reactivating a memory; deletion does not promise to erase every natural-language copy.
At operation entry, look up committed receipts by operationId first. On a hit, do not rerun the model, write plan, old-source validation, or coverage-cursor CAS; resolve visible results using only current read authorization and suppression state. Committed fact/coverage outcomes remain unchanged. Do not return cached old bodies or rerun creation when items have been deleted or replaced. Only uncommitted work reacquires sources, candidates, and write authority. Historical content already returned by the original request cannot be retracted retroactively. Caches, projections, and exports share visibility rules; tool results already loaded into a Run also undergo the pre-send revocation check in section 2.5. If suppression checking fails, do not release the affected memory sources; healthy results that are safe to provide may still be returned.
2.7 Retiring MEMORY.md and handling existing data
The target runtime must not read, initialize, rewrite, or synchronize MEMORY.md/PENDING.md. Remove related prompt advice, old settings entrypoints, and documentation guidance. Do not generate a database summary file that remains independently editable or introduce a dual-write compatibility layer.
Provide explicit, one-time import for existing main user data: freeze a source snapshot, preview items and scope mappings, and, after confirmation, import in batches through the same write adjudicator with idempotent import receipts. Do not automatically delete old files. Clearly explain that unimported content will no longer load automatically; do not silently lose the user's existing content.
- Import user-confirmed Markdown content as protected items. Only a user-confirmed subset within budget becomes always-provided; do not silently pin the entire file or truncate it.
- When migrating an existing atomic store, distinguish automatic and explicitly requested items using their actual origin. Import alone does not pin atomic items. Unverifiable origin/scope must not upgrade authority or broaden visibility.
- Defer old session scopes, path aliases, or project scopes that cannot be mapped, with per-item reasons; do not quietly make them global. Unverifiable sources may remain historical provenance but must not be presented as verified citations.
- Import obeys current deletion/correction suppression. Previewing an import does not authorize restoring deleted content. Migration occurs only through this explicit entrypoint, with no background full-disk scan.
3. PR breakdown and dependencies
| PR | Suggested title | Independently usable/acceptable delivery | Dependencies |
|---|---|---|---|
| 1 | feat(memory): add scoped user-controlled memory records |
Real Host item-ID management, user protection, retained correction/deletion records, sources, and atomic receipts | Target branch |
| 2 | feat(memory): reconcile duplicate and conflicting writes |
Exact and bounded semantic adjudication, unified protection/suppression and concurrent commits; explicit save/edit integration | 1 |
| 3 | feat(recall): retrieve effective memories with suppression guards |
Ordinary fact recall, provenance, and suppression for historical fallback/caches | 1, 2 |
| 4 | feat(memory): replace markdown memory with user-owned context |
Always-provided user content, budgets/recovery/revocation, explicit legacy import, and retirement of the Markdown protocol | 1, 2, 3 |
| 5 | feat(memory): extract grounded memories from conversation ranges |
Evidence-backed explicit remember and on-demand organization, with queryable actual outcomes and costs | 2, 3, 4 |
| 6 | feat(memory): extract requested memories after completed runs |
Model marking, incremental background extraction after completion, permission/stop/recovery | 5 |
| 7 | feat(memory): extract from durable automatic compaction boundaries |
Automatic compaction trigger, shared cursors, checkpoint recovery, and deduplication | 6 |
| 8 | feat(memory): manage unified memories in the shared interface |
Complete management UI, pinned editing, automatic-memory correction/deletion, sources/history/unresolved results, and status | 1–7 |
Recommended order: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8. Move the original management UI to the end. Split automatic extraction into requested and compaction PRs because their trigger authorities, source freezing, and recovery windows differ. Each PR includes the necessary schema/SDK/product composition, behavior tests, and documentation; do not submit unused storage frameworks or empty services.
PR 1 must not claim to prevent arbitrary semantic re-creation. Bounded-retrieval suppression becomes available only when PR 2 adds semantic judgment. Commands/APIs in PRs 1–7 expose all necessary controls, results, and status without making UI delivery a prerequisite for backend acceptance. PR 8 provides the sole production management page.
4. Implementation and acceptance by PR
PR 1: Shared records, user authority, and deterministic operations
Behavior example: A user saves, corrects by ID, and deletes an item through a trusted entrypoint. State survives restart, and another window's stale write cannot overwrite the latest value.
- Add memory-domain contracts to Agent api/facts/state/native, using RootStore, Host journals/receipts, and existing Root migration registration and its migration ledger. Do not copy the separate TS memory.sqlite database or introduce another lease system; a historical ledger name does not justify adding a SQLx execution path.
- Add create/read/paginate/edit-by-ID/delete/explicit-save-again interfaces. Implement the three modes, version-bound evidence, and correction/deletion matching records. Manual bodies in PR 1 come from user input; do not expose a create channel through which the model can impersonate direct UI input.
- Scope combines the Host/Agent namespace with project/location identity already resolved by the Host. Reuse
folder:<resolved host path>/git:<resolved common directory>. Git worktrees share the existing common project identity; an explicitly selected repository subdirectory must not expand to the entire repository. Do not add physical workspace UUIDs or root-directory markers. On relocation, users explicitly decide whether to migrate memory scope; model-supplied paths grant no authority. - Reuse the existing
MemoryPolicy.enabled / agent_read_enabledconfiguration shell and wire actual read controls. The presence of fields is not an implementation. Automatic-write permission has separate semantics; disabling model reads must not remove the user's ability to correct memories through management interfaces. - Check expectedRevision, operationId, source identity, and authorization at commit. Store bodies/sources/state/indexes/scope generations/receipts in the same transaction and return actual mutation results.
Acceptance: Cross-session use/restart; CAS between two windows; replay after lost results; retained deleted bodies inaccessible to ordinary APIs; direct user sources distinguished from conversation evidence; Host/Agent/project isolation; disablement and Incognito boundaries. Exercise real Host consumers, not only isolated SQL functions.
PR 2: Unified write deduplication, conflicts, and deletion suppression
Behavior example: Repeated expressions of one preference across two sessions produce one current fact. An explicit new default replaces an old automatic preference. Recognized equivalent versions of a user-deleted/corrected assertion cannot become effective under new IDs.
- Implement the full flow in section 2.4. Every create/edit/import/later extraction shares one commit plan. Explicit commands may initially propose content through existing ordinary-session tools, but require real user authorization and citation validation and cannot claim success prematurely. PR 5 adds the dedicated extractor over frozen ranges.
- Implement exact-hash lookup and safe normalization. An exact match does not skip scope/time or permission checks. Candidate retrieval covers ordinary items, protected items, deletion records, and correction matching indexes; deduplicate within each batch as well.
- Use one bounded batch semantic judgment to return target IDs/versions, relationships, evidence references, and actions. Reject nonexistent targets, unauthorized actions, and replacements without evidence.
- An explicit user save of an existing automatic fact may confirm it as user-managed; an automatic duplicate cannot downgrade it. Keep different scopes/conditions separate. Unresolved candidates stay out of context without silently discarding new information.
- Run model calls outside transactions and check relevant scope revisions and target revisions at commit, with bounded rereads after changes. Cover races involving deletion/user edits and two concurrent new inserts.
- Do not fall back to direct writes after call failure. Distinguish created, evidence_added, revised, suppressed, unresolved, and conflict/retryable outcomes; one generic no-op must not hide a rejected user correction.
Acceptance: Same body with different scope/time; Postgres paraphrases and spelling variants; Chinese/English keywords; duplicates versus negation; explicit Chinese-to-English replacement; coexistence of scoped conditions; delayed extraction from old chats; new-ID bypasses of protected items; suppression candidates not displaced by ordinary Top-K results; within-batch and cross-session races; no unadjudicated writes on model failure. Report semantic retrieval misses, false merges, and incorrect suppression rather than claiming database-enforced semantic uniqueness.
PR 3: Effective-fact Recall and every read outlet
Behavior example: A project-database query returns current facts and evidence. After deletion or correction, old conclusions do not return through cached facts or already-linked original chat spans.
- Extend both existing Rust Recall model-tool results and UI service results, distinguishing memory facts from history passages. Facts carry ID, version, scope, accessible sources, and completeness status.
- Use bounded keyword queries, batched reads, and maintained indexes. Give added facts explicit item/token limits; do not assume every old Recall path is already bounded. Measure broad-prefix scan/grouping costs rather than claiming fixed cost from a final LIMIT.
- Normal reads exclude suppressed, unresolved, and old assertion versions. User protection does not imply global cross-scope visibility. A worker having the Recall tool does not grant it personal-memory access.
- Cover source navigation, neighbor expansion, continuation reads, material, caches, and receipt resolution. Filtering known suppressed spans must preserve other valid facts in the same message. Distinguish explicit original-session viewing from automatic memory use.
- Unavailable/incomplete data returns gaps, not a falsely empty store, and must not fall back to unchecked deleted content. Healthy results may be returned independently.
Acceptance: Consistent model-tool/UI queries; no leakage through deleted items, old receipts, or caches; no bypass through source neighbors or continued expansion; other facts in the same event remain; default/restricted worker access; N+1 reads, broad keywords, many suppressed records, and stable pagination.
PR 4: User-owned always-provided context and Markdown retirement
Behavior example: An explicit user command pins a memory, making it available in new sessions without Recall. Automation cannot modify it, and unpinning preserves user protection.
- Implement projection and revocation rules from section 2.5 in the actual
capture_current_run / capture_behavior / freeze_run_valuespaths. Record loaded versions and recover the admitted content. - Do not ask the model to rewrite pinned bodies. Use stable order and encoding without meaningless timestamps that disturb caches. Injection does not open another model turn.
- Validate aggregate budgets both at mutation and actual model admission. Fail explicitly rather than silently selecting Top-K. Direct commands/APIs support pin/unpin and loaded-result inspection; production buttons arrive in PR 8.
- Audit and remove any MEMORY.md/PENDING.md loading, initialization, write guidance, and settings wiring in the target product. Do not recreate absent legacy wiring merely to migrate it. AGENTS.md/global instructions remain separate.
- Provide explicit import preview/confirmation/receipts from section 2.7. Only confirmed user content and scopes enter the store. Represent missing sources honestly; retain old files in place without continuing to read them.
Acceptance: First-session and later Runs; one pinned block remains after compaction; user protection; aggregate budgets; ordinary edits versus revocation for admitted Runs; frozen recovery after restart; actual native/supported-executor wire content; legacy-file retirement and repeated import; unmappable scopes do not broaden authority.
PR 5: Evidence-backed explicit remember and on-demand organization
Behavior example: “Remember the preference I just mentioned” synchronously returns what was actually saved, supplemented, or replaced. “Organize this discussion” produces sourced candidates while respecting user protection and deletion suppression.
- Migrate main's frozen source ranges, proposals, bounded same-session localization when needed, isolated evidence review, and deterministic citation checks. Direct user edits and model extraction from conversations are different source types.
- Reuse immutable HistoryCut, message revision/digest, and range pagination. Only committed user-authored bodies in the currently permitted range may support facts. Assistant/tool/quoted/compaction-summary content cannot automatically replace user evidence.
- Explicitly requested items use the current user authorization; incidental extractions use automatic authority. All candidates enter PR 2, with no append-only extraction bypass.
- Initially retain independent evidence review, followed by at most one batch relationship judgment for candidates not resolved by the exact-match path. Do not open a model request per candidate. Bounded localization, retries, and adjudication share an explicit per-range total budget; mechanically retaining main's three-call limit must not starve the new stage.
- Reuse model authority, cancellation, and usage records. Separate model attempts from final business receipts. Explicit references and arbitrarily selected ranges are independently idempotent: a successful save neither automatically advances the Session incremental cursor nor moves it backward. Only contiguous, actually settled coverage beginning at the current cursor may advance it. Commit outcomes, that coverage's cursor, evidence, and memory changes atomically; failures must not masquerade as successful extraction.
Acceptance: Current/older-message localization; forged/out-of-scope quotes; assistant/tool contamination; distinct explicit and incidental authority; Incognito/revocation during execution; sensitive information; empty results; model/schema failure; lost response after commit; concurrent user edits; evidence additions for exact duplicates; actual token/call/retry records.
PR 6: Incremental extraction requested by the model after completion
Behavior example: With automatic memory enabled, the model marks a turn as containing durable information. Background storage follows actual Run completion without delaying the completed answer.
- Provide a main-equivalent
memory_extracttrigger that accepts no arbitrary body. Coalesce repeated marks within one turn. A mark requests extraction and must not report “saved” early. Without a mark or compaction, do not add model extraction to every completed Run. - Automatic extraction defaults off. Explicit enablement authorizes creation/maintenance of
auto_recall, not modification of user memories or pinned content. Control model reads separately from automatic writes through existing settings/commands, without depending on Bot/Scheduler. - Persist the request mark and frozen boundary; durable
RunTerminated/Completedis the trigger authority, not UI stream completion or provider finishReason. Register pending work atomically with completion, or reconcile through durable termination sequences to cover crashes after completion but before dispatch. Recovery processes only successfully completed Runs with existing valid marks, not every Run automatically. - The owner manages durable pending work, bounded concurrency/cancellation, same-session coalescing, and finite retries. Read sequence ranges rather than scanning full history each time. Coverage states distinguish success, empty results, policy skips, and failed settlement after retry exhaustion. The cursor marks the contiguous settled boundary, not successful extraction of every segment. Retain failure reasons and receipts so later ranges can proceed; reprocessing requires explicit authorization or a separate bounded retry record.
- Initial enablement starts at a recorded boundary. Disabled intervals form policy barriers that cannot be backfilled automatically. Re-enabling does not fill disabled history; explicit backfill uses PR 5.
- Background failure does not change the original user Run's result. APIs/commands expose status, failures, pending ranges, and auxiliary usage. Resolve committed-operation receipts under section 2.6; only uncommitted retries repeat current protection/suppression, source, and write-authorization checks.
Acceptance: Dispatch only after a marked Run completes successfully; no dispatch without a mark; coalescing consecutive short turns; concurrent setting changes; restart/unconfirmed commits; no duplicate evidence for the same range; finite retries that do not silently block later work forever; bounded queues/queries across many sessions. The target already includes #6907: use its actual termination state, not a shadow completion event.
PR 7: Automatic compaction extraction and shared recovery
Behavior example: When automatic compaction is about to replace context, the main Agent continues normally. After the checkpoint is durable, background work saves new memories from original user evidence.
- Integrate automatic compaction points actually supported by the target. Use committed
ContextCompacted, source capture/cut, covered_through, digest, and checkpoint identity. Manual compact is not automatically permission to backfill. - Register pending work and recovery identity after the checkpoint. The main Agent and compaction never wait for extraction retrieval or model calls. If registration is not atomic with the checkpoint, provide reconciliation advancing by durable sequence to cover crashes after persistence but before dispatch.
- Share Session continuous-coverage cursors, source deduplication, failed ranges, and the committer with PR 6. Arbitrarily selected ranges from PR 5 retain independent receipts and must not skip gaps in automatic coverage. Out-of-order or overlapping compaction/completion triggers must not duplicate creation or overwrite newer facts.
- Summaries may aid interpretation but cannot supply user-fact evidence. Fail explicitly when original evidence is inaccessible; settle as a no-op only when the range is confirmed to contain no eligible user evidence. Do not guess the contents of undecodable summaries such as CodexNative payloads.
- A Run that does not terminate successfully may still have a valid compaction checkpoint. Evaluate the checkpoint and policy at that time independently; do not incorrectly apply PR 6's Completed prerequisite here.
- Bound chunking and model budgets, recheck current permission, and prevent crossing disabled intervals. Reuse PR 6's failure settlement, explicitly distinguishing discarded/failed from success. Later coverage need not remain blocked forever, and advancing a cursor must not disguise unextracted evidence as success.
Acceptance: Automatic compaction does not interrupt the primary path; checkpoint persisted but pending work lost; out-of-order compaction/completion; overlapping ranges; older-range recovery; chunking large ranges; background results arriving after UI deletion/correction; no bypass through disabled intervals or summaries; pinned content remains once after compaction.
PR 8: Unified management interface, delivered last
Behavior example: In one page, users inspect automatic memories, protect them by correction, pin them for automatic loading in new sessions, and delete them so they stop appearing as memories.
- Connect the same Host service through NSH's shared workbench settings/management entrypoint. Reuse SettingsPage, shared rows/groups, and draft save/leave rules: body edits save explicitly; independent toggles apply immediately. Prioritize desktop while validating terminal layout and keyboard use; do not copy main's Electron paths.
- Provide two clear areas: “Used in every session” for user-maintained items and “On-demand memories” for automatic/user-maintained items, sharing details, sources, and history. Support bounded pagination, scope filtering, search, manual create/edit, pin/unpin, and deletion.
- Editing an automatic item protects it. Check budgets when editing pinned content. Deletion has one primary action with a brief retention explanation. Users do not need to understand resolvers, hashes, scope revisions, or several Forget buttons.
- Distinguish user edits, explicit commands, and automatic extraction in source presentation. Old evidence belongs to old versions; unresolved conflicts are separate from current facts. Accepting an unresolved change creates new user authorization; ignoring a suggestion leaves existing facts unchanged.
- On CAS conflict, preserve the draft and show the latest value; do not use last-write-wins. Distinguish insufficient permission, missing sources, temporarily unreadable sources, extraction failure, and budget overflow.
- The management page controls model reads, automatic extraction, and pinned content, and shows scope, loaded versions, background status, and usage. Import preview/confirmation uses PR 4; on-demand organization uses PR 5, without another bulk background scan.
- Ordinary lists do not show deleted bodies. Any management restoration entrypoint requires the user to open restricted history and explicitly save again; it must not return deleted data to the ordinary model. Exports include only effective items by default.
Acceptance: Automatic creation → visible in UI → user correction → old tasks cannot overwrite or restore under a new ID → pinned loading → deletion → equivalent re-extraction blocked → explicit save again. All tests exercise the real Host. Cover draft conflicts, source/version correspondence, budgets, pagination, model-read controls, import, and desktop/terminal interaction. This PR adds the product interface, not backend semantics left unfulfilled by PRs 1–7.
5. Rust integration locations and rules
| Responsibility | Existing location and implementation requirement |
|---|---|
| Types/public contracts | plugins/agent/api/src/contract/, plugins/agent/facts/src/; add explicit memory modules/types with closed states represented by enums |
| Persistence/transactions | plugins/agent/state/src/, state/migrations/; reuse RootStore, Prepared/Statement, and Host transactions, following owner/presets CAS/receipt paths |
| Permissions/commands/live work | plugins/agent/native/src/owner/, owner/access.rs, native/src/tools.rs, service dispatch; keep business policy in plugins, not model policy in state |
| Frozen context | owner/send.rs, owner/assistant.rs, owner/capture.rs, owner/driver_assembly.rs, assistant/src/prompt.rs, facts/src/execution.rs |
| Recall | owner/recall*.rs, state/src/recall/, assistant/src/recall/, api/src/contract/recall.rs; wire both model and UI result contracts |
| Sources/compaction | facts/src/history_snapshot.rs, state/src/session_history*, engine/src/driver/compaction.rs, state/src/sql_compaction.rs, state/src/fold.rs |
| Shared UI/SDK | products/maka/workbench/app/, relevant plugin UI, packages/plugin-sdk/src/generated/{methods,runtime}.ts; regenerate from the final schema |
6. Validation, cost, and completion criteria
Required cross-PR matrix
- Authority: Four entrypoints × three modes × active/unresolved/suppressed. Equal user authority can correct; automatic authority cannot overwrite or bypass.
- Semantics: Exact/equivalent/negated/conditional addition/explicit replacement/time change/cross-scope/typo/Chinese-English alias cases. Report retrieval misses separately from model-judgment errors.
- Evidence: Repeated evidence additions; old evidence not supporting new bodies; direct user edits; multiple facts in one message; deleted/modified/unauthorized sources; branch and replay deduplication.
- Deletion/correction: Rewording from new sources, same/new IDs, old receipts, caches, history neighbors/expansion, backup imports, in-flight jobs, and simultaneous cross-Session inserts.
- Execution: New sessions, later Runs, within-Run freezing, compaction, restart, projection revocation, Incognito, disabled intervals, and unavailable external executors.
- UI: Pinned budgets, edit protection, one deletion meaning, sources/history, CAS drafts, pagination, unresolved changes, and desktop/terminal use.
Deterministic behavior tests may be hard acceptance gates. Evaluate semantic capabilities using fixed source examples, real-model sampling, and per-stage metrics; do not claim global natural-language uniqueness or zero resurrection. Code must enforce higher-priority user authority and known suppression matches rather than relying only on prompts.
Performance and cost acceptance
- Measure reads/writes/indexes/recovery as current facts, protected items, suppression records, evidence, and history grow. Include broad keywords, cross-session contention, and retries on frequently changing scope generations.
- Report exact-match rate, candidate-retrieval coverage, candidates/tokens per batch, added model calls, extraction p50/p95, explicit-remember wait time, background backlog, database query plans, and batched-read counts.
- Report false merges, missed deletion suppression, incorrect suppression, independent useful Recall facts, and retention of user corrections. Fewer items alone do not prove success.
- Initially keep independent evidence review and batch relationship judgment when needed. Combining them later requires evidence that source boundaries and semantic quality do not regress. The exact-match fast path reduces work but does not promise to eliminate original extraction calls automatically.
- Source tokens, candidate/suppression-candidate tokens, and call/retry counts must have fixed per-range bounds included in existing usage records. Set numeric bounds using representative fixtures in the relevant PR and commit corresponding tests; do not merge unbounded defaults.
Maintain test suites/routing centrally in scripts/ci.mjs and its modules, reused by just/workflows; do not add a separate scheduling script. Check actual consumers of generated SDKs, schemas, plugin declarations, embedded prompts, and other non-Cargo inputs. Validate behavior and failure windows, not source-text matches or fixed sleeps. Record actual NSH screens where visual acceptance is necessary.
Completion criteria
After PRs 1–4, explicit unified memory, deletion suppression, on-demand recall, and user-owned pinned content are usable. PRs 5–7 complete main's explicit/requested/compaction extraction behaviors with the same write authority and adjudication. PR 8 then delivers the complete management interface.
Completion must leave no MEMORY.md runtime dependency, automatic write path bypassing the resolver, automatic overwrite of user-owned items, archive behavior masquerading as deletion, old-ID-only checks that ignore new IDs, or UI editing of a separate summary that a model can overwrite. Evaluation results must honestly report the probabilistic limits of semantic detection.
This batch does not promise physical erasure of every copy, cross-Host synchronization, absolute resolution of arbitrary natural-language conflicts, vector retrieval, or automatic decay. Discuss material product choices through CONTRIBUTING's project process. Local planning and code preparation do not require another permission request and do not authorize automatic external messages.
Activity
feat(memory): add scoped user-controlled memory records (#6970)
feat(memory): reconcile duplicate and conflicting writes (#6981)