Skip to content

Stop automatic cards in Chat on macOS and mobile - #20665

Merged
Git-on-my-level merged 9 commits into
mainfrom
lane/no-auto-chat-cards
Oct 4, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
lane/no-auto-chat-cards

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Chat no longer receives automatic goal/task/meeting-notes entries. Opening Chat, finishing a capture/meeting, changing tasks/goals, and releasing a deferral no longer insert goal/task/question/meeting-note cards. Existing automatic cards are hidden by provenance. Agent tool blocks and renderers stay available.

Producer inventory

Producer Entry path Change
Daily goal/task opener chat_first._daily_opener_blocks / _maybe_persist_daily_opener during materialize fetch Deleted preparation and persistence
Rich/sparse cold start _maybe_persist_cold_start -> proactive_engine -> server intent Deleted producers
Sparse script continuation kernel appendNextColdStartSequenceQuestion after an answer terminalizes Deleted automatic continuation; user answers remain
Task/goal mutation judgment action_items/goals post-commit wakes -> proactive_engine Deleted wakes and engine
Capture arrival finalizer -> persist_capture_arrival_intent Deleted arrival write
Desktop meeting notes meeting_receipt -> persist_receipt_intent, from-segments, finalized processing, deferred enrichment, repair/backfill Retain audit receipt and notes; remove Chat intent and repair writes
Deferred question resurfacing deferral outbox -> /v1/chat/deferrals -> release_due_deferrals -> materialization Acknowledge retired outboxes without queue persistence or resurfacing
Proactive delivery /v1 and /v2/chat/materialize-prompts, Swift presence/foreground/meeting coordinator, API driver, kernel materialize operations Backend returns an empty compatible response; remove runner/driver; kernel rejects without a journal write
macOS proactive notification copy FloatingControlBarWindow notification journal admission Keep TTL-bounded context for explicit follow-ups; no Chat write or automatic answer row
Mobile daily-summary push FCM -> MessageProvider.addMessage/history/cache Suppress automatic day_summary history; notification/recap renderer remains
Empty-history greeting GET /v2/messages initial_message_util fallback History reads return an empty list and never synthesize a greeting

meeting_notes_wiring/process_conversation prepare canonical notes and meeting context; they do not independently journal cards. Mobile has no proactive materializer: it consumes mirrored backend rows and cached/pushed messages. The old task/goal/question enum values now decode as text, so preserve the original wire kind for legacy filtering.

Deleted versus filtered

Deleted the opener/cold-start preparation, proactive engine and wake hooks, capture/meeting arrival persistence and repair, queue adapter, Swift fetch/ack/materialize driver, kernel automatic continuation, and tests asserting retired behavior. Kept released endpoint and receipt shapes, stored historical records, canonical meeting receipts, tools, and all rich renderers. No feature flags or historical-data mutation.

Filter markers: chatFirstIntentId/chatFirstIntentSource, cold-start producer/script subject, proactive_notification origin or an AI-turn notification continuity key, legacy task/goal/question kinds, and day_summary. Backend filtering runs before visible pagination; macOS filters the shared journal projection; mobile filters server history, older pages, cache, and push ingestion. Old mobile caches discarded provenance; a cache-format version causes a canonical history refresh before those rows can render. Ordinary rich-block types alone never hide a reply.

History visibility

Automatic rows do not consume the offset readers' reported-row scan budget, including automatic rows also marked reported. They are crossed in batches of at most 100 until the visible page fills or the collection ends. The released list response has no scan-continuation field, so another arbitrary automatic-row ceiling would still look like EOF to mobile; retain the existing reported-row allowance without capping automatic prefixes. Clean pages continue reading only the requested rows.

Cache-aligned history counts the same visibility predicate using a scoped projection of reported, sender, metadata, message_source, type, and content_blocks. Serialized provenance cannot be excluded by an aggregate. This adds projected document reads across the scope for the exact count, but preserves the existing 10–17 visible-message append epochs without a migration or a new durable counter. The subsequent history read requests only that visible limit; redundant reported overfetch is removed.

The notification: continuity prefix hides AI turns only. User follow-ups and cold-start answers with sequence metadata remain visible in backend history, macOS projection, and mobile cache replay. The meeting banner's failure comment now points to saved conversations and notes, without adding a UI fallback.

Product invariants affected

  • INV-CHAT-1: one canonical journal; the shared projection filters automatic provenance across surfaces without another timeline
  • INV-NAV-1: retained explicit notification follow-up and Chat destinations
  • INV-AGENT-*: retain owner/capability/run fences for user-requested tools and block appends
  • INV-6: preserve user-turn continuity and rich resources; update the retired notification-copy rule in the component guide

Failure-Class: none
This implements David's 2026-10-04 product ruling removing automatic Chat entries, rather than a new inference or rollout flag.

Validation

Affected checks:

  • Backend, from backend/: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=../.agent-brief/no-auto-chat-review-files.txt ./test.sh tests/unit/test_get_messages_reported_pagination.py tests/unit/test_chat_message_count.py tests/unit/test_chat_messages_pagination.py: 23 passed. The selector contains those three file paths; positional arguments alone do not narrow this runner.
  • Named-session history regression, from backend/: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=../.agent-brief/no-auto-chat-session-test-files.txt ./test.sh tests/unit/test_chat_session_app_identity.py: 6 passed, including the unchanged Clear Chat greeting test. The selector contains that one file path. Empty named-session GETs preserve app/session scoping, return [], and call neither the greeting helper nor message persistence. A search of the backend tests found no other positive GET-empty-history greeting assertion.
  • Flutter, from app/: flutter test test/unit/server_message_content_blocks_test.dart: 12 passed.
  • Swift, from desktop/macos/: xcrun swift build --build-tests --package-path Desktop, followed by xcrun swift test --skip-build --package-path Desktop --filter KernelTurnRecordedProjectionTests: build passed; 41 tests passed.

Dense-prefix regressions use 1,201 automatic rows before real messages for ordinary offset, app, and cache-aligned reads. Cache count tests retain session/app fences and exclude automatic/reported rows. All three platforms assert user notification continuity and cold-start answer visibility while preserving the AI notification filter.

Manual macOS E2E flows were not launched. No production endpoints, credentials, Firestore, app bundles, deployment, or CI monitoring. Clear Chat, initial-message routes, and integration messages are outside this change's follow-up scope.

Line-Count-Exception: backend/database/chat.py | 1524 -> 1549 | Filter automatic provenance before pagination while preserving user replies and rich blocks

🤖 Generated with Claude Code

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

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

18 issues found across 61 files

Confidence score: 3/5

  • KernelTurnJournal.swift can miss legacy automatic turns because the codec drops coldStartSequence blocks before provenance detection runs. Check the canonical marker before decoding strips it.
  • chat_history_state.dart can restore stale cached messages when canonical history loads successfully but has no visible rows. Preserve the success-versus-empty distinction before falling back to cache.
  • chat_history_state_test.dart does not validate cached-message restoration: the raw preference list is ignored unless the schema is set to 1. Set up the preferences through the schema-aware path.
  • test_chat_first_proactive_router.py no longer covers the capability and owner-fence gates, even though the endpoints still enforce them. Restore assertions for those 404 cases.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/integration/test_shared_task_acceptance_atomic_emulator.py">

