Skip to content

feat: add JIT knowledge ledger foundation and guarded adoption - #12084

Merged
Git-on-my-level merged 245 commits into
mainfrom
codex/jit-processing-end-state
Aug 27, 2026
Merged

Git-on-my-level merged 245 commits into
mainfrom
codex/jit-processing-end-state

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What this PR is

Today Omi spends LLM money guessing: every finished conversation immediately gets memories extracted, a folder assigned, goal progress computed, and app summaries generated — and the desktop app additionally runs a vision model over your screen roughly 37 times an hour asking "is anything here interesting?". Most of that output is never read: measured on real accounts, ~81% of auto-extracted memories are about other people, and most expire unread. We pay for processing nobody asked for, and users see the noise as bad memories and bad tasks.

This PR lands the just-in-time (JIT) processing architecture: do the cheap, user-facing work eagerly (transcription, the summary/notes you actually read, search indexing), and do everything else only when there is a real user intention — opening a conversation, asking a question in chat, or a deliberately planned trigger firing. Concretely:

  1. A knowledge ledger replaces guess-and-expire memories. One append-only store of timestamped fact rows (with slots, validity intervals, supersession, and provenance back to the source conversation). The user profile is a deterministic render of the open rows — no LLM call, no consolidation cron, no silent 48-hour expiry. Old memories are preserved as labeled history; a reversible migration moves users over.
  2. Memory formation moves to a bounded daily sweep instead of per-conversation extraction: ONE agent pass per user per completed local day. The whole day's conversation summaries go in as a single spine (so the model sees the day in context — cross-conversation dedup, morning-to-afternoon threads), alongside the user's current profile and existing memories (the same get_prompt_memories seam chat uses — the ledger render for migrated users). The agent may pull a bounded number of raw transcript excerpts (max 8, capped per fetch) to verify specifics, and may run bounded prior-memory ledger searches (max 4 keyword lookups, owner-scoped, provider fail-soft) to dedup and supersede — at most two provider calls per user per day, both inside one at-most-once billing fence. Every memory must cite the conversation ids it came from (uncited memories are dropped), carries a basis label (decided/proposed/observed), and may name a slot for standing attributes — an occupied slot turns the add into an amend through the existing canonical occupancy check, which is how the daily run maintains the user's profile (the profile is the deterministic render of slotted rows; no second write path, no separate profile LLM call). Budgets: max 32 candidates, 16 durable writes, direct user statements ranked above inferences, hard cost ceiling checked before any call. The same daily run backstops folder assignment for that day's unopened, unfiled conversations (first-open/user assignment always wins). Both phases share a byte-identical prompt prefix (pinned by a test) with a per-user prompt_cache_key; note the current gpt-5.6-luna cache was measured as exact-match rather than prefix-based, so this is future-proofing, not present savings.
  3. Expensive per-conversation work is deferred to first open (folder assignment and app summaries) for users in the rollout cohort. A conversation you never open never pays for them. Summary and search indexing still happen at capture, so nothing looks different in lists. Automatic goal-progress updates are removed from the JIT featureset entirely (product decision 2026-08-26): for JIT-admitted conversations, goals change only through explicit user action — the per-conversation goal LLM call is not deferred, it is gone. Non-cohort users keep today's automatic goal updates.
  4. Desktop proactivity flips from polling to triggers. Instead of a continuous LLM loop over screenshots, the agent writes planned triggers (standing intents with cheap match conditions) into the ledger; the client evaluates them locally for free and wakes one full agent turn only on a match. An ambient contextual lane with shared notification/model budgets covers the unplanned cases. Screen text is treated as untrusted data everywhere.
  5. Chat gets explicit grounding tools (search_historical_facts, evidence citations that deep-link into Rewind) instead of inferring history from wording. All reads are owner-scoped, bounded, and fail closed.
  6. Full Windows parity for the trigger runtime, keyframe retention/deletion convergence, and account-switch fencing; Flutter and web get the evidence surfaces.
  7. Isolated QA tooling: a reserved omi-jit-qa.app bundle that can target deployed dev or a fully local loopback stack (Firestore/Redis emulators + dev-GCP Vertex gateway), so we can dogfood without touching production data.

Why this saves money

For cohort users: of the ~7 LLM calls in every conversation finalization, the goal-progress call is eliminated outright, and folder assignment plus the per-app fan-out are deferred to first open (never paid for conversations that are never opened); the desktop proactivity spend becomes proportional to trigger matches per day instead of hours of screen time. The new costs are small and bounded by construction: one budgeted daily sweep run per user per day, and control-plane flag reads. Legacy memory-noise machinery (consolidation cron work, short-term expiry) shrinks as users migrate to the ledger.

How rollout is controlled

Everything is dark until deliberately opened, in this order of authority:

  • Per-user cohort: PostHog flag jit-processing-v1, resolved server-side per authenticated uid; clients cannot enroll themselves. A separate jit-processing-ledger-migration-v1 flag independently gates migration/writer-cutover. Kill switch jit-processing-kill-switch-v1 beats everything and is re-checked uncached before every paid call. Missing/malformed/timeout flag state fails closed (no JIT work). Note: admission requires the kill-switch flag to exist and be false — an absent kill-switch flag keeps everyone dark.
  • Daily sweep: additionally env-gated and cohort-gated by its own PostHog flag. Development now carries the live deployment values (ENABLED/MODEL_ENABLED on, MODEL_NAME gpt-5.6-luna matching the get_model('memories') declaration interlock, MAX_MODEL_COST_USD 0.80, COHORT_ENABLED on with COHORT_FLAG daily-memory-sweep-v1); production stays fully pinned off. Those values only let the job reach its cohort read — no memory forms for anyone until daily-memory-sweep-v1 exists and resolves true for a uid. The cost gate is a per-day worst-case ceiling checked before any provider call, covering phase B's clamped draft/reason/lookup overhead.
  • Migration: reversible, receipt-driven, rehearsed against a real Firestore emulator (interruption/resume, byte-stable no-op rerun, contention).

The control plane is now provisioned for a two-account development dogfood, and production remains dark by credential. POSTHOG_PROJECT_API_KEY was the literal placeholder string disabled in based-hardware-dev and did not exist at all in based-hardware until this PR's deploy wiring required it. Because _build_client rejects only an empty key, a placeholder builds a client that fails every request, which the authority maps to unknown — fail-closed, but indistinguishable from a working dark rollout, so no cohort could have been opened anywhere. Development now carries the real project key; production keeps the placeholder, which is what holds it dark. The three flags (jit-processing-v1, jit-processing-kill-switch-v1, daily-memory-sweep-v1) exist and were verified by running the shipped resolve_jit_rollout_sync at PAID_BOUNDARY against real PostHog: both owner uids resolve ENABLED, an unenrolled control uid resolves DISABLED, and the kill switch is present-and-false rather than absent.

daily-memory-sweep-v1 is deliberately empty (0% rollout, nobody enrolled). Eager per-conversation extraction is skipped only for non-compatibility writer modes, while the sweep's per-user admission checks the env authority and the cohort flag and nothing about writer mode -- so a cohort member who has not also been cut over to the ledger gets both memory-formation paths over the same conversations. The sweep cohort therefore stays closed until ledger migration admits the same user, and the two flags should be opened together rather than independently.

