Skip to content

feat: converge universal memory and task authority - #11433

Closed
Git-on-my-level wants to merge 21 commits into
mainfrom
codex/universal-memory-task-convergence
Closed

Git-on-my-level wants to merge 21 commits into
mainfrom
codex/universal-memory-task-convergence

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Summary

  • make canonical memory and task behavior universal for every authenticated account; remove UID whitelist/cohort entitlement and dogfood activation machinery
  • keep one canonical memory domain for all new writes while exposing existing users/{uid}/memories rows through a read-only historical adapter with deterministic mixed reads, durable suppression, and lazy per-item materialization on mutation
  • preserve released memory/task API shapes, account-generation and idempotency fences, device/privacy rules, Candidate review, goals/workstreams, Chat-first, What Matters Now, staged-task compatibility, and global incident controls
  • complete delete/export/account-erasure coverage across canonical and historical storage, and make maintenance use a bounded universal registry/cursor
  • retire obsolete rollout, enrollment, backfill-cutover, v3 compatibility-projection, environment, workflow, fixture, and runbook machinery; replace it with universal operations and repair documentation

Compatibility and rollout

  • no bulk historical backfill is required or performed
  • historical rows remain readable and are never a new-write authority
  • mutations of a historical identity materialize exactly that row into canonical state before applying the mutation; durable override/tombstone records prevent resurrection
  • rollback remains a deployment-wide intake pause plus the universal mixed reader, so canonical-only new records never disappear behind a legacy route
  • this PR does not deploy services, migrate production data, or delete production collections

Validation

  • backend changed-file CI: 825 isolated unit-test files passed
  • backend Pyright: 0 errors (existing unknown-type warnings remain)
  • focused universal memory/task, privacy, staged-task, MCP, graph, export, account deletion, maintenance, and contract suites passed
  • public, app-client, and integration-public OpenAPI snapshots are current; app-client compatibility passes against origin/main
  • workflow contracts, runtime-env validation for dev/prod, memory continuity gauntlet, versioned filename guard, dev-harness tests, and product file line-count ratchet passed

Product invariants affected

  • INV-AGENT-*
  • INV-AUTH-1
  • INV-CHAT-1
  • INV-MEM-1
  • INV-MEM-2
  • INV-MEM-3
  • INV-MEM-4
  • INV-MEM-5
  • INV-TASK-1
  • INV-CUTOVER-1
  • INV-DATA-1
  • INV-INT-1

Failure-Class: FC-split-mutation-authority

Review in cubic

@mintlify

mintlify Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
omi 🟢 Ready View Preview Aug 11, 2026, 10:29 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2443ce8fb6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +621 to +622
if mode not in {MemoryRolloutMode.write, MemoryRolloutMode.read}:
raise HTTPException(status_code=503, detail="Memory writes are globally paused")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enable canonical intake before routing every write to it

The checked production runtime manifests still set MEMORY_MODE=off, while this commit routes create, edit, review, and visibility requests through MemoryService and now rejects every non-write/read mode here. A normal deployment using backend/deploy/runtime_env/prod.overlay.yaml or the backend-listen chart will therefore return 503 for all non-delete memory mutations; previously off selected the functioning legacy writer. Change the deployed mode in the same rollout or retain a non-authoritative compatibility write path until canonical intake is enabled.

Useful? React with 👍 / 👎.

Comment on lines +1069 to +1073
historical_rows = self._history.all_live(uid, page_size=page_size)
merged = list(canonical_rows)
for record in historical_rows:
if record.memory.id not in canonical_ids:
merged.append(record.memory)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor historical tombstone overrides during export

When deletion of a historical-only memory writes its tombstone override but the explicitly best-effort physical cleanup fails, fetch_authoritative_product_memory_items returns no row for that ID because it scans only memory_items; this merge consequently adds the still-present historical document back to the account export. Normal reads consult _canonical_status and suppress it, but exports can disclose a memory the user already deleted. Include IDs from memory_historical_overrides in the suppression set before appending historical rows.

Useful? React with 👍 / 👎.

Comment on lines +903 to +905
results = list(by_id.values())
results.sort(key=lambda match: (-float(match.score), -match.memory.updated_at.timestamp(), match.memory.id))
return results[:capped]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve canonical relevance when merging search results

