Skip to content

feat(desktop): opt-in on-device embeddings with FTS hybrid retrieval; backend keyword fallback for screen search - #13456

Merged
Git-on-my-level merged 40 commits into
mainfrom
feat/desktop-local-embeddings-hybrid
Sep 21, 2026
Merged

Git-on-my-level merged 40 commits into
mainfrom
feat/desktop-local-embeddings-hybrid

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Desktop local embeddings: Apple NLContextualEmbedding (OS-managed, zero in-app download) is the first production engine, opt-in. Production-family bundles keep today's Gemini screen search; non-production dogfoods hybrid. A failed probe (once enabled) stays keyword-only (recordFallback to keyword). OMI_DISABLE_LOCAL_EMBEDDINGS remains the hard kill.
  • Hybrid retrieval (FTS + cosine, RRF) now covers screenshots, transcript chunks (window 8 / stride 6), and local memories behind a sourceKind filter, so search_screen_history stays screen-only. Cloud upload is unchanged. Session/memory completion never awaits NLCE.
  • Backend search_screen_activity keeps a bounded Firestore keyword fallback when vectors miss. Timestamp bounds reuse normalize_screen_activity_timestamp. SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS is a temporary server-owned opt-out (fail-closed CSV parse) until the plan/entitlement resolver owns it.

Why

Per-frame Gemini embedding is expensive. Phone search is Pinecone-only. Local-first free-tier retrieval needs an on-device vector + FTS path that never spends Gemini when the Apple probe fails. The ratified slice is measure-first: released behaviour must stay unchanged until the on-device benchmark and energy measurement land.

Product invariants affected

  • INV-AUTH-1 — Local embedding writes use RewindCaptureOwnerSnapshot and LocalMutationAuthorization leases; this does not change Firebase session death or AuthSessionCoordinator.
  • INV-CHAT-1 — search_screen_history / search_transcripts remain tools on the existing kernel conversation. Local hybrid hits are not a second transcript store.
  • INV-MEM-1 — local_embeddings(sourceKind=memory) is a retrieval projection of existing memories rows, not a fourth product memory tier.
  • INV-CHAT-2 — ChatScrollLiveEdgeTests.swift is this invariant's guard test; the only change is the test harness's main-run-loop drain (pump to the deadline instead of a single run(mode:before:)). No scroll ownership, placement, or virtualization behaviour changes; the guarded assertions are unchanged.

Failure-Class

Failure-Class: none

Coordinator defects (canonical timestamp bounds, UID flag parse, DefaultsKey) are instance fixes with regression tests, not a recurring ownership failure.

Line-Count-Exception

Line-Count-Exception: desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift | 5019 -> 5071 | reason: register local_embedding_benchmark next to local_summary_benchmark; body lives in LocalEmbeddingBenchmark.
Line-Count-Exception: desktop/macos/Desktop/Sources/Providers/ChatToolExecutor.swift | 3852 -> 3896 | reason: route search_screen_history through ScreenHistorySearchRoute and dispatch search_transcripts to ChatLocalHybridTool; new search body is not in this file.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/MemoryStorage.swift | 1837 -> 1860 | reason: index memories into local_embeddings on insert/update; table/FTS live in LocalEmbeddingStore.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3630 -> 3633 | reason: foundation migration hook only; store and search live in new files.
Line-Count-Exception: backend/database/firestore_index_registry.py | 1542 -> 1557 | reason: register SCREEN_ACTIVITY_KEYWORD_RANGE_QUERY so keyword fallback is a named serving spec.

What changed

Backend

  • backend/utils/retrieval/tools/screen_activity_tools.py — keyword fallback, canonical timestamp bounds, fail-closed UID opt-out.
  • backend/tests/unit/test_screen_activity_evidence.py — window-edge document and whitespace UID parse.
  • backend/utils/retrieval/ARCHITECTURE.md — keyword fallback + env flags.

Desktop — runtime

  • LocalInference/LocalEmbeddingService.swift, LocalEmbeddingRuntime.swift, LocalEmbeddingKillSwitches.swift, LocalEmbeddingProbeCache.swift — port, probe, in-process cache (TTL + thermal/kill-switch key), fail-closed ladder, production-family opt-in (isEnabled).
  • LocalInference/AppleNLContextualEmbeddingEngine.swift — actor (NL types are not Sendable): English model, multilingual fallback, bounded requestAssets, mean-pool + L2, chunk over max length.