Caveat worth carrying into the production decision: the organisation has exactly one PostHog project (302298), so development and production necessarily share a flag namespace. The only thing separating them today is that production's copy of the secret is a placeholder — the moment a real key is written there, the same cohort membership admits the same users in production. A second project, or environment-qualified flag keys, is the durable fix and is a deliberate decision rather than a code change.

The released desktop proactivity lane stays open. An earlier revision of this branch gated the pre-existing POST /v1/desktop/proactivity/completions route on cohort admission, which would have silently killed context-bucket insights for the whole shipped desktop fleet on deploy day. That gate was removed during takeover review: the legacy lane keeps merge-base admission semantics (tier quotas only), JIT admission is enforced on the JIT reservation routes, and retiring the legacy lane remains a later explicit operation once clients have migrated.

Takeover review hardening (2026-08-26)

An independent five-surface review (backend memory core, backend shared paths, macOS, Windows, Flutter/web) ran against this head before merge; every confirmed finding that changes behavior for users outside the cohort — or breaks the cohort itself — was fixed on this branch:

  • Provider writes no longer take an account-wide lock. The new legal-hold deletion gate had wrapped every GCS upload and Pinecone/Typesense upsert in an exclusive per-account Firestore mutex with no lease — concurrent writes for one user hard-failed (audio drops, lost vectors) and a crash mid-operation bricked the account permanently. Writes now use a lock-free fence (blocked only during account deletion or a live destructive operation), destructive operations keep exclusive ownership, and abandoned gates self-expire after 6 hours.
  • Onboarding works again. The new server-owned onboarding admission returned False from an Optional[str] function (completed users passed an is not None check — the exact provenance forgery it was meant to prevent) and expired 20 minutes after app launch (slow onboarding, web/desktop clients silently lost onboarding questions and is_user tagging). Admission is now issued/refreshed at socket connect from the durable account state.
  • Legacy desktop proactivity preserved (see above).
  • Chat is byte-identical for non-cohort users: the five new JIT tools (search_knowledge, search_historical_facts, read_playbook, get_entity_timeline, look_at_frame) are withheld from the model unless the rollout admits the user, instead of executing and returning "no entries found".
  • Control-plane cost is bounded: unknown flag states are negative-cached (5s) so a dark fleet doesn't pay one PostHog call per conversation finalization; the screen-sync loop uses the cached decision instead of a forced refresh; sync-context resolution runs on a dedicated event loop (fixing cross-loop asyncio corruption that could permanently poison a user's decision); the memories-tab ledger-history endpoint answers empty without its 501-row scan for non-cohort users; the screen-sync rate limit no longer shares a 120/hour bucket with photo reads (two Macs would have starved it).
  • Ledger-cutover users' conversations finalize. Eager L1 extraction ran the model call and then had its write refused by writer admission — failing the whole finalization for every migrated user. Extraction is now skipped for non-compatibility writer modes (the daily sweep owns their memory formation), which is also where the per-conversation memory-extraction saving lands.
  • Export can't be permanently denied by a legacy photo row with no bytes anywhere (frame requests keep the fail-closed contract).
  • Windows: a leaked notification-delivery slot could permanently silence every proactive notification after one SQLite hiccup (fixed: try/finally + slot expiry); the ambient lane interpolated raw window titles into a tool-capable agent prompt (fixed: opaque context only); Google Calendar was polled every 60s before admission for non-cohort users (fixed: admission first); rollout-authority errors caused an unbacked-off ~1 req/s retry storm when offline (fixed: failure backoff); a JIT schema failure could abort opening the local DB for all features (fixed: guarded).
  • macOS: pre-PR screen-derived tasks lost their "Screen context / Open Rewind" row (fixed: legacy fallback restored); three unguarded ALTER TABLE migrations plus an initialize-latch could permanently brick the local ledger mirror on dogfood machines (fixed: guarded + latch after successful migrate); EventKit was queried before the flags check (fixed); a failed chat turn's notice could be injected into a different conversation's transcript after switching sessions mid-flight (fixed: transcript resets revoke the active turn).

Known limitations recorded for the rollout gates (not fixed here): turning the rollout off permanently strands admitted-but-unopened conversations without app enrichment (folder assignment is backstopped by the daily sweep for sweep-enrolled users; app fan-out is not — rollback rehearsal must account for it); explicit memory deletes now 503 (with retry semantics, tombstone already committed) when the vector provider is down — deliberate privacy fail-closed; the data export is now materialized before streaming (large accounts may need a longer timeout); the macOS failed-chat-turn notice survives relaunch for ordinary provider failures but not for pre-terminalized discards (user Stop / watchdog) — a characterization test in agent/tests/conversation-journal.test.ts pins the gap and the least-invasive fix is described there.

Main-sync note (2026-08-26, second sync): origin/main was red on its own tip when synced; three of its breakages are repaired in this PR so the merged tree goes green: the unused get_byok_keys import in backend/utils/subscription.py (pyright), the missing explicit self in the escaping mic-alert closure in AppState+Transcription.swift (all three Desktop Swift lanes, shipped red by d49f978), and the web/app/bun.lock entries for the prettier pin 64db30c791 added without regenerating the lockfile (frozen install). Clearing those exposed three more (each masked behind an earlier failure): Xcode 16.4's SILGen segfaults (signal 11) on the mic-alert presenter's stored-property default in AppState.swift (moved into init()); main's BYOK security tests still assert the pre-rewrite lenient contract that d0e3a4eb3a/1da8880175 deliberately replaced (rewritten to the shipped strict contract their own docstrings describe — pyright failing first had hidden the red tests on main); and subscription.py isn't pinned-black clean as main wrote it. Two more of the same pyright-masked pattern followed: the chat-router test harness and test_chat_quota's utils.byok fake both predate the BYOK rewrite's new imports (utils.llm.gateway_client in routers/chat.py, get_byok_uid/get_cached_byok_state in utils/subscription.py), so every suite reloading those real modules failed at import; the same held for test_desktop_transcribe (non-package utils.llm stub), test_paywall_reconnect_gate (escape-hatch tests missing the now-required BYOK uid context), and test_chat_session_app_identity (stale enforce_chat_quota stub signature). Finally, the macOS BYOK tests PR #11454 shipped red store raw keys without enrolling their fingerprints, which the enrollment-verified activation model now requires — their setups now enroll what they store. A dozen main-shipped defect clusters repaired in this sync in total; none change JIT behavior.