<violation number="1" location="backend/tests/integration/test_shared_task_acceptance_atomic_emulator.py:92">
P3: `wake` is now an orphan mock: the fixture no longer patches `action_items._wake_task_changes` (the hook was deleted from production in this PR), yet the mock is still created, yielded, and asserted with `wake.assert_not_called()` at both failure and retry points. These assertions always pass for any code path, so they would not catch a future change that re-introduces a proactive call into the accept flow. Remove the `wake` mock from the fixture/yield/unpack and delete both assertions.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_listen_finalization_cloud_tasks.py:1674">
P3: Removing the `capture_arrival` assertions left `expected_intent_kwargs` dead: it is still in the parametrize tuple and the test signature but no longer referenced anywhere, and the `omi` vs `desktop`/`external_data` cases no longer differ in any asserted behavior. Drop the parameter from the parametrize list and signature and reduce the cases to the dimensions that still matter (`discarded`), or re-add assertions that use them.</violation>
</file>

<file name="backend/tests/integration/test_goal_progress_history_emulator.py">

<violation number="1" location="backend/tests/integration/test_goal_progress_history_emulator.py:40">
P3: After removing the `_wake_goal_change` patch, the `wake` mock is never wired into any code path, so `wake.assert_not_called()` in `test_released_progress_failure_cannot_commit_only_the_goal_and_event` (line 110) is vacuous and can never fail — it no longer verifies anything. The prior intent (a failed commit does not trigger the wake) is now untested. Drop `wake = Mock()`, the fixture's `wake` yield, and the assertion, or keep a real producer seam if the guard is meant to survive.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_chat_first_proactive_engine.py:1">
P3: This file no longer contains any chat-first proactive-engine tests: both retained tests cover meeting treatment, and every `proactive_engine` / `ChatFirstEligibility` / rating-columns test was deleted while the filename `test_chat_first_proactive_engine.py` was kept. New developers searching for proactive-engine coverage will find an empty shell under a misleading name. Rename the file (e.g. `test_meeting_treatment.py`) or merge these two tests into the existing meeting-receipt test file.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_chat_messages_pagination.py:164">
P2: This new test is the only unit coverage for `database.chat.is_automatic_chat_message`, but it never exercises the `metadata['origin'] == 'proactive_notification'`, top-level `message_source == 'proactive_notification'`, legacy `type in {task, goal, question, day_summary}`, or `coldStartSequence`/`cold_start_sequence` content-block branches. The legacy `type` branch in particular is what the PR relies on to keep filtering legacy task/goal/question rows once they decode to text. Add positive assertions for each untested branch so regressions in them surface automatically.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_developer_from_segments_idempotency.py:429">
P3: This test's name still references the 'postprocess arrival adapter' that this PR deletes; it now only covers a None meeting-receipt record not failing conversation creation. Rename it (e.g. `test_meeting_receipt_record_failure_does_not_fail_creation`) to keep test intent discoverable.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/Chat/KernelTurnJournal.swift:346">
P1: This misses the canonical cold-start provenance marker used by the backend and mobile clients. Because `ChatContentBlockCodec.decode` drops unknown `coldStartSequence` blocks before this check, those legacy automatic entries remain visible in the macOS transcript; inspect the raw content-block JSON for both `coldStartSequence` and `cold_start_sequence` before decoding.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_shared_action_items.py:105">
P3: This test name still reads "creates_and_wakes", but the wake assertions were removed and production no longer wakes on shared-task acceptance (`_wake_task_changes` is deleted from `routers/action_items.py`). Rename it to reflect what it actually covers, e.g. `test_accept_shared_tasks_success_creates`.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_process_conversation_free_tier_branch.py:970">
P3: This test's name and docstring are stale: it claims a desktop meeting "still wakes Chat" and persists a chat intent, but the removed intent_spy assertions and the new AssertionError guard on mark_meeting_receipt_intent_persisted mean the test now asserts the chat-intent path is retired. Rename it (e.g. ..._still_persists_receipt_without_chat_intent) and update the docstring so the guard's intent is clear.</violation>
</file>

<file name="app/changelog/unreleased/no-automatic-chat-cards.json">

<violation number="1" location="app/changelog/unreleased/no-automatic-chat-cards.json:1">
P3: "Rich cards" is internal terminology (the PR calls them rich renderers), not a term users see in the app. Rephrase the second clause in user-facing language.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_chat_first_proactive_router.py:67">
P2: The rewrite drops the only coverage of the capability/fence gates these endpoints still enforce. `_require_materialization_capability` in routers/chat_first.py still returns 404 for capability-off and wrong `owner_fence` and 409 for a stale `control_generation`, in both `materialize-prompts` and `chat/deferrals`, but the removed tests (test_materialize_capability_off_..., test_materialize_rejects_wrong_owner_or_generation_..., test_deferral_receiver_is_capability_gated_...) were the only tests exercising those responses. A regression that loosens or drops the fence now passes. Restore parametrized gate tests covering wrong-owner → 404, stale generation → 409, and capability-off → 404 for both endpoints.</violation>

<violation number="2" location="backend/tests/unit/test_chat_first_proactive_router.py:114">
P3: The idempotency check reads `second.json()['deferral_id']` without asserting `second.status_code == 200`. If the retry were ever rejected (404/409), the comparison raises an obscure KeyError on `{'detail': ...}` instead of a clear assertion, and the second response's `state` is never verified. Assert the second response's status and state before comparing IDs.</violation>
</file>

<file name="desktop/macos/changelog/unreleased/20261004-no-automatic-chat-cards.json">

<violation number="1" location="desktop/macos/changelog/unreleased/20261004-no-automatic-chat-cards.json:1">
P3: `Rich cards` is internal renderer terminology (RichBlock views) and never appears in released changelog copy, where cards are described plainly ("file cards", "resource cards"). A user cannot tell what "rich" means here; say the cards still appear when they discuss goals, tasks, or meeting notes in a reply.</violation>
</file>

<file name="desktop/macos/e2e/flows/chat-first-question-deferral.yaml">

<violation number="1" location="desktop/macos/e2e/flows/chat-first-question-deferral.yaml:57">
P2: The `covers:` list still claims files this rewritten flow no longer reaches. The regression flow now only navigates to Chat, snapshots the tail, and asserts `chat_first_request_prompt_materialization` returns `false`; `mainWindowDidBecomeForeground()` is a hard-coded `false` in the retired coordinator, so the driver, journal materialization, block validation, content-block views, and deferral outbox are never invoked. Per the repo's e2e coverage rule, list a source only when the flow actually exercises and verifies its behavior: drop `ChatFirstPromptMaterializationDriver.swift`, `AgentRuntimeProcess+ChatFirstJournal.swift`, `ChatFirstBlockValidation.swift`, `ChatFirstContentBlockViews.swift`, and `ChatFirstDeferralOutboxDriver.swift` from this flow's `covers:` (the deleted step comments tied those entries to the S4/S8 reply/deferral and S8 driver-driving steps that no longer exist).</violation>
</file>