Desktop — storage / search

  • Rewind/Core/LocalEmbeddingStore.swift — local_embeddings, transcript_chunks + FTS5, memories_fts, sourceKind filter.
  • Rewind/Services/LocalHybridSearch.swift — hybrid ranker; .none → FTS-only; .disabled → Gemini (opt-out and hard kill).
  • Rewind/Services/LocalEmbeddingIndexer.swift, LocalInference/TranscriptChunker.swift — session finalize, memory insert/update, AC-bounded backfill. Indexer is a no-op when not opted in.
  • Providers/ChatLocalHybridTool.swift — search_transcripts.
  • Providers/ChatToolExecutor.swift — screen search route + transcript tool dispatch.
  • Rewind/Core/MemoryStorage.swift, TranscriptionStorage.swift, Rewind/Services/RewindIndexer.swift — index hooks / AC backfill. Session and memory completion capture the owner snapshot then Task(priority: .background) so they never await NLCE.

Desktop — benchmark / gates

  • LocalInference/LocalEmbeddingBenchmark.swift — synthetic fixture, recall@10 / nDCG@10.
  • DesktopAutomationBridge.swift — local_embedding_benchmark action (non-production).
  • changelog/unreleased/2026-09-10-local-hybrid-search.json, e2e/flows/local-hybrid-search.yaml.
  • LocalInference/ARCHITECTURE.md, desktop/macos/AGENTS.md.

How to enable locally

Default OFF on production-family bundles (stable and Beta). Default ON on non-production (AppBuild.isNonProduction).

  • Enable on a production-family bundle: UserDefaults localEmbeddingsEnabled or OMI_LOCAL_EMBEDDINGS=1.
  • Turn off even in non-production: OMI_LOCAL_EMBEDDINGS=0 (or false/off).
  • Hard kill (keep Gemini screen search): OMI_DISABLE_LOCAL_EMBEDDINGS=1 or UserDefaults disableLocalEmbeddings.
  • Pin an engine: OMI_FORCE_LOCAL_EMBEDDING_ENGINE=apple_nlce (unknown ids → keyword-only).
  • Backend keyword fallback: SCREEN_ACTIVITY_KEYWORD_FALLBACK_ENABLED (default on; 0/false/off disables).
  • Temporary vector opt-out: SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS (comma-separated UIDs; * disables globally). Server-owned until the plan/entitlement resolver replaces it.

When enabled: probe pass → hybrid; probe/asset failure → FTS-only, never Gemini.

Headless benchmark (non-production bundle): ./scripts/omi-ctl action local_embedding_benchmark.

Verification

xcrun swift build --build-tests --package-path desktop/macos/Desktop
# Build complete.

xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbedding|LocalHybrid|ScreenActivity|Rewind'
# 302 passed, 0 failures.

xcrun swift test --package-path desktop/macos/Desktop --filter AppleNLContextualEmbedding
# 3 passed (system probe either embeds or reports assets_unavailable).

python3 desktop/macos/scripts/check_desktop_test_quality.py
# OK.

desktop/macos/scripts/swift-format-wrapper.sh lint-scope
# swift-format: clean.

desktop/macos/scripts/swiftlint-wrapper.sh lint
# 0 violations.

BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh
# 16 passed in test_screen_activity_evidence.py after timestamp + UID fixes.

python3 desktop/macos/scripts/check-sources-root-layout.py fails on origin/main itself (94 loose Sources-root Swift files vs baseline 77). All new sources in this PR are in feature directories. Do not fix that debt here.

Benchmark (synthetic)

In-repo synthetic fixture only. Engine test_hash. No personal data. Gemini blobs were absent on the fixture, so Gemini mode is omitted.

slice mode recall@10 nDCG@10
name_heavy fts 1.0 1.0
name_heavy vector 1.0 1.0
name_heavy hybrid 1.0 1.0
paraphrase fts 0.0 0.0
paraphrase vector 0.5 0.187
paraphrase hybrid 0.5 0.187
date_bounded fts 0.6 0.6
date_bounded vector 0.8 0.674
date_bounded hybrid 0.8 0.674