Second review round (2026-08-26, post-sync): three parallel adversarial reviews (sweep correctness, injection/data-flow, semantic-merge + goals-removal completeness) over the code added since the overnight takeover. Merge integrity came back clean (cache_key plumbing, model routing, BYOK, and web imports all cohere with main's 92 new commits). Confirmed findings fixed on this branch:

  • Pre-call cost ceiling now covers phase B's model-controlled inputs. Draft memories, transcript-request reasons, and prior-memory lookup queries/results are all length-clamped in the runner, and the clamped worst case is added to the sweep's pre-call estimate (cap guidance is now ≥ ~$0.80).
  • A stage-schema bump can no longer stall a user's cursor forever. A staged page written under an older daily_memory_sweep_daily_summary_stage.* version is attested as an empty consumed day (the writing deployment owned that window's invocation and apply) instead of being re-read as permanently incomplete.
  • The folder backstop's check-and-set is transactional, so a concurrent first-open or user assignment can't be clobbered by a stale read.
  • Sweep-authored profile slots refresh. Equal-rank same-slot sweep candidates now amend a sweep-authored occupant (the profile-maintenance path was frozen after the first write); direct user statements are still never overwritten, and slotless subject matches still dedup.
  • Injection hardening: ``` fences in summaries, excerpts, and lookup results are neutralized so third-party speech can't break out of its prompt block; raw-transcript fallback rows are marked "(unstructured transcript excerpt)" and the prompt forbids sourcing profile slots or personal attributes from them without transcript verification (a test pins the marker to the rule).
  • Goals-removal cleanup: the dead first-open authority threading (authority_account_generation/authority_source_generation/effect_authorizer) is removed from update_goal_progress/extract_and_update_goal_progress; the stale jit-first-open-runtime.md doc no longer describes a goal-progress first-open effect. (database/goals.py's durable-event machinery is kept — it is generic and separately tested.)

Residual (reviewed, deliberately unchanged): the free-form slot namespace (an attacker-adjacent conversation could mint a new unoccupied slot; the personal-attribute and unstructured-row prompt gates mitigate, a slot allowlist would be a product decision), and database/goals.py dead-path excision beyond the utils layers.

Deployment readiness (2026-08-26, pre-merge)

Tracing what a real dogfood account would actually need surfaced three deployment facts that code review could not:

  • This PR's deploy wiring required a secret production did not have. POSTHOG_PROJECT_API_KEY is added under environment_shared for desktop_backend, frame-request-retention-job, and daily-memory-sweep-job; main declares it nowhere and prod.overlay.yaml does not remove it. The secret did not exist in based-hardware, so the next production desktop_backend deploy would have failed creating its revision — a manual-dispatch lane, so nothing breaks on merge day, and check_deployment_secret_boundary.py audits secret names rather than existence. A placeholder now exists in production, matching development's convention, which resolves the deploy and keeps production dark.
  • The flag provider was not live anywhere (see "How rollout is controlled") — now provisioned for development and verified end to end; production stays dark on its placeholder.
  • Development's data plane is production Firestore (dev.overlay.yaml sets data_plane_project: based-hardware), so the 18 new composite indexes are needed in production for a development or beta session to work, not just in based-hardware-dev. Both projects are being reconciled ahead of merge so the first cohort read does not race an index build. Note for whoever runs that reconcile again: provision_missing_indexes issues each gcloud ... create synchronously, so one slow backfill (production's conversations) consumes the entire timeout budget and the remaining indexes are never attempted — the run then reports a failure naming only that one index. Issuing the creates with --async and polling afterwards converges instead of stranding the tail.

Product invariants affected

  • INV-AGENT-*: JIT tools and both proactive lanes stay behind authenticated, bounded, manifest-owned execution paths.
  • INV-AUTH-1: existing Firebase identity remains the user authority; dev compute/data selection cannot retarget its audience.
  • INV-CHAT-1: evidence remains supplemental metadata on the shared assistant transcript.
  • INV-DATA-1: production routing is unchanged; QA targets require complete local-dev-GCP or deployed-dev endpoint tuples.
  • INV-NAV-1: evidence and proactive surfaces reuse existing conversation, Rewind, detail, and task navigation owners.
  • INV-MEM-1: legacy tiers remain a compatibility projection while generated content is preserved as labelled history.
  • INV-MEM-2: vector hits remain candidate IDs and require authoritative hydration before disclosure.
  • INV-MEM-3: all current and historical reads remain mediated by the fail-closed universal memory authority.
  • INV-MEM-4: daily sweep is automatic and owner-private, and only dedicated ledger authority writes ledger rows.
  • INV-TASK-1: JIT task evidence projects the canonical task owner rather than creating a second mutable task store.
  • INV-TASK-2: automatic capture remains suggestion-only and cannot silently promote third-party commitments.
  • INV-MEM-6 remains proposed until the rollout/adoption/rollback gates ratify cutover.

What does NOT change

  • Non-cohort users: conversation finalization, chat retrieval, the memories tab, export, and deletion behave exactly as before (verified by the changed-backend fanout, hermetic E2E, and mixed-version parity tests).
  • Production routing, Firebase identity, deletion/legal-hold controls.
  • This PR does not create cohorts, enroll users, run migrations, or deploy anything by merging.

Validation

  • Fresh-head backend conflict/regression matrix: 513 passed; hermetic E2E 116 passed / 3 skipped; web chat/evidence 19 passed; macOS ledger/JIT 66 passed; generated OpenAPI/Swift/TypeScript/Dart/Firestore-index/runtime-env checks exact.
  • Windows: full suite 5,502 passed / 29 skipped plus typecheck and lint; independent Sol review accepted with no P0/P1/P2.
  • Backend, macOS, and desktop-agent independent Sol reviews accepted at exact head; 691-test desktop agent runtime suite passed four consecutive runs.
  • Real Firestore-emulator migration/revert/reservation harnesses passed, including interruption/resume, byte-stable no-op rerun, privacy races, and real contention.
  • Repository PR preflight: 131 checks green; guarded pre-push (120-file changed-backend fanout, generated outputs, Swift build, Dart/Black formatting) green.
  • Isolated QA bundles (deployed-dev and local-dev-GCP) reached authenticated owner-ready state with deep strict code-sign verification; local bundle SHA-256 e41c6b53d84b47eea9073abac8015534830241f6ee460f47e8251e5f3b3ccf39.
  • Operational gates that intentionally remain open: human review, PostHog cohort creation/live resolution, 14-day and 95%-per-platform adoption, seven days of zero legacy reads/writes, rollback rehearsal, dogfood measurements, destructive retirement, final acceptance metrics.

Line-count exceptions

Line-Count-Exception: backend/database/conversations.py | 1962 -> 1974 | Keeps conversation deletion and source-retraction fencing in the existing transaction owner.
Line-Count-Exception: backend/database/memory_apply_store.py | 1932 -> 2883 | Keeps ledger apply, evidence staging, collision checks, rollback state, and privacy scrubbing inside the canonical Firestore transaction boundary.
Line-Count-Exception: backend/database/users.py | 2213 -> 2296 | Keeps deletion-generation and account-state reads in the existing user persistence owner.
Line-Count-Exception: backend/routers/chat.py | 1920 -> 1935 | Validates bounded evidence metadata at the shared chat persistence boundary without introducing another route owner.
Line-Count-Exception: backend/routers/conversations.py | 1917 -> 1955 | Routes deletion and cascade-retraction through the existing conversation API authority.
Line-Count-Exception: backend/routers/users.py | 2235 -> 2247 | Keeps export and deletion admission on the existing authenticated user routes.
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 2355 -> 2476 | Preserves the existing conversation finalization owner while adding canonical memory sweep handoff and failure fencing.
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 2606 -> 3450 | Keeps ledger compatibility mutations, owner checks, bounded history, lifecycle, and deletion projections behind the established canonical adapter.
Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 0 -> 4970 | Centralizes the daily canonical-memory formation state machine, the summary-spine agent producer, deterministic budgets, source fences, and replay-safe tests around one transaction-oriented workflow owner.
Line-Count-Exception: backend/utils/memory/memory_service.py | 2898 -> 3922 | Keeps bounded current and historical reads, trigger tools, canonical mutation readiness, and closed-history guards behind the universal memory authority.
Line-Count-Exception: backend/utils/other/storage.py | 1686 -> 1840 | Applies one owner-deletion gate across the existing GCS and local-storage mutation surface without creating a second storage client.
Line-Count-Exception: backend/utils/retrieval/agentic.py | 1550 -> 1635 | Carries bounded evidence and historical-query authority through the shared retrieval callback and core-tool registry.
Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarView.swift | 3012 -> 3127 | Adds the native bounded proactive preview and feedback controls within the floating bar's existing presentation owner.
Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarWindow.swift | 5309 -> 5311 | Preserves existing window ownership while routing the proactive preview state into that owner.
Line-Count-Exception: desktop/macos/Desktop/Sources/MainWindow/DesktopHomeView.swift | 1639 -> 1643 | Wires existing JIT navigation through the current desktop home composition root.
Line-Count-Exception: desktop/macos/Desktop/Sources/MainWindow/Pages/TasksPage.swift | 6668 -> 6680 | Keeps JIT task evidence navigation on the existing task-page authority.
Line-Count-Exception: desktop/macos/Desktop/Sources/OmiApp.swift | 1627 -> 1632 | Starts the JIT runtime from the existing application lifecycle composition root.
Line-Count-Exception: desktop/macos/Desktop/Sources/ProactiveAssistants/Assistants/TaskExtraction/TaskAssistant.swift | 1766 -> 1770 | Reuses the existing task proposal authority while preserving approval-independent task capture policy.
Line-Count-Exception: desktop/macos/Desktop/Sources/Providers/ChatProvider.swift | 6870 -> 6987 | Keeps JIT citations, feedback, and historical-tool results on the existing authenticated chat session owner.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/MemoryStorage.swift | 1014 -> 1837 | Keeps the durable lifetime ledger mirror, staging schema, and purge convergence in the existing local memory-store authority.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3481 -> 3540 | Adds nullable ledger compatibility columns and deletion indexes to the existing Rewind migration owner.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/UI/RewindPage.swift | 1529 -> 1607 | Adds bounded evidence-card navigation and feedback to the existing Rewind page without a parallel route owner.

Failure-Class: none

@mintlify

mintlify Bot commented Aug 23, 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 23, 2026, 8:42 AM

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

@Git-on-my-level Git-on-my-level changed the title feat: add JIT knowledge ledger foundation feat: add JIT knowledge ledger foundation and guarded adoption Aug 23, 2026
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from baa0f86 to c2f1a28 Compare August 23, 2026 16:49
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 44c4dbc to 20de7d2 Compare August 23, 2026 19:35
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 20de7d2 to 66f5daf Compare August 23, 2026 20:36
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 66f5daf to 1d1e580 Compare August 23, 2026 21:57
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 1d1e580 to 72d5693 Compare August 23, 2026 22:29
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 72d5693 to c55d57d Compare August 23, 2026 23:34
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 5aa974b to 0c866f1 Compare August 25, 2026 05:23
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from e63f20b to 4c161a3 Compare August 25, 2026 20:34
@Git-on-my-level
Git-on-my-level force-pushed the codex/jit-processing-end-state branch from 4c161a3 to 145b0c2 Compare August 25, 2026 23:05
Git-on-my-level and others added 7 commits August 26, 2026 17:00
…urface

Same pyright-masked pattern as the harness and test_chat_quota repairs:
- test_desktop_transcribe stubbed utils.llm as a non-package, so
  routers.chat's new utils.llm.gateway_client import could not resolve
  (50 failures); the submodule is now in its stub list.
- test_paywall_reconnect_gate's BYOK escape-hatch tests never set the
  request uid context that the enrollment-verifying rewrite requires
  (middleware sets it in production); they now do, and teardown clears it.
- test_chat_session_app_identity's enforce_chat_quota stub rejected the
  new required_llm_provider keyword.

All three suites pass locally (69 + 35 + 6).

Co-Authored-By: Claude Fable 5 <[email protected]>
PR #11454 moved macOS BYOK activation to enrollment-verified
fingerprints (isByokActive and usableBYOKEnvironment gate on
persistEnrolledFingerprints), and its own test lanes shipped red: the
tests store raw keys but never enroll them, so every key reads as
inactive. Their teardowns already clear enrollment — the setups now
enroll what they store, matching the production activation path. All 8
previously-failing cases (BYOKPaywallTests + the two
AgentRuntimeProcessTests BYOK-environment cases) pass locally.

Co-Authored-By: Claude Fable 5 <[email protected]>
The sweep's five deployment inputs were pinned off in every environment, so
cohort enrolment alone could never start it -- turning it on for a dogfood
account required a second PR. Development now carries the live values:

- ENABLED/MODEL_ENABLED on, so the job stops exiting at its first authority
  gate and the model authority can budget a route.
- MODEL_NAME pinned to gpt-5.6-luna, which is the declaration interlock the
  runner checks against get_model('memories') before any provider call.
- MAX_MODEL_COST_USD 0.80, the worst-case pre-call ceiling for a maximal day
  including phase B's clamped draft/reason/lookup overhead.
- COHORT_ENABLED on with COHORT_FLAG daily-memory-sweep-v1, so enrolment is a
  per-uid PostHog boolean and an unnamed cohort stays a closed rollout.

Production is deliberately untouched and stays fully pinned off. The job still
cannot form a memory for anyone until that flag exists and resolves true for a
uid, which remains a control-plane action rather than a deployment one.

Co-Authored-By: Claude Fable 5 <[email protected]>
Both conflicts are the same two defects this branch had already repaired
during the previous sync, which main has since fixed independently and
better. Main's versions win outright:

- AppState.swift: identical Xcode 16.4 SILGen dodge, with a comment that
  names the crashing pass and the commit that introduced the property.
- BYOKPaywallTests.swift: factors the fingerprint enrolment into an
  enroll(_:) helper, and re-enrols openrouter after setAllBYOKKeys()
  rewrites its key -- a fingerprint invalidation this branch's version
  did not account for.
The six daily-sweep occupant lookups were the only declarations in the
manifest without a trailing __name__ field -- 63 of 69 entries carry one,
and main had none missing it. Firestore appends the terminator itself and
reports the index back that way, so these six could never match the live
inventory.

The failure mode is not a missing index; the indexes build fine. It is that
reconciliation never converges: every run reports the same six as missing,
tries to create them, and fails on ALREADY_EXISTS. That takes down the
Firestore schema workflow on both environments permanently, and with it the
development backend deploy's readiness gate -- the same class of outage the
workflow's own header records from the hourly_usage index in PR #11979.

The derived specs previously appended their extra predicates to the base
spec's index_fields, which would have placed them after the terminator, so
the shared prefixes are now named explicitly and each spec ends with
__name__. Verified against real Firestore: reconciliation reports zero
missing indexes in both based-hardware and based-hardware-dev.

Co-Authored-By: Claude Fable 5 <[email protected]>
Both conflicts are adjacent additions, resolved as unions rather than by
choosing a side:

- firestore_index_registry.py: this branch's five JIT query specs and main's
  MESSAGES_BY_SESSION_ORDERED_QUERY are all kept and all registered in
  QUERY_SPECS.
- desktop/windows useChat.ts: this branch's chat-evidence import and main's
  pre-send quota gate are independent; both are kept.

Regenerating firestore.indexes.json from the merged registry drops one
conversations entry that git's textual merge of the generated file had
duplicated. Verified after regeneration: 72 indexes, zero duplicates, main's
messages/chat_session_id index present, and no entry missing its __name__
terminator.
Fence direct JIT tools and frame pixels, keep Windows account wipes safe after optional schema failures, and repair inherited CI regressions.

Failure-Class: none
@Git-on-my-level
Git-on-my-level merged commit 2af0832 into main Aug 27, 2026
47 of 49 checks passed
@Git-on-my-level
Git-on-my-level deleted the codex/jit-processing-end-state branch August 27, 2026 18:18
Git-on-my-level added a commit that referenced this pull request Aug 30, 2026
…ay (#12403)

## What

The daily memory sweep recognizes its own already-committed canonical
write when it replays after a crash, instead of superseding it with a
duplicate.

## The defect

`backend/scripts/daily_memory_sweep_emulator_test.py` — the
crash-after-canonical-before-receipt scenario — fails deterministically
on `main`, and has since #12084 introduced it. Reproduced 3/3 at
`origin/main`, at `c01861f3cf34`, and at `2af083251c` itself. It has
never passed on merged main.

Two behaviors combine:

1. `_claim_receipt` (`daily_memory_sweep.py:2175`) leases a receipt
claim for `RECEIPT_LEASE` (10 min), and the default claimant is a fresh
UUID per invocation (`:2854`). The next day's run is therefore always a
"different claimant" with an expired lease, so it silently re-claims and
redoes the work. That is by design and is safe when the redo is *exact*
— the apply layer's deterministic `_row_id` then yields
`idempotent_skip`.
2. `_apply_candidate` (`:2653`) breaks exactness for slotted facts. The
occupant it finds is *this same candidate's own write from the crashed
attempt*, but it matches the `sweep_slot_refresh` rule intended for
legitimate day-N+1 refreshes, so it takes the `amend` path. `amend_fact`
sets `supersedes=[prior]`, `_row_id()` hashes `supersedes`, the row id
changes, and deterministic idempotency never fires.

Result per event: the row self-supersedes. One correct active row
remains — this is not data loss and no wrong fact is shown — but it
leaves a phantom superseded version, duplicate operation and commit
rows, ~4 spurious outbox events that re-trigger downstream consumers,
and telemetry reporting `committed` where it should report `skipped`.
That last part is why this would not surface during a ramp: the health
metric lies in the same direction as the bug.

## The fix

Recognize the replay through the ledger's own sanctioned mechanism.
`evidence_id_for_ledger_provenance` hashes `{uid, source_id,
source_type, source_version, action_id}`, and the sweep's `action_id` is
deterministic per `(uid, local_date, source_key)` — invariant across the
add-vs-amend replay, while a next-day sweep derives a different
`_plan_id` and therefore a different identity. So a genuine slot refresh
is untouched; only the crash replay is recognized.

An occupant whose evidence is unreadable falls through to the ordinary
authority rules rather than suppressing a write it cannot account for.

## Evidence

- Emulator proof passes with the change (3 runs) and fails without it (3
runs) — verified by applying and reverting.
- The same test asserts the two behaviors that already worked, so both
are held: the crash still leaves exactly one pending receipt, and a
concurrent different claimant is still fenced with
`source_idempotency_conflict`.
- `tests/unit/test_daily_memory_sweep.py`: 51 passed. The first draft of
this change crashed
`test_sweep_slot_refresh_amends_sweep_occupant_but_never_user_statements`
on an occupant stub without `evidence`; that is what the defensive read
above fixes.
- Other scenarios in the emulator proof (deletion race, generation
contention, rollover, overlapping runners, paid-wipe) still pass.

## Why this was invisible

No workflow in `.github/workflows/` runs the Firestore emulator proofs —
they are local-only. `FC-daily-memory-sweep-fence` names
`daily_memory_sweep_emulator_test.py` as its canonical prevention
artifact, so the registry reads as covered while the guard was red on
main and never executed. Wiring these proofs into CI is the durable fix
and is not attempted here.

## Blast radius

The vulnerable window is between the canonical apply commit and the
`_finish_receipt` transaction (~100-300 ms per candidate). It does not
need a process crash — a residual post-retry failure of that one
transaction is enough; a Cloud Run Job task kill mid-batch also lands in
it. Because the receipt stays pending and the scheduler revisits pending
dates, every crash-in-window deterministically becomes a corruption
event on the next run. Order of magnitude ~1e-4 per user-day: negligible
at the current 2 enrolled accounts, roughly monthly at ~300, and worse
than linear because a larger batch also runs longer.

Failure-Class: FC-daily-memory-sweep-fence

Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 4970
-> 4994 | Splitting a ~5000-line transactional module is a strictly
larger risk than this 24-line correctness fix, which is an early-return
recognition inside one existing branch. The split is worth doing, but
not in the same change that repairs a red crash-recovery guard.

## Product invariants affected

- INV-MEM-1 — Held, unchanged. No tier is added, renamed, or split; the
change adds no collection and touches no tier assignment or access
policy. It only decides whether an already-committed canonical row is
re-applied.
- INV-MEM-4 — Held, and strengthened. Canonical promotion remains the
sole Long-term authority and every pending item still gets exactly one
terminal route. Before this change a crash replay gave one candidate a
*second* apply — a duplicate operation and commit against a row that had
already taken its route. Recognizing the landed effect restores the
one-item-one-route property; the skip is accounted as `skipped` on the
receipt rather than silently reported as a fresh `committed`.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12403?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 30, 2026
The crash-after-canonical-before-receipt scenario in the emulator proof has
failed since BasedHardware#12084 introduced it, on every ref tested. A replay always
presents a fresh claimant, so the expired 10-minute receipt lease is
re-claimed and the candidate re-applied. That is safe only while the redo is
exact; for a slotted fact the occupant found is the crashed run's own write,
which matches the day-N+1 slot-refresh rule and takes the amend path. The
resulting supersedes list changes the row id, so the apply layer's
deterministic idempotency never fires and the row self-supersedes.

Recognize the landed effect through evidence_id_for_ledger_provenance, whose
identity is invariant across the add-vs-amend replay but differs for a
genuine next-day refresh. An occupant with unreadable evidence falls through
to the ordinary authority rules rather than suppressing an unaccounted write.

Failure-Class: FC-daily-memory-sweep-fence
Git-on-my-level added a commit that referenced this pull request Aug 30, 2026
…12410)

## Live production regression

`https://api.omi.me/v1/conversations/from-segments` on PROD has been
returning 500 for most requests since 2026-08-28T01:58Z. Measured over
the 6h to 2026-08-30T01:00Z: **393x 500, 130x 200, 6x 422 — a 74%
failure rate**, steady at 200-480 exceptions/hour.