<file name="app/test/providers/chat_history_state_test.dart">

<violation number="1" location="app/test/providers/chat_history_state_test.dart:53">
P2: This test passes for the wrong reason. `SharedPreferencesUtil().cachedMessages` returns `[]` unless `cachedMessagesSchema == 1` (preferences.dart ~1083), and this test writes the raw string list directly while `setUp` starts from empty mock values, so the schema int is never set and `expect(provider.messages, isEmpty)` holds even if `setMessagesFromCache` had no filtering at all. The fixture message (`type: "text"`, no metadata) also is not `isAutomaticChatEntry`, so provenance isn't actually being exercised. Write the cache through the `cachedMessages` setter and include provenance metadata in the fixture so the assertion depends on the filter being verified.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/ChatFirstPromptMaterializationCoordinatorTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/ChatFirstPromptMaterializationCoordinatorTests.swift:7">
P3: The retained test only reads `fetchReceiptBatches` and `materializedBatches`, so the rest of `FakePromptMaterializationDriver` is now dead: `acknowledgementError`, `fetchError`, `suspendNextFetch`/`resumeFetch()`, `isFetchSuspended`, `fetchContinuation`, `windowForegroundValues`, and `acknowledgementBatches` were exercised only by the removed tests. Trim the fake down to the minimal protocol implementation so it no longer implies suspend/resume and error-injection behavior that nothing tests.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/KernelTurnRecordedProjectionTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/KernelTurnRecordedProjectionTests.swift:1458">
P3: This is the macOS suite's only exercise of the new `KernelJournalTurn.isAutomaticChatEntry` predicate, but the `entry` helper hardcodes `origin: "typed_chat"` and omits `producerId`, so several filter branches are never exercised: producerId prefixes (`chat-first-intent:`, `cold-start-sequence:`), `origin`/metadata `proactive_notification`, `messageType == "day_summary"`, and the `.questionCard(cold_start)` check. Legacy automatic entries predominantly carry `producerId: "chat-first-intent:...` or `cold-start-sequence:...`, so a regression in those branches would pass this test. Add turns covering at least the producerId-prefix and proactive_notification provenance paths.</violation>
</file>

<file name="app/lib/providers/chat_history_state.dart">

<violation number="1" location="app/lib/providers/chat_history_state.dart:275">
P2: Filtering `loaded` before the empty-history fallback can restore stale cached messages after canonical history contains no visible rows. Preserve the server success/empty distinction and only use the cache when the read is unavailable, rather than whenever the filtered projection is empty.</violation>
</file>

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

Re-trigger cubic

|| metadata["chatFirstIntentId"] != nil
|| metadata["chatFirstIntentSource"] != nil
|| metadata["messageType"] as? String == "day_summary"
|| (ChatContentBlockCodec.decode(contentBlocksJSON) ?? []).contains { block in

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: This misses the canonical cold-start provenance marker used by the backend and mobile clients. Because ChatContentBlockCodec.decode drops unknown coldStartSequence blocks before this check, those legacy automatic entries remain visible in the macOS transcript; inspect the raw content-block JSON for both coldStartSequence and cold_start_sequence before decoding.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/Desktop/Sources/Chat/KernelTurnJournal.swift, line 346:

<comment>This misses the canonical cold-start provenance marker used by the backend and mobile clients. Because `ChatContentBlockCodec.decode` drops unknown `coldStartSequence` blocks before this check, those legacy automatic entries remain visible in the macOS transcript; inspect the raw content-block JSON for both `coldStartSequence` and `cold_start_sequence` before decoding.</comment>

<file context>
@@ -336,6 +336,23 @@ struct KernelJournalRemoteTurn: Sendable {
+      || metadata["chatFirstIntentId"] != nil
+      || metadata["chatFirstIntentSource"] != nil
+      || metadata["messageType"] as? String == "day_summary"
+      || (ChatContentBlockCodec.decode(contentBlocksJSON) ?? []).contains { block in
+        if case .questionCard(_, _, _, let subjectKind, _, _, _) = block { return subjectKind == "cold_start" }
+        return false
</file context>

assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"chatFirstIntentSource":"' + marker + '"}'})
assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"chatFirstIntentId":"old-intent"}'})
assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"continuityKey":"notification:old"}'})
assert not chat_db.is_automatic_chat_message({**reply, 'metadata': 'malformed'})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: This new test is the only unit coverage for database.chat.is_automatic_chat_message, but it never exercises the metadata['origin'] == 'proactive_notification', top-level message_source == 'proactive_notification', legacy type in {task, goal, question, day_summary}, or coldStartSequence/cold_start_sequence content-block branches. The legacy type branch in particular is what the PR relies on to keep filtering legacy task/goal/question rows once they decode to text. Add positive assertions for each untested branch so regressions in them surface automatically.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_chat_messages_pagination.py, line 164:

<comment>This new test is the only unit coverage for `database.chat.is_automatic_chat_message`, but it never exercises the `metadata['origin'] == 'proactive_notification'`, top-level `message_source == 'proactive_notification'`, legacy `type in {task, goal, question, day_summary}`, or `coldStartSequence`/`cold_start_sequence` content-block branches. The legacy `type` branch in particular is what the PR relies on to keep filtering legacy task/goal/question rows once they decode to text. Add positive assertions for each untested branch so regressions in them surface automatically.</comment>

<file context>
@@ -128,11 +129,36 @@ def test_get_messages_empty_first_page_still_creates_greeting(monkeypatch):
+        assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"chatFirstIntentSource":"' + marker + '"}'})
+    assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"chatFirstIntentId":"old-intent"}'})
+    assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"continuityKey":"notification:old"}'})
+    assert not chat_db.is_automatic_chat_message({**reply, 'metadata': 'malformed'})
</file context>
Suggested change
assert not chat_db.is_automatic_chat_message({**reply, 'metadata': 'malformed'})
assert not chat_db.is_automatic_chat_message({**reply, 'metadata': 'malformed'})
assert chat_db.is_automatic_chat_message({**reply, 'metadata': '{"origin":"proactive_notification"}'})
assert chat_db.is_automatic_chat_message({**reply, 'message_source': 'proactive_notification'})
for legacy_type in ('task', 'goal', 'question', 'day_summary'):
assert chat_db.is_automatic_chat_message({**reply, 'type': legacy_type})
assert chat_db.is_automatic_chat_message(
{**reply, 'content_blocks': [{'type': 'taskCard', 'coldStartSequence': 0}]}
)

)
@pytest.mark.parametrize('version', ['v1', 'v2'])
@pytest.mark.parametrize('foreground', [False, True])
def test_chat_open_serves_no_daily_cold_start_capture_or_queued_intents(monkeypatch, version, foreground):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The rewrite drops the only coverage of the capability/fence gates these endpoints still enforce. _require_materialization_capability in routers/chat_first.py still returns 404 for capability-off and wrong owner_fence and 409 for a stale control_generation, in both materialize-prompts and chat/deferrals, but the removed tests (test_materialize_capability_off_..., test_materialize_rejects_wrong_owner_or_generation_..., test_deferral_receiver_is_capability_gated_...) were the only tests exercising those responses. A regression that loosens or drops the fence now passes. Restore parametrized gate tests covering wrong-owner → 404, stale generation → 409, and capability-off → 404 for both endpoints.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_chat_first_proactive_router.py, line 67:

<comment>The rewrite drops the only coverage of the capability/fence gates these endpoints still enforce. `_require_materialization_capability` in routers/chat_first.py still returns 404 for capability-off and wrong `owner_fence` and 409 for a stale `control_generation`, in both `materialize-prompts` and `chat/deferrals`, but the removed tests (test_materialize_capability_off_..., test_materialize_rejects_wrong_owner_or_generation_..., test_deferral_receiver_is_capability_gated_...) were the only tests exercising those responses. A regression that loosens or drops the fence now passes. Restore parametrized gate tests covering wrong-owner → 404, stale generation → 409, and capability-off → 404 for both endpoints.</comment>

<file context>
@@ -80,665 +62,53 @@ def _enable_chat_first(monkeypatch, *, generation: int = 7) -> None:
-    )
[email protected]('version', ['v1', 'v2'])
[email protected]('foreground', [False, True])
+def test_chat_open_serves_no_daily_cold_start_capture_or_queued_intents(monkeypatch, version, foreground):
+    _enable_chat_first(monkeypatch)
 
</file context>

result.detail.actionable_question_at_tail: "false"
result.detail.actionable_question_available: "false"
result.detail.deferrable_question_available: "false"
result.detail.prompt_materialization_requested: "false"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The covers: list still claims files this rewritten flow no longer reaches. The regression flow now only navigates to Chat, snapshots the tail, and asserts chat_first_request_prompt_materialization returns false; mainWindowDidBecomeForeground() is a hard-coded false in the retired coordinator, so the driver, journal materialization, block validation, content-block views, and deferral outbox are never invoked. Per the repo's e2e coverage rule, list a source only when the flow actually exercises and verifies its behavior: drop ChatFirstPromptMaterializationDriver.swift, AgentRuntimeProcess+ChatFirstJournal.swift, ChatFirstBlockValidation.swift, ChatFirstContentBlockViews.swift, and ChatFirstDeferralOutboxDriver.swift from this flow's covers: (the deleted step comments tied those entries to the S4/S8 reply/deferral and S8 driver-driving steps that no longer exist).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/e2e/flows/chat-first-question-deferral.yaml, line 57:

<comment>The `covers:` list still claims files this rewritten flow no longer reaches. The regression flow now only navigates to Chat, snapshots the tail, and asserts `chat_first_request_prompt_materialization` returns `false`; `mainWindowDidBecomeForeground()` is a hard-coded `false` in the retired coordinator, so the driver, journal materialization, block validation, content-block views, and deferral outbox are never invoked. Per the repo's e2e coverage rule, list a source only when the flow actually exercises and verifies its behavior: drop `ChatFirstPromptMaterializationDriver.swift`, `AgentRuntimeProcess+ChatFirstJournal.swift`, `ChatFirstBlockValidation.swift`, `ChatFirstContentBlockViews.swift`, and `ChatFirstDeferralOutboxDriver.swift` from this flow's `covers:` (the deleted step comments tied those entries to the S4/S8 reply/deferral and S8 driver-driving steps that no longer exist).</comment>

<file context>
@@ -37,115 +27,31 @@ preconditions:
-      result.detail.actionable_question_at_tail: "false"
-      result.detail.actionable_question_available: "false"
-      result.detail.deferrable_question_available: "false"
+      result.detail.prompt_materialization_requested: "false"
</file context>