Hybrid paraphrase recall@10 ≥ FTS-only (asserted).

Also in this PR

  • RealtimeTurnEvidenceTests.swift (untouched by the feature) is wrapped in #if DEBUG around the three tests that assign the DEBUG-only testingAttachRealtimeUserEvidence seam. CI's release-mode test step (swift test -c release) only runs when a PR touches desktop tests, so this latent break from fix(desktop): defer native PTT evidence attach until its journal row exists #13235 first surfaced here. Tracked as Desktop release-mode test build broken on main since #13235: RealtimeTurnEvidenceTests uses a #if DEBUG seam unguarded #13458; this commit is the minimal guard so the lane can run.

  • ChatScrollLiveEdgeTests.swift (also untouched by the feature): drainMainQueue now pumps the main run loop until its 50 ms deadline. UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing fails order-dependently in CI's worker-0-2-h1 batch on an unmodified origin/main desktop tree too; the isolation re-run it triggers (38 suites × ~55 s) is what pushed the suite step past its 1800 s budget. Minimal harness fix, same pattern as two other test files.

Follow-ups

  • Flip the production default after the on-device benchmark on real Rewind DBs and the 8-hour energy measurement.
  • Free-tier gating of the Gemini flush (product decision; unchanged here).
  • Downloadable CoreML embedder behind a SHA-verified store.
  • Self-hosted embedder on the backend for cross-device vectors.
  • Replace SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS with the plan/entitlement resolver.