Every failure is:

```
LegalHoldAuthorityUnavailable: destructive operation gate is not active in this context
```

## Cause

Bisected by log sampling: zero occurrences at 2026-08-27T12/16/20Z and
2026-08-28T00Z; first occurrence 2026-08-28T01:58:07Z on prod revision
`backend-add08a4-33114042056-1` (created 01:43Z), the deploy after
`backend-932e2f5-33095639201-1`. The only commit in `932e2f5..add08a4`
touching the implicated files is `2af083251c` — **#12084, the JIT
knowledge ledger foundation** — which added both the import and the
failing line.

`replace_conversation_source_firestore` requires
`explicit_memory_deletion` authority for an empty write set
(`memory_apply_store.py:1345`, *"empty replacement requires privacy gate
authority"*). That rule is deliberate and correct: emptying a
conversation's replacement set normally **retracts** its canonical rows.

The caller keys that decision on `not items`. Emptiness is a proxy for
two different things:

- *"remove this conversation's rows"* — genuinely destructive, and the
explicit-deletion callers hold a `destructive_operation_gate` (7 sites
in `canonical_memory_adapter.py`, plus `memory_service.py:137`), so
those work;
- *"this conversation produced no memories"* — an ordinary outcome.
Conversation finalization holds no gate, so `routers/developer.py:1824
-> process_conversation -> memory_service.py:3848 ->
replace_conversation_sourced_memories` raised and the request 500'd
unhandled through the ASGI stack.

## Change

Emptiness cannot distinguish the two callers, but the gate can — so ask
it, without letting the answer be fatal. When there are no extracted
items **and** no existing rows for the conversation, attempt to read the
deletion token: holding it means a deliberate deletion, so fall through
unchanged; not holding it means there is provably nothing to do and no
authority is required, so return a no-op.

Three cases, all preserved:

| State | Behavior |
|---|---|
| No items, no existing rows, no gate — conversation extracted nothing |
No-op return. **This is the prod fix.** |
| No items, no existing rows, gate held — explicit retraction removing
nothing | Falls through and still records the replacement, advancing
`source_generation`. |
| No items, existing rows to retract | Never reaches the short-circuit;
still refused without authority. |

**This does not relax the gate.** An empty replacement that would
genuinely retract rows has a non-empty `expected_source_items` and never
reaches this branch.

A first attempt short-circuited on emptiness alone. The repo's pre-push
gate caught it:
`test_ws_j_delete_privacy.py::test_memory_service_retract_records_empty_source_replacement`
asserts that an explicit retraction removing nothing must *still* be
recorded (`source_generation` 1 -> 2). That WS-J audit contract is why
the condition keys on the gate rather than on emptiness.

## Tests

Two added, in the file that already owns this boundary's contract:

- `test_conversation_yielding_no_memories_is_a_noop_not_a_deletion` —
reproduces the exact production exception without the change, and
asserts the destructive path is never reached (`injector.calls == 0`)
and control state is untouched.
- `test_empty_replacement_over_existing_rows_still_demands_the_gate` —
commits a row, then empties the same conversation, and asserts
`LegalHoldAuthorityUnavailable` is still raised and the row survives.
This is the half that keeps the repair from becoming a relaxation.

The pre-existing
`test_memory_service_retract_records_empty_source_replacement` is the
guard for the recorded-retraction case and passes unchanged.

Verified by reverting: the first new test fails with the production
exception, the second passes in both states. With the change: 5 + 3 + 39
passed across `test_conversation_replacement_backoff.py`,
`test_cascade_retract_convergence.py`, and
`test_ws_j_delete_privacy.py`.

## Note on scope

Fixing this on `main` reaches development only. **The production deploy
is a separate authorized step and is not part of this PR.**

Two things worth checking separately, not addressed here:
`process_conversation` is shared with normal mobile/desktop conversation
finalization, so the blast radius is likely wider than the developer
endpoint; and prod shows scattered 500s on `/v3/memories/{id}` (many
distinct ids, ~1 each) that may be unrelated.

Failure-Class: new

Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
3450 -> 3491 | The change is a 12-line guarded early return plus a
multi-line import; the remaining lines are the comment explaining why
returning before the destructive boundary is not a relaxation of the
deletion gate. That reasoning is the part a future reader most needs,
and a subtle compliance boundary is the wrong place to trade it for line
count. Splitting this module is worth doing, but not in the change
repairing a live 74%-failure production regression.

## Product invariants affected

- INV-MEM-4 — Held, and restored. Canonical promotion remains the sole
Long-term authority, and every pending item still takes exactly one
terminal route. The short-circuit fires only when there are no items and
no existing conversation-sourced rows, so no item exists to be routed
and none is created, promoted, archived, or retracted. Before this
change that state did not take a route at all — it raised, failing the
whole conversation enrichment, so the conversation got neither memories
nor a summary.
- INV-MEM-1 — Held, unchanged. No tier is added, renamed, or split; no
collection is created; no tier assignment or access policy is touched.
The change only decides whether to enter a write boundary that would
perform no writes.

## Blast radius (measured after opening this PR)

The developer endpoint is not the only caller. Grouping the app frames
across 25 prod tracebacks from the last 2h, every one converges on the
same call site — `canonical_memory_adapter.py:2029`, via
`memory_service.py:3831` and `process_conversation.py` — but they arrive
from three different entries:

| Entry frame | Occurrences |
|---|---|
| `routers/conversations.py:336` | 8 |
| `utils/conversations/lifecycle.py:323` | 7 |
| `routers/developer.py:1776` | 4 |

`routers/conversations.py` is the ordinary client-facing conversation
route, so this is affecting real client traffic, not only the developer
API. Because all paths funnel through the single guarded call site, this
change covers all of them.

Backend 5xx by endpoint over 3h for context: `/v3/memories/{id}` 263,
`/v1/conversations/from-segments` 157, `/v3/memories` 153,
`/v1/conversations` 15, `/v1/conversations/{id}/reprocess` 8. In a
90-minute sample of ERROR entries, 26 of 27 were this exception.

**Not characterized:** whether the `/v3/memories` and
`/v3/memories/{id}` 5xx share this cause. They did not appear as entry
frames in the traceback sample, and HTTP-request log entries do not join
1:1 with traceback entries, so they may be a separate fault. One
`RuntimeError: canonical write failed: ApplyStatus.invalid_patch (add
patch new_memory_id already exists)` also appeared. Worth a look
independently of this change.
Git-on-my-level added a commit that referenced this pull request Aug 30, 2026
## Why

Nothing runs the Firestore emulator proofs. Verified 2026-08-30: no
workflow in `.github/workflows/` invokes `emulators:exec`, and none
references any `*_emulator_test.py`. They execute only when someone runs
them by hand.

They are the strongest correctness evidence the memory system has —
crash recovery, deletion races, account-generation contention, day
rollover, overlapping runners, writer cutover — against a real Firestore
emulator, covering classes that fakes cannot reach and a green deploy
does not reveal.

The cost of that gap is concrete. The daily-sweep crash-replay proof was
**red on `main` from the day #12084 introduced it until #12403 repaired
it**, and nobody knew. Worse,
`.github/failure-classes/FC-daily-memory-sweep-fence.json` names
`daily_memory_sweep_emulator_test.py` as that class's
`canonical_prevention_artifact` — so the registry read as covered while
the guard was never executed. A guard artifact CI does not run is worse
than no guard, because it is counted as coverage.

In the same window, #12084 also shipped two live production regressions
of exactly the class these proofs cover (`LegalHoldAuthorityUnavailable`
on conversation finalization, since fixed in #12410; and a duplicate
`new_memory_id` on `/v3/memories`, still open). Both ran for two days.
Neither was surfaced by a test or an alarm — they were found by grepping
service logs after an unrelated deploy.

## What this adds

`backend/scripts/run-emulator-proofs.sh` and a `Backend Emulator Proofs`
workflow that runs it under `firebase emulators:exec`, on backend
memory/database changes.

`firebase.json` already pins the Firestore emulator to `127.0.0.1:8085`,
so `emulators:exec` supplies `FIRESTORE_EMULATOR_HOST` and tears the
emulator down afterwards — a failing proof cannot leave one holding the
port.

The script's environment mirrors `_subprocess_env()` in
`jit_qa_orchestrated_dogfood.py`. `MEMORY_MODE=read` is required: the
production canonical-intake fence defaults to off, and without it every
write-path scenario fails closed with `CanonicalMemoryIntakePausedError`
— a harness precondition, not a defect.

Gating proofs:

- daily sweep — crash / deletion / generation / paid-wipe
- ledger correction, revert, standalone reopen, privacy fence
- writer cutover / rollback / rollforward

## The arbitration proof runs but does not gate

`jit_proactivity_reservation_emulator_test.py` is intermittent against a
freshly started emulator. It deliberately runs concurrent transactions
to prove cross-device reservation, and a cold emulator sometimes loses
them: `Aborted: 409 Transaction lock timeout`, surfacing as `ValueError:
Failed to commit transaction in 5 attempts`. When it completes it
reports correct semantics (`planned=['reserved','rejected']`,
`full_turns=['rejected','reserved']`), so this is an emulator limit
rather than an assertion failure.

Measured today: 3/3 passes against a long-warmed emulator; then two
consecutive failures and one pass under fresh `emulators:exec`,
including a failure when run alone — so it is not accumulated state from
the preceding proofs. Warm-up looks like the mechanism, but that is a
handful of runs, not a characterisation, and the comment in the script
says so.

It therefore runs, reports, and does not gate. Making it fatal would
redden the lane unpredictably, and a lane that fails for reasons nobody
trusts is one nobody reads — precisely the failure this lane exists to
correct. Making it silent would throw away the signal. Characterising
the contention and promoting it back to gating is the obvious follow-up.

## Not a required check

A new workflow is not automatically in branch protection, so this
reports without blocking. Promote it to required once it has a stable
green history — deliberately not done here, since a brand-new lane
gating every backend memory change is how a lane gets disabled instead
of fixed.

## Verification

Run end to end locally against `origin/main` under `firebase
emulators:exec` with Temurin 21: all three gating proofs pass, and the
full run reports `All emulator proofs passed.` The script was also
observed correctly failing the lane (exit 1, named failure) when a proof
genuinely failed, before the arbitration proof was made non-gating.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12411?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. -->
Git-on-my-level added a commit that referenced this pull request Aug 30, 2026
…equires (#12443)

## What broke

Live-captured conversations stopped finalizing in production at
**2026-08-30T15:21:42Z** and are still failing.

The pusher had not deployed since **2026-07-01** (`2ae7f78841`). #12429
fixed the pre-Helm capacity gate that was failing the lane, and the
rollout that followed (Helm applied 15:16:28Z, complete 15:28:51Z)
carried two months of change onto a Deployment whose environment was
never extended to match.

The old pusher never ran this code. Its opcode-104 handler called
`process_conversation` directly and never touched the durable-job
architecture. Today is the **first time the pusher has ever executed
`finalize_persisted_conversation`** — cold activation of a dormant
subsystem, not a contract drift. Verified: `backend/routers/pusher.py`,
`backend/utils/listen_pusher_session.py` and
`_claim_finalization_job_txn` are byte-identical across
`6f7c57ac15..6134ebd`.

## Root cause

The pusher chart ships **68 env vars where backend-listen ships 115**,
and `MEMORY_ENABLED` is among the 50 it lacks. Confirmed against the
live cluster:

```
prod-omi-pusher          68 env vars, zero MEMORY_* vars
prod-omi-backend-listen  115 env vars, MEMORY_ENABLED=on
```

`rollout_mode_env_value()` fail-closes to `off` when the flag is unset
(`backend/config/memory_rollout.py`).
`MemoryService.ensure_canonical_mutation_ready()` — called
**unconditionally and unwrapped** by `_extract_memories_inner` for every
non-discarded conversation — then raises `HTTPException(503, "Memory
writes are globally paused")`. `finalizer.py` converts that to
`ConversationFinalizationError('processing_failed')`, and the listen
session retries roughly 4x per conversation.

Measured distribution in a clean window (23:00–23:10Z, all entries):

| Exception | Count | Share |
| --- | --- | --- |
| `HTTPException` (this bug) | 366 | 89.5% |
| `LegalHoldAuthorityUnavailable` | 43 | 10.5% |

This PR fixes the 89.5%. The remainder is a separate, older regression —
see below.

## Why nothing paged

`finalizer.py` logs only `type(error).__name__`. Production emitted
~16k/hour of bare `error=HTTPException` carrying no status code, no
detail and no traceback, so the signature read as already-known. The
listener itself stayed healthy throughout — WS connections in band, 5/5
ready pods, listen-LB 5xx at zero, every `Backend-listen` critical rule
inactive, and no client-side Sentry spike. Audio was captured and
transcribed; it simply never became a conversation.

## The fix

Set `MEMORY_ENABLED=on` for dev and prod pusher, matching
backend-listen. It is a plain literal, so it requires no key from the
pusher's ExternalSecret — deliberately avoiding the failure class from
#12298, where a chart consumed a secret key the ExternalSecret did not
enumerate.

The test asserts the **contract**, not the key: the env a chart ships
must resolve to a mode that permits memory writes, and the two co-hosts
may not disagree. Against the charts as they stood during the incident
it fails with `assert 'off' == 'write'`.

## Failure class

This reopens an existing class. Its prevention artifact,
`test_conversation_notes_v2_beta_rollout.py`, pins three named flags
across backend-listen and the Cloud Run backend. It does not generalize
to other flags, and it does not know the pusher is now a third host of
`process_conversation`.

Failure-Class: FC-rollout-flag-absent-from-a-cohost-of-its-code-path

## Deliberately not in this PR

- **The other 49 missing env vars**, including `GEMINI_API_KEY`,
`USE_VERTEX_AI`, `LISTEN_FINALIZATION_ORPHAN_STALE_SECONDS` and the
`FAIR_USE_*` set. Real exposure, but several are secret refs and
widening them under incident pressure risks the #12298 class. Needs its
own change.
- **`LegalHoldAuthorityUnavailable`** (10.5% of failures) —
`current_destructive_operation_token()` at
`backend/database/legal_holds.py:403`, reached from
`canonical_memory_adapter.py:2029`, requires an active
`destructive_operation_gate(...)` context that this call site never
enters. Introduced by #12084, first seen in prod 2026-08-28T01:51:36Z
and firing continuously for ~2.5 days on
`/v1/conversations/from-segments`. Independent of this bug and of
today's deploy.
- **`/v1/embeddings` 404s at the LLM gateway.** `prod-omi-llm-gateway`
runs image `c61d815` (2026-08-20), which predates #12337's gateway
embeddings route; `gcp_llm_gateway.yml` is dispatch-only and was never
run after that merge. Swallowed at `vector_db.py`, so not user-visible
as an error — but `save_structured_vector` has been failing silently
since ~13:44Z, meaning **no conversation created since then has a
summary vector in Pinecone**, and it will not self-heal without a
backfill. Fix is to deploy the gateway, not to change code.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12443?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 31, 2026
BasedHardware#12084 made replace_conversation_source_firestore require
explicit_memory_deletion authority for an empty write set, which is right when
emptying a conversation retracts its rows. The caller keys that on `not items`,
and emptiness also means "this conversation produced no memories" -- an
ordinary outcome. Conversation finalization holds no gate, so those requests
raised LegalHoldAuthorityUnavailable and 500'd: 393 of 529 requests to
/v1/conversations/from-segments on prod over six hours, since 2026-08-28T01:58Z.

Emptiness cannot separate the two callers, so ask the gate instead without
letting the answer be fatal. Holding it means a deliberate deletion and still
records the replacement; not holding it with nothing to write and nothing to
retract means no authority is required. An empty replacement that would
genuinely retract rows keeps a non-empty expected_source_items, never reaches
the branch, and is still refused.

Keying on emptiness alone also broke the WS-J contract that an explicit
retraction removing nothing is still recorded; that test is the guard.

Failure-Class: new
pull Bot pushed a commit to codingwatching/omi that referenced this pull request Aug 31, 2026
Nothing ran them. No workflow invoked emulators:exec or referenced any
*_emulator_test.py, so the strongest correctness evidence the memory system has
existed only when someone ran it by hand. The daily-sweep crash-replay proof was
red on main from the day BasedHardware#12084 introduced it until BasedHardware#12403 repaired it, while
FC-daily-memory-sweep-fence named that file as its canonical prevention
artifact -- the registry read as covered while the guard never executed.

Three proofs gate the lane: daily sweep, ledger correction/revert/reopen, and
writer cutover/rollback/rollforward. The arbitration proof runs for signal but
does not gate: it is intermittent against a cold emulator (409 transaction lock
timeout), and a lane that reddens unpredictably is one nobody reads.

Not added to branch protection; promote once it has a stable green history.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Sep 1, 2026
… row (#12524)

POST /v3/memories 500s at over a thousand requests per day since the #12084
deploy (2026-08-28): canonical write failed: ApplyStatus.invalid_patch (add
patch new_memory_id already exists), raised from create_memory through
write_canonical_extraction_memory.

Manual/API memory ids derive deterministically from content, but operation
identity folds the observed head commit into the operation id, so a duplicate
submission is replay-idempotent only while the account head has not moved.
Any other canonical write in between makes the duplicate propose a fresh
operation whose add collides with the existing row id — and a client
re-sending the same memory (retry, sync replay, re-import) gets a 500 for a
write that is already complete.

Resolve the collision at the write boundary: when the add's target row exists
with identical content and is still active, report the write complete with
the existing id and leave the row untouched. A collision with different
content (a client-supplied id reused for new text) or against a non-active
row keeps failing, so a resurrected id can never masquerade as a fresh
create; the privacy-deleted receipt branch is unchanged and still refuses.

Failure-Class: new

Co-authored-by: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 5, 2026
… fixture

Replaces the hardcoded exemption list added in the previous commit. Review was right that
the list is the defect, not the missing entry: it went stale between 2026-08-01 and the
alias landing in BasedHardware#12084, which is what turned a manifest addition into a red test.

I had claimed deriving was not possible. That was wrong, and I checked the wrong artifact —
`GeneratedToolCapabilities.swift` does not carry alias data, but this test does not read it.
It reads `agent/tests/fixtures/tool-manifest.json`, which carries both halves:

    get_screenshot:   executor.kind = localApiOnly, aliases = ["look_at_frame"]
    get_local_status: executor.kind = localApiOnly

So the exempt set is now computed from the fixture: a tool marked `localApiOnly`, plus any
alias inheriting its canonical entry's exemption. Nothing is hand-maintained, and the next
Local-API-only tool or alias is covered without editing this file.

An `XCTAssertFalse(localApiOnlyTools.isEmpty)` guards the derivation itself, so a fixture
that stopped marking executor kinds would fail loudly rather than silently exempting
nothing — which is the failure mode a derived set introduces and a literal list does not.

Verification: 23/23. Mutation-checked twice — dropping alias inheritance fails with
`Missing agent tool declaration for look_at_frame`, and (on the previous commit) dropping a
canonical name fails with its own missing-declaration error, so the assertion still has
teeth in both directions.

Failure-Class: none
undivisible pushed a commit that referenced this pull request Sep 7, 2026
…ion check (#12705)

* test(desktop): exempt the get_screenshot alias from the tool-declaration check

`ChatDiscoverabilityTests.testDesktopCapabilitiesExistInAgentToolDeclarations` fails on
`main`, in isolation:

    XCTAssertTrue failed - Missing agent tool declaration for look_at_frame

`look_at_frame` is not a tool of its own. `omi-tool-manifest.ts` declares it inside
`get_screenshot`'s `aliasCapabilityDocs`, and `LocalAgentAPIServer.swift:318` maps it
straight back:

    let canonicalToolName = toolName == "look_at_frame" ? "get_screenshot" : toolName

Both capability docs state "Local API only", so it is never advertised to the `pi-mono`
or `omi-tools-stdio` adapters the assertion reads — exactly like `get_screenshot`, which
the exemption list already covers.

The alias reached `DesktopCapabilityRegistry` in #12084 (2026-08-27); the exemption list
had not been touched since 2026-08-01, so the assertion has failed since that merge.

Adding the canonical name's alias to the same list is the narrow fix. Deriving aliases
instead would be better, but the alias relationship lives in the TypeScript manifest and is
not carried into `GeneratedToolCapabilities.swift`, so there is nothing to derive from on
the Swift side without changing the generator.

Verification: 23/23 in the suite. Mutation-checked — dropping `get_local_status` from the
same list fails the assertion with `Missing agent tool declaration for get_local_status`,
so the check still has teeth and this is an exemption, not a disablement.

Failure-Class: none

* test(desktop): derive the Local-API-only exemptions from the manifest fixture

Replaces the hardcoded exemption list added in the previous commit. Review was right that
the list is the defect, not the missing entry: it went stale between 2026-08-01 and the
alias landing in #12084, which is what turned a manifest addition into a red test.

I had claimed deriving was not possible. That was wrong, and I checked the wrong artifact —
`GeneratedToolCapabilities.swift` does not carry alias data, but this test does not read it.
It reads `agent/tests/fixtures/tool-manifest.json`, which carries both halves:

    get_screenshot:   executor.kind = localApiOnly, aliases = ["look_at_frame"]
    get_local_status: executor.kind = localApiOnly

So the exempt set is now computed from the fixture: a tool marked `localApiOnly`, plus any
alias inheriting its canonical entry's exemption. Nothing is hand-maintained, and the next
Local-API-only tool or alias is covered without editing this file.

An `XCTAssertFalse(localApiOnlyTools.isEmpty)` guards the derivation itself, so a fixture
that stopped marking executor kinds would fail loudly rather than silently exempting
nothing — which is the failure mode a derived set introduces and a literal list does not.

Verification: 23/23. Mutation-checked twice — dropping alias inheritance fails with
`Missing agent tool declaration for look_at_frame`, and (on the previous commit) dropping a
canonical name fails with its own missing-declaration error, so the assertion still has
teeth in both directions.

Failure-Class: none
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