test('old caches with discarded provenance are rehydrated instead of rendered', () async {
final prefs = SharedPreferencesUtil();
prefs.saveStringList('cachedMessages', [

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: This test passes for the wrong reason. SharedPreferencesUtil().cachedMessages returns [] unless cachedMessagesSchema == 1 (preferences.dart ~1083), and this test writes the raw string list directly while setUp starts from empty mock values, so the schema int is never set and expect(provider.messages, isEmpty) holds even if setMessagesFromCache had no filtering at all. The fixture message (type: "text", no metadata) also is not isAutomaticChatEntry, so provenance isn't actually being exercised. Write the cache through the cachedMessages setter and include provenance metadata in the fixture so the assertion depends on the filter being verified.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/test/providers/chat_history_state_test.dart, line 53:

<comment>This test passes for the wrong reason. `SharedPreferencesUtil().cachedMessages` returns `[]` unless `cachedMessagesSchema == 1` (preferences.dart ~1083), and this test writes the raw string list directly while `setUp` starts from empty mock values, so the schema int is never set and `expect(provider.messages, isEmpty)` holds even if `setMessagesFromCache` had no filtering at all. The fixture message (`type: "text"`, no metadata) also is not `isAutomaticChatEntry`, so provenance isn't actually being exercised. Write the cache through the `cachedMessages` setter and include provenance metadata in the fixture so the assertion depends on the filter being verified.</comment>

<file context>
@@ -48,6 +48,64 @@ void main() {
 
+  test('old caches with discarded provenance are rehydrated instead of rendered', () async {
+    final prefs = SharedPreferencesUtil();
+    prefs.saveStringList('cachedMessages', [
+      '{"id":"old","created_at":"2026-01-01T00:00:00Z","sender":"ai","type":"text","text":"Task","content_blocks":[{"type":"taskCard","id":"card","taskId":"task"}]}',
+    ]);
</file context>

meeting_receipt_mod.jobs_db,
'mark_meeting_receipt_intent_persisted',
MagicMock(return_value=True),
MagicMock(side_effect=AssertionError('automatic Chat intents are retired')),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This test's name and docstring are stale: it claims a desktop meeting "still wakes Chat" and persists a chat intent, but the removed intent_spy assertions and the new AssertionError guard on mark_meeting_receipt_intent_persisted mean the test now asserts the chat-intent path is retired. Rename it (e.g. ..._still_persists_receipt_without_chat_intent) and update the docstring so the guard's intent is clear.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_process_conversation_free_tier_branch.py, line 970:

<comment>This test's name and docstring are stale: it claims a desktop meeting "still wakes Chat" and persists a chat intent, but the removed intent_spy assertions and the new AssertionError guard on mark_meeting_receipt_intent_persisted mean the test now asserts the chat-intent path is retired. Rename it (e.g. ..._still_persists_receipt_without_chat_intent) and update the docstring so the guard's intent is clear.</comment>

<file context>
@@ -972,12 +967,12 @@ def minimum_process(_uid, _lang, conv, **kwargs):
         meeting_receipt_mod.jobs_db,
         'mark_meeting_receipt_intent_persisted',
-        MagicMock(return_value=True),
+        MagicMock(side_effect=AssertionError('automatic Chat intents are retired')),
     )
     monkeypatch.setattr(
</file context>

second = _client().post('/v1/chat/deferrals', json=body)
assert first.status_code == 200
assert first.json()['state'] == 'released'
assert first.json()['deferral_id'] == second.json()['deferral_id']

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The idempotency check reads second.json()['deferral_id'] without asserting second.status_code == 200. If the retry were ever rejected (404/409), the comparison raises an obscure KeyError on {'detail': ...} instead of a clear assertion, and the second response's state is never verified. Assert the second response's status and state before comparing IDs.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_chat_first_proactive_router.py, line 114:

<comment>The idempotency check reads `second.json()['deferral_id']` without asserting `second.status_code == 200`. If the retry were ever rejected (404/409), the comparison raises an obscure KeyError on `{'detail': ...}` instead of a clear assertion, and the second response's `state` is never verified. Assert the second response's status and state before comparing IDs.</comment>

<file context>
@@ -80,665 +62,53 @@ def _enable_chat_first(monkeypatch, *, generation: int = 7) -> None:
+    second = _client().post('/v1/chat/deferrals', json=body)
+    assert first.status_code == 200
+    assert first.json()['state'] == 'released'
+    assert first.json()['deferral_id'] == second.json()['deferral_id']
</file context>
Suggested change
assert first.json()['deferral_id'] == second.json()['deferral_id']
assert second.status_code == 200
assert second.json()['state'] == 'released'
assert first.json()['deferral_id'] == second.json()['deferral_id']

@@ -0,0 +1 @@
{"change":"Removed automatic goal, task, and meeting-note cards from Chat while keeping rich cards in replies"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Rich cards is internal renderer terminology (RichBlock views) and never appears in released changelog copy, where cards are described plainly ("file cards", "resource cards"). A user cannot tell what "rich" means here; say the cards still appear when they discuss goals, tasks, or meeting notes in a reply.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/changelog/unreleased/20261004-no-automatic-chat-cards.json, line 1:

<comment>`Rich cards` is internal renderer terminology (RichBlock views) and never appears in released changelog copy, where cards are described plainly ("file cards", "resource cards"). A user cannot tell what "rich" means here; say the cards still appear when they discuss goals, tasks, or meeting notes in a reply.</comment>

<file context>
@@ -0,0 +1 @@
+{"change":"Removed automatic goal, task, and meeting-note cards from Chat while keeping rich cards in replies"}
</file context>
Suggested change
{"change":"Removed automatic goal, task, and meeting-note cards from Chat while keeping rich cards in replies"}
{"change":"Removed automatic goal, task, and meeting-note cards from Chat while keeping those cards in replies"}

@@ -3,357 +3,21 @@ import XCTest
@testable import Omi_Computer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The retained test only reads fetchReceiptBatches and materializedBatches, so the rest of FakePromptMaterializationDriver is now dead: acknowledgementError, fetchError, suspendNextFetch/resumeFetch(), isFetchSuspended, fetchContinuation, windowForegroundValues, and acknowledgementBatches were exercised only by the removed tests. Trim the fake down to the minimal protocol implementation so it no longer implies suspend/resume and error-injection behavior that nothing tests.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/Desktop/Tests/ChatFirstPromptMaterializationCoordinatorTests.swift, line 7:

<comment>The retained test only reads `fetchReceiptBatches` and `materializedBatches`, so the rest of `FakePromptMaterializationDriver` is now dead: `acknowledgementError`, `fetchError`, `suspendNextFetch`/`resumeFetch()`, `isFetchSuspended`, `fetchContinuation`, `windowForegroundValues`, and `acknowledgementBatches` were exercised only by the removed tests. Trim the fake down to the minimal protocol implementation so it no longer implies suspend/resume and error-injection behavior that nothing tests.</comment>

<file context>
@@ -3,357 +3,21 @@ import XCTest
-      materializationReceipts: [receipt],
-      coldStartSequenceTerminalReceipts: [terminalReceipt]
-    )
+  func testOpeningForegroundingAndCompletingMeetingNeverFetchOrMaterialize() async {
     let driver = FakePromptMaterializationDriver(
-      context: ChatFirstMaterializationContext(ownerID: "owner", controlGeneration: 3),
</file context>

"metadataJson": metadata, "createdAtMs": 1000,
]))
}
let old = try entry(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This is the macOS suite's only exercise of the new KernelJournalTurn.isAutomaticChatEntry predicate, but the entry helper hardcodes origin: "typed_chat" and omits producerId, so several filter branches are never exercised: producerId prefixes (chat-first-intent:, cold-start-sequence:), origin/metadata proactive_notification, messageType == "day_summary", and the .questionCard(cold_start) check. Legacy automatic entries predominantly carry producerId: "chat-first-intent:... or cold-start-sequence:..., so a regression in those branches would pass this test. Add turns covering at least the producerId-prefix and proactive_notification provenance paths.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/Desktop/Tests/KernelTurnRecordedProjectionTests.swift, line 1458:

<comment>This is the macOS suite's only exercise of the new `KernelJournalTurn.isAutomaticChatEntry` predicate, but the `entry` helper hardcodes `origin: "typed_chat"` and omits `producerId`, so several filter branches are never exercised: producerId prefixes (`chat-first-intent:`, `cold-start-sequence:`), `origin`/metadata `proactive_notification`, `messageType == "day_summary"`, and the `.questionCard(cold_start)` check. Legacy automatic entries predominantly carry `producerId: "chat-first-intent:...` or `cold-start-sequence:...`, so a regression in those branches would pass this test. Add turns covering at least the producerId-prefix and proactive_notification provenance paths.</comment>

<file context>
@@ -1438,6 +1438,37 @@ import XCTest
+            "metadataJson": metadata, "createdAtMs": 1000,
+          ]))
+      }
+      let old = try entry(
+        "automatic", metadata: #"{"chatFirstIntentId":"old","chatFirstIntentSource":"capture_arrival"}"#)
+      provider.messages = [old.chatMessage()]
</file context>

Git-on-my-level and others added 3 commits October 4, 2026 22:35
Exclude automatic rows from the reported-row scan budget and cache epoch count. Restrict notification continuity filtering to AI turns and retain cold-start user answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep named-session app scoping coverage while asserting an empty history response and no greeting persistence. Preserve the clear-chat greeting regression.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 509f492 into main Oct 4, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/no-auto-chat-cards branch October 4, 2026 17:01
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Oct 6, 2026
Both fail on main itself and red every branch's Backend unit shards:
- BasedHardware#15171 moved the TTS routes to redis_db.check_tts_rate_limit_for_user, but
  test_desktop_tts_updates.py still matched check_tts_rate_limit.
- BasedHardware#20665 removed routers.action_items._wake_task_changes, which
  test_accept_shared_tasks_unavailable_claim_returns_503 still patched.

Byte-identical to BasedHardware#20748, so whichever merges first leaves the other a no-op.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
aryanorastar added a commit that referenced this pull request Oct 21, 2026
## Summary

Adds an opt-in, quiet macOS meeting-memory pilot on the existing
Conversations page. Within two hours of an upcoming local calendar
event, it can show a short card from a prior, confidently matched Omi
conversation: a decision, the user's open follow-up, and/or an
unresolved question. Every displayed item opens its source transcript.
When a completed meeting has cited, user-owned commitments, the
conversation menu can prepare an editable, copy-only follow-up draft.
The app never sends it.

This deliberately does not create a Chat card or notification. Automatic
cards in Chat were removed by #20665; this pilot keeps meeting context
in the Conversations destination and only when the user enables it.

## Matching and safety

- Match by the same local system-calendar event ID, or by an exactly
normalized event title of at least 8 characters **and** an overlapping
attendee email. A shorter, generic title ("Sync", "1:1") needs the exact
event ID, because one shared attendee cannot tell recurring meetings
apart. Never infer the match from an AI-generated conversation title
alone.
- Limit candidate conversations to completed, unlocked, non-deleted,
non-discarded meetings within 180 days. Skip a recent match with no
cited facts and try an older cited meeting; otherwise show nothing.
- Show only structured summary sections or explicit user-owned,
incomplete action items that carry transcript segment IDs. Clicking a
fact opens the source conversation and focuses those segments.
- Find a decision or open question first under a matching heading
("Decisions", "Open questions"), otherwise in the first cited summary
line that states it. Production summaries title sections by topic, so
most outcomes live in the text. One veto covers both paths: any negation
(except one that negates the agreed action itself: "agreed not to ask",
"decided never to store", "chose to not renew"), dispute ("disagreed",
"objected"), discussion, proposal, question, or pending wording omits
the line. The text fallback also needs a settled verb ("decided",
"agreed", "chose", "approved", "made a decision"), so "We will discuss
the decision next week" is not a decision. Imperatives under a real
Decisions heading ("Ship the smaller pilot first") still count. Lines
are classified whole and only shortened for the card, at the last whole
word with an ellipsis. When matched meetings yield no fact, the app logs
a count-only line.
- The brief setting offers an explicit Calendar access request;
background brief refreshes never prompt. Brief reads are read-only and
do not upload calendar data. (The pre-existing recording-context feature
has its own independent permission path.) A missing grant, match,
citation, owner, or network response fails quietly.
- Fence conversation reads and source navigation to the current
authorization snapshot so an account switch cannot display another
account's result. Dismissal keys include owner and meeting identity.
- Follow-up drafts require cited user-owned actions, stay editable,
include every eligible action in full (no truncation, so dates, links
and qualifiers survive), and have only a Copy action (no recipient or
send action).

## Product invariants affected

- `INV-AUTH-1`: optional conversation list/detail reads capture the
current authorization snapshot, recheck it after awaits, and never
publish stale owner content. The existing session invalidation and 401
policy are unchanged.
- `INV-NAV-1`: the brief is added to the canonical Conversations page,
preserving its established search, filters, folders, selection,
pagination, and navigation. No alternate shell-specific destination is
introduced.

Failure-Class: new

New class: Calendar purpose string without signing entitlement. The
initial pilot bundle had the Calendar purpose string but not the
hardened-runtime Calendar entitlement. `tccd` explicitly refused to
prompt (`kTCCServiceCalendar requires entitlement
com.apple.security.personal-information.calendars`), so the app never
appeared in System Settings. Both development and release signing inputs
now include the entitlement, and the named-bundle fallback has a
regression assertion.

## Verification

- Composer tests: 23 passed, 0 failed.
`testANegativeDecisionIsStillADecision` is built from the live
production summary line, and restoring the old blanket negation veto
fails it with 5 assertions. `testLongCardLinesEndAtAWordWithAnEllipsis`
fails 2 assertions against the old raw 240-character cut.
- Targeted Swift tests: 44 passed, 0 failed (matching, omission/locking,
citation focus, calendar read permissions, conversation decoding, draft
safety, and visible card rendering).
- SwiftLint: 0 new violations across 1,817 Swift files.
- Pinned swift-format and `git diff --check` passed on the changed Swift
and patch.
- The entitlement regression test and `plutil -lint` passed for
development/release entitlements and `Info.plist`.
- Isolated named macOS bundle `com.omi.omi-meeting-brief-pilot` passed
the full dependency audit, installed, and launched signed in. Its
effective code signature contains
`com.apple.security.personal-information.calendars=true`. After the
user-requested permission test, macOS listed the exact bundle with
**Full Access on**, and the Meeting Briefs setting became **on**. Audio
and screen capture were disabled in this test bundle.
- ![Live pilot app with Meeting Briefs enabled after Calendar
grant](https://raw.githubusercontent.com/aryanorastar/omi/feat/meeting-memory-brief/.agent-artifacts/ui-evidence/20824/001-desktop-macos-meeting-brief-calendar-enabled.png)
Live permissions/settings proof; this does **not** assert that a
source-matched card was shown.
- ![Meeting brief card rendered from synthetic, cited test
data](https://raw.githubusercontent.com/aryanorastar/omi/feat/meeting-memory-brief/.agent-artifacts/ui-evidence/20824/002-desktop-macos-meeting-brief-card-fixture.png)
UI fixture only, **not** a live matched calendar meeting or before/after
proof.
- Tracked evidence:
[.agent-artifacts/ui-evidence/20824/001-desktop-macos-meeting-brief-calendar-enabled.png](.agent-artifacts/ui-evidence/20824/001-desktop-macos-meeting-brief-calendar-enabled.png)
and
[.agent-artifacts/ui-evidence/20824/002-desktop-macos-meeting-brief-card-fixture.png](.agent-artifacts/ui-evidence/20824/002-desktop-macos-meeting-brief-card-fixture.png).
- **Live source-matched card, verified against production (Oct 12).** I
created a "Brief test sync" event on the synced calendar and joined a
real Discord voice call during it. The meeting detector marked the
session `role=meeting` and stored the event. A scripted two-voice
planning meeting (macOS `say`) then played through the speakers: 12 min
recorded, 6 min of speech, with one decision, one assigned follow-up,
one open question and an explicit "pricing is not decided". Production
(`api.omi.me`) summarized it and linked it to the event. I then moved
the event 40 minutes later. The Conversations page showed the card for
the upcoming occurrence, matched by the same system-calendar event ID.
- ![Live brief card before the next Brief test
sync](https://raw.githubusercontent.com/aryanorastar/omi/feat/meeting-memory-brief/.agent-artifacts/ui-evidence/20824/003-desktop-macos-meeting-brief-live-card.png)
Decided and Open question, both from the production summary. "Pricing
was not decided" was correctly not shown as a decision. Captured before
the ellipsis change, so the lines still end mid-word ("permissi"). They
now end at a whole word with "…".
- ![Clicking Decided opens the cited
transcript](https://raw.githubusercontent.com/aryanorastar/omi/feat/meeting-memory-brief/.agent-artifacts/ui-evidence/20824/004-desktop-macos-meeting-brief-live-source.png)
The source arrow opens the conversation with the transcript drawer on
the cited segment.
- Tracked evidence:
[.agent-artifacts/ui-evidence/20824/003-desktop-macos-meeting-brief-live-card.png](.agent-artifacts/ui-evidence/20824/003-desktop-macos-meeting-brief-live-card.png)
and
[.agent-artifacts/ui-evidence/20824/004-desktop-macos-meeting-brief-live-source.png](.agent-artifacts/ui-evidence/20824/004-desktop-macos-meeting-brief-live-source.png).
- The live run first showed only the open question. The decision line
("The team agreed not to ask for calendar access at first launch") was
vetoed by its "not". That is why negations that scope the agreed action
now count (above). No "You owe" line appeared because production created
no user-owned action item: the synthetic voice assigned the note to a
name spoken by Speaker 2, not to the account owner. This is the intended
fail-safe. The follow-up path stays covered by tests, not by this live
run.

## Pilot scope and follow-up

The first version searches the newest 100 completed conversations, so it
intentionally returns no card if the relevant prior meeting is older
than that fetch window. It has no external model calls and no new server
persistence. Dogfood should measure useful, source-confirmed briefs,
wrong matches, dismissals, and reviewed follow-ups before considering
broader exposure.
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
* test(backend): catch main up to the TTS rate-limit rename and retired task wake

#15171 renamed the offloaded rate-limit call to
redis_db.check_tts_rate_limit_for_user but left the desktop TTS unit
stub and its identity assertion on the old function name, and #20665
retired routers.action_items._wake_task_changes while the shared-task
503 regression still patched it. Both files failed on origin/main and
blocked every backend unit shard. Align the stub and assertion with the
renamed call and drop the stale wake patch.

* test(listen): guard lag-probe wiring and /metrics exposition

Prod listen pods showed no omi_listen_event_loop_lag_seconds series. The
code path is correct: every listen deployment runs an image older than
#22397 (backend:8d7778a is its parent), while Cloud Run backend runs
4f43b2d, which contains it. Pin the two links the D0b gate depends on:
run_listen_session starts the probe before building the runtime, and the
listen /metrics handler renders the histogram from import. Document the
image-tag check for a missing series.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(listen): tie exposition test to the route wiring; fix frame-histogram doc

Grok review on #22608: the exposition test did not use the listen route
import, and the doc said every loop histogram renders from import, which
is false for the codec-labelled frame histogram. Assert the route ->
runtime -> probe module chain and the import-time registry collector, and
document that the frame series appears only after the first timed frame.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(listen): frame histogram child appears at receive-loop entry, not first frame

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(listen): exercise the deployed app's /metrics exposition in a fresh process

Codex review: the exposition test imported routers.listen.runtime itself
and called the metrics handler directly, so it kept passing if main.py
stopped registering metrics.router, and its zero-count check only asserted
the series name after earlier tests in the same file had already
incremented the process-global histogram.

Run the assertion path in a fresh interpreter instead: install the
hermetic network blocker, import main (the deployed listen entrypoint per
backend/Dockerfile CMD), make an unauthenticated request (401) and an
authenticated one (200) through the real app routing, and assert the exact
import-time 'omi_listen_event_loop_lag_seconds_count 0.0' with no probe
started before or after serving. Subprocess CPU is not charged to the
fast-unit duration guard, and the network blocker proves the path stays
hermetic for the no-Redis CI lane.

Failure-Class: none

* test(sync): legacy import ratchet and enrichment outbox contracts

Plan C (legacy sync consolidation) PR C1. Tests only; no runtime change.

- tests/unit/test_sync_legacy_import_ratchet.py + fixtures/sync_legacy_import_baseline.json:
  freezes the 10 current importers (outside utils/sync and routers/sync.py) of the
  19 legacy sync modules scheduled for retirement; new edges fail, stale edges must
  be removed, every edge carries a reviewed "why".
- tests/integration/test_enrichment_outbox_contract_emulator.py: Firestore-emulator
  contracts for the sync enrichment outbox that the utils/enrichment move must keep:
  first-summary wake within 120s, coalescing, stale-token refusal, lease expiry
  repaired by the sweep, redirect custody transfer and the privacy fence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(sync): address review — selector coverage, keyword imports, fixture teardown

- Ratchet now runs for every in-scope importer on changed-file CI, not only
  the post-merge --all run: new shared scope predicate
  (tests/support/sync_legacy_ratchet_scope.py) wires the selector the same
  way the background-task ratchet is wired, so an importer under e.g.
  backend/utils/apps selects test_sync_legacy_import_ratchet.py. Contract
  tests pin the predicate against the ratchet's own scope.
- import_module detection also accepts the keyword form
  (name='utils.sync.pipeline'); non-literal names still detect nothing.
- Enrichment outbox emulator fixture deletes dormant receipts and synthetic
  conversation documents by key on teardown (uid is cleared on dormant rows,
  so the uid-query teardown misses them; parent deletes keep subcollections).
- All function-local imports in the integration test hoisted to module
  scope (backend AGENTS.md import rules).
- Baseline gains the reviewed upstream edge
  scripts/cap_hold_durability_emulator_test.py -> utils.sync.pipeline
  (rebased onto main that introduced cap-hold durability).

* test(sync): address review — aliased import_module, survivor scope, selector tuple

- import_module detection now resolves aliases bound by
  'from importlib import import_module as load'; calls through the alias
  with a literal module name are dynamic-import edges. Non-importlib
  aliases with the same call shape still detect nothing (parametrized).
- The ratchet no longer excludes the whole utils/sync/ package: only the
  retiring modules themselves and routers/sync.py are out of scope, so
  surviving in-tree callers (cap-hold core, recording_session_target)
  are scanned and their legacy edges are frozen in the baseline with
  reviewed whys. These are exactly the edges C11 (#22635, keep the
  cap-hold core) must cut; the shared selector predicate keeps its
  cheap superset and still defers narrow area selection to AREA_TESTS.
- SYNC_LEGACY_RATCHET_TESTS now selects only the ratchet itself.
  test_workflow_contracts.py has no legacy-ratchet assertions; it keeps
  its own selection via workflow contract sources and backend/testing/
  full-run prefixes, instead of riding every backend-Python selection.

* test(listen): keep the child's network guard referenced for its whole body

Codex review: 'block_outbound_network().__enter__()' drops the only
reference to the _GeneratorContextManager, so CPython finalizes it (and
its finally block restores the socket functions) before 'import main'
runs — the hermetic claim was inert, and an environment supplying Stripe
credentials could turn the import into real network calls. Enter the
guard through an ExitStack held for the entire child body.

Failure-Class: none

* test(sync): address review — proven import_module bindings, relative targets, fence/IO contracts

- Dynamic-import detection now requires proven importlib bindings: attribute
  receivers bound by 'import importlib [as imp]' and bare names bound by
  'from importlib import import_module [as load]'. An unrelated
  obj.import_module(...) or a local function named import_module no longer
  fabricates a legacy edge and fails changed-file CI (V8).
- Relative import_module targets ('.pipeline', package='utils.sync') resolve
  against the literal package argument — positional or keyword — with each
  leading dot beyond the first trimming the package, mirroring the
  interpreter. A relative name without a literal package detects nothing (-s).
- Privacy-fence contract now exercises the race it names: phase 1 keeps the
  pre-blocked discard (entry fence), phase 2 lands the block between the
  entry fence and the claimed callback and proves the adapter's inner
  discard_blocked discards without ever invoking work; blocks are cleared
  between phases so each parametrized block path is really driven (-z).
- Malformed-binding rejection now proves 'before any IO': the Firestore
  client accessor is replaced with a fail-fast mock for both the adapter and
  the outbox, so any pre-validation read/write fails the test (WB).

* test(jobstore): port recovery discovery and progress parity invariants

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): carry recovery custody invariants across job stores

Failure-Class: FC-empty-asr-without-context-recovery

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): pin recap fixture to a reproducible admission time

The unmodified main test fails five assertions before noon because its fixture and recap selection use different dates. Pass one explicit afternoon instant through the existing production input seam; keep every assertion and production behavior unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): port recovery and admission parity invariants

Carry PL-057, PL-072 and PL-086 through the shared Store matrix. Keep the new-store cancellation gap strict and linked to issue #23761.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mobile-perf): upload-success window, sparse scoring, semantics knob; tag lag stalls with work in flight

- --upload accept --upload-wals N appends wal_sync_upload_success: synthetic
  uploads and jobs drive real sync phases, persistence and reconcile.
- cold_start, home_idle_sync_refresh and the upload window are sparse: cold
  readiness keeps the 15% spread gate and each run has a stall budget (<=2
  stalls over 100 ms, <=500 ms). Dense windows keep 15% p90; no run dropped.
- Semantics is off for heavy perf by default; --semantics on is a separate
  dataset and compare refuses mixed settings.
- LagWorkRegistry: bounded, allocation-free begin/end; mobile_lag_stall
  records overlapping sync/upload/reconcile/WAL-load work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mobile-perf): dry-run tests pass an explicit artifact root

Without one, device_run.main() exits 2 on hosts with no scratch mount, so
the manifest check failed on ordinary Linux checkouts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(jobstore): qualify fenced shard pulls across stores

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(jobstore): require available backends in the selected proof lane

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(outbox): preserve durable enqueue across wake failures (PL-042)

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(outbox): verify committed enqueue result identity

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): qualify partial-pull leases across store backends

Port PL-194 into the shared scheduler/Store matrix and existing emulator proof lane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): qualify pending deletion across old and new stores

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): PL-049 positive-speech custody follows the one Soniox second chance

Main a866d27 (10-30) gives Modulate-empty held units with positive speech one independent Soniox
second chance. The PL-049 case written 10-26 asserted no second provider at all, so it failed on every
store after the merge. It now pins the new contract: the second chance is spent at most once across
repeated sweeps, and an uncertain call keeps audio, intent and custody held. Measured silence still
settles without any paid call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: qualify pull-batch parity across Firestore and Postgres

Preserve PL-321/322/323 at frame boundaries, buffered query overlays and bounded walk stops. Register the shared matrix in the existing emulator-proof runner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: clean coordination fixtures within their owned namespace

Include merge holds beside pull claims and prove cleanup preserves foreign namespaces and synthetic customer rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): enforce held-custody and no-spend recovery parity

Qualify PL-061, PL-105 and PL-363 on old Firestore, new Postgres
and the simulator through the existing Store harness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): keep partial-custody identity distinct from producer outcomes

Use PL-396 for phone custody and leave PL-061 producer client_status
as a separate missing invariant in the parity ledger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): declare isolated stage and fence paid refusal markers

Make the conformance fixture independent of CI stage defaults and
reject paid-attempt metadata on a local no-spend refusal. Clarify
minimum CI stores versus all-store cutover qualification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* style(firmware): match CI clang-format on the safe-mode snapshot initializer