Commits

  • b91d3a214d feat(backend): add bounded keyword fallback for screen search
  • b323ab2d4c feat(desktop): add fail-closed local embedding runtime port
  • 25ba3a20b6 feat(desktop): add model-isolated local hybrid screen retrieval
  • 0b52cacf9c fix(backend): reuse canonical screen-activity timestamp bounds
  • 0ee5b102a4 fix(backend): fail-closed parse of screen vector opt-out UIDs
  • 3b355db015 feat(desktop): add Apple NLCE engine, probe cache, and hybrid transcript/memory indexing
  • 5c34682070 feat(desktop): add synthetic local embedding retrieval benchmark
  • 8c0365125d docs: document local embedding kill switches, keyword fallback, and e2e covers
  • 468808c4de fix(desktop): route local embedding kill switches through DefaultsKey
  • 4dd3ab5f1a docs(desktop): keep AGENTS.md under the lean byte budget
  • d2b6dc0856 docs(desktop): fix LocalInference ARCHITECTURE.md pointer path
  • 7733524500 fix(backend): register screen keyword fallback as a named Firestore query spec
  • 2d7391233d fix(desktop): keep released-bundle screen search on Gemini until local embeddings are opted in
  • 0fa0b7883e fix(desktop): never await local embedding on session or memory completion
  • df87de6f6a fix(desktop): use scoped locking in the capture-path embedding hang test
  • a20bab008b fix(desktop): park capture-path embedding hangs on an actor
  • cf48da50d2 fix(desktop): drop MainActor XCTest super.tearDown in local embedding tests
  • cae43203c7 fix(backend): keep the external-input shape check on screen vector hits typed as Any (pre-push pyright gate)
  • 6c4d3cfff3 fix(desktop): bound local embedding engine calls so a stuck NLCE cannot park the indexer
  • 818061b3bc fix(desktop): drain detached local embedding work before test teardown
  • 0fcadb3536 test(desktop): guard the DEBUG-only turn-evidence seam so the release-mode test build compiles (unblocks this PR's release lane; latent main breakage tracked in Desktop release-mode test build broken on main since #13235: RealtimeTurnEvidenceTests uses a #if DEBUG seam unguarded #13458)
  • b2ff5225c3 test(desktop): pump the main run loop to the deadline in the live-scroll drain (pre-existing order-dependent flake in UserScrollDetectorTests, reproduced on unmodified main; it cost CI's suite step its 1800s budget via per-suite re-runs)

CI note (2026-09-11)

@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.

All reported issues were addressed across 33 files

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

Re-trigger cubic

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor pass for this context — review-thread reconciliation only, no new commits (head stays dbde4c39).

Verified against the current head that the three outstanding review threads were already addressed by pushed commits, and resolved them:

Thread Concern Fixed by (verified in head) Status
LocalEmbeddingStore.swift backfill completeness partial/replaced sessions permanently skipped b8e5cb76c7 + 142e5c4672 + 8a092169cb — completed-only backfill selector, replaceTranscriptChunks delete-then-insert reconcile, stale-chunk mismatch detection Resolved
local-hybrid-search.yaml trivially-true expect flow never gated the benchmark result b4d02e9610 — expect: result.detail.kind: local_embedding_benchmark Resolved
LocalHybridSearch.swift keyword rank from recency FTS rank lost before RRF fusion b8e5cb76c7 — keywordCandidates returns rows in bm25() order, no recency re-sort; fusion derives rank from array position Resolved

All other review threads on this PR were already resolved. No new bot comments since the last push; all checks green except the two Desktop Swift jobs still pending on the existing head.

Git-on-my-level added a commit that referenced this pull request Sep 11, 2026
A batch that the watchdog kills, or that exits non-zero, kept its combined
log only in the temp dir; the step summary named the batch and nothing else.
Two CI attempts on #13456 hung the same half-batch with no test name in the
log. Print the last XCTest progress lines and any failure/crash lines for a
non-zero batch and for a timed-out solo suite.

Verification: bash -n; python3 .github/scripts/test_desktop_swift_ci_contract.py
(35 tests OK); .github/scripts/test_pre_push_ci_prediction.py OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 11, 2026
A batch that the watchdog kills, or that exits non-zero, kept its combined
log only in the temp dir; the step summary named the batch and nothing else.
Two CI attempts on #13456 hung the same half-batch with no test name in the
log. Print the last XCTest progress lines and any failure/crash lines for a
non-zero batch and for a timed-out solo suite.

Verification: bash -n; python3 .github/scripts/test_desktop_swift_ci_contract.py
(35 tests OK); .github/scripts/test_pre_push_ci_prediction.py OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the feat/desktop-local-embeddings-hybrid branch from 59c76ac to bfdebc6 Compare September 11, 2026 12:50
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — failing check fixed by commit, CI restarted.

Desktop Swift Build & Tests was red because Desktop Swift Release Compile was cancelled at its 60-minute job ceiling — all three attempts of the previous head (59c76ac) were killed at exactly ~60 min, and attempt 3 had the compile finished plus all 11 UserNotifications regression tests passing under a second before the kill. The required gate then hard-failed on RELEASE_RESULT=cancelled by design.

Commit bfdebc69 (branch rebased onto latest main first; force-pushed with lease, no commits lost — the only non-patch-equivalent remote commit is upstream-merged via #13468):

  • desktop-swift-ci.yml: raise desktop-swift-release-compile timeout-minutes 60 → 90 so a grown branch's whole-module release compile stops being cancelled with the work already done. The ceiling stays a wedge-guard; main's baseline compile (~25 min) is unaffected.
  • test_desktop_swift_ci_contract.py: MACOS_JOB_TIMEOUT_MINUTES updated in lockstep so the pinned runner-budget contract still holds.

Also refreshed the stale Line-Count-Exception for firestore_index_registry.py (1527→1542 → 1542→1557) in the PR body after the rebase onto main grew that file.

Verification: local pre-push gate passed for all changed-file-selected checks (incl. desktop-swift-ci-contract, now 35/35), plus the hermetic desktop launcher test scripts; the push used the documented narrow --no-verify bypass only because the host python3 (3.9) predates the repo scripts' syntax — the equivalent gate was run manually with Homebrew Python and passed.

CI is re-running on the new head with the 90-minute ceiling.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — upstream time-bomb test fixed, backend shards green again (3b56505).

Backend unit shard 3/4 / Backend unit suite were failing on test_memories_archive_and_read_contracts.py::test_memory_item_to_memorydb_attaches_belief_view_only_when_flag_on (assert 'history' == 'fading'). Root cause is an upstream time-bomb, not this PR's diff: the test hardcoded captured_at = 2026-07-13 with half_life_days=30 while memory_item_to_memorydb reads the real clock — currency decayed past the fading floor (0.25 at 60 days) at 2026-09-11T12:00Z, exactly between the previous green run (06:45Z) and the failing one (12:54Z).

Fix (commit 3b565059cb4): anchor captured_at to now() - 30d so the item is exactly one half-life old (currency 0.5, fading floor) whenever the suite runs — same deterministic-clock style as test_belief_model.py.

Verification: BACKEND_UNIT_TEST_FILE_LIST=tests/unit/test_memories_archive_and_read_contracts.py bash test.sh → 11 passed (previously 1 failed). Post-push CI on the new head: all backend unit shards + suite green; Desktop Swift checks re-running. No review threads were open or added.

Git-on-my-level added a commit that referenced this pull request Sep 11, 2026
…ve (#13506)

The belief-view assertion uses wall-clock now. A frozen 2026-08-12
captured_at ages into the history band ~60 days later and fails CI.
Anchor captured_at to now-minus-one-half-life so currency stays 0.5.

Extracted from #13456 so other PRs are not blocked by the rot.

Failure-Class: none
huiyuansun28-cmyk added a commit to huiyuansun28-cmyk/omi that referenced this pull request Sep 15, 2026
@huiyuansun28-cmyk

Copy link
Copy Markdown
Contributor

PR: #14041

AUTO (AI Agent). Authorship disclosed.

Git-on-my-level and others added 9 commits September 17, 2026 07:34
Use Firestore keyword recall after embedding/vector failure, empty or malformed
vector results, or server-owned account vector opt-out. Scan the newest 500
screens in the requested window (default seven days), require every query
term, rank by occurrence count and recency, and preserve text/evidence shape.
Read snapshots through the shared boundary; report keyword relevance and
honest empty scan counts without logging queries, OCR, or provider errors.

SCREEN_ACTIVITY_KEYWORD_FALLBACK_ENABLED defaults on.
SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS accepts comma-separated UIDs or *;
an unset list preserves legacy accounts' vector eligibility.

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 27 passed across test_screen_activity_evidence.py (14), test_screen_activity_search_utc.py (5), and test_screen_activity_tool_result_bound.py (8).
- git diff --check: passed.
All tool invocations used fake providers and Firestore. No live service was
contacted. Env/guide documentation and PR gates belong to the follow-up agent.
Define the Sendable on-device embedding service, task types, capabilities,
and readiness probe. Selection checks the kill switch, configured engine,
assets, hardware, 32-token fixture, dimension and measured two-second budget.
Failures produce no local vectors. There is no HTTP or cloud adapter in the
runtime; the default engine registry is deliberately empty.

Add env-or-UserDefaults disable/forced-engine resolution. Hash-based engines
and an injected fail-on-HTTP trap exist only in the test target.

Verification:
- xcrun swift build --build-tests --package-path desktop/macos/Desktop: passed on installed Xcode with strict-concurrency=complete and warnings-as-errors. Existing linker warnings remain.
- xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|OCREmbeddingLosslessTests|ScreenActivityLosslessSyncTests': 22 passed, including 3 runtime tests.
- desktop/macos/scripts/swift-format-wrapper.sh format -i on changed Swift files: passed.
- python3 desktop/macos/scripts/check_desktop_test_quality.py: passed.
- python3 desktop/macos/scripts/check-sources-root-layout.py: existing failure, 94 loose Sources-root files versus baseline 77; git ls-tree at bf079e0 confirms the same 94. All new files are in feature directories.

The probe budget is an admission measurement, not preemption of an engine
that ignores cancellation. Apple asset/probe integration, docs, changelog,
e2e coverage and PR preflight remain assigned to the follow-up agent.
Add local_embeddings with source/model uniqueness, dimension/blob checks,
text hashes and timestamps. Share the existing completed five-minute app/
window winner SQL with Gemini selection. Local vectors never use the cloud
embedding column. Bind stores to the captured owner's pool, fence commits,
and reject stale screenshot text or deleted sources at commit time.

Fuse FTS5 BM25 top 50 with vDSP cosine top 50 using RRF k=60. Scan newest
local vectors first in bounded batches, at most 20,000, filtering exact model,
dimension, date and app. Return typed keyword/vector/both evidence with stable
tie ordering. A selected engine's failure stays keyword-only. Chat retains
its legacy Gemini path and threshold/output when local is disabled/unavailable.
Existing Gemini flush and cloud sync remain untouched.

Verification:
- xcrun swift build --build-tests --package-path desktop/macos/Desktop: passed.
- xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|OCREmbeddingLosslessTests|ScreenActivityLosslessSyncTests': 22 passed (8 foundation, 3 runtime, 2 OCR, 9 sync).
- Foundation tests call production migration/storage/fusion APIs with a fixture DB, including model isolation, uniqueness, owner revocation, stale writes, completed buckets, filters, scan limits, query failure and actual ChatToolExecutor disabled-local rendering.
- desktop/macos/scripts/swift-format-wrapper.sh format -i on changed Swift files: passed.
- python3 desktop/macos/scripts/check_desktop_test_quality.py: passed.
- python3 desktop/macos/scripts/check-sources-root-layout.py: existing failure (94 vs baseline 77), unchanged from bf079e0; no new loose Sources-root files.
- git diff --check: passed.
Tests were hermetic; no app launch or production service was used. The build
still reports existing README-resource and webp deployment-floor linker warnings.

Setup used make -o setup-main -o setup-backend setup to install/verify the
worktree hook dispatchers while preserving the user-pinned base and ready venv.
No branch refresh, push, PR, or workflow changes were performed.

Follow-up ownership: NLContextualEmbedding adapter and real asset probe,
screenshot indexing integration with the selected engine, transcript-chunk
FTS/indexing, memory indexing, synthetic retrieval benchmark, changelog,
e2e covers, LocalInference/desktop docs, free-tier Gemini-flush policy,
and PR body/preflight mechanics.
Keyword fallback now formats Firestore range bounds through
normalize_screen_activity_timestamp, including the post-scan window
filter, so a document written at the window edge is found.

Failure-Class: none

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 16 passed in test_screen_activity_evidence.py including the new window-edge case.

Co-authored-by: Cursor <[email protected]>
Read SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS through the same whitespace-
tolerant CSV/flag parsing as other backend flags so empty tokens cannot
crash dispatch. This remains a temporary server-owned opt-out.

Failure-Class: none

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 16 passed, including whitespace/star UID parsing.

Co-authored-by: Cursor <[email protected]>
…ipt/memory indexing

Apple NLContextualEmbedding is the production default behind the existing kill
switches; a failed probe stays keyword-only (never Gemini). Probe verdicts are
cached in-process. Transcript chunks and memories join hybrid search behind a
sourceKind filter so screen search stays screen-only.

Verification: xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbedding|AppleNLContextualEmbedding' — 20 passed (benchmark not in this commit).
Co-authored-by: Cursor <[email protected]>
In-repo synthetic fixtures only. Reports recall@10 and nDCG@10 for FTS,
vector, and hybrid. Headless via omi-ctl action local_embedding_benchmark.

Verification: xcrun swift test --package-path desktop/macos/Desktop --filter LocalEmbeddingBenchmarkTests — 1 passed; hybrid paraphrase recall@10 >= FTS-only with HashEmbeddingEngine.
Co-authored-by: Cursor <[email protected]>
…2e covers

LocalInference crossed 12 source files. Changelog fragment and
local-hybrid-search.yaml covers entries satisfy the desktop pre-push gates.

Co-authored-by: Cursor <[email protected]>
SwiftLint omi_inline_userdefaults_key and force_unwrapping rejected the new
runtime files. Typed keys keep the same UserDefaults names.

Verification: desktop/macos/scripts/swiftlint-wrapper.sh lint — 0 violations; xcrun swift test --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|LocalEmbeddingBenchmarkTests|AppleNLContextualEmbedding' — 20 passed.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
Git-on-my-level and others added 21 commits September 17, 2026 07:34
… tests

Xcode 16.4 rejects non-Sendable XCTestCase transfers from @mainactor async lifecycle hooks.

Co-authored-by: Cursor <[email protected]>
…ts typed as Any

The pre-push pyright gate flagged isinstance(m, dict) as unnecessary because
search_screen_activity_vectors is typed List[Dict[str, Any]]. The runtime
check is deliberate (Pinecone metadata is external input), so iterate over
cast(List[Any], ...) as the original tool did. No behaviour change.

Verification: BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-suites.txt bash backend/test.sh
(evidence 16 passed, utc 8 passed, result-bound 5 passed).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ot park the indexer

Race each embed/probe engine call against Task.sleep; on timeout record engine_timeout and fail closed to keyword, never Gemini.

Co-authored-by: Cursor <[email protected]>
A HangGate resume-before-park race left work parked on LocalEmbeddingIndexer.shared and wedged later suites in the same SwiftPM batch.

Co-authored-by: Cursor <[email protected]>
…vector dimension

Existing chunks no longer skip backfill: completed sessions are rewritten when
the source fingerprint changes, including an empty result. Keyword candidates
keep FTS BM25 order into fusion, write() checks the engine dimension instead of
vector.count, and hybrid search exposes a vector-only retrieval mode.

Review: 3984237061, 3984237113, 3984237136, 3984237067
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingFoundationTests/'
  →  (run with owned-suite batch after remaining commits)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
A hit the model cannot read is useless. Fetch each matched chunk (capped at
the search limit) and append a timestamp plus a 300-character content preview
before formatting the tool response.

Review: 3984237058
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'ChatLocalHybridToolTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…e chunks

Fabricating startedAt as Date() would poison date filters. If getSession
fails, record missing_session_origin and return. Re-indexing deletes the
session's old chunks before writing, and drainForTesting cancels parked
detached work instead of only awaiting it.

Review: 3984237075, 3984237061, 3984237117
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…ctor rank

Date-bounded fixtures now include out-of-range distractors so a missing date
filter fails the slice. Vector mode searches with retrieval=.vector instead of
post-filtering fused hits, and the unused Mode.gemini case is removed.

Review: 3984237064, 3984237067, 3984237131
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingBenchmarkTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
… seconds

Concurrent searches for the same engine now share one probe task. The probe
itself races LocalEmbeddingCallBound so a hung engine falls back to FTS-only
instead of waiting past the budget. Cancellation is stored as reason cancelled
and is not cached.

Review: 3984237072, 3984237099
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingRuntimeTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
syncServerMemories reconciled rows without indexing, so hybrid memory search
stayed FTS-only until a later backfill. Schedule scheduleMemoryIndex for each
inserted/adopted row after the write, detached and never awaited.

Review: 3984237089
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…glish

prepareAssets now takes englishDominant and requests the multilingual model
when that is the selected engine. The system-engine test asserts permits only
when the probe succeeded (reason empty), so a first-embed timeout is not a
false failure.

Review: 3984237092, 3984237104
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'AppleNLContextualEmbeddingTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
… teardown

The previous test only checked completed==0, which also holds if scheduling is
removed, and a synchronous-await regression would hang on gate.park(). Assert
a continuation actually parked, fail if the 400ms bound expires, and cancel
detached indexer tasks in drainForTesting before the DB is torn down.

Review: 3984237111, 3984237117
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Natural-language queries failed because every token, including "when"/"was"/"I",
had to appear in the same screen record. Keep only content tokens (length > 1,
not in a small stopword list) before the all-token match.

Review: 3984237093
Verification:
  /Users/dazheng/workspace/omi/upstream-keep-clean/backend/.venv/bin/python -m pytest tests/unit/test_screen_activity_evidence.py -q
  → 17 passed in 0.30s
  scripts/backend-python-format --write on the two files
  PYRIGHT_PYTHON=... backend/scripts/typecheck.sh → 0 errors

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…drives

local-hybrid-search now expects result.detail.kind=local_embedding_benchmark.
covers lists the sources the benchmark action actually reaches, including
ChatLocalHybridTool via the bridge, while capture-lifecycle covers the
indexer and chunker on the session-finalize path.

Review: 3984237095, 3984237097
Verification:
  python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict
  → Uncovered: 0

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Drop the internal rollout clause from the unreleased changelog fragment so the
entry states what the user gains (faster, offline, private, on-device search).

Review: 3984237120
Verification:
  python3 -c 'import json; json.load(open("desktop/macos/changelog/unreleased/2026-09-10-local-hybrid-search.json"))'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…west bound

sessionsNeedingTranscriptChunks was limiting to the 20 newest completed
sessions and then filtering those, so older unchunked sessions were never
picked up. Restore the original unchunked-with-segments progress query (LIMIT
bound) and add a separate bounded stale-reconcile set using stored segment
count/max id so Swift re-chunk does not scan all history.

Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingFoundationTests/'
  → testUnchunkedOlderSessionIsPickedUpPastTheBound passed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…e task

embedTexts now drops items that already have a matching local_embeddings
textHash for the selected model, so a memory API refresh does not re-run
NLCE. syncServerMemories schedules one detached batch instead of one task per
row.

Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'
  → testUnchangedMemoryRefreshDoesNotReembed passed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
A batch that the watchdog kills, or that exits non-zero, kept its combined
log only in the temp dir; the step summary named the batch and nothing else.
Two CI attempts on #13456 hung the same half-batch with no test name in the
log. Print the last XCTest progress lines and any failure/crash lines for a
non-zero batch and for a timed-out solo suite.

Verification: bash -n; python3 .github/scripts/test_desktop_swift_ci_contract.py
(35 tests OK); .github/scripts/test_pre_push_ci_prediction.py OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… teardown

Memory and transcription suites spawned LocalEmbeddingIndexer tasks that outlived
RewindStorageTestIsolation.tearDown, then hit SQLite error 10 against a deleted
user directory and entered handleCorruptedDatabase — the path that wedges CI's
Xcode 16.4 half-batch. Isolation now cancel-drains the indexer (5s per task)
before closing or deleting the DB, resets OCR/indexer state, and cancelled
indexing returns before writes or recovery.

Verification:
  Before: xcrun swift test --package-path Desktop --filter '<worker-1-1-h0 50 suites>'
    → 393 tests, 0 failures; grep -c 'Database is corrupted' = 2
  After (3/3): same filter
    → 393 tests, 0 failures; grep -c 'Database is corrupted' = 0, 0, 0
  Owned: LocalEmbeddingFoundationTests|Runtime|OptIn|CapturePath|AppleNL|Benchmark|ChatLocalHybrid
    → 39 tests, 0 failures

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…t -e

grep exits 1 when a batch log has no matching line; under the runner's
set -e that ended the worker before it preserved the failed suite log
(tests/test-swift-test-suites.sh: 'runner did not preserve the failed
suite log'). The diagnostic greps are best-effort now.

Verification: bash desktop/macos/tests/test-swift-test-suites.sh → PASS;
python3 .github/scripts/test_desktop_swift_ci_contract.py → OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Three consecutive attempts of this branch's Desktop Swift Release
Compile were cancelled at the 60m job ceiling with the compile already
finished and the UserNotifications regression passing under a second
before the kill, which hard-failed the required Build & Tests gate on
RELEASE_RESULT=cancelled. The branch grew the Desktop package, so its
whole-module compile now legitimately needs ~60m. Raise the ceiling to
90m so completed work stops being cancelled; main's baseline compile
(~25m) is unaffected.
@Git-on-my-level
Git-on-my-level force-pushed the feat/desktop-local-embeddings-hybrid branch from 3b56505 to 10c742e Compare September 17, 2026 11:50
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Merge-forward blocked on a 1-file owner edit (merge-loop, 2026-09-20): desktop/macos/AGENTS.md is at 47001 bytes vs the 47000-byte lean budget. The branch's net AGENTS.md delta adds one line (- Local embeddings (opt-in): [ARCHITECTURE.md link].) but main's side shrank only ~4 bytes, so the merged file lands 1 byte over. Writes to AGENTS.md files are owner-protected, so the merge-forward stops here. Smallest fix (either one): trim ~1+ byte from the added line (e.g. drop the backticks around the link: - Local embeddings (opt-in): [ARCHITECTURE.md](Desktop/Sources/LocalInference/ARCHITECTURE.md).), or move the line to .github/agent-docs/ per the lean-check guidance. Once a lane pushes that edit, the rest of the merge-forward (origin/main merged, RewindDatabase migration-list conflict unioned, ownership audit clean at 39 owned files) is ready to rebase on top.

…beddings-hybrid

# Conflicts:
#	desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift
…a fixed epoch

The tool searches a [now-7d, now] window; the fixed 2026-09-10 fixture
fell out of range after Sep 17 and the suite began failing on every run.
Also assert a 4-digit year via regex instead of the literal 2026.
@Git-on-my-level
Git-on-my-level merged commit 09be5ae into main Sep 21, 2026
64 of 66 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/desktop-local-embeddings-hybrid branch September 21, 2026 09:53
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.

2 participants