Repository navigation
feat(memory): belief model — weights, not deletion (flag-gated) - #12701
Git-on-my-level merged 21 commits into
Conversation
Grounded seams for weights-not-deletion: read-side currency, evidence-only writes, admission-time judge, and flag-gated time-only status transitions. Co-authored-by: Cursor <[email protected]>
Pure belief-model module with no I/O: exponential currency from one stored half-life, named-date valid_to, legacy prior derivation, and the proactive bar. Co-authored-by: Cursor <[email protected]>
Classify subject and horizon at admission when the belief-model flag is on, without changing flag-off prompts or defaulting unknown subjects to the user. Co-authored-by: Cursor <[email protected]>
Populate the belief view on memory reads when the flag is on, hedge chat citations with as_of, and keep JIT/proactive triggers in the current user band. Co-authored-by: Cursor <[email protected]>
Judge admission neighbors as restated, contradicted, resolved, or unrelated; write those events on review and edit; and stop TTL from changing status on age alone when the flag is on. Co-authored-by: Cursor <[email protected]>
Close resolved claims with valid_to only. Do not flip status to superseded, which would hide them from the default memory list. Co-authored-by: Cursor <[email protected]>
Widen archive-item sequence types, coerce LLM content to text, and export a public user-mutation alias so evidence apply is type-clean. Co-authored-by: Cursor <[email protected]>
Read the item audit-bag category without introducing a new tracked consolidation_symbol in utils/memory. Co-authored-by: Cursor <[email protected]>
Record landed SHAs, tests, preflight, and the few places the implementation had to deviate from the plan. Co-authored-by: Cursor <[email protected]>
Existing rows carry no class, so the read-side fallback invented a state horizon for durable facts. Classify per-uid through the apply path, and leave unclassified long_term rows undecayed until that run. Co-authored-by: Cursor <[email protected]>
API, manual, integration, and user_asserted rows default to primary_user. Only conversation extraction uses the classifier, which treats the owner's name as the user and no longer invents media_screen from keywords. Co-authored-by: Cursor <[email protected]>
A prompt-only reject was writing hidden, which dropped 582 rows from the list. Under the flag, reject archives as active meta_residue instead; flag-off still hides. Co-authored-by: Cursor <[email protected]>
Skip the conflict LLM unless a neighbor scores at least 0.75, and schedule the remaining judge through llm_executor so POST /v3/memories does not block on vector lookup or a model call. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…p-client contract stays compatible Co-Authored-By: Claude Fable 5.1 <[email protected]>
…es to third_party The app-client OpenAPI contract pins the released enum, so widening it is a breaking change. Extractor and backfill may still label media/on-screen content; it is stored as third_party, which is what the surface bars need. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…y fields Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
30 issues found across 41 files
Confidence score: 2/5
backend/utils/memory/jit_trigger_contract.pycan still authorize and charge fading or historical triggers: the belief gate is bypassed on snapshot/reservation paths, and replayed observations are evaluated atoccurred_atrather than now. Enforce the current-belief check in the shared paid-work authorization path using an explicit evaluation time.backend/utils/memory/short_term_promotion.pyleaves expired rows ineligible for both TTL rejection and consolidation when the belief model is enabled, causing them to remainshort_termindefinitely; update_is_promotable_for_consolidationto handle expired rows.backend/utils/memory/memory_service.pyandbackend/utils/memory/chat_memory_adapter.pycan expose inconsistent belief metadata: re-evidenced memories may receive stale currency/as-of values, while vector chat results omitcurrency_bandentirely. Reuse the canonicalMemoryItemoverlay across both search paths.backend/utils/conversations/process_conversation.pyandbackend/utils/memory/belief_evidence.pyallow non-user or un-retrieved memories to receive proactive treatment or evidence updates, whilebackend/utils/llm/working_observations.pyandbackend/models/memory_contracts.pyaccept invalid belief durations/classes that can fail during application. Enforce subject scope, restrict evidence targets to retrieved neighbors, and validate contract fields at ingestion.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/utils/memory/belief_backfill.py">
<violation number="1" location="backend/utils/memory/belief_backfill.py:47">
P2: Non-finite LLM overrides bypass the positive-value check and can poison stored currency calculations. Constrain `half_life_days` to a finite positive number at the backfill schema boundary.</violation>
<violation number="2" location="backend/utils/memory/belief_backfill.py:112">
P2: The backfill trusts the payload memory ID without fencing it to the document being streamed. Reject payload/document-ID mismatches before adding rows to `pending` so maintenance cannot classify a different memory than the one read.</violation>
<violation number="3" location="backend/utils/memory/belief_backfill.py:172">
P2: The default applier builds its patch from the stale scan item instead of the authoritative item read by the canonical mutation. Use the callback’s current item so concurrent changes to `user_asserted` cannot produce the wrong half-life.</violation>
<violation number="4" location="backend/utils/memory/belief_backfill.py:175">
P2: Hidden rows are selected for backfill but can never be written by the default applier because the canonical mutation reader only returns active items. Use a mutation path that can authoritatively read and update hidden items, or exclude hidden rows explicitly if they are not intended to be backfilled.</violation>
<violation number="5" location="backend/utils/memory/belief_backfill.py:246">
P3: The post-apply status guard can never trigger: `apply_row` (the default `_default_applier`) reads a fresh item via `apply_canonical_user_mutation` and returns `updated` without mutating the `item` passed in, so `_item_status(item)` always equals `original_status`. The warning therefore never fires, giving false assurance that status was verified. Compare against the returned `updated` item or drop the guard.</violation>
</file>
<file name="backend/utils/memory/short_term_promotion.py">
<violation number="1" location="backend/utils/memory/short_term_promotion.py:269">
P1: With MEMORY_BELIEF_MODEL_ENABLED=true, expired short-term rows are no longer rejected by TTL but also remain ineligible for consolidation, so they stay short_term indefinitely. _is_promotable_for_consolidation requires `effective_short_term_expiry(item) > current_time` for processed rows, so the consolidator never sees these expired rows; each maintenance pass re-fetches them and logs a spurious 'expired_without_recorded_disposition' warning. Resolve expired rows in the belief model path (e.g., let consolidation accept them, or transition them to active/archive) instead of leaving them stuck.</violation>
</file>
<file name="backend/utils/memory/jit_trigger_contract.py">
<violation number="1" location="backend/utils/memory/jit_trigger_contract.py:725">
P1: When an observation is delayed or replayed, this gate evaluates currency at `occurred_at` instead of the current evaluation time. A stale trigger can therefore pass the current-belief bar; use an explicit evaluation `now` for the bar and reserve `occurred_at` for event matching and snooze semantics.</violation>
<violation number="2" location="backend/utils/memory/jit_trigger_contract.py:726">
P1: The belief gate is not on the authoritative proactive-work path. The snapshot and reservation paths can still arm and charge a fading or historical trigger, so enforce the current-belief bar in the shared paid-work authority gate rather than only in this unused evaluator.</violation>
</file>
<file name="backend/tests/unit/test_chat_memory_adapter.py">
<violation number="1" location="backend/tests/unit/test_chat_memory_adapter.py:451">
P3: The `assert ... or 'as_of:' in result` disjunction is always true because the line above already asserted `'as_of:' in result`. As written it can never fail, so it gives false confidence that the legacy `date:` stamp is suppressed. Drop the `or 'as_of:' in result` clause and assert `f'date: {now.strftime("%Y-%m-%d")}' not in result` directly.</violation>
</file>
<file name="backend/tests/unit/test_belief_model.py">
<violation number="1" location="backend/tests/unit/test_belief_model.py:243">
P3: This test does not actually validate reading `category` from the item audit bag. `derive_half_life_days` returns None for `tier='long_term'` no matter what category resolves to (and the implementation ignores category with `_ = category`), so `view.half_life_days is None` passes even if `_record_category` is broken. To verify the audit-bag read, assert on something the category actually influences, or drop the misleading name.</violation>
</file>
<file name="backend/utils/memory/chat_memory_adapter.py">
<violation number="1" location="backend/utils/memory/chat_memory_adapter.py:288">
P2: When the belief flag is enabled, vector chat results never include `currency_band`: the vector search response serializes `MemoryItem` directly, unlike the product search path that applies the belief overlay. Because this branch appends the band only when the key exists, vector memory lines contain `as_of` but no band; apply the belief overlay before formatting vector items.</violation>
</file>
<file name="backend/utils/memory/memory_service.py">
<violation number="1" location="backend/utils/memory/memory_service.py:3137">
P1: When a canonical memory has been re-evidenced, this second overlay recomputes currency from the lossy `MemoryDB` projection instead of the original `MemoryItem`. The product search can therefore report stale `as_of`/currency and classify a refreshed memory as fading or history; reuse the source-item overlay or preserve `last_corroborated_at` through the projection before recomputing here.</violation>
</file>
<file name="backend/utils/conversations/process_conversation.py">
<violation number="1" location="backend/utils/conversations/process_conversation.py:1423">
P1: When `_l1_candidate_subject` identifies a third-party claim, `candidate.subject_scope="primary_user"` still wins here because the resolver prioritizes the extracted scope. This can make non-user memories pass proactive surfaces; only honor the extracted scope when it agrees with the grounded attribution.</violation>
</file>
<file name="backend/utils/memory/canonical_consolidation.py">
<violation number="1" location="backend/utils/memory/canonical_consolidation.py:1529">
P2: When a pending source already has a belief class, flag-on rejection never carries it because `ConsolidationAgentDecision` has no `belief_class` field. Read the class from `source` so archived rejected rows retain their configured half-life instead of being forced to the one-day `meta_residue` prior.</violation>
</file>
<file name="backend/models/memory_apply.py">
<violation number="1" location="backend/models/memory_apply.py:601">
P2: When an update payload supplies `half_life_days` or `belief_class`, this extraction bypasses `DurableMemoryPatch` validation and the update uses unvalidated `model_copy` data. A string half-life can be persisted and make read-time currency computation fail; leave these fields in `raw` so the typed patch path handles them.</violation>
</file>
<file name="backend/utils/memory/memory_api_contract.py">
<violation number="1" location="backend/utils/memory/memory_api_contract.py:61">
P2: When the flag is turned off after belief metadata has been backfilled, `_materialize_legacy` sends this redacted payload to canonical storage and permanently drops `belief_class` and `half_life_days`. Keep flag-based response redaction separate from internal and persistence serialization so rollback does not erase metadata.</violation>
</file>
<file name="backend/utils/memory/memory_read_api.py">
<violation number="1" location="backend/utils/memory/memory_read_api.py:133">
P2: When either product-memory query receives `now`, filtering uses that timestamp but this line computes the belief band from wall-clock time. A historical or boundary-time read can therefore return a row whose visibility and currency were evaluated at different instants; propagate the effective `now` into `_product_memory_result`.</violation>
</file>
<file name="backend/utils/memory/belief_evidence.py">
<violation number="1" location="backend/utils/memory/belief_evidence.py:154">
P2: Concurrent restatement admissions can lose corroboration events because the retrying mutation builder reuses the count from the first read. Rebuild restated extras from the retry's `_item` and `_now` inside `build_patch`.</violation>
<violation number="2" location="backend/utils/memory/belief_evidence.py:203">
P1: A judge response can select any active memory ID, not just one of the retrieved neighbors, and this code will apply the evidence event to it. Restrict `target_memory_id` to the neighbor IDs before reading or applying the target.</violation>
<violation number="3" location="backend/utils/memory/belief_evidence.py:271">
P2: The admission judge is fired onto `llm_executor`, the shared 6-worker pool that also serves live chat, via `submit_with_context`. Each admission runs a vector query plus a blocking `get_llm(...).invoke(...)` judge call, which routinely exceeds the repo rule that `submit_with_context()` is only for short sync fire-and-forget work (<10s). A burst of new memories (conversation extraction reprocessing, POST /v3/memories) can saturate the chat LLM pool. Run admission LLM judge calls on a dedicated executor (or cap them) rather than the shared chat lane.</violation>
</file>
<file name="backend/utils/llm/working_observations.py">
<violation number="1" location="backend/utils/llm/working_observations.py:89">
P1: When the model emits `0` or a negative `half_life_days`, the new schema accepts it and the canonical conversation path raises an uncaught `ValueError` while applying the candidate. Constrain this field to positive finite values at the LLM boundary so invalid model output follows the existing parse-failure handling instead of escaping finalization.</violation>
</file>
<file name="backend/tests/unit/test_memories_archive_and_read_contracts.py">
<violation number="1" location="backend/tests/unit/test_memories_archive_and_read_contracts.py:383">
P2: The `currency_band == "fading"` assertion depends on the real wall clock, not the fixed `now`. `memory_item_to_memorydb` computes the overlay with `datetime.now(timezone.utc)`, so the band for this captured_at (2026-07-13, half_life 30d) is only "fading" while the run date is within a ~30-60 day window; otherwise it resolves to "current" or "history" and the test fails. Anchor `captured_at` to the real current time instead of the fixed 2026 date so `days_since` is always ~30 at run time.</violation>
</file>
<file name="backend/models/memories.py">
<violation number="1" location="backend/models/memories.py:124">
P2: With `MEMORY_BELIEF_MODEL_ENABLED=true`, clients can submit an unknown `belief_class` or non-positive `half_life_days`, which later raises during belief-overlay computation. Validate the class against the supported classes and require a positive half-life at the `Memory` request boundary before writing the row.</violation>
<violation number="2" location="backend/models/memories.py:726">
P2: Mapping `Memory.valid_to` straight to `invalid_at` makes a fact with a future `valid_to` inactive immediately. `MemoryDB.is_active` is `self.invalid_at is None`, and retrieval paths (e.g. `utils/llms/memory.py` lines 119/130, `utils/memory/learned_today.py:76`, `utils/memory/memory_service.py:514`) exclude any row whose `invalid_at` is set. In the belief model `valid_to` is a validity-until boundary (a plan with a future `valid_to` is still current until that date, see `compute_currency`/`test_named_date_is_current_until_valid_to_then_history`), so writing it directly into `invalid_at` deactivates a still-valid row. Gate on the clock: set `invalid_at` only when `valid_to <= now`, or make `is_active`/currency compare `invalid_at > now` rather than `is None`.</violation>
</file>
<file name="backend/models/product_memory.py">
<violation number="1" location="backend/models/product_memory.py:194">
P2: When belief mode is enabled, malformed persisted metadata can break memory reads: non-positive half-lives and unknown classes raise during currency calculation, while NaN yields invalid currency. Constrain `half_life_days` to finite positive values and `belief_class` to the ratified class set at this model boundary.</violation>
</file>
<file name="backend/models/memory_contracts.py">
<violation number="1" location="backend/models/memory_contracts.py:518">
P1: DurableMemoryPatch accepts an arbitrary `belief_class` string and any `half_life_days` float with no validation, and both are persisted verbatim into MemoryItem rows (memory_apply.py writes `patch.belief_class`/`patch.half_life_days` directly). The read path is not defensive: `derive_half_life_days` raises `ValueError("unknown belief_class: ...")` for a class outside HALF_LIFE_DAYS_BY_CLASS and `ValueError("half_life_days must be positive")` for a non-positive stored value, and `compute_currency` raises on a non-positive half-life. With MEMORY_BELIEF_MODEL_ENABLED=true, `public_belief_overlay` runs this on every read, so a single row carrying an unknown class or a bad half-life (e.g. via an update patch) would 500 `/v3/memories` and related read surfaces. The backfill path validates the taxonomy (belief_backfill.py field_validator), but this contract model does not. Validate `belief_class` against the known set and require `half_life_days > 0` when set, or make the read path coerce/fall back instead of raising.</violation>
</file>
<file name="backend/scripts/backfill_belief_classes.py">
<violation number="1" location="backend/scripts/backfill_belief_classes.py:78">
P2: When any classification or write is skipped, this command still exits 0, so operators and automation can accept a partial backfill as successful. Return a nonzero status whenever `report.skipped` is nonzero.</violation>
</file>
<file name="backend/utils/memory/canonical_memory_adapter.py">
<violation number="1" location="backend/utils/memory/canonical_memory_adapter.py:1366">
P2: When the belief flag is off, this loop still persists caller-supplied `half_life_days` and `belief_class`; invalid values then raise during flagged reads and can break memory listing. Gate these fields behind `belief_model_enabled()` or validate and reject them regardless of the flag.</violation>
</file>
<file name="backend/utils/memory/belief_model.py">
<violation number="1" location="backend/utils/memory/belief_model.py:95">
P2: When an enabled read encounters a persisted or client-supplied unknown `belief_class`, this exception aborts the memory read instead of degrading safely. Treat unknown classes as unclassified and return a safe fallback such as no decay.</violation>
</file>
<file name="backend/utils/memory/decision_path_telemetry.py">
<violation number="1" location="backend/utils/memory/decision_path_telemetry.py:34">
P2: Adding the bare first name to `user_aliases` means any `about` that exactly equals the user's first name is classified `primary_user`. For common names (Sam, Alex, Chris, Lee, Pat, Kim...) a memory whose `about` refers to a different person with that name is now misattributed as `primary_user`, which sets `memory.subject_scope = "primary_user"` in `subject_scope_from_extraction` and changes half-life/decay and nudge handling. The `len(first_name) >= 2` guard only excludes 1-char names and does not address this ambiguity. Consider requiring the first name match only when `about` is a name-like token that is not also a common word/name, or gating first-name aliasing on confidence before it drives subject_scope.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| disposition = None | ||
| if item.tier == MemoryLayer.short_term and effective_short_term_expiry(item) <= current_time: | ||
| expired = item.tier == MemoryLayer.short_term and effective_short_term_expiry(item) <= current_time | ||
| if expired and not belief_model_enabled(): |
There was a problem hiding this comment.
P1: With MEMORY_BELIEF_MODEL_ENABLED=true, expired short-term rows are no longer rejected by TTL but also remain ineligible for consolidation, so they stay short_term indefinitely. _is_promotable_for_consolidation requires effective_short_term_expiry(item) > current_time for processed rows, so the consolidator never sees these expired rows; each maintenance pass re-fetches them and logs a spurious 'expired_without_recorded_disposition' warning. Resolve expired rows in the belief model path (e.g., let consolidation accept them, or transition them to active/archive) instead of leaving them stuck.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/short_term_promotion.py, line 269:
<comment>With MEMORY_BELIEF_MODEL_ENABLED=true, expired short-term rows are no longer rejected by TTL but also remain ineligible for consolidation, so they stay short_term indefinitely. _is_promotable_for_consolidation requires `effective_short_term_expiry(item) > current_time` for processed rows, so the consolidator never sees these expired rows; each maintenance pass re-fetches them and logs a spurious 'expired_without_recorded_disposition' warning. Resolve expired rows in the belief model path (e.g., let consolidation accept them, or transition them to active/archive) instead of leaving them stuck.</comment>
<file context>
@@ -264,8 +265,16 @@ def run_canonical_short_term_ttl_lifecycle(
disposition = None
- if item.tier == MemoryLayer.short_term and effective_short_term_expiry(item) <= current_time:
+ expired = item.tier == MemoryLayer.short_term and effective_short_term_expiry(item) <= current_time
+ if expired and not belief_model_enabled():
disposition = ShortTermDisposition.reject_or_hide
+ elif expired:
</file context>
| observation_fingerprint=_observation_fingerprint(observation), | ||
| ) | ||
| if belief_model_enabled(): | ||
| at = observation.occurred_at or datetime.now(timezone.utc) |
There was a problem hiding this comment.
P1: When an observation is delayed or replayed, this gate evaluates currency at occurred_at instead of the current evaluation time. A stale trigger can therefore pass the current-belief bar; use an explicit evaluation now for the bar and reserve occurred_at for event matching and snooze semantics.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/jit_trigger_contract.py, line 725:
<comment>When an observation is delayed or replayed, this gate evaluates currency at `occurred_at` instead of the current evaluation time. A stale trigger can therefore pass the current-belief bar; use an explicit evaluation `now` for the bar and reserve `occurred_at` for event matching and snooze semantics.</comment>
<file context>
@@ -720,6 +721,14 @@ def evaluate_memory_item_trigger(
observation_fingerprint=_observation_fingerprint(observation),
)
+ if belief_model_enabled():
+ at = observation.occurred_at or datetime.now(timezone.utc)
+ if not record_passes_proactive_bar(item, now=at):
+ return TriggerDecision(
</file context>
| ) | ||
| if belief_model_enabled(): | ||
| at = observation.occurred_at or datetime.now(timezone.utc) | ||
| if not record_passes_proactive_bar(item, now=at): |
There was a problem hiding this comment.
P1: The belief gate is not on the authoritative proactive-work path. The snapshot and reservation paths can still arm and charge a fading or historical trigger, so enforce the current-belief bar in the shared paid-work authority gate rather than only in this unused evaluator.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/jit_trigger_contract.py, line 726:
<comment>The belief gate is not on the authoritative proactive-work path. The snapshot and reservation paths can still arm and charge a fading or historical trigger, so enforce the current-belief bar in the shared paid-work authority gate rather than only in this unused evaluator.</comment>
<file context>
@@ -720,6 +721,14 @@ def evaluate_memory_item_trigger(
)
+ if belief_model_enabled():
+ at = observation.occurred_at or datetime.now(timezone.utc)
+ if not record_passes_proactive_bar(item, now=at):
+ return TriggerDecision(
+ status=TriggerDecisionStatus.no_match,
</file context>
| "agent_use": "default_access_memory", | ||
| "access_reason": "default_memory_allowed", | ||
| "superseded_by": None, | ||
| **public_belief_overlay_json(memory, now=now or datetime.now(timezone.utc)), |
There was a problem hiding this comment.
P1: When a canonical memory has been re-evidenced, this second overlay recomputes currency from the lossy MemoryDB projection instead of the original MemoryItem. The product search can therefore report stale as_of/currency and classify a refreshed memory as fading or history; reuse the source-item overlay or preserve last_corroborated_at through the projection before recomputing here.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/memory_service.py, line 3137:
<comment>When a canonical memory has been re-evidenced, this second overlay recomputes currency from the lossy `MemoryDB` projection instead of the original `MemoryItem`. The product search can therefore report stale `as_of`/currency and classify a refreshed memory as fading or history; reuse the source-item overlay or preserve `last_corroborated_at` through the projection before recomputing here.</comment>
<file context>
@@ -3133,6 +3134,7 @@ def default_product_search(
"agent_use": "default_access_memory",
"access_reason": "default_memory_allowed",
"superseded_by": None,
+ **public_belief_overlay_json(memory, now=now or datetime.now(timezone.utc)),
}
)
</file context>
| ) | ||
| if belief_model_enabled(): | ||
| resolved_scope = subject_scope_from_extraction( | ||
| extracted_scope=candidate.subject_scope, |
There was a problem hiding this comment.
P1: When _l1_candidate_subject identifies a third-party claim, candidate.subject_scope="primary_user" still wins here because the resolver prioritizes the extracted scope. This can make non-user memories pass proactive surfaces; only honor the extracted scope when it agrees with the grounded attribution.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/conversations/process_conversation.py, line 1423:
<comment>When `_l1_candidate_subject` identifies a third-party claim, `candidate.subject_scope="primary_user"` still wins here because the resolver prioritizes the extracted scope. This can make non-user memories pass proactive surfaces; only honor the extracted scope when it agrees with the grounded attribution.</comment>
<file context>
@@ -1413,6 +1418,23 @@ def _extract_memories_canonical(
)
+ if belief_model_enabled():
+ resolved_scope = subject_scope_from_extraction(
+ extracted_scope=candidate.subject_scope,
+ attribution=subject_attribution.value,
+ about=candidate.about,
</file context>
| subject_scope=memory.subject_scope, | ||
| belief_class=memory.belief_class, | ||
| half_life_days=memory.half_life_days, | ||
| invalid_at=memory.valid_to, |
There was a problem hiding this comment.
P2: Mapping Memory.valid_to straight to invalid_at makes a fact with a future valid_to inactive immediately. MemoryDB.is_active is self.invalid_at is None, and retrieval paths (e.g. utils/llms/memory.py lines 119/130, utils/memory/learned_today.py:76, utils/memory/memory_service.py:514) exclude any row whose invalid_at is set. In the belief model valid_to is a validity-until boundary (a plan with a future valid_to is still current until that date, see compute_currency/test_named_date_is_current_until_valid_to_then_history), so writing it directly into invalid_at deactivates a still-valid row. Gate on the clock: set invalid_at only when valid_to <= now, or make is_active/currency compare invalid_at > now rather than is None.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/models/memories.py, line 726:
<comment>Mapping `Memory.valid_to` straight to `invalid_at` makes a fact with a future `valid_to` inactive immediately. `MemoryDB.is_active` is `self.invalid_at is None`, and retrieval paths (e.g. `utils/llms/memory.py` lines 119/130, `utils/memory/learned_today.py:76`, `utils/memory/memory_service.py:514`) exclude any row whose `invalid_at` is set. In the belief model `valid_to` is a validity-until boundary (a plan with a future `valid_to` is still current until that date, see `compute_currency`/`test_named_date_is_current_until_valid_to_then_history`), so writing it directly into `invalid_at` deactivates a still-valid row. Gate on the clock: set `invalid_at` only when `valid_to <= now`, or make `is_active`/currency compare `invalid_at > now` rather than `is None`.</comment>
<file context>
@@ -710,6 +720,10 @@ def from_memory(
+ subject_scope=memory.subject_scope,
+ belief_class=memory.belief_class,
+ half_life_days=memory.half_life_days,
+ invalid_at=memory.valid_to,
)
memory_db.scoring = MemoryDB.calculate_score(memory_db)
</file context>
| return | ||
| from utils.executors import llm_executor, submit_with_context | ||
|
|
||
| submit_with_context( |
There was a problem hiding this comment.
P2: The admission judge is fired onto llm_executor, the shared 6-worker pool that also serves live chat, via submit_with_context. Each admission runs a vector query plus a blocking get_llm(...).invoke(...) judge call, which routinely exceeds the repo rule that submit_with_context() is only for short sync fire-and-forget work (<10s). A burst of new memories (conversation extraction reprocessing, POST /v3/memories) can saturate the chat LLM pool. Run admission LLM judge calls on a dedicated executor (or cap them) rather than the shared chat lane.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/belief_evidence.py, line 271:
<comment>The admission judge is fired onto `llm_executor`, the shared 6-worker pool that also serves live chat, via `submit_with_context`. Each admission runs a vector query plus a blocking `get_llm(...).invoke(...)` judge call, which routinely exceeds the repo rule that `submit_with_context()` is only for short sync fire-and-forget work (<10s). A burst of new memories (conversation extraction reprocessing, POST /v3/memories) can saturate the chat LLM pool. Run admission LLM judge calls on a dedicated executor (or cap them) rather than the shared chat lane.</comment>
<file context>
@@ -0,0 +1,279 @@
+ return
+ from utils.executors import llm_executor, submit_with_context
+
+ submit_with_context(
+ llm_executor,
+ admit_claim_against_neighbors,
</file context>
| report.skipped += 1 | ||
| continue | ||
| report.written += 1 | ||
| if original_status is not None and _item_status(item) != original_status: |
There was a problem hiding this comment.
P3: The post-apply status guard can never trigger: apply_row (the default _default_applier) reads a fresh item via apply_canonical_user_mutation and returns updated without mutating the item passed in, so _item_status(item) always equals original_status. The warning therefore never fires, giving false assurance that status was verified. Compare against the returned updated item or drop the guard.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/belief_backfill.py, line 246:
<comment>The post-apply status guard can never trigger: `apply_row` (the default `_default_applier`) reads a fresh item via `apply_canonical_user_mutation` and returns `updated` without mutating the `item` passed in, so `_item_status(item)` always equals `original_status`. The warning therefore never fires, giving false assurance that status was verified. Compare against the returned `updated` item or drop the guard.</comment>
<file context>
@@ -0,0 +1,250 @@
+ report.skipped += 1
+ continue
+ report.written += 1
+ if original_status is not None and _item_status(item) != original_status:
+ logger.warning("belief backfill must not change status memory_id=%s", memory_id)
+ report.class_counts = dict(class_counts)
</file context>
| assert result is not None | ||
| assert 'as_of:' in result | ||
| assert 'band:' in result | ||
| assert f'date: {now.strftime("%Y-%m-%d")}' not in result or 'as_of:' in result |
There was a problem hiding this comment.
P3: The assert ... or 'as_of:' in result disjunction is always true because the line above already asserted 'as_of:' in result. As written it can never fail, so it gives false confidence that the legacy date: stamp is suppressed. Drop the or 'as_of:' in result clause and assert f'date: {now.strftime("%Y-%m-%d")}' not in result directly.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_chat_memory_adapter.py, line 451:
<comment>The `assert ... or 'as_of:' in result` disjunction is always true because the line above already asserted `'as_of:' in result`. As written it can never fail, so it gives false confidence that the legacy `date:` stamp is suppressed. Drop the `or 'as_of:' in result` clause and assert `f'date: {now.strftime("%Y-%m-%d")}' not in result` directly.</comment>
<file context>
@@ -425,3 +425,28 @@ def test_chat_get_memories_memory_list_decision_matches_search_denied_empty_and_
+ assert result is not None
+ assert 'as_of:' in result
+ assert 'band:' in result
+ assert f'date: {now.strftime("%Y-%m-%d")}' not in result or 'as_of:' in result
+ assert 'date:' not in result.split('content_quoted=', 1)[1]
</file context>
| assert f'date: {now.strftime("%Y-%m-%d")}' not in result or 'as_of:' in result | |
| assert f'date: {now.strftime("%Y-%m-%d")}' not in result |
| tier="long_term", | ||
| ) | ||
| view = belief_view_for_record(record, now=NOW) | ||
| assert view.half_life_days is None |
There was a problem hiding this comment.
P3: This test does not actually validate reading category from the item audit bag. derive_half_life_days returns None for tier='long_term' no matter what category resolves to (and the implementation ignores category with _ = category), so view.half_life_days is None passes even if _record_category is broken. To verify the audit-bag read, assert on something the category actually influences, or drop the misleading name.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_belief_model.py, line 243:
<comment>This test does not actually validate reading `category` from the item audit bag. `derive_half_life_days` returns None for `tier='long_term'` no matter what category resolves to (and the implementation ignores category with `_ = category`), so `view.half_life_days is None` passes even if `_record_category` is broken. To verify the audit-bag read, assert on something the category actually influences, or drop the misleading name.</comment>
<file context>
@@ -0,0 +1,288 @@
+ tier="long_term",
+ )
+ view = belief_view_for_record(record, now=NOW)
+ assert view.half_life_days is None
+
+
</file context>
… hour `run-unit-ci.sh` is the only backend unit lane and it runs `not integration and not slow`. Nothing overrides that mark expression anywhere, so 22 files and 126 assertions — coverage ratchets, hermeticity contracts, the direct-provider boundary, the LLM-endpoint inventory pin — have been executing nowhere. The README told authors to mark codebase greps `slow` rather than allowlist them, which is a sound rule if `slow` means "runs in the other lane". There was no other lane, and an exact-set pin that fails nothing is a comment. It is not hypothetical. #12701 added two managed `get_llm` call sites that `test_managed_call_sites_absent_from_the_inventory_fail_ci` rejects, and merged anyway, within an hour of that pin landing, because nothing ran it. The file it changed also does not select the test that pins it, which is why the new lane is unconditional: a check whose job is to notice a change nobody anticipated cannot be gated on the change set that triggered the run. The cost premise does not survive measurement. The pin runs in 2.6 seconds; all 19 currently-green files run in 31. The three files that are red today are named in the manifest header rather than omitted from it, so the gap stays countable. Each needs its own fix. Co-Authored-By: Claude Opus 5 <[email protected]>
…un, and #12701 slipped past the LLM inventory pin because of it (#12727) ## The repository's codebase guardrails have never run in CI `backend/scripts/run-unit-ci.sh` is the only backend unit lane, and it runs `not integration and not slow`. No workflow anywhere overrides that mark expression. So every test marked `@pytest.mark.slow` — 22 files, 126 assertions, including coverage ratchets, hermeticity contracts, the direct-provider boundary guardrail and the LLM-endpoint inventory pin — executes nowhere. This is not one author's slip. `backend/tests/README.md` instructs that codebase-wide greps be marked `slow` "rather than being allowlisted", and the duration-allowlist header repeats it. The rule assumes `slow` means *runs in some other lane*. There was no other lane. **It is already costing us.** #12701 (belief model) added two managed `get_llm` call sites: ``` utils/memory/belief_backfill.py::feature:<dynamic> utils/memory/belief_evidence.py::feature:memory_conflict ``` `test_managed_call_sites_absent_from_the_inventory_fail_ci` rejects both. It merged anyway, within an hour of the pin landing, because nothing ran the pin. That is the exact failure the pin was written to prevent, on its first opportunity. The cost premise does not survive measurement either. These are greps, not stress tests: | | | |---|---| | LLM-inventory pin alone | **2.6s** | | All 19 manifest files, one session | **31s**, 126 passed | ### What this adds - **`backend/scripts/run-slow-guardrails-ci.sh`** — runs `slow and not integration` over the files named in a manifest. It fails loudly if the manifest is missing, names a file that does not exist, or selects nothing: a lane that runs zero tests must not pass. - **`backend/tests/slow_guardrail_manifest.txt`** — the 19 files that are green today, and, named in the header rather than silently omitted, the three that are not: ``` tests/unit/test_subscription_restructure.py 32 failed, 2 passed tests/unit/test_firestore_query_coverage_ratchet.py 1 failed, 1 passed tests/unit/test_sys_modules_hermeticity.py 1 failed, 1 passed ``` Each needs its own fix and its own PR. Listing them keeps the gap countable instead of invisible — which is the whole failure being repaired here. - **One step in `backend-unit-tests.yml`**, unselected and unconditional. A guardrail whose job is to notice a change nobody anticipated cannot be gated on the change set that triggered the run — that is the second half of why #12701 slipped through, since the file it changed does not select the test that pins it. - **The two missing inventory rows**, so the pin is green the moment it starts running. Both belong to `langchain_feature_routing`: they are internal memory-formation calls reached through `canonical_memory_adapter`, not a new user-triggerable entrypoint. - **`tests/README.md`** — the rule that produced this is now qualified, so the next guardrail author lands in the lane instead of outside it. ### Automatic-or-dead check The lane is its own check, and it is not vacuous by construction: delete the manifest, empty it, or list a path that does not exist and `run-slow-guardrails-ci.sh` exits non-zero rather than reporting success over nothing. Revert either inventory row and `test_managed_call_sites_absent_from_the_inventory_fail_ci` fails **in CI** — which is the thing that was not true before this PR. ### Proof - `PYTHON=.venv/bin/python bash scripts/run-slow-guardrails-ci.sh` → **126 passed, 516 deselected, 31.03s**. - Red-proof on the real inventory file: with the two rows removed, `pytest -m slow tests/unit/test_llm_gateway_coverage_guardrails.py` → `AssertionError: managed call sites absent from the inventory: utils/memory/belief_backfill.py::feature:<dynamic>; utils/memory/belief_evidence.py::feature:memory_conflict`. Restored by putting the lines back, not by `git checkout`. - Every slow-marked unit file measured individually to build the manifest; the three exclusions are the measured failures, not guesses. ### Cut list - Fixing the three red files. Each is someone's owned surface and deserves its own diagnosis; bundling them here would make this PR unreviewable and would couple a CI-plumbing change to three unrelated product judgements. - Extending the lane to `tests/services/` or `tests/integration/`. - Any change to what `run-unit-ci.sh` selects. The PR lane keeps its latency budget exactly as it is; this is a second, additive lane. ### Product invariants none — no locked invariant path glob matched. ### Failure class No `fix:` commits in this range. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/12727?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…2751) Omi Beta serves its data from the dev backend, so this is the beta-first lane for #12701. MEMORY_BELIEF_MODEL_ENABLED='true' is declared beside every dev MEMORY_ENABLED site (backend-listen, pusher, backend, backend-sync, backend-sync-backfill, backend-integration, memory-maintenance-job, daily-memory-sweep-job) and mirrored into the two Helm values files, so the gated path resolves identically on every host that runs it. Prod stays unset, which the flag treats as off. The deploy validator's Cloud Run state fixture carries the flag wherever MEMORY_ENABLED appears, so a dev deploy that drops it on any host fails validation instead of shipping. Co-authored-by: Claude Fable 5.1 <[email protected]>
Summary
Flag-gated belief model for canonical memory: weights, not deletion. Memory currency becomes a read-side formula with one stored parameter (a half-life), only judged evidence events write to a row, and no job changes a row's status on the clock. Flag
MEMORY_BELIEF_MODEL_ENABLED, default off; with the flag unset every payload and write path is byte-identical to today.Design and grounding live in the workspace knowledge base at
omi-knowledge-base/projects/memory-forgetting/(README plus the 2026-09-02 owner-store grounding record). Short version of why: today's forgetting is wrong in both directions. The 7-day consolidation cron hides rows on age alone (it archived durable family facts and a stated trust preference), while stale state and plans from months ago stay active at full weight. Truth fields exist with no writers:confidenceis null on every row andcorroboration_countonly moves on duplicate ingestion.What changes with the flag on
utils/memory/belief_model.pycomputescurrency = 0.5 ** (days_since_last_evidenced / half_life_days)(1.0 when the half-life is null;valid_toin the past is history). Bands: current > 0.5, fading 0.25–0.5, history < 0.25./v3/memories, product search, and chat memory lines gain additivecurrency,currency_band,as_of; nothing extra is hidden.belief_class+half_life_daysat extraction: identity/relationship null, preference 180 d, state 30 d, plan 30 d or a namedvalid_to, episodic 7 d, meta split into standing instruction (null) vs session residue (1 d).user_assertedrows never decay. Unclassified long-term rows do not decay until classified.utils/memory/belief_evidence.py:restatedresets the clock and bumps corroboration,contradictedzeroes confidence (and supersedes when the new source is at least as authoritative),resolvedcloses the row as dated history viavalid_towhile it stays listed,unrelatedwrites nothing. Events are journaled inmemory_operationswith a pointer. Review true/false and content edits map to events. Retrieval count never writes.memory_conflictlane). A cosine gate (MEMORY_BELIEF_ADMISSION_MIN_SCORE, default 0.75) decides whether to ask the judge, never what to write.POST /v3/memoriesschedules the judge onllm_executorand does not wait.primary_user/third_party; the extractor may saymedia_screen, which is stored asthird_partybecause the released app-client contract pins the enum) using the existingclassify_model_aboutwith the user's name. Manual, API, developer-API, and integration writes stayprimary_userunless the payload says otherwise. Non-user subjects are kept but never drive proactive nudges.bandandas_ofso answers can hedge. The memory list hides nothing.reject_or_hided by the TTL lifecycle; consolidatorrejectbecomesarchivetier / active status /meta_residueinstead ofhidden.backend/scripts/backfill_belief_classes.py --uid <uid>classifies rows with nobelief_classon thememory_category(nano) lane. Dry-run by default;--applyrequires the flag and never touches status, tier,expires_at, or content. Idempotent.How to test
MEMORY_BELIEF_MODEL_ENABLED=true:GET /v3/memories: every row carriescurrency_bandandas_of; durable identity/preference/relationship rows arecurrent; months-old state and episodic rows arehistory; row count is unchanged.band: history, as_of: <date>and the answer is dated.confidencebecomes 0 and it stops driving JIT cards; the row stays listed.POST /v3/memories: response returns without waiting on the judge; the row hassubject_scope=primary_user.Scored against the owner's real store (3,582 active rows) with the read-side formula: flag on before backfill leaves every row current; with classes applied the split is 1,917 current / 193 fading / 1,472 history with zero durable facts about the user in history, and nothing deleted.
Verification
BACKEND_UNIT_TEST_FILE_LIST+backend/test.sh).backend/scripts/typecheck.sh: 0 errors.OMI_PR_BODY_FILE=... make preflight: 28 checks passed locally.run-unit-ci.sh --changed-filesselection fans out to ~1,000 files viaproduct_memory.py; left to CI.MemoryDBfields: app-client OpenAPI JSON, Dartmemories_wire, four TypeScriptomiApi.generated.ts, SwiftOmiApi.generated.swift. The local pre-push Swift compile was skipped withPRE_PUSH_SKIP_DESKTOP_SWIFT=1because SwiftPM cannot resolve the orphaned FluidAudio pin19600a48on a cold clone (pre-existing, unrelated to this PR); the CI Swift job is the arbiter for the generated Swift file.Not in this PR
backend/deploy/runtime_envmanifests (unset already fails closed).subject_scope=primary_user.INV-MEM-1
INV-MEM-3
INV-MEM-4
INV-TASK-2
Failure-Class: none
Line-Count-Exception: backend/database/memory_apply_store.py | 2883 -> 2885 | Persist half_life_days / belief_class on create.
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 2793 -> 2815 | Flag-gated subject/horizon classification on extraction write.
Line-Count-Exception: backend/utils/memory/canonical_consolidation.py | 2337 -> 2348 | Reject stays listed as residue under the belief flag.
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3593 -> 3705 | Admission/review evidence events and belief overlay on the existing mutation owner.
Line-Count-Exception: backend/utils/memory/memory_service.py | 3949 -> 3951 | Attach public belief overlay on product search dicts.
🤖 Generated with Claude Code