CI's clang-format 18 attaches the compound-literal brace and drops the
space before it; break nothing else and keep the initializer alignment
one column left.

* test(backend): keep the enrichment proof clock a real clock

The consumer's heartbeat hold cap reads time.monotonic, so the injected
consumer clock must carry the full time module with only the wall-clock
pinned, or every PL-397 delivery dies on AttributeError before the
callback runs.

* style(firmware): drop the compound-literal brace space CI's clang-format rejects

CI formats firmware with clang-format 18, which attaches the brace after
the compound-literal cast; the local 23 kept a space and realigned one
column right, so the Formatting job failed on the merge preview. Commit
with clang-format 18 first on PATH so the pre-commit hook agrees.

* test(backend): inventory lifecycle writers and latch invariant gaps

* test(backend): re-baseline the legacy-sync import ratchet to the folded tree

The ratchet fixture arrived from #22390 with a baseline ~4.5k commits stale:
main gained nine importers of the retiring legacy sync modules (staging
syncsplit proof, backfill worker control/job, empty-success guard, watch
recovery e2e, capture coverage lanes) and lost two baseline edges
(enrichment callback, cap_recovery_audio coverage replay). Regenerated with
the ratchet's own --write pass, then reviewed each edge's why against the
retire milestones (C10/C11).

* test(backend): align partial-pull conformance with the current lease API

The PL-194 file predates two scheduler changes main landed since its base:

- The pull transaction now returns (receipts-or-None, eligible, observations)
  where each receipt is (lease, enqueued_at, relet); Scheduler.pull is what
  unwraps receipts into LeasedWork. The conformance helper treated
  result[0][0] as a lease, so its committed list held receipt tuples against
  pull's LeasedWork list, and aborted['lease'].item raised AttributeError.
  Unwrap receipts to the lease on both sides so the whole test speaks the
  one shape main's lease API returns.

- A multi-lease abort rolls back every receipt in its transaction, so the
  exact 'failing_lease - 1 committed' count only holds one lease per
  transaction; pin the documented BATCH_PULL_MULTI_LEASE_ENABLED kill
  switch (as the file already pins shard spread and cap dispatch).

- Shard-spread selection reads control_candidates (plural fanout), not the
  singular control_candidate the overlap test paused; hook both, each
  wrapping its own original, since the singular delegates to the plural.

All 24 partial-pull parametrizations plus both overlap cases pass on sim
and Postgres locally; emulator legs stay with CI's proofs job.

---------

Co-authored-by: David Zhang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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