For queries with multiple canonical matches, CanonicalMemoryBackend.search assigns every result score=1.0 even though search_canonical_memories has already returned them in hybrid relevance order. This newly added sort treats those scores as ties and reorders the canonical results by updated_at, so a newer weak match can displace an older highly relevant match, even when no historical result is involved. Carry the canonical ranking score/rank into the merge or preserve its established order for tied scores.

Useful? React with 👍 / 👎.

Comment thread backend/routers/staged_tasks.py Outdated
Comment on lines 391 to 394
# Scores belong only to the released historical review UI. Candidate
# authority deliberately ignores unknown Candidate IDs here.
staged_tasks_db.batch_update_staged_scores(uid, [score.model_dump() for score in request.scores])
return {'status': 'ok'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply staged scores to newly created Candidate IDs

New POST /v1/staged-tasks calls now create only Candidate records, but this endpoint still forwards score updates exclusively to users/{uid}/staged_tasks; that helper filters out IDs with no historical document. The current macOS prioritization flow calls this endpoint with the IDs returned by create, so every score for a newly created task is silently ignored, and /v1/staged-tasks/promote then chooses among unscored Candidates by timestamp rather than the client's relevance ranking. Preserve scoring in Candidate authority or migrate the in-tree client away from this released flow.

AGENTS.md reference: AGENTS.md:L88-L88

Useful? React with 👍 / 👎.

Comment on lines +133 to +136
registry = cast(Any, collection(CANONICAL_MEMORY_MAINTENANCE_REGISTRY_COLLECTION))
query = registry.where("uid", ">", cursor) if cursor else registry
query = query.order_by("uid")
page = list(query.limit(bounded_limit).stream())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Seed the maintenance registry for existing memory accounts

The maintenance job now enumerates only the newly introduced top-level registry, but entries are created exclusively when ensure_canonical_apply_control_state runs; there is no seeding path for accounts that already have canonical control and pending Short-term rows. After the old cohort enumeration is removed, an existing account that does not perform a new canonical write after deployment is absent from this query indefinitely, so its pending memories never receive required processing, TTL routing, consolidation, or outbox draining even after maintenance is enabled. Populate the neutral registry from existing authoritative state as part of convergence rather than requiring user activity or enrollment.

AGENTS.md reference: backend/AGENTS.md:L168-L168

Useful? React with 👍 / 👎.

Comment thread backend/utils/memory/memory_service.py Outdated
Comment on lines +1296 to +1302
def retract_conversation_memories(self, uid: str, conversation_id: str) -> Optional[Dict[str, Any]]:
backend = self._resolve_mutation_backend(uid)
if backend is self._legacy:
return None
return retract_conversation_sourced_memories(uid, conversation_id, db_client=self._db_client)
result = retract_conversation_sourced_memories(uid, conversation_id, db_client=self._db_client)
if result:
self._write_historical_overrides(
uid,
list(result.get("retracted_memory_ids") or []),
MemoryItemStatus.tombstoned,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retract historical memories when deleting their conversation

For cascade=true conversation deletion and merge cleanup, callers now use this method for every account, but retract_conversation_sourced_memories scans only canonical memory_items; the returned IDs therefore never include pre-convergence rows in users/{uid}/memories. The removed legacy path called delete_memories_for_conversation, so after this change an existing conversation-derived historical memory remains readable through the mixed adapter after its source conversation has been deleted. Resolve and tombstone historical rows associated with the source before allowing the source deletion to complete.

Useful? React with 👍 / 👎.

Comment thread backend/utils/memory/memory_service.py Outdated
Comment on lines +1269 to +1272
# Suppression is committed before cleanup so a partial cleanup cannot
# resurrect a historical row. Canonical rows also receive an override;
# this keeps the identity ledger explicit for export and account purge.
self._write_historical_overrides(uid, requested, MemoryItemStatus.tombstoned)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make mixed-origin batch deletion retry-safe

When a batch contains canonical and historical-only IDs, canonical tombstones commit first and the historical override batch commits separately here. If the override write fails, the request returns 503 after canonical records are already deleted; retrying the same request then encounters the canonical tombstone in _canonical_status during prevalidation and returns 404 before suppressing or cleaning any historical IDs. A transient failure can therefore leave part of a requested privacy deletion permanently visible unless the client reconstructs a historical-only batch. Commit both authority changes atomically or make validation accept the operation's already-tombstoned IDs on retry.

Useful? React with 👍 / 👎.

Comment on lines 413 to 417
try:
await run_blocking(
server_memories = await run_blocking(
db_executor,
memories_db.save_memories,
MemoryService(db_client=getattr(db_client_module, 'db', None)).create_external_memory_batch,
uid,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate the whole memory batch before committing any item

The router removed its prevalidation loop and now delegates directly to create_external_memory_batch, whose canonical backend implements write_batch as sequential per-item writes. Because Memory.content accepts empty or whitespace-only strings and required_processing_payload does not reject them, a batch such as [valid, whitespace-only] commits the first memory and then fails the second canonical write, returning 503 despite partial persistence. Restore whole-batch validation before the first write, and avoid advertising batch success semantics over a sequence that can partially commit.

Useful? React with 👍 / 👎.

Comment thread backend/utils/memory/memory_service.py Outdated
Comment on lines +466 to +472
# Read one bounded prefix and merge/order it in the universal service;
# never scan the historical collection for a normal page.
fetch_limit = bounded_offset + bounded_limit
if fetch_limit > self.MAX_COMPATIBILITY_WINDOW:
raise HTTPException(status_code=413, detail="Historical memory pagination window exceeded")
try:
raw_rows = memories_db.get_memories(uid, fetch_limit, 0, **self._firestore_kwargs())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Page historical memories using the final sort order

This reads only the requested prefix through database.memories.get_memories, which orders documents by legacy scoring DESC, created_at DESC, and then the universal service re-sorts that prefix by updated_at. With more than one page of historical rows, a recently updated low-scoring or non-manual memory can lie outside the fetched prefix while much older manual rows occupy the first page, so it is omitted from the page that the advertised final order says it belongs to and pagination becomes inconsistent. Query the historical stream in the same timestamp/ID order used by the merge, or use a real two-stream cursor.

Useful? React with 👍 / 👎.

Comment thread backend/utils/memory/memory_service.py Outdated
Comment on lines +812 to +816
for record in historical:
if record.memory.id in canonical_ids:
MEMORY_HISTORICAL_SUPPRESSION_TOTAL.labels(reason="canonical_identity").inc()
continue
status = self._canonical_status(uid, record.memory.id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Batch canonical suppression checks for historical pages

For every non-colliding historical row, _canonical_status performs one point read of memory_items and, when absent, another point read of memory_historical_overrides, all serially inside this loop. The default /v3/memories page of 100 legacy rows therefore adds up to 200 sequential Firestore RPCs, and the permitted 500-row page adds up to 1,000, replacing the previous single-query legacy read for the existing-user population and making endpoint timeouts and database-executor starvation likely. Load canonical statuses and overrides in bounded batches or derive a suppression map once per request.

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10 issues found across 375 files

Confidence score: 2/5

  • In backend/routers/memories.py, routing mutations through canonical intake while intake is paused under MEMORY_MODE=off can block create/edit/review/visibility flows in current deployment config, creating immediate user-facing write failures — align router gating with deployed mode or add an explicit compatibility path before rollout.
  • In backend/database/memory_apply_store.py, rollback read mode still permits canonical mutations, which can bypass the intended deployment-wide pause and allow writes during mixed-read fallback — enforce mutation rejection in rollback mode to preserve operational safety.
  • In backend/routers/memories.py, the batch delete retry path can surface a 404 after partial tombstoning, leaving mixed canonical/historical state and making retries non-idempotent — treat already-tombstoned IDs as safe/no-op or reconcile partial state before returning.
  • In backend/database/review_queue.py and backend/routers/memories.py (create_memories_batch), loss of atomicity means accepted reviews or earlier batch items may persist even when later steps fail, causing inconsistent review/memory state despite request errors — wrap these flows in a service-level transaction (or compensating rollback) and validate full batch payloads up front.
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/tests/unit/test_tools_rest_memory_runtime_adapter.py">

<violation number="1" location="backend/tests/unit/test_tools_rest_memory_runtime_adapter.py:23">
P2: The rewrite drops the negative guards that the previous tests provided: _UnexpectedLegacyMemoryDb/_UnexpectedLegacyVectorDb asserted that database.memories.get_memories/get_memories_by_ids and database.vector_db.find_similar_memories never run for REST reads. The new tests only patch MemoryService and assert on its mock contract, so a regression that silently re-wires REST reads to the legacy DB path would pass CI undetected. Retain a guard-style assertion that the legacy read modules are never invoked (e.g. patch them to raise, as before), since bypassing them is the central invariant of this convergence.</violation>
</file>

<file name="backend/AGENTS.md">

<violation number="1" location="backend/AGENTS.md:168">
P3: This line renames the job to "universal Short-term maintenance", but the same file's Directory Structure section still describes modal/memory_maintenance_job.py as "canonical ST→LT maintenance (Cloud Run Job)". The stale term leaves two conflicting descriptions of the same service; update that directory-structure entry to match the new universal terminology.</violation>
</file>

<file name="backend/tests/unit/test_knowledge_graph_canonical_mutation_routes.py">

<violation number="1" location="backend/tests/unit/test_knowledge_graph_canonical_mutation_routes.py:10">
P3: The new test's name claims "without_projection_mutation," but it removed the monkeypatch and the `delete_calls == []` assertion that previously verified `delete_knowledge_graph` is never invoked when a conflict is raised. The parametrized test only asserts the 409 status/detail, so a regression where the route deletes the knowledge graph before raising 409 would go unnoticed.</violation>
</file>

<file name="backend/database/review_queue.py">

<violation number="1" location="backend/database/review_queue.py:851">
P1: Accepting a review is no longer an atomic resolution: a failed conflict deletion or later ledger append can leave the accepted fact active while some conflicts or the review state remain unresolved. A service-level transaction or idempotent atomic resolution operation would keep the canonical mutation, conflict suppression, and resolution commit together.</violation>
</file>

<file name="backend/tests/unit/test_mcp_data_endpoints.py">

<violation number="1" location="backend/tests/unit/test_mcp_data_endpoints.py:667">
P3: The universal-memory conversion left dead seams in these test helpers: `_rest_universal_patches`/`_sse_universal_patches` take an `adapter_attr` argument that they immediately discard with `del adapter_attr`, and `_denied_result` takes a `read_decision` argument it likewise drops. The callers still pass `'list_default_mcp_memories'`/`'search_default_mcp_memories_vector'` in, even though those adapters are no longer patched, and the helpers round out with a no-op `patch.object(rest, 'db', rest.db)` that reassigns a module attribute to itself. This makes it look like the adapter calls are still exercised when they are not, which will confuse future maintainers about what these tests actually verify. I'd suggest dropping the unused parameters (and the no-op db patches) so the helpers reflect that reads now go through the universal `MemoryService` only.</violation>
</file>

<file name="backend/routers/memories.py">

<violation number="1" location="backend/routers/memories.py:323">
P0: Memory mutations are now routed through canonical intake, but intake is explicitly paused unless `MEMORY_MODE` is `write` or `read`. With deployment config still using `MEMORY_MODE=off`, create/edit/review/visibility requests can fail with 503 in normal runtime. Consider shipping the mode transition with this rollout, or keeping a compatibility write path until canonical intake is enabled.</violation>

<violation number="2" location="backend/routers/memories.py:414">
P1: `create_memories_batch` now writes through the service without validating the entire payload up front. If a later item is invalid, earlier items can already be persisted while the request still fails, which breaks all-or-nothing batch behavior for clients. A full prevalidation pass before the first write would avoid partial commits.</violation>

<violation number="3" location="backend/routers/memories.py:634">
P1: This batch delete path delegates to mixed-origin `delete_batch` and maps `ValueError` to 404. If a prior attempt already tombstoned canonical IDs but failed before historical overrides, a retry can now fail fast with 404 and leave requested historical deletions incomplete. Making retries idempotent for already-tombstoned canonical IDs would keep privacy deletes recoverable after transient failures.</violation>
</file>

<file name="backend/tests/unit/test_memories_batch_delete.py">

<violation number="1" location="backend/tests/unit/test_memories_batch_delete.py:58">
P3: The test_batch_delete_route_has_no_legacy_or_mirror_mutation test sniffs the live implementation source text instead of exercising behavior. It calls source.index("def delete_memory(", start+1), which raises ValueError whenever the batch function is not immediately followed by that exact definition name, and it asserts global strings ("_mirror_delete", "memories_db") across the entire file, so unrelated future edits to memories.py will break the batch-delete test. This couples a unit test to file layout and makes it a maintenance hazard disguised as a contract test.</violation>
</file>

<file name="backend/database/memory_apply_store.py">

<violation number="1" location="backend/database/memory_apply_store.py:67">
P1: Rollback read mode still accepts new canonical memory mutations, so the deployment-wide intake pause can be bypassed and writes can continue while the system is intended to serve mixed reads only. Restrict the mutation guard to the write-enabled mode (or use the rollout mode's explicit intake-enabled predicate).</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

created = await run_blocking(
db_executor,
memories_db.create_memory,
MemoryService(db_client=getattr(db_client_module, 'db', None)).create_external_memory,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0: Memory mutations are now routed through canonical intake, but intake is explicitly paused unless MEMORY_MODE is write or read. With deployment config still using MEMORY_MODE=off, create/edit/review/visibility requests can fail with 503 in normal runtime. Consider shipping the mode transition with this rollout, or keeping a compatibility write path until canonical intake is enabled.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/memories.py, line 323:

<comment>Memory mutations are now routed through canonical intake, but intake is explicitly paused unless `MEMORY_MODE` is `write` or `read`. With deployment config still using `MEMORY_MODE=off`, create/edit/review/visibility requests can fail with 503 in normal runtime. Consider shipping the mode transition with this rollout, or keeping a compatibility write path until canonical intake is enabled.</comment>

<file context>
@@ -555,62 +309,32 @@ async def create_memory(
+        created = await run_blocking(
             db_executor,
-            memories_db.create_memory,
+            MemoryService(db_client=getattr(db_client_module, 'db', None)).create_external_memory,
             uid,
-            memory_write_payload(memory_db, MemoryApiExposure.LEGACY),
</file context>

Comment thread backend/utils/memory/memory_service.py Resolved
Comment thread backend/routers/integration.py Resolved
mode = MemoryRolloutMode(rollout_mode_env_value())
except ValueError as exc:
raise CanonicalMemoryIntakePausedError("canonical memory intake mode is malformed") from exc
if mode not in {MemoryRolloutMode.write, MemoryRolloutMode.read}:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Rollback read mode still accepts new canonical memory mutations, so the deployment-wide intake pause can be bypassed and writes can continue while the system is intended to serve mixed reads only. Restrict the mutation guard to the write-enabled mode (or use the rollout mode's explicit intake-enabled predicate).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/memory_apply_store.py, line 67:

<comment>Rollback read mode still accepts new canonical memory mutations, so the deployment-wide intake pause can be bypassed and writes can continue while the system is intended to serve mixed reads only. Restrict the mutation guard to the write-enabled mode (or use the rollout mode's explicit intake-enabled predicate).</comment>

<file context>
@@ -51,6 +53,21 @@ class MemoryFirestoreApplyError(Exception):
+        mode = MemoryRolloutMode(rollout_mode_env_value())
+    except ValueError as exc:
+        raise CanonicalMemoryIntakePausedError("canonical memory intake mode is malformed") from exc
+    if mode not in {MemoryRolloutMode.write, MemoryRolloutMode.read}:
+        raise CanonicalMemoryIntakePausedError("canonical memory intake is globally paused")
+
</file context>
Suggested change
if mode not in {MemoryRolloutMode.write, MemoryRolloutMode.read}:
if mode is not MemoryRolloutMode.write:


def _rest_legacy_patches(adapter_attr, result):
def _rest_universal_patches(adapter_attr, result):
del adapter_attr

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The universal-memory conversion left dead seams in these test helpers: _rest_universal_patches/_sse_universal_patches take an adapter_attr argument that they immediately discard with del adapter_attr, and _denied_result takes a read_decision argument it likewise drops. The callers still pass 'list_default_mcp_memories'/'search_default_mcp_memories_vector' in, even though those adapters are no longer patched, and the helpers round out with a no-op patch.object(rest, 'db', rest.db) that reassigns a module attribute to itself. This makes it look like the adapter calls are still exercised when they are not, which will confuse future maintainers about what these tests actually verify. I'd suggest dropping the unused parameters (and the no-op db patches) so the helpers reflect that reads now go through the universal MemoryService only.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_mcp_data_endpoints.py, line 667:

<comment>The universal-memory conversion left dead seams in these test helpers: `_rest_universal_patches`/`_sse_universal_patches` take an `adapter_attr` argument that they immediately discard with `del adapter_attr`, and `_denied_result` takes a `read_decision` argument it likewise drops. The callers still pass `'list_default_mcp_memories'`/`'search_default_mcp_memories_vector'` in, even though those adapters are no longer patched, and the helpers round out with a no-op `patch.object(rest, 'db', rest.db)` that reassigns a module attribute to itself. This makes it look like the adapter calls are still exercised when they are not, which will confuse future maintainers about what these tests actually verify. I'd suggest dropping the unused parameters (and the no-op db patches) so the helpers reflect that reads now go through the universal `MemoryService` only.</comment>

<file context>
@@ -655,45 +647,56 @@ def test_every_tool_has_a_dispatch_branch(self):
 
-def _rest_legacy_patches(adapter_attr, result):
+def _rest_universal_patches(adapter_attr, result):
+    del adapter_attr
+    service = MagicMock()
+    service.read.return_value = []
</file context>

Comment thread backend/AGENTS.md
@@ -165,7 +165,7 @@ Serving STT provider/surface policy and canonical model order are owned exclusiv
- **nllb-translation** (`nllb_translation/`) — GPU translation service. Called by backend when `HOSTED_TRANSLATION_API_URL` is set and NLLB is selected.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This line renames the job to "universal Short-term maintenance", but the same file's Directory Structure section still describes modal/memory_maintenance_job.py as "canonical ST→LT maintenance (Cloud Run Job)". The stale term leaves two conflicting descriptions of the same service; update that directory-structure entry to match the new universal terminology.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/AGENTS.md, line 168:

<comment>This line renames the job to "universal Short-term maintenance", but the same file's Directory Structure section still describes modal/memory_maintenance_job.py as "canonical ST→LT maintenance (Cloud Run Job)". The stale term leaves two conflicting descriptions of the same service; update that directory-structure entry to match the new universal terminology.</comment>

<file context>
@@ -165,7 +165,7 @@ Serving STT provider/surface policy and canonical model order are owned exclusiv
 - **backend-sync** (`main.py`, same image as backend) — Cloud Run admission service for `/v2/sync-local-files`. The server classifies whole batches: recordings no more than six hours old enter `sync-jobs` (fresh), while older or untrusted batches enter `sync-backfill` and the scale-to-zero **backend-sync-backfill** worker. Fresh keeps its bounded inline fallback; backfill never falls into fresh/inline capacity. Backfill defaults to one in-flight job per UID, four processed speech hours per UID/day, 555 processed speech hours globally/day, a 30-day lookback, and four queue workers. Live fair-use reads only `realtime + sync_fresh`; `sync_backfill` is separately metered. A 45-day Firestore content ledger protects transcription and usage side effects across job expiry and re-upload. Audio playback merges (`/v1/sync/audio/*`) follow the same pattern via queue `audio-merge` building 30-day MP3 artifacts under `playback/` (`AUDIO_MERGE_DISPATCH_MODE`) — per-part files plus one dense per-conversation `conversation.mp3` whose spans manifest + audio_files fingerprint are stamped on the conversation doc (`conversation_audio`); a fingerprint mismatch after late chunks re-enqueues the build. In production, account deletion requires `ACCOUNT_DELETION_DISPATCH_MODE=cloud_tasks` and complete Cloud Tasks bindings to enqueue opaque job IDs to queue `account-deletion`, which posts `/v1/users/account-deletion-wipes/run`; startup rejects inline or incomplete configuration, reconciliation only re-dispatches tasks so the OIDC handler is the sole wipe executor, and the post-deploy queue-drain window accepts the former sync OIDC audience only for legacy UID payloads. API success is returned only after the deletion marker is persisted and the wipe task is durably enqueued.
 - **notifications-job** (`modal/job.py`) — Cron job, reads Firestore/Redis, sends push notifications and runs X connector sync. It has no canonical maintenance flags or Typesense secrets; its deploy workflow removes only those retired bindings and preserves unrelated notification/X-sync env.
-- **memory-maintenance-job** (`modal/memory_maintenance_job.py`) — Cloud Run Job for canonical maintenance (normalization → TTL audit → terminal consolidation/promotion). Deploy manually via `.github/workflows/gcp_memory_maintenance_job.yml`; auto-dev on `main` via `gcp_memory_maintenance_job_auto_dev.yml`. Flag ownership and readiness order: `docs/runbooks/canonical-memory-rollout-flags.md`. Env contract is validated by `backend/scripts/validate-backend-runtime-env.py`; Scheduler owns cadence; prod declares `MEMORY_MODE=off` until Gate 3; job users come from `CANONICAL_MEMORY_USERS` in `config/canonical_memory_cohort.py`. When enabled, L2/required-processing uses the gateway-only `omi:auto:memory-l2` Luna lane; workflows derive the endpoint after the serving gate and Cloud Run VPC probe.
+- **memory-maintenance-job** (`modal/memory_maintenance_job.py`) — Cloud Run Job for universal Short-term maintenance (normalization → TTL audit → terminal consolidation/promotion). Deploy manually via `.github/workflows/gcp_memory_maintenance_job.yml`; auto-dev on `main` via `gcp_memory_maintenance_job_auto_dev.yml`. Global incident/readiness controls and rollback order live in `docs/runbooks/universal-memory-operations.md`; there is no UID inventory or enrollment step. Env contract is validated by `backend/scripts/validate-backend-runtime-env.py`; Scheduler owns cadence. When enabled, L2/required-processing uses the gateway-only `omi:auto:memory-l2` Luna lane; workflows derive the endpoint after the serving gate and Cloud Run VPC probe.
 - **monitoring** (`backend/charts/monitoring/`) — Prometheus, Grafana, Loki, Alloy, alerts, and HPA metric adapters for backend services.
 - **agent-vm-reaper** (`backend/charts/agent-vm-reaper/`) — CronJob that deletes stale `omi-agent-*` GCE VMs left by desktop agent sandboxes.
</file context>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6663f10347

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1458 to +1461
result = replace_conversation_sourced_memories(uid, conversation_id, items, db_client=self._db_client)
retracted = list(result.get("retracted_memory_ids") or [])
if retracted:
self._write_historical_overrides(uid, retracted, MemoryItemStatus.tombstoned)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Suppress historical source rows during replacement

When an existing account reprocesses a conversation that already has rows in users/{uid}/memories, process_conversation.py calls this method, but retracted_memory_ids contains only canonical rows discovered by replace_conversation_sourced_memories; historical rows whose conversation_id or evidence references the same conversation are never overridden or cleaned up. Although the final code now handles historical rows in explicit retract_conversation_memories, this replacement path remains uncovered, so an empty or changed reprocess leaves the obsolete historical memories visible beside the replacement set. Include matching historical source rows in the tombstone/cleanup closure.

Useful? React with 👍 / 👎.

Comment on lines +251 to +255
memories = sorted(
(
memory
for memory in by_id.values()
if memory.get('user_review') is not False and (include_invalidated or memory.get('invalid_at') is None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Filter invalid rows before bounding the sorted window

For an account whose newest candidate_limit documents include rejected or invalidated memories, both Firestore queries are limited before this filter runs, so the removed rows are not replaced with older eligible documents. The universal reader can consequently return a short or empty page while valid historical memories still exist, and MCP/developer pagination loops interpret that short page as exhaustion. Continue scanning or over-fetch until the requested number of eligible rows is collected.

Useful? React with 👍 / 👎.

Comment on lines +501 to +503
# The old recovery moved rows directly into action_items and bypassed
# Candidate authority. Keep the endpoint decodable, permanently inert.
del limit, cursor, uid

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep legacy conversation-task recovery functional

For a user whose tasks were moved from action_items into staged_tasks by the retired conversation migration, the current macOS TasksStore.restoreLegacyConversationItemsIfNeeded still calls this endpoint before allowing server state to delete its cached tasks. Returning an unconditional zero-result marks that recovery complete without restoring or canonically accepting those rows, so the following full sync can remove the user's cached tasks while the records remain only as staged suggestions. Preserve the recovery goal through Candidate acceptance or keep the existing marked-row restoration until every affected account has converged.

Useful? React with 👍 / 👎.

Comment on lines +319 to +320
items = _merged_staged_projection(uid, account_generation=control.account_generation)
return {'items': items[offset : offset + limit], 'has_more': len(items) > offset + limit}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound staged-task list work to the requested page

Every GET /v1/staged-tasks, even limit=1, now calls _merged_staged_projection, which exhaustively pages all Candidates for the account and streams the complete historical staged_tasks collection before slicing here. Candidate history and completed historical rows are retained, so request latency and Firestore reads grow with the account's lifetime task history and can eventually time out this released list endpoint. Page and merge the two ordered sources only far enough to produce the requested window.

Useful? React with 👍 / 👎.

Comment on lines +1076 to +1079
db_client = getattr(db_client_module, 'db', None)
memory_service = MemoryService(db_client=db_client)
memory_service.ensure_canonical_mutation_ready(uid)
return _extract_memories_canonical(uid, conversation, db_client=db_client, parity_capture=parity_capture)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve locked status on universal conversation memories

For a paywalled conversation with conversation.is_locked, _extract_memories_canonical sets MemoryDB.is_locked, but the canonical apply payload/model and memory_item_to_memorydb do not persist or restore that field. Routing every account through this canonical extractor therefore turns newly extracted facts from locked conversations into ordinary unlocked memories that /v3/memories, MCP, developer search, and chat can expose in full; the removed legacy writer retained is_locked and its readers truncated or rejected the content. Carry the lock/access state through canonical authority or exclude locked source content from universal extraction.

Useful? React with 👍 / 👎.

Comment on lines +27 to +28
"""All authenticated accounts use assertion-backed graph semantics."""
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Migrate graph rebuild callers before disabling the route

Making every authenticated account assertion-backed causes _require_legacy_graph_mutation to return 409 for every rebuild request, but in-tree clients were not migrated: Flutter onboarding calls KnowledgeGraphApi.rebuildKnowledgeGraph() when a graph is absent, and the Flutter, macOS, Windows, and web graph views still expose rebuild actions against this route. Those flows now either silently skip graph prebuild or surface a permanent rebuild error for every user. Remove or replace those callers in the same change, or retain a canonical rebuild operation with the intended semantics.

AGENTS.md reference: AGENTS.md:L88-L88

Useful? React with 👍 / 👎.

Comment on lines +150 to +153
MemoryService(db_client=db_client).write_batch(
uid,
[memory.model_dump(mode='python') for memory in saved_memories],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep explicit integration memories in required processing

When an external integration supplies the explicit memories list, this code now sends those rows through raw write_batch together with already-extracted text memories. The previous canonical branch deliberately sent explicit rows through create_external_memory, which adds required_processing_payload; without that metadata, canonical apply defaults them to processing_state=processed, making unprocessed integration text immediately readable and eligible for consolidation instead of withholding it until the required processor normalizes or rejects it. Preserve the explicit-row distinction when constructing the batch.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Superseded by combined PR #11447.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Git-on-my-level added a commit that referenced this pull request Aug 13, 2026
## Summary

- supersede #11431 and #11433 with one integrated branch on current
`main`
- ship universal memory/task convergence together with context-bucket
proactivity
- add configurable 24-hour notification active periods, persistent
frequency budgets, quiet-period cost short-circuiting, typed
notification presentation, and deterministic QA controls
- repair notification permission lifecycle, message-action hit testing,
and repeated screen-derived Suggested Task reconciliation

## Validation

- 4,730 Desktop tests passed, 1 skipped, 0 failed before main
integration
- 91 focused merged-tree Swift tests passed
- 19 merged-tree backend proactivity/quota tests passed
- SwiftLint and swift-format clean
- product file line-count ratchet and mutation fixtures pass
- final bounded pre-push gate passed after current-main integration;
backend pyright: 0 errors
- 27 focused notification/suggestion Swift tests, 56 memory/export
tests, and 34 privacy tests pass
- signed `/Applications/omi-qa-main.app` rebuilt from the final branch;
03:00–06:00 active period and Maximum frequency persist across relaunch

## Product invariants affected

- INV-AGENT-*
- INV-AUTH-1
- INV-CHAT-1
- INV-MEM-1
- INV-MEM-2
- INV-MEM-3
- INV-MEM-4
- INV-MEM-5
- INV-TASK-1
- INV-CUTOVER-1
- INV-DATA-1
- INV-INT-1
- INV-UI-1

Failure-Class: FC-split-mutation-authority


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11447?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. -->
pull Bot pushed a commit to codingwatching/omi that referenced this pull request Aug 13, 2026
@undivisible
undivisible deleted the codex/universal-memory-task-convergence branch August 20, 2026 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant