Skip to content

refactor: thermo-nuclear quality repayment (macOS + backend) - #9327

Merged
Git-on-my-level merged 30 commits into
mainfrom
refactor/thermo-nuclear-macos-backend
Jul 10, 2026
Merged

Git-on-my-level merged 30 commits into
mainfrom
refactor/thermo-nuclear-macos-backend

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Single-branch thermo-nuclear quality repayment across backend and macOS desktop (waves 1–8):

Related: #8844, #9029, #9239

Product invariants affected

Characterization / coverage additions

  • test_utils_import_boundary.py, test_task_integrations_ops.py
  • test_memory_replace_policy.py
  • test_listen_session_bootstrap.py
  • STTSessionStateTests, combined-memory script
  • Existing sync/listen/APIClient suites updated as move anchors

Verification (local)

cd backend && python3 scripts/check_workflow_contracts.py
cd backend && ./test.sh tests/unit/test_utils_import_boundary.py tests/unit/test_task_integrations_ops.py \
  tests/unit/test_memory_replace_policy.py tests/unit/test_listen_session_bootstrap.py \
  tests/unit/test_sync_v2.py tests/unit/test_workflow_contracts.py
cd desktop/macos && xcrun swift test --package-path Desktop --filter 'STTSessionStateTests|APIClient|MemoryAuthoritativeTierSyncTests'
bash desktop/macos/scripts/swift-test-combined-memory.sh

Out of scope (deferred Wave 9+)

  • MemoryWritePolicy / ListenReceiveLoop peel / sync v1/v2 unify / Chat models extract / ConversationsRepository
  • Mega-UI (FloatingControlBar, TasksPage, Dashboard dual-home)
  • Full AppState god split, production DI for all singletons

Made with Cursor

Review in cubic

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 025db77a1f

ℹ️ About Codex in GitHub

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

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

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

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

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

1 issue found across 4 files (changes from recent commits).

You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/testing/e2e/test_core_flow_expansion.py">

<violation number="1" location="backend/testing/e2e/test_core_flow_expansion.py:168">
P0: The monkeypatches in this test may not actually override the targeted functions. `routers/sync.py` imports `retrieve_vad_segments`, `process_segment`, `_reprocess_merged_conversations`, `build_person_embeddings_cache`, `decode_files_to_wav`, `get_wav_duration`, and `FAIR_USE_ENABLED` via `from ... import` style, which binds them as local names in `routers.sync`'s namespace. When Python's `from X import Y` is used, patching `X.Y` after import does not update the local `Y` reference in the importing module—so the real functions will still execute instead of the fakes. This means the test could silently exercise real logic, making it unreliable. To fix this, either revert to patching `sync_router` (the importing module) for functions used locally in `routers/sync.py`, or update the imports in `routers/sync.py` to use `import utils.sync.pipeline as sync_pipeline` and call functions as `sync_pipeline.retrieve_vad_segments(...)` etc.</violation>
</file>

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

Re-trigger cubic

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

1 issue found and verified against the latest diff

Confidence score: 2/5

  • In desktop/macos/Desktop/Sources/OmiHTTPTransport.swift, the transport helpers default includeBYOK to true, so BYOK API keys can be attached to unrelated requests; merging as-is risks leaking external credentials to endpoints that should never receive them. Flip the default to opt-in (or gate key injection to explicit LLM/provider calls only) and add a targeted test to verify non-LLM requests never carry BYOK headers before merging.

You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/OmiHTTPTransport.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/OmiHTTPTransport.swift:57">
P2: BYOK provider API keys are attached by default to every request because `includeBYOK` defaults to `true` in the transport helpers. This causes raw external credentials to be sent to endpoints that do not trigger LLM/STT work (conversation CRUD, goals, user profile, etc.) unless each call site remembers to opt out. Consider changing the default to `false` so callers must explicitly opt in when an endpoint actually needs BYOK keys; this closes the secret-propagation gap at the transport level instead of relying on every future call site to remember the opt-out.</violation>
</file>

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

Re-trigger cubic

Comment thread backend/utils/task_integrations_ops.py Resolved
Comment thread backend/utils/task_integrations_ops.py Resolved
Comment thread backend/utils/task_integrations_ops.py Resolved
Comment thread backend/utils/sync/pipeline.py Resolved
@Git-on-my-level
Git-on-my-level force-pushed the refactor/thermo-nuclear-macos-backend branch from 043318e to e9dd8f8 Compare July 9, 2026 13:48
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor review-fix summary

Addressed 13 of 19 trusted bot review threads (Codex/Cubic). 6 threads intentionally left unresolved as out-of-scope or false positives (see below).

Fixed (13 threads)

Backend — task_integrations_ops.py

  • T3/P1: connected check now uses is False so legacy records missing the key fall through to access_token validation; refresh now sets connected=True on success
  • T4/P1: Asana/Google Tasks POST calls in create_task_internal wrapped with perform_request_with_token_retry — 401 during task creation is recovered, not permanent failure
  • T5/P1: Narrowed broad except Exception in ensure_valid_oauth_token to ValueError/TypeError; refresh failures propagate instead of being retried with a stale token
  • T11/P2: Token refresh/disconnect now writes narrow payloads (access_token, refresh_token, expires_at, connected) instead of full integration.copy(), preventing concurrent field overwrites via Firestore set(merge=True)

Backend — sync/pipeline.py

  • T7/P1: Exception text in process_segment error handler now sanitized via sanitize() to prevent signed URLs/tokens leaking into logs and job results

Backend — listen_session_bootstrap.py

  • T17/P2: Vocabulary dedup changed from set() to dict.fromkeys(['Omi'] + vocabulary) — preserves user term priority for downstream STT vocabulary[:100]

Backend tests

  • T12/P2: 5 structural tests in test_sync_v2.py fixed to use \nasync def/\ndef boundary markers for pipeline.py (was using stale \n@router. markers from sync.py)
  • T18/P2: Added test_canonical_reextract_failure_preserves_existing_memories mirroring the legacy failure-preservation test

Desktop — OmiHTTPTransport.swift → Sources/Services/

  • T1+T19/P2: Moved to feature subdirectory; check-sources-root-layout.py now passes (78→77 baseline)
  • T13/P2: ISO8601DateFormatters cached as static properties instead of allocated per decoded Date field
  • T15/P2: Added makeEncoder() with matching ISO8601 date strategy; POST bodies use it instead of bare JSONEncoder()
  • T16/P2: Force-unwrap URL(string:)! replaced with guard let + throw APIError.invalidResponse

Desktop — STTSessionState.swift

  • T6/P1: beginLocalToCloudFallback() now clears sessionForceLocal so cloud fallback isn't blocked by stale session-local preference; added regression test

Desktop — RewindStorageTestIsolation.swift

  • T9/P2: Raw string "auth_userId" replaced with typed DefaultsKey.authUserId; check-userdefaults-key-ratchet.py improved (184→182)

Not addressed (6 threads)

  • T2/P0: Monkeypatch target — false positive. The test already patches sys.modules["utils.sync.pipeline"] (the importing module for pipeline-local calls). routers/sync.py imports via from utils.sync.pipeline import ..., so the e2e test correctly patches the pipeline module namespace where the functions are called.
  • T8/P1: asyncio.wait_for on run_blocking threads — architecturally invasive (requires restructuring executor cancellation). Pre-existing design limitation, out of scope for a refactor PR.
  • T10/P2: Parallel test execution on global singletons — pre-existing test pattern across the codebase. Wrapping in an actor would require changes to all suites using RewindStorageTestIsolation.
  • T14/P2: BYOK default-to-false — behavior change affecting all call sites. Would need a full audit of every endpoint to determine which need BYOK. Out of scope.

Verification

  • check-sources-root-layout.py: OK (77 baseline)
  • check-userdefaults-key-ratchet.py: improved (184→182)
  • check-desktop-changelog.py: fragment found
  • Python AST parse: all changed files OK
  • Swift xcrun swiftc -parse: all changed files OK
  • Pre-push async blocker gate: 0 blocking findings
  • CI: Hermetic Backend E2E ✅, Backend unit suite ✅, Desktop Swift Release Compile ✅, Formatting ✅, Static Contracts ✅, contracts ✅, Hygiene ✅, Public Developer API contract ✅

Git-on-my-level added a commit that referenced this pull request Jul 9, 2026
…wift hardening

Addresses trusted bot review comments on PR #9327:

Backend (task_integrations_ops.py):
- Change connected check to is False so legacy records missing the key
  fall through to access_token validation instead of being blocked (T3)
- Set connected=True after successful token refresh (T3)
- Wrap Asana/Google Tasks POST calls with perform_request_with_token_retry
  so 401 during task creation is recovered (T4)
- Narrow broad except Exception in ensure_valid_oauth_token to
  ValueError/TypeError; refresh failures propagate instead of retrying
  with a stale token (T5)
- Use narrow update payloads for Firestore writes (T11)

Backend (sync/pipeline.py):
- Sanitize exception text in process_segment error handler (T7)

Backend (listen_session_bootstrap.py):
- Replace set-based vocabulary dedup with order-preserving dict.fromkeys (T17)

Backend tests:
- Fix 5 structural tests in test_sync_v2.py boundary markers (T12)
- Add canonical-path failure-preservation test (T18)

Desktop (OmiHTTPTransport.swift -> Services/):
- Move to Sources/Services/ to pass root-layout ratchet (T1/T19)
- Cache ISO8601DateFormatter instances statically (T13)
- Add makeEncoder() with matching date strategy (T15)
- Replace force-unwrap URL with guard let (T16)

Desktop (STTSessionState.swift):
- Clear sessionForceLocal in beginLocalToCloudFallback (T6)

Desktop (RewindStorageTestIsolation.swift):
- Use typed DefaultsKey.authUserId (T9)
Git-on-my-level and others added 16 commits July 9, 2026 21:18
Extract task integration ops (create + OAuth helpers) from routers to
utils/task_integrations_ops.py so task_sync no longer imports routers.
Add import-boundary ratchet and Todoist characterization tests.

Verification: pytest tests/unit/test_utils_import_boundary.py
tests/unit/test_task_integrations_ops.py tests/unit/test_task_sync_async.py

Co-authored-by: Cursor <[email protected]>
Extract-first legacy/canonical re-extract so LLM failures cannot wipe
conversation memories. Cascade delete removes memories and action items
before the conversation document. Add memory replace policy tests.

Verification: pytest tests/unit/test_ws_i_write_convergence.py
tests/unit/test_ws_j_delete_privacy.py tests/unit/test_memory_replace_policy.py

Co-authored-by: Cursor <[email protected]>
Extract connect-time Firestore reads into listen_session_bootstrap with
run_blocking offload. Register listen_ws_session workflow contract and
add characterization tests (#9239).

Verification: check_workflow_contracts.py + listen bootstrap test suite
Co-authored-by: Cursor <[email protected]>
RecurringTaskScheduler no longer constructs a shadow ChatProvider; it
receives the canonical TaskChatCoordinator from ViewModelContainer.
Add INV-6 tripwire ensuring production Sources only call ChatProvider()
in ViewModelContainer (previews excluded).

Verified: xcrun swift test --filter ChatTimelineContinuityTests (20/20),
StartupWarmupPolicyTests.testRecurringTaskScheduler (1/1).

Co-authored-by: Cursor <[email protected]>
Move decode→VAD→STT→merge pipeline from routers/sync.py into
utils/sync/pipeline.py so the router stays thin and utils never
imports routers. Update workflow contract sources and test anchors.

Verification: pytest tests/unit/test_sync_v2.py
tests/unit/test_sync_cloud_tasks.py tests/unit/test_sync_ordered_assignment.py
tests/unit/test_sync_silent_failure.py tests/unit/test_workflow_contracts.py
tests/unit/test_utils_import_boundary.py (248 passed)

Co-authored-by: Cursor <[email protected]>
Replace five scattered STT booleans with a pure STTSessionState type that
encodes cloud↔local resolution, sticky flags, and fallback mutex rules.
Hermetic STTSessionStateTests cover BLE/Intel paths, debug force-cloud,
one-shot cloud→local fallback, app-run cloud stickiness, and reentry.

Verified: xcrun swift test --package-path Desktop --filter STTSessionStateTests (9/9 passed)
Co-authored-by: Cursor <[email protected]>
Add RewindStorageTestIsolation helper and migrate the three leaky memory
suites to close() before user-dir delete. Includes a single-process
combined-memory regression script for #9029.

Verified: bash scripts/swift-test-combined-memory.sh (12/12 pass);
per-suite filters for all three suites pass in isolation.

Co-authored-by: Cursor <[email protected]>
Move URLSession setup, header assembly, GET/POST/DELETE verbs, 401 retry,
and JSON decode/error handling from APIClient into OmiHTTPTransport; APIClient
delegates with unchanged public surface. Add APIClient.swift line-count ratchet.

Verified: pytest test_app_client_swift_generator + test_desktop_rest_inventory;
xcrun swift test --filter APIClient (1 pre-existing routing assertion failure).

Co-authored-by: Cursor <[email protected]>
Allowlist slow import-boundary tests; fix file_paths test to load
utils.sync.pipeline instead of a MagicMock after wave 4 extract.

Co-authored-by: Cursor <[email protected]>
Point sync pipeline and task-integration mocks at utils.sync.pipeline
and utils.task_integrations_ops, and assert lazy storage client init.

Co-authored-by: Cursor <[email protected]>
Map STTSessionState, OmiHTTPTransport, RecurringTaskScheduler, and
ViewModelContainer to existing tier-1/2 harness flows.

Co-authored-by: Cursor <[email protected]>
Point structural and patch targets at utils.sync.pipeline, listen_session_bootstrap,
and task_integrations_ops after the thermo-nuclear refactor.

Co-authored-by: Cursor <[email protected]>
…wift hardening

Addresses trusted bot review comments on PR #9327:

Backend (task_integrations_ops.py):
- Change connected check to is False so legacy records missing the key
  fall through to access_token validation instead of being blocked (T3)
- Set connected=True after successful token refresh (T3)
- Wrap Asana/Google Tasks POST calls with perform_request_with_token_retry
  so 401 during task creation is recovered (T4)
- Narrow broad except Exception in ensure_valid_oauth_token to
  ValueError/TypeError; refresh failures propagate instead of retrying
  with a stale token (T5)
- Use narrow update payloads for Firestore writes (T11)

Backend (sync/pipeline.py):
- Sanitize exception text in process_segment error handler (T7)

Backend (listen_session_bootstrap.py):
- Replace set-based vocabulary dedup with order-preserving dict.fromkeys (T17)

Backend tests:
- Fix 5 structural tests in test_sync_v2.py boundary markers (T12)
- Add canonical-path failure-preservation test (T18)

Desktop (OmiHTTPTransport.swift -> Services/):
- Move to Sources/Services/ to pass root-layout ratchet (T1/T19)
- Cache ISO8601DateFormatter instances statically (T13)
- Add makeEncoder() with matching date strategy (T15)
- Replace force-unwrap URL with guard let (T16)

Desktop (STTSessionState.swift):
- Clear sessionForceLocal in beginLocalToCloudFallback (T6)

Desktop (RewindStorageTestIsolation.swift):
- Use typed DefaultsKey.authUserId (T9)
@Git-on-my-level
Git-on-my-level force-pushed the refactor/thermo-nuclear-macos-backend branch from 2077824 to e78c93f Compare July 9, 2026 14:22
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor review-fix summary

Addressed 13 of 19 trusted bot review threads (Codex/Cubic). 6 threads intentionally left unresolved as out-of-scope or false positives (see below).

Fixed (13 threads)

Backend — task_integrations_ops.py

  • T3/P1: connected check now uses is False so legacy records missing the key fall through to access_token validation; refresh now sets connected=True on success
  • T4/P1: Asana/Google Tasks POST calls in create_task_internal wrapped with perform_request_with_token_retry — 401 during task creation is recovered, not permanent failure
  • T5/P1: Narrowed broad except Exception in ensure_valid_oauth_token to ValueError/TypeError; refresh failures propagate instead of being retried with a stale token
  • T11/P2: Token refresh/disconnect now writes narrow payloads (access_token, refresh_token, expires_at, connected) instead of full integration.copy(), preventing concurrent field overwrites via Firestore set(merge=True)

Backend — sync/pipeline.py

  • T7/P1: Exception text in process_segment error handler now sanitized via sanitize() to prevent signed URLs/tokens leaking into logs and job results

Backend — listen_session_bootstrap.py

  • T17/P2: Vocabulary dedup changed from set() to dict.fromkeys(['Omi'] + vocabulary) — preserves user term priority for downstream STT vocabulary[:100]

Backend tests

  • T12/P2: 5 structural tests in test_sync_v2.py fixed to use \nasync def/\ndef boundary markers for pipeline.py (was using stale \n@router. markers from sync.py)
  • T18/P2: Added test_canonical_reextract_failure_preserves_existing_memories mirroring the legacy failure-preservation test

Desktop — OmiHTTPTransport.swift → Sources/Services/

  • T1+T19/P2: Moved to feature subdirectory; check-sources-root-layout.py now passes (78→77 baseline)
  • T13/P2: ISO8601DateFormatters cached as static properties instead of allocated per decoded Date field
  • T15/P2: Added makeEncoder() with matching ISO8601 date strategy; POST bodies use it instead of bare JSONEncoder()
  • T16/P2: Force-unwrap URL(string:)! replaced with guard let + throw APIError.invalidResponse

Desktop — STTSessionState.swift

  • T6/P1: beginLocalToCloudFallback() now clears sessionForceLocal so cloud fallback isn't blocked by stale session-local preference; added regression test

Desktop — RewindStorageTestIsolation.swift

  • T9/P2: Raw string "auth_userId" replaced with typed DefaultsKey.authUserId; check-userdefaults-key-ratchet.py improved (184→182)

Not addressed (6 threads)

  • T2/P0: Monkeypatch target — false positive. The test already patches sys.modules["utils.sync.pipeline"] (the importing module for pipeline-local calls). routers/sync.py imports via from utils.sync.pipeline import ..., so the e2e test correctly patches the pipeline module namespace where the functions are called.
  • T8/P1: asyncio.wait_for on run_blocking threads — architecturally invasive (requires restructuring executor cancellation). Pre-existing design limitation, out of scope for a refactor PR.
  • T10/P2: Parallel test execution on global singletons — pre-existing test pattern across the codebase. Wrapping in an actor would require changes to all suites using RewindStorageTestIsolation.
  • T14/P2: BYOK default-to-false — behavior change affecting all call sites. Would need a full audit of every endpoint to determine which need BYOK. Out of scope.

Verification

  • check-sources-root-layout.py: OK (77 baseline)
  • check-userdefaults-key-ratchet.py: improved (184→182)
  • check-desktop-changelog.py: fragment found
  • Python AST parse: all changed files OK
  • Swift xcrun swiftc -parse: all changed files OK
  • Pre-push async blocker gate: 0 blocking findings
  • CI: Hermetic Backend E2E ✅, Backend unit suite ✅, Desktop Swift Release Compile ✅, Formatting ✅, Static Contracts ✅, contracts ✅, Hygiene ✅, Public Developer API contract ✅

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor address merge conflicts and give me an assessment of how we did and what the major risk areas are

@cursor

cursor Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Merge conflicts resolved

Merged latest main into refactor/thermo-nuclear-macos-backend and pushed (acdd448b8). Three conflicts:

File Resolution
backend/testing/workflow_contracts.json Kept both workflows: your listen_ws_session + main's canonical_memory_pipeline (#9328)
backend/tests/fast_unit_duration_allowlist.txt Unioned allowlist entries from both branches
desktop/macos/Desktop/Sources/APIClient.swift Hybrid: OmiHTTPTransport for headers/codec/session; main's RequestAuthPolicy + centralized 401 refresh/invalidate (#9324 ghost-session fix) preserved in APIClient

check_workflow_contracts.py passes. CI should re-run on the push.


Assessment: how we did

Overall: strong refactor PR with good discipline. ~52 files, +3.6k / −2.1k lines across 8 waves, with characterization tests and workflow contracts at most move points. That's the right shape for a repayment branch.

What went well

  • 13/19 trusted bot threads addressed — real bugs fixed (OAuth token lifecycle, Firestore merge clobbering, vocabulary ordering, STT fallback state, log sanitization), not just style.
  • Import hygiene — utils→routers violation fixed; task_integrations_ops extraction is clean.
  • Safety-oriented memory work (W2) — extract-first re-extract + cascade delete ordering; failure-preservation tests for legacy and canonical paths.
  • Structural extractions with anchors — sync pipeline, listen bootstrap, OmiHTTPTransport, STTSessionState all have move/structure tests.
  • CI was green pre-merge — Hermetic E2E, backend unit, desktop release compile, contracts, hygiene all passed.

Where it's thinner

  • 6 review threads intentionally deferred — some are fair (executor cancellation is invasive), but parallel test isolation and BYOK defaults are real debt.
  • OmiHTTPTransport extraction is partial post-merge — auth policy lives in APIClient; transport still has HTTP verb helpers with older 401 behavior (unused today, but a footgun).
  • Large blast radius — sync pipeline + memory + listen + desktop auth all touch production-critical paths in one PR.
  • Overlap with main — memory confidence ladder (Memory confidence ladder: INV-MEM guards, pipeline E2E, gauntlet, Gate 2 tooling #9328) landed on main while this branch was open; both touch memory semantics. Merge keeps both workflow contracts, but runtime interaction needs CI to confirm.

Major risk areas (ranked)

1. Sync pipeline extraction (utils/sync/pipeline.py) — highest

Cloud Tasks retry/idempotency, segment failure accounting, staged blob cleanup, BYOK inline fallback. A subtle regression could double-count usage, leak GCS blobs, or mark failed segments complete. Mitigated by test_sync_v2.py structural + behavioral tests and the sync_cloud_tasks workflow contract — but this is the highest-impact surface.

2. Memory re-extract atomicity (W2) — high

Extract-first ordering changes when memories are deleted vs written. Tests cover failure preservation, but production LLM extraction flakiness (empty results vs exceptions) can still cause user-visible memory churn. Overlaps with main's canonical memory pipeline work (#9328).

3. Listen connect bootstrap (W3) — high

Connect-time Firestore reads moved off the event loop. Vocabulary ordering fix is in, but asyncio.wait_for on run_blocking threads (review T8) remains — a hung Firestore read can still block connect. Real-user impact: slow/failed listen sessions.

4. Desktop auth + transport split — medium-high

Merge preserves ghost-session fix (RequestAuthPolicy.sessionPreserving). Risk: future callers might use OmiHTTPTransport HTTP helpers directly and bypass auth policy. APIClientAuthRecoveryTests guard the intended path — watch for drift in wave 9.

5. STTSessionState fallback transitions (W6) — medium

beginLocalToCloudFallback() clearing sessionForceLocal is a behavior change (correct per review). Risk: unexpected cloud/local flips during long sessions or BLE reconnects. Needs live listen exercise, not just unit tests.

6. Task integration OAuth fixes — medium

Narrow Firestore writes and token retry are improvements, but this path hits Todoist/Asana/Google live APIs. Token refresh races with concurrent task creation are the main residual risk.

7. Test isolation harness (RewindStorageTestIsolation) — medium (CI flake)

Global singleton mutation without serialization (review T10). Can cause intermittent desktop test failures under parallel XCTest — pre-existing pattern, not introduced here, but this PR adds more usage.

8. Deferred items — lower but real

  • BYOK default includeBYOK: true — credentials sent to non-LLM endpoints unless callers opt out.
  • Monkeypatch target (T2) — assessed as false positive; hermetic e2e patches utils.sync.pipeline namespace correctly.

Recommended post-merge checks

  1. Let CI run on acdd448b8 — especially Hermetic Backend E2E, sync tests, desktop release compile, and APIClientAuthRecoveryTests.
  2. If green, do one manual smoke: listen connect → transcribe → sync upload → memory re-extract on a dev account.
  3. Wave 9 follow-ups: finish OmiHTTPTransport auth-policy port (or remove unused verb helpers), BYOK opt-in default, test isolation actor.

The PR is in good shape for a refactor of this size; the main concern is concentrated production-path risk (sync + memory + listen) rather than merge quality. Conflict resolution is clean and preserves both branches' contract registrations.

Open in Web Open in Cursor 

cursoragent and others added 2 commits July 9, 2026 17:24
- Keep both listen_ws_session and canonical_memory_pipeline workflow contracts
- Union fast-unit duration allowlist entries from both branches
- Reconcile APIClient: retain OmiHTTPTransport for headers/codec/session while
  preserving main's RequestAuthPolicy 401 recovery (ghost-session fix #9324)

Co-authored-by: David Zhang <[email protected]>
Restore compact APIClient.delete shape so INV-AUTH-1 source ratchet still
sees performVoidRequest; raise APIClient line-count high-water for the
auth-recovery merge; allowlist prompt-cache kwargs CPU duration.

Co-authored-by: Cursor <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor review-fix pass — no code changes needed

Re-verified the 3 remaining unresolved trusted bot review threads. All are correctly classified as out-of-scope for this refactor PR (pre-existing patterns preserved verbatim during extraction). No code changes warranted.

Threads reviewed (all cubic-dev-ai)

Thread Location Verdict
asyncio.wait_for on run_blocking threads (P1, conf 9) backend/utils/sync/pipeline.py:945 Pre-existing — pattern extracted verbatim from routers/sync.py. Fixing requires restructuring executor cancellation semantics; out of scope for a code-extraction refactor.
Parallel test execution on global singletons (P2, conf 7) RewindStorageTestIsolation.swift:1 Mirrors pre-existing StagedTaskSyncIntegrityTests lifecycle. No xctestplan enables parallel execution; SwiftPM runs tests sequentially by default.
BYOK keys attached by default (P2, conf 7) OmiHTTPTransport.swift:75 includeBYOK: Bool = true default extracted verbatim from APIClient.swift. Changing to opt-in would require auditing every endpoint — cross-cutting behavior change, out of scope.

CI status

All checks pass on fe657c0:

  • Backend unit suite ✅
  • Hermetic Backend E2E ✅
  • Desktop Swift Build & Tests ✅
  • Desktop Swift Release Compile ✅
  • Formatting / Hygiene / Static Contracts / contracts ✅
  • Public Developer API contract ✅

# Conflicts:
#	desktop/macos/Desktop/Sources/AppState/AppState+Transcription.swift
…t formatting

Merge conflict left bare 'useLocalSTT' at line 66 (added by #9349 in main).
Migrated to 'sttSession.useLocalSTT' per the PR's W6 STTSessionState refactor.
Also restored Dart files to origin/main formatting (pre-commit hook had
reformatted them during merge).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor summary — conflict resolution + merge fix

What changed

Resolved the DIRTY/CONFLICTING merge state by merging latest origin/main (22 commits ahead) and fixing two issues the merge introduced:

  1. AppState+Transcription.swift:66 — Merge left a bare useLocalSTT (from fix(listen): bind recordings by client identity #9349 client-identity binding in main) instead of the PR's sttSession.useLocalSTT (W6 STTSessionState refactor). Migrated to sttSession.useLocalSTT.
  2. AppState+Transcription.swift:986 — Conflict resolution combined the PR's sttSession.useLocalSTT migration with main's new currentClientConversationId = nextClientConversationId assignment (fix(listen): bind recordings by client identity #9349).
  3. Dart formatting — Restored app/lib/main.dart and app/utils/analytics/analytics_manager.dart to origin/main versions (pre-commit hook had reformatted them during the merge commit).

Unresolved review threads (3, all previously triaged)

All 3 remaining cubic-dev-ai threads were independently re-verified against current code. Each is a pre-existing pattern extracted verbatim during the refactor, not a new issue introduced by this PR:

Thread Location Verdict
asyncio.wait_for on run_blocking threads (P1) backend/utils/sync/pipeline.py:945 Extracted verbatim from routers/sync.py:1381. Architecturally invasive to fix; out of scope.
Parallel test execution on global singletons (P2) RewindStorageTestIsolation.swift:1 Mirrors pre-existing test lifecycle pattern across all Rewind storage test suites. No xctestplan enables parallel execution.
BYOK keys attached by default (P2) OmiHTTPTransport.swift:75 includeBYOK: Bool = true extracted verbatim from APIClient.swift:83. Changing default requires auditing every endpoint.

Verification

  • xcrun swiftc -parse AppState+Transcription.swift: clean (0 errors)
  • git diff --check: clean (no whitespace issues)
  • CI on f30e3c333 (all pass):
    • Backend unit suite ✅
    • Hermetic Backend E2E ✅
    • Desktop Swift Build & Tests ✅
    • Desktop Swift Release Compile ✅
    • Formatting ✅
    • Hygiene / Static Contracts / contracts ✅
    • Public Developer API contract ✅
  • PR state: OPEN, MERGEABLE (was DIRTY/CONFLICTING before this run)

Git-on-my-level and others added 10 commits July 10, 2026 07:05
…covers)

Conflicts resolved across 3 files:
- backend/routers/sync.py: combined client_device import with pipeline imports;
  kept HEAD (pipeline-extracted) versions of inline functions; device params
  already threaded by main's #9364 endpoint changes
- backend/utils/sync/pipeline.py: added client_device_id/client_platform params
  to process_segment and _run_full_pipeline_background_async; pass through to
  CreateConversation (main's #9364 device provenance)
- backend/tests/unit/test_sync_v2.py: kept both log_sanitizer and client_device
  mock stubs from both sides
- desktop/macos/e2e/flows/capture-lifecycle.yaml: kept both STTSessionState and
  TranscriptionService cover paths
Main's #9364 added X-App-Platform/X-Device-Id-Hash Header() params to the v2
sync endpoint, but the merge resolution dropped the Header import from fastapi.
- test_device_provenance: read process_segment from pipeline.py (W4 extract)
- client_device mocks: use MagicMock instead of types.SimpleNamespace
  (avoids UnboundLocalError when 'import types' appears later in method)
Prevent detached sync workers from mutating finalized jobs, keep injected OAuth clients through retries, avoid stale Todoist writes, default low-level BYOK headers off, and serialize Rewind singleton fixtures.

Verified: 182 focused backend tests; backend isolation/import/async/workflow scanners; 127 focused Swift tests; combined memory suite; parallel Rewind suites; desktop source-layout and auth-session checks.
Route the merged automation action through ConversationRepository once, avoiding both the async MainActor compile error and duplicate PATCH requests.

Verified: xcrun swift test --package-path Desktop --filter 'DesktopAutomationSecondaryActionTests|BYOKPaywallTests|STTSessionStateTests|ChatTimelineContinuityTests' (63 tests).
# Conflicts:
#	desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift
@Git-on-my-level
Git-on-my-level merged commit 4ea8a4c into main Jul 10, 2026
22 checks passed
@Git-on-my-level
Git-on-my-level deleted the refactor/thermo-nuclear-macos-backend branch July 10, 2026 01:32
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