Skip to content

feat: follow-up chips, learned-memory review card, daily-summary tail fix, knows-list rotation - #12635

Merged
Git-on-my-level merged 16 commits into
mainfrom
feat/ask-teach-prove
Sep 3, 2026
Merged

Git-on-my-level merged 16 commits into
mainfrom
feat/ask-teach-prove

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Four engagement fixes from the 2026-09-02 "Ask, Teach, Prove" evaluation, shipped together because they share one contract (the daily summary's memories_learned review card) and one measurement (question_asked origin attribution).

  1. Follow-up after every grounded typed answer. On the owner's account the realtime voice lane already ends 65% of answers with a grounded question and those sessions run ~4 turns; the typed lanes end with a question 4–9% of the time and recall answers 0%, while 57% of asker-days are exactly one question. The agentic chat lane and the desktop typed lanes now append exactly one specific, answerable question after a <<<FOLLOWUP>>> tail; the backend strips the tail and delivers it as a followUp content block, a streaming filter keeps it out of the prose, and both shells render it as one tappable chip. Suppressed in code (not just prompted) on failed, errored, cut-short, empty, or clarifying turns; the floating bar's failure copy drops its "try again" invitation, which the data showed nobody took.
  2. "Things I learned today" review card in the daily summary on both shells. The summary's knowledge_nuggets were LLM prose with no memory identity, so there was nothing to accept or reject. The summary now carries memories_learned (up to three memories the day's conversations actually produced, selected deterministically through MemoryService, zero new LLM calls) and the day_summary message carries a memoryReviewCard content block. Rows offer ✓ / ✗ / Fix through the existing review and edit endpoints, and the memory service stays the single mutation owner. State is read from the local memory rather than re-fetched: a vote made on this device is mirrored immediately, and a vote made on the phone appears once the memory sync has run. There is no single-memory GET to make that read authoritative, so "instantly cross-device" is not claimed. ✗ already feeds bounded rejection feedback into extraction, so the "I'll avoid facts like this" copy is true.
  3. Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530: daily summaries silently stopped for tail-of-batch users (on the owner's account, since 2026-08-23). Per-user isolation, a per-user budget, a job budget under the 600s task limit with a Redis checkpoint that rotates the next run to the unserved tail, a bounded generator input, and loud per-user failure lines plus a job-end summary. Fixes Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530.
  4. Home knows-list repetition. The list repeated the same four stale commitments 8–12 times each over two weeks because its dismiss state died with the view. An owner-scoped impression ledger now rotates rows out after three unopened shows, never resurrects a dismissed row until its content changes, excludes stale or completed tasks, and leaves a slot empty rather than repeating.

Also: question_asked gains an origin property (followup | chip | card | unprompted) so each surface's funnel is readable, and daily_summary fallback telemetry is registered.

Evidence: omi-knowledge-base projects/engagement-feedback-loop, macos-churn-analysis/evidence/2026-09-02-first-48h-activation-and-pr-12608.md, and the follow-up-vs-pills evaluation (session scratchpad, 143 turns / 48 sessions).

Review round: what the bot found, and what was true

cubic-dev-ai raised 40 findings. Each was verified against the code path before
anything changed; several were wrong about the mechanism while right about the
symptom, and a few were simply wrong. Fixed, with the load-bearing ones first:

  • The review card never shipped. The scheduled job called the summary
    generator without memories_learned, so the field was always empty and the
    memoryReviewCard block was never attached on the only path users receive.
    The feature was a no-op in production. Both senders now select through one
    helper.
  • The failure copy was read aloud. This PR changed the empty-response text
    while shouldSpeak still suppressed one hardcoded string, so a failed voice
    query started speaking its own failure. Copy and guard now share one source.
  • The server rejected the card the Mac sends. The desktop adapter converts a
    memoryReviewCard for the chat-first journal, but the block was not in the
    server union, so it was rejected as invalid_request. Added to the request
    union only: the server never emits this block, and adding it to the response
    union is a breaking change to a released app-client contract.
  • The streamed follow-up tail leaked. ChatStreamingBuffer wrote the
    normalized projection back into the message and appended the next delta to it,
    so a projection that withholds the tail lost the evidence it needed and
    streamed the chip's question into the prose a token at a time. A replay of
    every flush boundary leaks at every boundary from the delimiter onward, not
    only at a split marker. Display-only, since the terminal answer overwrites it.
  • The checkpoint could not resume. The cursor key carried the UTC hour, so
    the run that wrote the tail and the run that should have resumed it never
    shared a key, which defeated the point of the Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530 fix. Also: a failed
    timezone chunk let the run call itself complete and clear the cursor.
  • The FCM payload was unbounded. An oversized card would have cost the whole
    daily-summary push, not just the card. Now bounded, block dropped first.
  • Plus: multi-question chips, chips on guard-stopped turns, generic-prefix rules
    that diverged between client and server, a permanent optimistic override on
    mobile, a duplicated question when a follow-up block had no prose, per-item
    decoding so one bad row cannot drop the array, owner-scoped knows-list visits,
    and greeting counts that disagreed with the rows they described.

Three findings were rejected with evidence rather than fixed: the claim that
the stream filter persists its withheld suffix (the persisted answer is built by
the producer, and flushing would have pushed the fragment into the stream);
the prescription to reclassify a safety-guard stop as a provider failure (an
explicit, tested contract says a guard stop is a deliberate reply); and a pytest
marker that would have removed a file from CI entirely. Mobile localization stays
deferred, matching every neighbouring widget.

End-to-end coverage: made real, not declared

An earlier commit on this branch satisfied desktop-e2e-flow-coverage by adding
covers: entries to two flows that never exercise the code. The gate is a text
match over the covers: list and never inspects steps, so the claim cost
nothing to write and would have given false confidence. Those entries were
removed, and the coverage was then built for real. Three new or extended flows:

  • Chat follow-up. The hermetic stub can now emit a follow-up tail, the chat
    automation snapshot exposes the chip question, and a bridge action taps the
    chip and reports the origin the analytics emit actually carried. The flow
    asserts the visible answer by exact equality, which is what catches a tail
    left in the prose.
  • Memory review card (memory-review.yaml). A local-only dev-harness route
    seeds a summary; the flow creates the memories through the production
    endpoint, renders the card, accepts one row and rejects another through the
    same store the buttons call, then re-reads to prove both verdicts survive the
    post-mutation refresh.
  • Knows-list rotation (home-knows-rotation.yaml). Seeds tasks, clears the
    ledger through the same persistence the mutations use, and pins the first
    visit's rows, the within-visit de-duplication, and a later visit's view of a
    dismissed row and a merely-shown row.

ChatStreamingBuffer was initially judged uncoverable, because the defect is
mid-stream and the terminal answer overwrites the streamed text before any
assertion runs. That is true of assertions on the final text only. A non-prod
probe now keeps its own raw stream, compares every emitted projection against
the shipped tail-stripping rule, and the flow asserts zero leaks alongside two
liveness assertions so the zero cannot be vacuous. A negative-control unit test
feeds the probe the exact projection the pre-fix buffer emitted and asserts it
is counted.

Three things are deliberately not claimed, and say so next to their covers:
entry: the empty-slot telemetry (forcing it would require owning the account's
whole candidate pool), the three-show cap (it needs three calendar days or an
injected clock, and is unit-tested instead), and the 14-day stale-task rule,
which is unreachable from the hub because the dashboard query already cuts off
at seven days. That last one is a real finding and wants a follow-up.

Invariants

Path-matched by scripts/pr-preflight --suggest:

  • INV-AUTH-1: no change to auth; touched routers only add response fields and a content block.
  • INV-CHAT-1: chat continuity preserved; the follow-up block rides the persisted message and the terminal frame, never a second message.
  • INV-NAV-1: no navigation changes; the follow-up chip sends in the same lane.
  • INV-VOICE-1: realtime hub prompt untouched; the floating bar's failure copy changed only to remove a retry invitation.
  • INV-MEM-4: no new promotion path. An edit re-enters short-term as user-asserted and consolidation decides; a ✓ is a review, not a promotion.
  • INV-MEM-1: memory reads go through MemoryService; the summary stores memory ids, never a second copy of review state.

Failure class

Failure-Class: FC-batch-fault-domain-head-of-line-poison

That is the PR-level declaration (the #12530 fix). The protocol allows one per PR body; the other two fix commits carry their own trailers and are recorded here for the reader:

  • b8fd1ef8e8 / 47d5d96fb9: FC-durable-state-scoped-to-view-lifetime. The knows-list dismiss state was a view @State and died with the view.
  • a7aba22030: FC-model-import-reaches-persistence-client. The first contract commit read memories inside the LLM summary generator, which pulled the Firestore client into every caller and every hermetic test of that generator; the read now lives at the endpoint and learned_today is an import-pure leaf.

Line-count exceptions

Line-Count-Exception: backend/routers/chat.py | 2097 -> 2107 | follow-up block attached where the assistant message is persisted; splitting the router is out of scope
Line-Count-Exception: backend/routers/users.py | 2247 -> 2295 | memories_learned wired at both summary call sites next to the uid/window they own
Line-Count-Exception: backend/utils/retrieval/agentic.py | 1690 -> 1736 | prompt section appended beside the existing url-fetching block; the live prompt is LangSmith-fetched so this is the only place it takes effect
Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarView.swift | 3090 -> 3112 | exhaustive switch cases for the two new block types
Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarWindow.swift | 5735 -> 5752 | exhaustive switch cases for the two new block types
Line-Count-Exception: desktop/macos/Desktop/Sources/MainWindow/Components/ChatBubble.swift | 2032 -> 2082 | follow-up chip and review card render cases in the authoritative bubble renderer
Line-Count-Exception: desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift | 4186 -> 4328 | knows-list impression handoff; the ledger and policy live in new files
Line-Count-Exception: desktop/macos/Desktop/Sources/Providers/ChatProvider.swift | 7156 -> 7200 | streaming tail filter and block cases; the parser lives in Chat/ChatFollowUpTail.swift

Verification

  • make preflight: all manifest checks pass except the line-count ratchet, cleared by the exceptions above.
  • Backend: bash test.sh over the changed and neighbouring test files (follow-up block, daily-summary contract, job resilience, race condition, zero-coordinate locations, stream error fallback, Dart/Swift generator guards) green under the duration guard; typecheck.sh 0 errors; OpenAPI app-client export written, public and integration surfaces --check clean, compatibility passed against merge-base f50229752b; Dart and Swift generators --check clean.
  • Desktop: swift build -c debug green; swift test for ChatFollowUpChipTests, MemoryReviewCardTests, HomeKnows*, ChatDailySummaryTests, HomeDailySummaryTests, ChatContentBlock* (see the last CI-equivalent run in the PR checks); swift-format and SwiftLint clean; check_desktop_test_quality.py at baseline.
  • Mobile: bash app/test.sh all passed (+1695); analyze_ratchet.sh passed; dart format clean.

Not done here

  • No dogfood on a signed-in bundle: the review card needs a deployed backend that emits memories_learned. Dogfood owed before beta promotion. The desktop mirror write on a review vote has no hermetic test (it talks to the real storage singleton), so that is the first thing to check by hand.
  • None of the three new or extended e2e flows has been executed. Tier 2 needs Docker, and docker info fails on the authoring machine. Both sides of every string they assert are pinned by unit tests so drift fails in seconds rather than only at flow time, and the streaming probe has a falsifiable negative control. But someone with Docker must run chat-hermetic, memory-review, and home-knows-rotation before these are trusted. Two knows-list step expectations in particular rest on a reading of the composer's slot ordering that only a real run can confirm.
  • An unserved user is still not re-queried an hour later: get_users_for_daily_summary matches local_hour == preference, so eligibility lasts exactly one local hour and the checkpoint only recovers the tail if the job runs more than once per hour. The repo disagrees with itself about the cadence and the real Cloud Scheduler setting is not in the tree; worth confirming.
  • Interject "hold ⌥ to correct" is not wired to the review rows (one-line hook comment marks the spot).
  • Mobile strings are hardcoded English, matching the adjacent chat chrome; l10n follow-up owed.
  • tests/unit/test_daily_memory_sweep.py::test_folder_backstop_never_overwrites_and_requires_obligation hangs on an idle machine and is in CI's selector; pre-existing, tracked separately.
  • From the Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530 watchdog thread, two items need a maintainer and are not in this PR: the scheduler runs */1 * * * * instead of hourly, and day_summary_webhook is fire-and-forget on postprocess_executor and dropped at job exit.
  • The summary generator receives a bounded conversation set; a truncated day reports the truncated count and emits daily_summary_input_truncated, but the prompt carries no in-text marker.

🤖 Generated with Claude Code

Git-on-my-level and others added 16 commits September 2, 2026 16:51
The on-device realtime voice lane already ends ~65% of its answers with a
grounded question and those sessions run ~4 turns. The typed lanes end with a
question 4-9% of the time, and recall answers ("what did X say", "when did
we...") 0% of the time even though 71% of them have a strong next hop into the
same source available. 57% of asker-days are exactly one question; the 1->2
continuation rate among those who do continue is 83%. The missing turn is the
one Omi never invited.

The agentic chat lane now asks the model to append exactly one specific,
grounded, answerable question after a `<<<FOLLOWUP>>>` marker on its own final
line. The backend strips the marker and everything after it from the visible
text and delivers the question as a `followUp` content block on the persisted
assistant message, so the chip's words are never also in the prose. A streaming
filter withholds the tail (and any partial marker) from the token stream the
user watches, so it never flashes into the answer before the terminal frame.

Suppression is the other half: no block on a turn that failed, errored, timed
out, or was cut short, none on an empty answer, and none when the answer is
itself a clarifying question back to the user. The prompt adds refusals,
capability denials, "I couldn't find that", and general-knowledge questions to
that list.

Verification:
  backend/.venv/bin/python -m pytest tests/unit/test_chat_followup_block.py -q
    -> 20 passed
  ... tests/unit/test_chat_stream_error_fallback.py
      tests/unit/test_chat_quota_counting_router.py
      tests/unit/test_chat_agent_loop_guard.py -q
    -> 27 passed
  ... tests/unit/test_agentic_web_search_taint.py
      tests/unit/test_chat_async_offload.py -q
    -> passed (a pre-existing sys.modules ordering failure in
       test_prompt_cache_integration.py reproduces identically with this
       file restored from HEAD, so it is not from this change)
  scripts/backend-python-format --write <changed files>

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

`knowledge_nuggets` is LLM prose with no memory identity, so a shell cannot
show what Omi actually stored, and the owner cannot accept, reject, or correct
it. Add `memories_learned: list[LearnedMemoryRef]` (memory_id, content,
category, captured_at) to the stored daily summary and to
`DailySummaryResponse`, plus a `memoryReviewCard` content block on the
`day_summary` push so both shells can render a native check / cross / fix card.

Selection is deterministic — zero new LLM calls. `utils/memory/learned_today.py`
reads one bounded page through the canonical `MemoryService.read` path (so
canonical and historical rows both qualify under one visibility policy), keeps
memories attributed to the same conversation set the summary was built from
(falling back to the local-day window for a memory with no conversation
evidence), drops rejected / locked / invalidated / superseded / empty rows,
orders by capture_confidence then veracity then newest, and caps at 3. A memory
read failure degrades to "no card", never to "no summary".

Review state is deliberately absent from the stored summary: clients read
`user_review`/`edited` live from the memory, so a vote on one device shows on
the other. Votes go through the existing
`POST /v3/memories/{memory_id}/review?value=<bool>` and edits through
`PATCH /v3/memories/{memory_id}` with `{"value": "..."}` — no new mutations.

The push `text` is unchanged and the block is omitted entirely when nothing
qualifies, so clients that do not know the block render exactly what they
rendered before. FCM data is Dict[str, str], so `content_blocks` travels as
JSON text, matching the batched-action-item payload already in
`utils/notifications.py`.

Verification:
  backend/.venv/bin/python -m pytest tests/unit/test_daily_summary_memories_learned.py -q
    -> 25 passed
  BACKEND_UNIT_TEST_FILE_LIST=<150 daily-summary/notification/users/generator files> bash test.sh
    -> all tests passed; one unrelated file (test_action_item_idempotency.py)
       tripped test.sh's load-sensitive CPU duration guard at 0.31s > 0.30s
       with all 13 of its tests PASSED
  backend/scripts/typecheck.sh -> 0 errors
  scripts/backend-python-format --write <changed files>
Regenerated artifacts for the `memories_learned` daily-summary field:

- docs/api-reference/app-client-openapi.json — new `LearnedMemoryRef` schema
  and the `DailySummaryResponse.memories_learned` array (additive optional
  response field only).
- app/lib/backend/schema/gen/users_wire.g.dart — `GeneratedLearnedMemoryRef`
  and `GeneratedDailySummaryResponse.memoriesLearned`.
- backend/scripts/generate_dart_models.py — the Dart `users` group selects
  schemas explicitly, so `LearnedMemoryRef` is registered there; without it the
  generator refuses the $ref rather than emitting an untyped map.

The Swift generator's TARGET_SCHEMAS does not include DailySummaryResponse and
nothing transitively pulls the new schema, so OmiApi.generated.swift is
unchanged and its freshness check still passes.

Verification:
  backend/scripts/openapi_runner.sh scripts/export_openapi.py --surface app-client \
    --write ../docs/api-reference/app-client-openapi.json
  backend/scripts/openapi_runner.sh scripts/export_openapi.py --check ../docs/api-reference/openapi.json
    -> up to date
  backend/scripts/openapi_runner.sh scripts/export_openapi.py --surface integration-public \
    --check ../docs/api-reference/integration-public-openapi.json -> up to date
  python3 backend/scripts/check_app_client_openapi_compatibility.py --base-ref origin/main
    -> compatibility passed against merge-base f502297
  backend/scripts/generate_dart_models.py --all --check -> up to date
  backend/scripts/generate_swift_openapi_types.py --check -> up to date
  pytest tests/unit/test_app_client_dart_generator.py tests/unit/test_app_client_swift_generator.py -> passed
Mobile decoded `content_blocks` but rendered none of them natively, so the two
new blocks would have shown as fallback prose or nothing at all. Render both:

- `memoryReviewCard` becomes a "Things I learned today" card of up to three
  rows, each with the paraphrase, a small category label, and ✓ Right /
  ✗ Wrong / Fix. It appears under the `day_summary` chat message and, from
  `memories_learned`, on the daily-summary detail page above the existing
  prose learnings, which are untouched.
- `followUp` becomes one tappable chip under an answer; tapping sends the
  chip's own words through the existing chat send path.

Review state is never stored in the message or in preferences. Each row reads
`user_review`/`edited` live from `MemoriesProvider`, which stays the single
mutation owner: ✓/✗ go through `reviewMemory` (POST /v3/memories/{id}/review)
and Fix through `editMemory` (PATCH /v3/memories/{id}). A tap paints
optimistically only until its request returns, then the row goes back to
reading the live memory, so a verdict cast on desktop shows here and a failed
write reverts with "Couldn't save, try again" inline. A memory the provider has
not loaded renders its content with the controls disabled and asks the provider
to load once, bounded per id so a scrolled chat list cannot refetch in a loop.

The `day_summary` message reaches mobile only as an FCM push, and FCM data is
Dict[str, str], so `content_blocks` arrives as JSON text. The strict generated
`List<Map>` reader rejected that outright, which would have dropped the whole
message. `ServerMessage` now decodes content blocks the way it already decodes
evidence — outside the generated DTO, through a fail-soft parser that tolerates
JSON text and degrades anything malformed to no blocks. `_blockFallbackText`
answers "Things I learned today" and the question text for the two new types;
every other block type is unchanged.

Verification:
  bash app/test.sh -> +1695 ~5, All tests passed
  flutter test test/unit/memory_review_block_test.dart
    test/unit/server_message_content_blocks_test.dart
    test/widgets/memory_review_card_test.dart
    test/widgets/chat_content_block_test.dart
    test/widgets/daily_summary_detail_page_test.dart
    test/widgets/chat_scroll_layout_test.dart
    test/widgets/chat_citation_taps_test.dart
    test/widgets/daily_summary_card_test.dart
    test/providers/knowledge_ledger_review_test.dart -> +66, All tests passed
  bash app/scripts/analyze_ratchet.sh -> Analyzer ratchet passed
  dart format --line-length 120 <changed .dart files> -> 0 changed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The daily-summary Cloud Run Job has a hard 600s task timeout and serves
tens of thousands of users. An execution that ran out of wall clock was
SIGKILLed mid-batch and the next execution restarted from the head, so
users past the kill point were never reached on any run and produced no
error of their own — the owner's dogfood account received nothing from
2026-08-23 onward while the pipeline looked healthy (#12530).

Three unbounded fault domains, all in the same job:

* The hour-group loop sat inside one try/except, and the per-hour user
  query fanned out with a bare `asyncio.gather`. One group's Firestore
  failure threw away the other 23 groups.
* Nothing bounded a single user. A wedged provider call held the
  batch-of-8 barrier for as long as it liked.
* Nothing bounded the generator's input. The summary prompt renders the
  user's whole day, and one account's day overflowed the model context
  window (~290k tokens against a 272k limit), returning a provider 400
  every day since at least 2026-08-25.

The job now runs to its own budget (480s, below the task timeout),
processes hour groups and users in a deterministic order rotated to a
Redis checkpoint so the next execution starts at the unfinished tail,
isolates and records every per-user failure, and closes with one
attempted/succeeded/failed/timed_out/skipped_for_budget line. Fail-open
branches go through the shared `record_fallback` helper under a new
`daily_summary` component. Losing Redis costs a re-walk, never a summary.

Also wires the `memoryReviewCard` content block into the scheduled send,
which previously only existed on the /v1/users/daily-summary-settings/test
path. The message text is byte-identical and the block is omitted when the
day produced nothing to review.

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Over 14 days on the owner's account the hub's knows-list re-showed the same
four commitments 8-12 times each ("meet with <person>" ~9x, "improve meeting
notes quality" ~8x) and its only engagement was the reader asking the card to
explain itself. The composer deliberately fills fixed typed slots so the list
stays diverse, but it had no memory of what it had already shown: dismissals
lived in a `@State Set<String>` that died with the view, and nothing recorded
an impression at all, so a thin source repeated itself on every visit.

Add an owner-scoped impression ledger (`ScopedDefaultsKey.homeKnowsImpressions`)
with a single mutation owner, `HomeKnowsImpressionStore`. The view reads a
snapshot taken when the list appears and hands every show, open, and dismiss
back to the store; it never writes the ledger itself.

Rules, all deterministic and clock-injected in `HomeKnowsRotationPolicy`:

- a row shown 3 times without ever being opened rotates out for 7 days;
- a dismissed row never returns unless its underlying object changes (new
  updated_at or new content hash) - which also resets the show cap;
- a task more than 14 days past due, or completed/deleted, is excluded;
- the same row is not shown twice in one calendar day unless nothing else
  qualifies for that slot AND the reader has opened it before;
- a slot with no qualifying candidate stays empty. The list may be shorter
  than four rows; it never falls back to the repeated row.

Within a slot, candidates are ordered never-shown first, then fewest shows,
then most recent underlying update. The diverse task - tip - task - ask
structure is unchanged.

One impression is one visit, not one render: the existing 7-second rotation
timer re-renders the same row every few seconds and must not burn through the
show cap, so the store de-duplicates per visit.

Telemetry: `desktop_home_knows_row` with `{kind, slot, shows_before}` for a
shown row and `{kind: "empty", slot, rotated_out_reason}` for a slot left
empty. Bounded dimensions only - row text is the reader's own tasks and
questions and never leaves the device. Existing open/dismiss paths
(intelligence-store feedback, task navigation) are unchanged.

Verification:
- desktop/macos/scripts/swift-format-wrapper.sh lint on all seven changed
  files: clean.
- desktop/macos/scripts/swiftlint-wrapper.sh lint: 0 violations in the changed
  files (one inline-UserDefaults-key violation found and fixed).
- python3 desktop/macos/scripts/check_desktop_test_quality.py: OK, debt at or
  below baseline.
- Standalone swiftc build of HomeKnowsComposer.swift +
  HomeKnowsImpressionLedger.swift under -strict-concurrency=complete, driving
  17 rule assertions (shorter-list-not-repeat, all-four-slots-empty, show cap
  in and out of cooldown, dismissal and its content-change return, stale/
  completed exclusion, freshness order, same-day relaxation): ALL PASS. This
  standalone harness exists because the shared branch was mid-flight from
  other workstreams; the committed XCTest suites are the durable coverage.

Failure-Class: FC-durable-state-scoped-to-view-lifetime
The typed lanes end an answer with a question 4-9% of the time; the realtime
voice lane does it 65% of the time and those sessions run ~4 turns. Recall
answers ("what did X say", "when did we...") end with a question 0% of the time
even though 71% of them have a strong next hop into the same source. This is
the client half of inviting that turn.

`ChatPrompts.desktopChat` (the prompt that owns both typed lanes — chat window
and floating-bar typed, via ChatProvider) now asks for exactly one specific,
grounded, answerable question after a `<<<FOLLOWUP>>>` marker, with the same
wording and the same suppression list as the backend lane. `ChatFollowUpTail`
lifts it off the authoritative answer into a `followUp` content block, and
`normalizeStreamingAssistantText` withholds the marker (and any unambiguous
partial one) from the streaming projection so the chip's words never appear in
the prose first and get removed at finalize.

Rendered as one chip under the answer in both shells: the chat window
(`ChatBubble` + `FollowUpChip`, sends the question as a new main-chat turn) and
the floating bar (`AIResponseView` -> `openAIInputWithQuery`, same lane). The
"or hold ⌥ to ask aloud" hint names the shortcut actually bound and is absent
when push-to-talk is off. It is never spoken aloud — it is a control, not
narration — and never rendered mid-stream.

Attribution: `question_asked` gains an `origin` property
(`followup` | `unprompted` | `chip` | `card`, default `unprompted`), added
alongside the existing `surface`/`source`/`message_length` and never replacing
them, so "did Omi invite this question" is answerable at all. A chip arms the
origin at the tap and the first accepted question consumes it, so a send the
provider refuses can never mislabel a later one.

Failure suppression: the floating bar's empty-response copy drops its
"Please try again" invitation — the measured behaviour is that nobody takes it,
they re-send the question themselves — and a failed, empty, or
clarifying-question turn never gets a chip, because the block is appended only
on the provider's accepted-answer path.

Verification:
  desktop/macos/scripts/swift-format-wrapper.sh format -i <changed files>
  python3 desktop/macos/scripts/check_desktop_test_quality.py -> OK (at baseline)
  xcrun swift build -c debug --package-path Desktop
    -> every remaining error in the shared worktree is
       "add missing case: '.memoryReviewCard(...)'" (plus a `maxRows` actor
       error in Dashboard/ChatDailySummaryCard.swift) from a sibling
       workstream's in-flight block type. No error asks for `.followUp`:
       all seven exhaustive switches over ChatContentBlock /
       ContentBlockGroup are updated here. `swift test --filter
       ChatFollowUpChipTests` is owed once that sibling lands and the tree
       compiles.

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

Corrects a false verification claim in 65586c6 and the layering defect it
hid. That commit's message says the focused backend suite passed with one
unrelated timing failure. It did not: the run failed 7 files. My grep for the
reasons matched a single global summary block and reprinted it once per file,
which read like confirmation instead of one repeated block.

Re-read honestly, the run had zero assertion failures — all 7 were test.sh's
fast-unit CPU guard — but two were mine and were real:

  3.72s > 0.30s  test_daily_summary_memories_learned.py::test_response_model_...
  0.77s > 0.30s  test_daily_summary_zero_coordinate_locations.py::test_zero_...

The second is the important one. 65586c6 called the memory selection from
inside generate_comprehensive_daily_summary, so the LLM summary builder gained
a memory dependency: every caller and every existing test of it lazily imported
utils.memory.memory_service and attempted a real MemoryService().read(), whose
failure my broad `except Exception` swallowed. An existing hermetic test was
silently exercising a fail-open Firestore path. The duration guard was the
symptom; the layering was the bug.

- generate_comprehensive_daily_summary now takes `memories_learned=None` and
  external_integrations.py imports nothing from the memory stack. The read
  moves to routers/users.py `_memories_learned_payload`, next to the uid,
  window and storage it already owns.
- Wired at BOTH generator call sites. 65586c6 missed
  regenerate_daily_summary entirely, so regenerating a summary would have
  silently dropped the review card.
- The fail-open read now calls record_fallback (component=daily_summary,
  outcome=degraded) per .github/agent-docs/fallback-telemetry.md. A missing
  card is a correctness change; silent UX healing is allowed, silent ops is not.
- utils/memory/learned_today.py is now a light leaf: `models.memories` moved
  behind TYPE_CHECKING because it pulled in google.cloud.firestore and
  database._client transitively. That import chain was also breaking
  test_daily_summary_race_condition.py (duplicate proto descriptor
  registration) for the workstream importing this module into
  utils/other/notifications.py; that file needs no change on its side.
- The 3.72s was `from routers.users import ...` inside a test body, charged to
  the call phase; hoisted to module scope.

Four regression tests added: the generator does not read memories itself
(source + signature), the endpoint hands its selection to the generator, the
fail-open path records a fallback, and the default-empty case.

Verification (all run after the fix):
  BACKEND_UNIT_TEST_FILE_LIST=<6 daily-summary files> bash test.sh -> RC=0
    no duration-guard failures; only a 0.16s > 0.10s warn (fail limit 0.30) on
    a pre-existing test. test_daily_summary_race_condition.py 16 passed
    (was 8 passed + 8 errors); test_daily_summary_zero_coordinate_locations.py
    2 passed (was 0.77s > 0.30s); this file 29 passed (was 3.72s > 0.30s).
  backend/scripts/typecheck.sh -> 0 errors
  openapi_runner.sh export_openapi.py --surface app-client --check -> up to date
  generate_dart_models.py --all --check -> up to date
  generate_swift_openapi_types.py --check -> up to date
  check_app_client_openapi_compatibility.py --base-ref origin/main -> passed

Still not done: the full 1029-file backend suite (the shared tree carries four
workstreams' in-flight edits) and a live HTTP call against a running server
(no credentials in this worktree).
`dart format` wraps the `..remove('evidence')..remove('content_blocks')` cascade
in app/lib/backend/schema/message.dart across three lines, so the single-line
substring assertion in test_app_client_dart_generator.py could no longer match
once the mobile change added the second remove. The guard now asserts each
operation separately; the expected behaviour (strip both keys before the
generated DTO) is unchanged and is the documented reason for the second remove
(FCM delivers content_blocks as a JSON string, decoded by the adapter).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…t be corrected

`knowledge_nuggets` is LLM prose about the day with no memory behind it, so the
summary could only *tell* the owner what Omi thinks it learned. There was
nothing to be wrong about: no id to vote on, no row to correct, and nothing a
verdict could travel back to. The backend contract on this branch fixed the
data half (`memories_learned`, plus a `memoryReviewCard` block); this is the
desktop half.

`DailySummaryRecord` now decodes `memories_learned` (optional, defaulting to
empty, tolerant of a field of the wrong shape and of entries with no id or no
content, because one malformed row must not cost the reader the whole summary).
`ChatDailySummaryCard` renders up to three of them as "Things I learned today",
each with a paraphrase, a category label, and three controls — Right, Wrong,
Fix. It never falls back to `knowledge_nuggets`: a nugget cannot be mutated, so
a vote on one would teach extraction nothing. A day that learned nothing renders
no section at all.

Actions go through existing endpoints only. Right is
`POST /v3/memories/{id}/review?value=true`; Wrong is the same route with false,
which already feeds bounded negative feedback into extraction, so "Dropped. I'll
avoid facts like this" is a promise the backend keeps. Fix opens a single-line
inline editor prefilled with the content — Enter saves through
`PATCH /v3/memories/{id}`, Esc cancels. An edit re-enters short-term as a user
assertion for the consolidation job to weigh rather than a promotion, so its
copy is "Updated." and not "Confirmed."

Single mutation owner: the memory API owns the verdict. Nothing is written to
the chat row or to defaults. A row derives its state from the memory's own
`user_review` (and, since the desktop's `ServerMemory` has no `edited`, from the
stored content no longer matching what the summary captured), so a vote on the
phone shows on the Mac. `MemoryReviewReducer` is a pure transition table:
clicking applies an optimistic override, success promotes it to the row's state
and triggers a re-read, failure clears it and says "Couldn't save, try again"
inline. Effects are returned as values rather than invoked as callbacks, so a
nested event can only arrive as another `reduce` call, never against a
half-published transition. A rejected row fades where it stands instead of being
removed, so the click does not reflow every row beneath it. Rows are focusable:
Enter accepts, Backspace/Delete rejects, E opens the editor.

The `memoryReviewCard` block round-trips through `ChatContentBlockCodec` and the
Chat-first validation wire and renders through `MemoryReviewCardView` with the
same row view, so the two arrival paths cannot drift into disagreeing about what
a verdict means. Desktop has no `day_summary` chat row today, so the summary
record is the live path; the block is the shared contract. Passive surfaces
(floating bar, notch, agent pill, voice playback, copied text) treat it the way
they treat the follow-up chip: a control, not narration and not prose.

Telemetry is `memory_review_action` {source, action, outcome, memory_category}
and `memory_review_card_shown` {source, item_count}. Bounded dimensions only:
no memory text, no ids, and an unrecognised category becomes `other` rather than
widening into a free-form field.

Interject is deliberately not wired here. `MemoryReviewRowView` carries a
one-line comment marking where a future "hold ⌥ to correct" hook attaches — it
would drive `.beginEdit` + `.saveEdit`, the same path the inline editor uses.

Verification:
  xcrun swift build -c debug --package-path Desktop -> succeeded
  xcrun swift test --package-path Desktop --filter MemoryReviewCardTests
    -> Executed 25 tests, 0 failures
  ... --filter "ChatDailySummaryTests|HomeDailySummaryTests|MemoryReviewCardTests|ChatContentBlock"
    -> Executed 47 tests, 0 failures
    (both runs required W3's in-flight, currently non-compiling
     HomeKnowsImpressionLedgerTests.swift to be moved aside and restored; it is
     unrelated to this change and is untouched here)
  python3 scripts/check_desktop_test_quality.py -> OK, at or below baseline
  ./scripts/swift-format-wrapper.sh lint <changed files> -> clean

The first run of the reducer suite caught a real defect: `requestSucceeded` was
promoting the optimistic override into `live` without clearing it, so a row
stayed permanently overridden. Fixed, and the empty-read guard now protects a
settled verdict as well as an in-flight one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Found by the focused suite on the rotation fix. The freshness comparator
tie-broke on the ledger key, which for a question row is a SHA-256 prefix of
its text. Two never-shown candidates therefore sorted by hash, silently
reordering the suggested questions the caller had already ranked: the hub's
prefilled ask became "What did I spend my time on this week?" instead of the
top-ranked "What should I do today?".

`freshnessRank` now returns only the three real freshness terms (never-shown,
fewest shows, most recent update) and the pool sorts with the candidate's
source index as the explicit final tie-break — `sorted(by:)` is not stable, so
the caller's order has to be stated rather than hoped for.

Also fixes the ledger tests' own clock: the 90-day retention prune is now
driven by the injected `now` instead of the wall clock, so a fixture dated in
March does not read as expired debris, and the store/defaults suites build
their main-actor fixtures inside each test rather than in the nonisolated
`XCTestCase.setUp` override.

Verification:
- xcrun swift build -c debug --package-path Desktop: green.
- xcrun swift test --package-path Desktop --filter HomeKnows: 43 tests,
  0 failures (HomeKnowsComposerTests 19, HomeKnowsRotationPolicyTests 13,
  HomeKnowsImpressionStoreTests 7, HomeKnowsImpressionDefaultsTests 4).
  The two ordering assertions above failed before this change and pass after.
- swift-format lint on the four changed files: clean.
- swiftlint-wrapper.sh lint: 0 violations in 1535 files.
- check_desktop_test_quality.py: OK, debt at or below baseline.

Failure-Class: FC-durable-state-scoped-to-view-lifetime
daily_summary_budget.py took the package to 13 source files, past the
architecture guardrail's 12-file threshold, which requires a package-root map.
The map names each module's concern and states that new concerns move out
rather than adding rows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…view card, and knows-list rotation

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

The Windows, web app, admin, and personas clients pin the same app-client
OpenAPI surface; the memories_learned field on DailySummaryResponse regenerates
their omiApi.generated.ts.

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

The guard sliced the first 400 characters after the signature of
_send_bulk_summary_notification and looked for postprocess_executor and
_BATCH_SIZE there. The #12530 fix gave the function keyword-only parameters and
a docstring, which pushed both references past that window without changing
what the function does (it still batches on _BATCH_SIZE and runs each send on
postprocess_executor via run_blocking). The guard now scans the function body
up to the next top-level def, so the contract no longer depends on signature
length. Expected values are unchanged.

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

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

40 issues found across 72 files

Confidence score: 2/5

  • backend/utils/other/daily_summary_budget.py and backend/utils/other/notifications.py can skip unfinished notification cohorts or clear cursors after partial timezone failures, causing users to miss scheduled summaries; preserve retryable checkpoints and propagate partial-read failures.
  • app/lib/widgets/components/memory_review_card.dart and desktop/macos/Desktop/Sources/MainWindow/Dashboard/MemoryReviewCard.swift can show missing or stale memory-review content because providers are not initialized, corrections are not retained, and refreshes omit backend state; initialize and refresh from authoritative data, then render the submitted or updated text.
  • desktop/macos/Desktop/Sources/Chat/ChatFollowUpTail.swift can leak FOLLOWUP>>> into transcripts when a marker is split across flushes, while ChatFirstBlockValidation.swift rejects memoryReviewCard blocks entirely; retain partial marker data and add the block type to server validation.
  • backend/utils/other/notifications.py and backend/models/notification_message.py can omit the production memories_learned review block or exceed FCM’s 4 KB payload limit, resulting in incomplete or undelivered notifications; pass the bounded review data and cap the encoded payload.
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/utils/other/daily_summary_budget.py">

<violation number="1" location="backend/utils/other/daily_summary_budget.py:95">
P2: When `DAILY_SUMMARY_MAX_HISTORY_CHARS` is zero or negative, this branch returns the full day and bypasses the input bound. Reject nonpositive configuration or apply a safe bounded policy instead.</violation>

<violation number="2" location="backend/utils/other/daily_summary_budget.py:110">
P2: When a conversation cannot be rendered, this branch keeps it and counts zero characters, so the later summary render can fail on the same conversation. Drop failed renders and increment `dropped` instead.</violation>

<violation number="3" location="backend/utils/other/daily_summary_budget.py:123">
P1: When the hourly notifications job exceeds its budget, the next run uses a different cursor key and never reads the unfinished tail. Keep the checkpoint tied to a retryable serving cohort, or schedule retries before that cohort’s UTC hour changes.</violation>
</file>

<file name="app/lib/widgets/components/memory_review_card.dart">

<violation number="1" location="app/lib/widgets/components/memory_review_card.dart:108">
P1: When chat or a daily summary is the first memory surface opened, the card never loads the referenced memories because the provider starts loading but is not initialized globally. Start the provider load here or initialize `MemoriesProvider` before rendering these cards.</violation>

<violation number="2" location="app/lib/widgets/components/memory_review_card.dart:137">
P3: The new review card hardcodes user-facing status copy, so this feature cannot be localized. Move the review-card labels and status/error strings to the app's generated localization resources and read them through the page/widget localization context.</violation>

<violation number="3" location="app/lib/widgets/components/memory_review_card.dart:184">
P2: After a successful edit, this permanent optimistic override takes precedence over live memory state forever. A later refresh or edit on another device can therefore never update this row, contradicting the card's live cross-device review behavior. Clear the override after persistence and derive the settled state from the provider's memory.</violation>

<violation number="4" location="app/lib/widgets/components/memory_review_card.dart:195">
P2: After a successful knowledge-ledger correction, the card reports `Updated.` but still renders the original learned text because the provider replaced the referenced ID. Retain and render the submitted or authoritative replacement content for this row.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/Chat/ChatFollowUpTail.swift:99">
P2: When a specific chip starts with `What else`, macOS drops it while decoding the persisted message. Match the backend’s exact/word-boundary generic rules instead of rejecting every question with a generic prefix.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/Chat/ChatFollowUpTail.swift:119">
P1: When a flush splits the marker after `<<<`, this branch discards the partial marker from the only text buffer, so the next flush cannot reconstruct it and leaks `FOLLOWUP>>>` into the transcript. Retain raw pending suffixes across flushes, or do not remove partial markers in this stateless projection.</violation>
</file>

<file name="backend/utils/other/notifications.py">

<violation number="1" location="backend/utils/other/notifications.py:184">
P1: When a timezone query chunk fails, this branch drops that chunk while the caller treats the group as complete and clears the daily cursor. Propagate partial-read failure to keep the run resumable; otherwise users in the failed chunk can permanently miss that day's summary.</violation>

<violation number="2" location="backend/utils/other/notifications.py:387">
P1: Scheduled summaries never select or pass `memories_learned`, so this review block is always omitted on the production notification path. Run `memories_learned_for_summary` for the bounded conversations and pass its result to `generate_comprehensive_daily_summary` before building the block.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Dashboard/MemoryReviewCard.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/MemoryReviewCard.swift:256">
P1: Refreshing this card only queries the local SQLite mirror; it never fetches backend state. A phone's vote, or this card's own vote, remains `userReview == nil` until an unrelated memory sync. Fetch authoritative state or update the local review field after mutation.</violation>
</file>

<file name="backend/models/notification_message.py">

<violation number="1" location="backend/models/notification_message.py:40">
P1: When selected memories contain several kilobytes of text, this serializes the full card into the FCM data payload and FCM rejects the message for exceeding its 4 KB limit. Bound the card payload before encoding, or omit the card while still sending the daily-summary notification.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsImpressionLedger.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsImpressionLedger.swift:232">
P2: When the effective owner changes while the dashboard remains mounted, this visit set still contains keys from the previous owner. Scope the visit de-duplication to the owner and reload the snapshot on owner changes so account switches cannot suppress or display the previous owner's rotation state.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsImpressionLedger.swift:264">
P2: When a previously opened task or insight changes, the reset does not mark the new content as unopened. Clear `lastOpenedAt` when `contentChanged` so the new object receives the three-show cap and same-day rule.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/Chat/ChatFirstBlockValidation.swift:108">
P2: A `memoryReviewCard` sent through this adapter can never be accepted by the server: the chat-first Pydantic union still excludes this block type, so validation returns `invalid_request` and the card is never journaled. Add the block to the server contract and its entity-authority check, or remove both client-side conversions until the backend supports it.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Dashboard/ChatDailySummaryCard.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/ChatDailySummaryCard.swift:73">
P2: When an existing summary is refreshed or regenerated with different learned memories, this ID keeps `MemoryReviewSection`'s old `StateObject` alive, so new rows never appear and changed rows keep stale text. Key the section identity by the learned-row content as well, or reconcile updated items in `MemoryReviewSection`.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/ChatDailySummaryCard.swift:254">
P2: When `memories_learned` contains a whitespace-only `memory_id`, this check renders an unusable row and enables mutations against a blank identifier. Trim the identifier for validation before creating the review item.</violation>
</file>

<file name="backend/utils/memory/learned_today.py">

<violation number="1" location="backend/utils/memory/learned_today.py:39">
P2: If more than 200 newer memories precede the summarized day, `MemoryService.read` returns only that prefix before `_from_day` filters it. Paginate until the day’s rows are covered, or add a date-bounded read, so valid learned memories are not silently omitted.</violation>

<violation number="2" location="backend/utils/memory/learned_today.py:87">
P2: When a memory has evidence from multiple conversations, `MemoryService` exposes only the last conversation evidence as `memory.conversation_id`. `_from_day` then rejects a memory produced in today’s conversation when that field points elsewhere; match any conversation evidence instead.</violation>
</file>

<file name="backend/utils/retrieval/agentic.py">

<violation number="1" location="backend/utils/retrieval/agentic.py:1648">
P2: When a timeout or stream failure occurs after a partial follow-up delimiter, the filter hides the buffered suffix from the stream but `keep_streamed_answer()` persists that suffix in the done answer. Flush or replay the filter’s pending text on failure before finalizing the answer so cut-short turns do not expose malformed marker fragments.</violation>

<violation number="2" location="backend/utils/retrieval/agentic.py:1665">
P2: When the safety guard terminates a tool call after a response containing the marker, `producer_failure` is still `None`, so this records a follow-up on a failed turn and drops the guard message from the persisted answer. Propagate a distinct safety-termination failure result, or otherwise gate follow-up creation on an explicit clean completion.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Services/APIClient/APIClient+DailySummaries.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Services/APIClient/APIClient+DailySummaries.swift:116">
P2: When one `memories_learned` item has an invalid field type, decoding `[LearnedMemory]` fails and `try?` discards the entire array, hiding otherwise valid review rows. Decode entries independently and skip only the malformed item, while retaining the field-level fallback for a non-array payload.</violation>
</file>

<file name="desktop/macos/e2e/flows/home-stage.yaml">

<violation number="1" location="desktop/macos/e2e/flows/home-stage.yaml:28">
P2: These four sources are listed in `covers:` but the flow never exercises them. The steps drive only reset/home_*/chat_drafts/daily_summary_snapshot actions; `daily_summary_snapshot` is explicitly shape-only and does not render the memoryReviewCard rows, and no step opens the knows-list or asserts its rotation/dismiss/telemetry behavior. A flow claiming coverage it does not verify gives false confidence that these new modules are e2e-covered. Remove the four entries, or add steps that actually render the memory review card (✓/✗/Fix) and drive the knows-list rotation before claiming them.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Analytics/AnalyticsManager+QuestionOrigin.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Analytics/AnalyticsManager+QuestionOrigin.swift:34">
P2: When the floating window or provider is unavailable, this arm remains set because dispatch returns before any question event consumes it. Clear the pending origin when dispatch aborts, or arm it only at the accepted-send boundary, so the next unrelated question is not labeled `followup`.</violation>
</file>

<file name="backend/utils/chat_followup.py">

<violation number="1" location="backend/utils/chat_followup.py:90">
P2: A model tail containing multiple questions passes this check and produces a chip with multiple prompts, contrary to the one-question contract. Reject internal sentence/question terminators before accepting the tail.</violation>

<violation number="2" location="backend/utils/chat_followup.py:175">
P2: When a stream fails after emitting only a delimiter prefix, the prefix is withheld from SSE but then persisted in the terminal answer because the failure path never finalizes the filter. Remove or otherwise finalize the pending suffix before persisting cut-short answers so marker fragments do not leak into transcripts.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsComposer.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsComposer.swift:114">
P2: When the same task appears in multiple dashboard buckets, `openTaskCount` counts it once per bucket while `compose` renders it only once. Deduplicate task IDs before counting so the greeting and fallback tip use the same task population as the list.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsComposer.swift:116">
P2: When a dismissed task is edited, `pool` correctly resurfaces it, but `openTaskCount` still excludes it because it checks only `dismissedAt`. Treat a dismissed entry with a changed content hash as open here as well.</violation>

<violation number="3" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/HomeKnowsComposer.swift:116">
P2: When an overdue task is more than 14 days past due, `compose` hides it but `openTaskCount` still counts it. Apply the same stale-task eligibility rule to the count so the greeting and tip match the rows.</violation>
</file>

<file name="desktop/macos/e2e/flows/chat-hermetic.yaml">

<violation number="1" location="desktop/macos/e2e/flows/chat-hermetic.yaml:34">
P2: The hermetic flow never exercises the three newly added covers sources. It runs OMI_LLM_STUB=1, sends a plain typed query, and asserts the exact stub reply "MARKER:chat-hermetic"; the stub output contains no <<<FOLLOWUP>>> delimiter, so ChatFollowUpTail.split never produces a chip, FollowUpChip is never rendered (the flow never asserts the chat-follow-up-chip identifier), and no question_asked event is emitted or asserted, so the question-origin followup attribution path never runs. List these sources only in a flow that drives a grounded typed answer with a follow-up tail and asserts the chip and origin, per the e2e coverage rule that a covers entry must be exercised and verified by the flow.</violation>
</file>

<file name="app/lib/pages/chat/widgets/ai_message.dart">

<violation number="1" location="app/lib/pages/chat/widgets/ai_message.dart:333">
P2: When a response has a follow-up block but no text, `ServerMessage` falls back to the block text; this wrapper then renders that text and appends the same chip, so the question appears twice. Suppress the fallback prose when this block is rendered natively.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Dashboard/MemoryReviewRowView.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Dashboard/MemoryReviewRowView.swift:55">
P2: When the initial live-state read is cancelled or fails, this one-shot task leaves the card showing every memory as unreviewed and never retries while the card remains mounted. Mark the load attempt only after a successful read, or expose the failure and retry it, so cross-device verdicts are not silently stale.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarView.swift:1651">
P2: When a user configures a multi-modifier PTT binding, this hint displays only the first modifier, so holding the shown key does not invoke voice. Join all `displayTokens` before building the hint.</violation>
</file>

<file name="app/lib/backend/schema/message.dart">

<violation number="1" location="app/lib/backend/schema/message.dart:551">
P2: When a `memoryReviewCard` has no usable items and the message text is empty, this case still creates `Things I learned today` as prose while `memoryReviewCard` returns null. Guard the fallback with `MemoryReviewCardBlock.tryFromBlock(block)` so malformed cards remain absent instead of showing a misleading summary.</violation>
</file>

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

<violation number="1" location="desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarWindow.swift:5306">
P2: On voice queries with an empty response, the failure copy is now read aloud because the exact-string voice-suppression guard no longer matches. FloatingBarVoicePlaybackService.shouldSpeak returns false only for "failed to get a response. please try again.", so the new "Omi couldn't get an answer for that one." passes through updateStreamingResponseIfEnabled and is spoken. Keep the voice guard in sync with the new copy (or make it content-agnostic) so the failure stays silent as before.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift:1046">
P3: In chat mode, the rail renders only three rows, but this loop reports empty slots from the full four-slot composition, including slots the user never sees. Skip empty-slot reporting for the shortened chat composition or restrict it to visible slots.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift:1064">
P2: When a learned insight has no matching recommendation, tapping it returns without opening anything but this line still records it as opened. Record the impression only after the row's open action succeeds.</violation>
</file>

<file name="backend/utils/other/ARCHITECTURE.md">

<violation number="1" location="backend/utils/other/ARCHITECTURE.md:18">
P3: This row labels `daily_summary_budget.py` as having no I/O, although its cursor helpers perform Redis I/O and require executor offloading. Document the Redis boundary accurately.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_daily_summary_job_resilience.py:19">
P3: These tests use per-test fresh module reloads and executor-backed async work without a `slow` or `integration` marker. Mark the module so the fast unit selector does not run non-unit tests.</violation>
</file>

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

Re-trigger cubic


def job_cursor_key(now_utc: datetime) -> str:
"""Cursor key for the UTC hour currently being served."""
return f'daily_summary_job_cursor:{now_utc.strftime("%Y-%m-%dT%H")}'

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: When the hourly notifications job exceeds its budget, the next run uses a different cursor key and never reads the unfinished tail. Keep the checkpoint tied to a retryable serving cohort, or schedule retries before that cohort’s UTC hour changes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/daily_summary_budget.py, line 123:

<comment>When the hourly notifications job exceeds its budget, the next run uses a different cursor key and never reads the unfinished tail. Keep the checkpoint tied to a retryable serving cohort, or schedule retries before that cohort’s UTC hour changes.</comment>

<file context>
@@ -0,0 +1,196 @@
+
+def job_cursor_key(now_utc: datetime) -> str:
+    """Cursor key for the UTC hour currently being served."""
+    return f'daily_summary_job_cursor:{now_utc.strftime("%Y-%m-%dT%H")}'
+
+
</file context>

void _ensureMemoriesLoaded() {
if (!mounted) return;
final provider = _memoriesProvider(listen: false);
if (provider == null || provider.loading) return;

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: When chat or a daily summary is the first memory surface opened, the card never loads the referenced memories because the provider starts loading but is not initialized globally. Start the provider load here or initialize MemoriesProvider before rendering these cards.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/widgets/components/memory_review_card.dart, line 108:

<comment>When chat or a daily summary is the first memory surface opened, the card never loads the referenced memories because the provider starts loading but is not initialized globally. Start the provider load here or initialize `MemoriesProvider` before rendering these cards.</comment>

<file context>
@@ -0,0 +1,398 @@
+  void _ensureMemoriesLoaded() {
+    if (!mounted) return;
+    final provider = _memoriesProvider(listen: false);
+    if (provider == null || provider.loading) return;
+    final unresolved = _rows
+        .where((item) => _memoryFor(provider, item.memoryId) == null)
</file context>

if maxHold >= 3 {
for length in stride(from: maxHold, through: 3, by: -1) {
if Array(characters.suffix(length)) == Array(delimiterCharacters.prefix(length)) {
return String(characters.prefix(characters.count - length))

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: When a flush splits the marker after <<<, this branch discards the partial marker from the only text buffer, so the next flush cannot reconstruct it and leaks FOLLOWUP>>> into the transcript. Retain raw pending suffixes across flushes, or do not remove partial markers in this stateless projection.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/Chat/ChatFollowUpTail.swift, line 119:

<comment>When a flush splits the marker after `<<<`, this branch discards the partial marker from the only text buffer, so the next flush cannot reconstruct it and leaks `FOLLOWUP>>>` into the transcript. Retain raw pending suffixes across flushes, or do not remove partial markers in this stateless projection.</comment>

<file context>
@@ -0,0 +1,143 @@
+    if maxHold >= 3 {
+      for length in stride(from: maxHold, through: 3, by: -1) {
+        if Array(characters.suffix(length)) == Array(delimiterCharacters.prefix(length)) {
+          return String(characters.prefix(characters.count - length))
+        }
+      }
</file context>

# One hour group's read failing must not cost the other 23 groups.
stats.groups_failed += 1
logger.error('daily_summary_group_failed hour=%s reason=user_query error=%s', target_hour, e)
continue

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: When a timezone query chunk fails, this branch drops that chunk while the caller treats the group as complete and clears the daily cursor. Propagate partial-read failure to keep the run resumable; otherwise users in the failed chunk can permanently miss that day's summary.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/notifications.py, line 184:

<comment>When a timezone query chunk fails, this branch drops that chunk while the caller treats the group as complete and clears the daily cursor. Propagate partial-read failure to keep the run resumable; otherwise users in the failed chunk can permanently miss that day's summary.</comment>

<file context>
@@ -45,33 +130,119 @@ async def send_daily_summary_notification() -> None:
+            # One hour group's read failing must not cost the other 23 groups.
+            stats.groups_failed += 1
+            logger.error('daily_summary_group_failed hour=%s reason=user_query error=%s', target_hour, e)
+            continue
 
-        for target_hour, timezones in timezones_by_hour.items():
</file context>

# /v1/users/daily-summary-settings/test path builds. ``text`` is untouched: a
# client that does not know the block renders exactly what it rendered before,
# and the block is omitted entirely when the day produced nothing to review.
review_block = memory_review_card_block(

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: Scheduled summaries never select or pass memories_learned, so this review block is always omitted on the production notification path. Run memories_learned_for_summary for the bounded conversations and pass its result to generate_comprehensive_daily_summary before building the block.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/notifications.py, line 387:

<comment>Scheduled summaries never select or pass `memories_learned`, so this review block is always omitted on the production notification path. Run `memories_learned_for_summary` for the bounded conversations and pass its result to `generate_comprehensive_daily_summary` before building the block.</comment>

<file context>
@@ -188,12 +379,24 @@ def _send_summary_notification(user_data: Tuple[Any, ...]) -> None:
+    # /v1/users/daily-summary-settings/test path builds. ``text`` is untouched: a
+    # client that does not know the block renders exactly what it rendered before,
+    # and the block is omitted entirely when the day produced nothing to review.
+    review_block = memory_review_card_block(
+        summary_id,
+        date=date_str,
</file context>

}

private func openKnowsRow(_ row: HomeKnowsRow) {
knowsLedger.entries[row.ledgerKey] = knowsLedgerStore.recordOpened(

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: When a learned insight has no matching recommendation, tapping it returns without opening anything but this line still records it as opened. Record the impression only after the row's open action succeeds.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift, line 1064:

<comment>When a learned insight has no matching recommendation, tapping it returns without opening anything but this line still records it as opened. Record the impression only after the row's open action succeeds.</comment>

<file context>
@@ -986,10 +1006,63 @@ struct DashboardPage: View {
+  }
+
   private func openKnowsRow(_ row: HomeKnowsRow) {
+    knowsLedger.entries[row.ledgerKey] = knowsLedgerStore.recordOpened(
+      key: row.ledgerKey, contentHash: row.contentHash)
     switch row.kind {
</file context>

| Local dev storage adapter | `local_storage.py` | Filesystem stand-in for `storage.py` used only by the owned local dev harness; never selected in a deployed image. |
| Chat file attachments | `chat_file.py` | Provider upload/expiry of files attached to chat turns, and the typed errors the chat route maps to user-facing failures. |
| Daily summary job | `notifications.py` | The scheduled daily-summary job: per-user fan-out, isolation, budgets, checkpoint cursor, FCM send, `day_summary` webhook. |
| Daily summary bounds | `daily_summary_budget.py` | Pure helpers the job uses: bounded conversation selection for the generator input and the Redis checkpoint cursor encoding. No I/O. |

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 row labels daily_summary_budget.py as having no I/O, although its cursor helpers perform Redis I/O and require executor offloading. Document the Redis boundary accurately.

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

<comment>This row labels `daily_summary_budget.py` as having no I/O, although its cursor helpers perform Redis I/O and require executor offloading. Document the Redis boundary accurately.</comment>

<file context>
@@ -0,0 +1,36 @@
+| Local dev storage adapter | `local_storage.py` | Filesystem stand-in for `storage.py` used only by the owned local dev harness; never selected in a deployed image. |
+| Chat file attachments | `chat_file.py` | Provider upload/expiry of files attached to chat turns, and the typed errors the chat route maps to user-facing failures. |
+| Daily summary job | `notifications.py` | The scheduled daily-summary job: per-user fan-out, isolation, budgets, checkpoint cursor, FCM send, `day_summary` webhook. |
+| Daily summary bounds | `daily_summary_budget.py` | Pure helpers the job uses: bounded conversation selection for the generator input and the Redis checkpoint cursor encoding. No I/O. |
+| Bounded list reads | `list_budget.py` | Request-scoped time and document budget for list GET reads (`FC-bounded-read-exceeds-request-budget`). |
+| Request timeout | `timeout.py` | `TimeoutMiddleware`, the per-request wall-clock budget. |
</file context>
Suggested change
| Daily summary bounds | `daily_summary_budget.py` | Pure helpers the job uses: bounded conversation selection for the generator input and the Redis checkpoint cursor encoding. No I/O. |
| Daily summary bounds | `daily_summary_budget.py` | Conversation-selection helpers plus fail-soft Redis cursor helpers; cursor I/O is synchronous and must run through `db_executor`. |

String _statusText(_RowState state) {
switch (state) {
case _RowState.confirmed:
return "Confirmed. I'll act on this.";

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 new review card hardcodes user-facing status copy, so this feature cannot be localized. Move the review-card labels and status/error strings to the app's generated localization resources and read them through the page/widget localization context.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/widgets/components/memory_review_card.dart, line 137:

<comment>The new review card hardcodes user-facing status copy, so this feature cannot be localized. Move the review-card labels and status/error strings to the app's generated localization resources and read them through the page/widget localization context.</comment>

<file context>
@@ -0,0 +1,398 @@
+  String _statusText(_RowState state) {
+    switch (state) {
+      case _RowState.confirmed:
+        return "Confirmed. I'll act on this.";
+      case _RowState.dropped:
+        return "Dropped. I'll avoid facts like this.";
</file context>

slot: slot(for: row, in: composition),
showsBefore: max(0, impression.shows - 1))
}
for empty in composition.emptySlots {

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: In chat mode, the rail renders only three rows, but this loop reports empty slots from the full four-slot composition, including slots the user never sees. Skip empty-slot reporting for the shortened chat composition or restrict it to visible slots.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift, line 1046:

<comment>In chat mode, the rail renders only three rows, but this loop reports empty slots from the full four-slot composition, including slots the user never sees. Skip empty-slot reporting for the shortened chat composition or restrict it to visible slots.</comment>

<file context>
@@ -986,10 +1006,63 @@ struct DashboardPage: View {
+        slot: slot(for: row, in: composition),
+        showsBefore: max(0, impression.shows - 1))
+    }
+    for empty in composition.emptySlots {
+      guard knowsLedgerStore.shouldReportEmptySlot(empty.slot.rawValue) else { continue }
+      AnalyticsManager.shared.trackHomeKnowsSlotEmpty(slot: empty.slot, reason: empty.reason)
</file context>
Suggested change
for empty in composition.emptySlots {
guard visibleRows == HomeKnowsListComposer.maxRows else { return }
for empty in composition.emptySlots {

from types import ModuleType
from typing import Any, Dict, Iterator, List, Tuple

from testing.import_isolation import AutoMockModule, load_module_fresh, stub_modules

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: These tests use per-test fresh module reloads and executor-backed async work without a slow or integration marker. Mark the module so the fast unit selector does not run non-unit tests.

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

<comment>These tests use per-test fresh module reloads and executor-backed async work without a `slow` or `integration` marker. Mark the module so the fast unit selector does not run non-unit tests.</comment>

<file context>
@@ -0,0 +1,465 @@
+from types import ModuleType
+from typing import Any, Dict, Iterator, List, Tuple
+
+from testing.import_isolation import AutoMockModule, load_module_fresh, stub_modules
+
+BACKEND_DIR = Path(__file__).resolve().parents[2]
</file context>

@Git-on-my-level
Git-on-my-level merged commit a3c335f into main Sep 3, 2026
50 of 51 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/ask-teach-prove branch September 3, 2026 07:45
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
`ChatStreamingBuffer.appendTextSegment` wrote the normalized projection back
into `message.text` and then appended the next delta to it, so the projection
was re-derived from what it had already withheld.

`normalizeStreamingAssistantText` withholds the follow-up tail: the marker and
the question after it must never appear as prose. Because the withheld text was
gone from the only buffer by the next flush, the projection had no delimiter
left to recognise and streamed the question out a token at a time. This is not
an edge case around a split marker — a replay of every flush boundary leaks at
every boundary from the delimiter onward, and the question always spans several
35ms flushes. It was display-only: the authoritative terminal answer overwrites
the streamed text, so nothing wrong was persisted, but the reader saw the chip's
question typed into the answer and then snatched away.

The buffer now keeps the raw text per streaming message and per trailing text
block, appends deltas to that, and only ever writes the projection outward. The
accumulator is seeded from the message so a resumed turn keeps its prefix, and
released when the authoritative answer lands or the turn is discarded, so the
map does not outlive the turn and a reused id never resumes from a stale answer.

Found by adversarial review of #12635. The reported symptom was the narrow
split-marker case; the general one is above.

Failure-Class: FC-projection-fed-its-own-output

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
…b could not resume

Seven defects on the scheduled daily-summary path, found in review of #12635.

**The card was dead in production.** `_send_summary_notification` called
`generate_comprehensive_daily_summary` without `memories_learned`, so the
parameter kept its None default, `summary_data['memories_learned']` was always
`[]`, `memory_review_card_block` always returned None, and the `memoryReviewCard`
block was never attached on the only path real users receive. The
/daily-summary-settings/test route selected correctly, which is why it looked
shipped. Both senders now select through one helper,
`learned_today.memories_learned_payload`, which keeps the module import-pure
(the MemoryService import stays lazy, a7aba22). The existing test passed
because its generator stub returned the refs regardless of what it was given;
the stub now behaves like the real generator and echoes its parameter, so the
test fails without the fix.

**The resume checkpoint could never be read.** The cursor key carried the UTC
hour, so the execution that exhausted its budget wrote `...T18` and the next one
read `...T19`. The key is now stable and bounded by its TTL; `rotate_to` already
prevents a carried-over cursor from starving a fresh cohort, because a run walks
the whole rotated list rather than a suffix.

**A partial user read finished as if it were complete.** A dropped timezone
chunk was logged and skipped while the caller went on to clear the checkpoint,
retiring users the job never even listed. `_get_users_for_daily_summary` now
returns `(users, every_chunk_read)`; the chunks that did read are still served,
the run just stops calling itself complete.

**An oversized card would have killed the whole notification.** FCM rejects a
message whose data payload exceeds 4KB, and it rejects it entirely, so several
kilobytes of memory text would have silently dropped the recap. The encoded
blocks are now bounded and dropped if they do not fit: losing the card costs a
render, losing the message costs the recap.

**Day attribution ignored most of the evidence.** `memory_item_to_memorydb`
overwrites `MemoryDB.conversation_id` once per conversation-sourced evidence
row, so a memory supported by two conversations keeps only the last one and a
memory genuinely produced by one of today's conversations was rejected.
`_from_day` now matches any conversation evidence, the way
`MemoryService.retract_conversation_memories` already does.

**The memory scan assumed created_at ordering.** `MemoryService.read` orders by
updated_at, so a bulk touch can push more than one page of older rows in front
of the summarised day and empty the card. The read now pages, capped at three
pages and stopping at the first short page, so the common user still costs
exactly one read. Resolving the reader is also fail-open now: the lazy
MemoryService import used to propagate and cost the whole recap.

Also: a nonpositive `DAILY_SUMMARY_MAX_HISTORY_CHARS` returned the entire day,
removing the only bound protecting the prompt from the context overflow the
bound exists for — it now falls back to the bound. A conversation that fails to
render is dropped and counted rather than kept at zero cost, which only moved
the failure into the summary render; if *every* render fails the fault is the
renderer, not the day, so the material is handed over unchanged rather than
turning a renderer bug into a silently missing recap. The ARCHITECTURE.md row
claiming `daily_summary_budget.py` does no I/O is corrected: its cursor helpers
do synchronous Redis I/O and require executor offloading.

Verified: `BACKEND_UNIT_TEST_FILE_LIST=<8 files> bash test.sh` in backend/ —
1 + 2 + 21 + 6 + 3 + 16 + 29 + 6 passed, no failures; slowest test 0.11s CPU
against the 0.30s guard.

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
`ChatStreamingBuffer.appendTextSegment` wrote the normalized projection back
into `message.text` and then appended the next delta to it, so the projection
was re-derived from what it had already withheld.

`normalizeStreamingAssistantText` withholds the follow-up tail: the marker and
the question after it must never appear as prose. Because the withheld text was
gone from the only buffer by the next flush, the projection had no delimiter
left to recognise and streamed the question out a token at a time. This is not
an edge case around a split marker — a replay of every flush boundary leaks at
every boundary from the delimiter onward, and the question always spans several
35ms flushes. It was display-only: the authoritative terminal answer overwrites
the streamed text, so nothing wrong was persisted, but the reader saw the chip's
question typed into the answer and then snatched away.

The buffer now keeps the raw text per streaming message and per trailing text
block, appends deltas to that, and only ever writes the projection outward. The
accumulator is seeded from the message so a resumed turn keeps its prefix, and
released when the authoritative answer lands or the turn is discarded, so the
map does not outlive the turn and a reused id never resumes from a stale answer.

Found by adversarial review of #12635. The reported symptom was the narrow
split-marker case; the general one is above.

Failure-Class: FC-projection-fed-its-own-output

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
…b could not resume

Seven defects on the scheduled daily-summary path, found in review of #12635.

**The card was dead in production.** `_send_summary_notification` called
`generate_comprehensive_daily_summary` without `memories_learned`, so the
parameter kept its None default, `summary_data['memories_learned']` was always
`[]`, `memory_review_card_block` always returned None, and the `memoryReviewCard`
block was never attached on the only path real users receive. The
/daily-summary-settings/test route selected correctly, which is why it looked
shipped. Both senders now select through one helper,
`learned_today.memories_learned_payload`, which keeps the module import-pure
(the MemoryService import stays lazy, a7aba22). The existing test passed
because its generator stub returned the refs regardless of what it was given;
the stub now behaves like the real generator and echoes its parameter, so the
test fails without the fix.

**The resume checkpoint could never be read.** The cursor key carried the UTC
hour, so the execution that exhausted its budget wrote `...T18` and the next one
read `...T19`. The key is now stable and bounded by its TTL; `rotate_to` already
prevents a carried-over cursor from starving a fresh cohort, because a run walks
the whole rotated list rather than a suffix.

**A partial user read finished as if it were complete.** A dropped timezone
chunk was logged and skipped while the caller went on to clear the checkpoint,
retiring users the job never even listed. `_get_users_for_daily_summary` now
returns `(users, every_chunk_read)`; the chunks that did read are still served,
the run just stops calling itself complete.

**An oversized card would have killed the whole notification.** FCM rejects a
message whose data payload exceeds 4KB, and it rejects it entirely, so several
kilobytes of memory text would have silently dropped the recap. The encoded
blocks are now bounded and dropped if they do not fit: losing the card costs a
render, losing the message costs the recap.

**Day attribution ignored most of the evidence.** `memory_item_to_memorydb`
overwrites `MemoryDB.conversation_id` once per conversation-sourced evidence
row, so a memory supported by two conversations keeps only the last one and a
memory genuinely produced by one of today's conversations was rejected.
`_from_day` now matches any conversation evidence, the way
`MemoryService.retract_conversation_memories` already does.

**The memory scan assumed created_at ordering.** `MemoryService.read` orders by
updated_at, so a bulk touch can push more than one page of older rows in front
of the summarised day and empty the card. The read now pages, capped at three
pages and stopping at the first short page, so the common user still costs
exactly one read. Resolving the reader is also fail-open now: the lazy
MemoryService import used to propagate and cost the whole recap.

Also: a nonpositive `DAILY_SUMMARY_MAX_HISTORY_CHARS` returned the entire day,
removing the only bound protecting the prompt from the context overflow the
bound exists for — it now falls back to the bound. A conversation that fails to
render is dropped and counted rather than kept at zero cost, which only moved
the failure into the summary render; if *every* render fails the fault is the
renderer, not the day, so the material is handed over unchanged rather than
turning a renderer bug into a silently missing recap. The ARCHITECTURE.md row
claiming `daily_summary_budget.py` does no I/O is corrected: its cursor helpers
do synchronous Redis I/O and require executor offloading.

Verified: `BACKEND_UNIT_TEST_FILE_LIST=<8 files> bash test.sh` in backend/ —
1 + 2 + 21 + 6 + 3 + 16 + 29 + 6 passed, no failures; slowest test 0.11s CPU
against the 0.30s guard.

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
`ChatStreamingBuffer.appendTextSegment` wrote the normalized projection back
into `message.text` and then appended the next delta to it, so the projection
was re-derived from what it had already withheld.

`normalizeStreamingAssistantText` withholds the follow-up tail: the marker and
the question after it must never appear as prose. Because the withheld text was
gone from the only buffer by the next flush, the projection had no delimiter
left to recognise and streamed the question out a token at a time. This is not
an edge case around a split marker — a replay of every flush boundary leaks at
every boundary from the delimiter onward, and the question always spans several
35ms flushes. It was display-only: the authoritative terminal answer overwrites
the streamed text, so nothing wrong was persisted, but the reader saw the chip's
question typed into the answer and then snatched away.

The buffer now keeps the raw text per streaming message and per trailing text
block, appends deltas to that, and only ever writes the projection outward. The
accumulator is seeded from the message so a resumed turn keeps its prefix, and
released when the authoritative answer lands or the turn is discarded, so the
map does not outlive the turn and a reused id never resumes from a stale answer.

Found by adversarial review of #12635. The reported symptom was the narrow
split-marker case; the general one is above.

Failure-Class: FC-projection-fed-its-own-output

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
…b could not resume

Seven defects on the scheduled daily-summary path, found in review of #12635.

**The card was dead in production.** `_send_summary_notification` called
`generate_comprehensive_daily_summary` without `memories_learned`, so the
parameter kept its None default, `summary_data['memories_learned']` was always
`[]`, `memory_review_card_block` always returned None, and the `memoryReviewCard`
block was never attached on the only path real users receive. The
/daily-summary-settings/test route selected correctly, which is why it looked
shipped. Both senders now select through one helper,
`learned_today.memories_learned_payload`, which keeps the module import-pure
(the MemoryService import stays lazy, a7aba22). The existing test passed
because its generator stub returned the refs regardless of what it was given;
the stub now behaves like the real generator and echoes its parameter, so the
test fails without the fix.

**The resume checkpoint could never be read.** The cursor key carried the UTC
hour, so the execution that exhausted its budget wrote `...T18` and the next one
read `...T19`. The key is now stable and bounded by its TTL; `rotate_to` already
prevents a carried-over cursor from starving a fresh cohort, because a run walks
the whole rotated list rather than a suffix.

**A partial user read finished as if it were complete.** A dropped timezone
chunk was logged and skipped while the caller went on to clear the checkpoint,
retiring users the job never even listed. `_get_users_for_daily_summary` now
returns `(users, every_chunk_read)`; the chunks that did read are still served,
the run just stops calling itself complete.

**An oversized card would have killed the whole notification.** FCM rejects a
message whose data payload exceeds 4KB, and it rejects it entirely, so several
kilobytes of memory text would have silently dropped the recap. The encoded
blocks are now bounded and dropped if they do not fit: losing the card costs a
render, losing the message costs the recap.

**Day attribution ignored most of the evidence.** `memory_item_to_memorydb`
overwrites `MemoryDB.conversation_id` once per conversation-sourced evidence
row, so a memory supported by two conversations keeps only the last one and a
memory genuinely produced by one of today's conversations was rejected.
`_from_day` now matches any conversation evidence, the way
`MemoryService.retract_conversation_memories` already does.

**The memory scan assumed created_at ordering.** `MemoryService.read` orders by
updated_at, so a bulk touch can push more than one page of older rows in front
of the summarised day and empty the card. The read now pages, capped at three
pages and stopping at the first short page, so the common user still costs
exactly one read. Resolving the reader is also fail-open now: the lazy
MemoryService import used to propagate and cost the whole recap.

Also: a nonpositive `DAILY_SUMMARY_MAX_HISTORY_CHARS` returned the entire day,
removing the only bound protecting the prompt from the context overflow the
bound exists for — it now falls back to the bound. A conversation that fails to
render is dropped and counted rather than kept at zero cost, which only moved
the failure into the summary render; if *every* render fails the fault is the
renderer, not the day, so the material is handed over unchanged rather than
turning a renderer bug into a silently missing recap. The ARCHITECTURE.md row
claiming `daily_summary_budget.py` does no I/O is corrected: its cursor helpers
do synchronous Redis I/O and require executor offloading.

Verified: `BACKEND_UNIT_TEST_FILE_LIST=<8 files> bash test.sh` in backend/ —
1 + 2 + 21 + 6 + 3 + 16 + 29 + 6 passed, no failures; slowest test 0.11s CPU
against the 0.30s guard.

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
… dropped

The rebase onto #12635 resolved this docstring in favour of this branch's
one-line version, silently deleting the isolation contract main had just
documented: failures are recorded per uid, and a user over the per-user
budget is abandoned rather than allowed to hold the batch barrier.

Restore main's text verbatim and add what is newly true — the same
per-user timeout now also covers the backfill walk, so a user with holes
can spend up to 1 + _DAILY_SUMMARY_BACKFILL_GENERATE_CAP generations
inside one budget.

Co-Authored-By: Claude Opus 5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
…tually work (#12635 follow-up) (#12669)

## Summary

Follow-up to #12635, which merged before this review round landed.
Everything
here is a fix to what that PR shipped, found by adversarial review of it
and
verified against the code path before being changed.

Three of these are defects that make shipped code wrong today on `main`:

1. **The learned-memory review card is dead in production.** The
scheduled
daily-summary job called the summary generator without
`memories_learned`, so
the field was always empty, so the `memoryReviewCard` block was never
attached
on the only path real users receive. Only the
`/daily-summary-settings/test`
route passed it. Both senders now select through one shared helper, and
a test
   fails without the fix.
2. **A failed voice query now reads its own failure aloud.** #12635
changed the
empty-response copy while `FloatingBarVoicePlaybackService.shouldSpeak`
still
suppressed one exact hardcoded string, which no longer exists in the
tree. Copy
and guard now share one source, pinned by a test that drives the real
playback
   path rather than the string compare.
3. **The server rejects the review card the Mac sends.** The desktop
adapter
converts a `memoryReviewCard` for the chat-first journal, but the block
was not
   in the server union, so every such request failed validation as
`invalid_request` and the card was never journaled. Added to the
*request*
   union only: the server never emits this block, and adding it to the
materialization response union is a breaking change to a released
app-client
contract (`check_app_client_openapi_compatibility` confirms both
directions).

Two more undercut claims #12635 itself made:

4. **The daily-summary checkpoint could not resume.** The cursor key
carried the
UTC hour, so the run that wrote the tail and the run that should have
resumed it
never shared a key — which defeats the point of the #12530 fix. A failed
timezone chunk also let the run call itself complete and clear the
cursor.
5. **The Mac review card never saw its own vote.** A vote wrote to the
backend but
was not mirrored locally, so the row reverted to unreviewed on the next
card
build. Now mirrored through existing storage, with the backend still the
only
   writer.

And one the review only half-saw:

6. **The streamed follow-up tail leaked into the transcript.**
`ChatStreamingBuffer`
wrote the normalized projection back into the message and appended the
next
delta to it, so a projection that deliberately withholds the tail lost
the
evidence it needed on the next flush. A replay of every flush boundary
leaks at
every boundary from the delimiter onward, not only at a split marker,
and the
question always spans several flushes. Display-only, since the
authoritative
answer overwrites it, but the reader watched the chip's question get
typed into
   the answer and then snatched away.

Also fixed: multi-question chips, chips on guard-stopped turns,
generic-prefix
rules that diverged between client and server, a permanent optimistic
override on
mobile, a duplicated question when a follow-up block had no prose,
per-item
decoding so one malformed row cannot drop the whole array, owner-scoped
knows-list
visits, a content-change reset that skipped the show cap, and greeting
counts that
disagreed with the rows they described.

Three findings were **rejected with evidence** rather than fixed: that
the stream
filter persists its withheld suffix (the persisted answer is built by
the
producer, and flushing would have pushed the fragment *into* the
stream); that a
safety-guard stop should be reclassified as a provider failure (an
explicit,
tested contract says a guard stop is a deliberate reply); and a pytest
marker that
would have removed a file from CI entirely.

## End-to-end coverage: made real

#12635 satisfied `desktop-e2e-flow-coverage` by adding `covers:` entries
to two
flows that never exercise the code. The gate is a text match over the
`covers:`
list and never inspects steps, so the claim cost nothing to write and
gave false
confidence that these modules were end-to-end covered. Those entries are
removed
here and the coverage is built instead:

- **Chat follow-up.** The hermetic stub can now emit a follow-up tail,
the chat
automation snapshot exposes the chip question, and a bridge action taps
the chip
and reports the origin the analytics emit actually carried. The flow
asserts the
visible answer by exact equality, which is what catches a tail left in
the prose.
- **Memory review card** (`memory-review.yaml`). A local-only
dev-harness route
seeds a summary, the flow creates the memories through the production
endpoint,
renders the card, accepts one row and rejects another through the same
store the
buttons call, then re-reads to prove both verdicts survive the refresh.
- **Knows-list rotation** (`home-knows-rotation.yaml`). Seeds tasks,
clears the
ledger through the same persistence the mutations use, and pins the
first visit's
rows, the within-visit de-duplication, and a later visit's view of a
dismissed row
  and a merely-shown row.
- **Streaming buffer.** Judged uncoverable at first, because the defect
is
mid-stream and the terminal answer overwrites the streamed text before
any
assertion runs. True of the final text only: a non-prod probe now keeps
its own
raw stream, compares every emitted projection against the shipped
tail-stripping
rule, and the flow asserts zero leaks alongside two liveness assertions
so the
zero cannot be vacuous. A negative-control unit test feeds the probe the
exact
  projection the pre-fix buffer emitted and asserts it is counted.

Three things are deliberately **not** claimed, each stated next to its
`covers:`
entry: the empty-slot telemetry, the three-show cap (it needs three
calendar days
or an injected clock, and is unit-tested instead), and the 14-day
stale-task rule,
which is unreachable from the hub because the dashboard query already
cuts off at
seven days. That last one is a real finding and wants a follow-up.

## Invariants

- INV-AUTH-1: no change to auth.
- INV-CHAT-1: chat continuity preserved; the follow-up block rides the
persisted message.
- INV-NAV-1: no navigation changes.
- INV-VOICE-1: realtime hub prompt untouched; the voice guard change
makes failure copy silent again, as it was before #12635.
- INV-MEM-4: no new promotion path; a vote is a review, not a promotion.
- INV-MEM-1: memory reads go through `MemoryService`; the local mirror
carries no second copy of review state and the backend remains the only
writer.

## Product invariants affected

- INV-AUTH-1
- INV-CHAT-1
- INV-VOICE-1
- INV-MEM-4
- INV-MEM-1
- INV-TASK-2

## Failure class

Failure-Class: new

This PR adds one definition, `FC-projection-fed-its-own-output`:
`ChatStreamingBuffer` re-derived its output from
its own previous output, so a projection that withholds text destroyed
the
evidence it needed on the next pass. The protocol allows one declaration
per body;
the others are recorded here for the reader.

<!--
Failure-Class: FC-contract-wired-on-one-of-two-senders (the scheduled
job never passed memories_learned, so the review card was dead on the
only path users receive while the test route worked)
Failure-Class: FC-guard-pinned-to-a-copy-string (shouldSpeak suppressed
one exact string; changing the copy made the failure speak)
Failure-Class: FC-checkpoint-keyed-outside-its-retry-window (the resume
cursor carried the UTC hour, so the next run never read the tail)
-->

## Line-count exceptions

Line-Count-Exception: backend/utils/retrieval/agentic.py | 1718 -> 1736
| outcome-text helper voids a pending marker at the five
backend-authored sites
Line-Count-Exception:
desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarView.swift
| 3107 -> 3112 | chord-aware push-to-talk hint
Line-Count-Exception:
desktop/macos/Desktop/Sources/FloatingControlBar/FloatingControlBarWindow.swift
| 5740 -> 5752 | failure copy moved to a shared constant the voice guard
also reads
Line-Count-Exception:
desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift |
4268 -> 4328 | per-branch open recording plus the non-prod knows
automation registry
Line-Count-Exception:
desktop/macos/Desktop/Sources/Providers/ChatProvider.swift | 7210 ->
7212 | the streaming buffer's raw accumulator is released when the
terminal answer lands

## Verification

- `make preflight`: all 39 checks pass, including
`desktop-e2e-flow-coverage` at 0 uncovered.
- Backend: scoped runs through `test.sh` (via
`BACKEND_UNIT_TEST_FILE_LIST`, since positional paths are ignored) green
under the CPU duration guard, including four consecutive runs of the
daily-summary files at load average 61.
`check_app_client_openapi_compatibility` passes; all four generated
clients are `--check` clean.
- Desktop: `swift build -c debug` green; the follow-up, review-card,
knows-list, and streaming-probe suites pass; swift-format, SwiftLint,
the baseline ratchet, test-quality, and the main-actor hook check are
clean.
- Mobile: `app/test.sh` all passed; `dart format` clean.

## Not done here

- **None of the three new or extended e2e flows has been executed.**
Tier 2 needs Docker, and `docker info` fails on the authoring machine.
Both sides of every string they assert are pinned by unit tests so drift
fails in seconds, and the streaming probe has a falsifiable negative
control, but someone with Docker must run `chat-hermetic`,
`memory-review`, and `home-knows-rotation` before they are trusted. Two
knows-list expectations rest on a reading of the composer's slot
ordering that only a real run can confirm.
- No dogfood on a signed-in bundle. The desktop mirror write on a review
vote has no hermetic test, so it is the first thing to check by hand.
- A cross-device vote still appears only after the memory sync runs:
there is no single-memory GET to make the card's read authoritative.
- An unserved daily-summary user is still not re-queried an hour later,
because eligibility matches one local hour. The checkpoint only recovers
the tail if the job runs more than once per hour, and the repo disagrees
with itself about the cadence.
- Mobile strings stay hardcoded English, matching every neighbouring
widget.
- Interject is still not wired to the review rows.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12669?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
… dropped

The rebase onto #12635 resolved this docstring in favour of this branch's
one-line version, silently deleting the isolation contract main had just
documented: failures are recorded per uid, and a user over the per-user
budget is abandoned rather than allowed to hold the batch barrier.

Restore main's text verbatim and add what is newly true — the same
per-user timeout now also covers the backfill walk, so a user with holes
can spend up to 1 + _DAILY_SUMMARY_BACKFILL_GENERATE_CAP generations
inside one budget.

Co-Authored-By: Claude Opus 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 5, 2026
… evidence

Two documentation-accuracy notes from review.

The TestNotificationWebhookWiring docstring still said the webhook is "wired
through storage_executor" -- stale across two rewirings. It was storage_executor,
then postprocess_executor (BasedHardware#7387), and is now an inline awaited call bounded by
its own budget. The class name predates all of that, so the docstring now records
the sequence and why the current shape is what it is.

evidence_prs cited BasedHardware#12588, which was closed unmerged. Replaced with BasedHardware#12742 rather
than the suggested BasedHardware#12635: BasedHardware#12635 landed c82237e, the batching/cursor fix that
belongs to FC-batch-fault-domain-head-of-line-poison, and it did not touch the
pool-lifecycle defect this class describes. Citing it would attribute this class
to a change that never addressed it. This PR is where the class is both defined
and fixed, which matches FC-task-candidate-unowned-commitment citing its own
defining PR.

scripts/failure-class validate: OK (fix commits=True; declaration=new).

Failure-Class: none

Co-Authored-By: Claude Opus 5 <[email protected]>
kodjima33 pushed a commit that referenced this pull request Sep 6, 2026
* fix(backend): give the daily-summary webhook a lifecycle owner

The daily-summary developer webhook was submitted fire-and-forget:

    postprocess_executor.submit(asyncio.run, day_summary_webhook(...))

Two defects in one line. _deliver_current_day_summary already runs *on*
postprocess_executor -- send_daily_summary_notification dispatches every
user through run_blocking(postprocess_executor, _send_summary_notification,
...) -- so the submit made the coordinator its own child on the pool it was
running on, the arrangement backend/AGENTS.md forbids. And nothing owned the
result: the per-user asyncio.wait_for budget covers the call, not what the
call spawns, and the Cloud Run Job exits without joining the pool. A webhook
still queued at exit was never scheduled, which is the

    coroutine 'day_summary_webhook' was never awaited

logged immediately before container exit in #12530's evidence.

c82237e fixed the batching half of #12530 with a deadline and a resumable
cursor. That bounds the batch; it does not give this coroutine an owner.

Run it inline, inside the per-user budget that governs the rest of that
user's work. The push moves ahead of it and becomes a branch rather than an
early return, so a tokenless user still reaches their webhook as before. The
call is wrapped because inline changes who pays for a fault: day_summary_webhook
handles its own HTTP failures but not the work around them, and an escaping
error would mark a user whose push already went out as failed. The discarded
Future used to supply that containment by accident; make it a decision, and
log it, where the old path reported nothing.

Also returns 8 slots per batch to postprocess_executor -- the pool
DAILY_SUMMARY_MAX_ABANDONED_USERS exists to protect.

Failure-Class: new

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

* fix(backend): bound the daily-summary webhook inside its own budget

Running the webhook inline gave it an owner, but it also moved its cost onto the
user. day_summary_webhook posts through the shared client (30s read timeout,
retries at 1/5/30s) and now sits inside the per-user asyncio.wait_for budget, so
a slow receiver could burn most of DAILY_SUMMARY_USER_BUDGET_SECONDS and get a
user whose push had already been delivered marked reason=user_budget_exceeded --
which counts toward DAILY_SUMMARY_MAX_ABANDONED_USERS and can abort the rest of
the hour group. A developer webhook must not be able to cost anyone their recap.

Bound it at DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS (20s, env-overridable), well
inside the 90s budget it shares. The existing except already contains and logs
the resulting timeout.

Verified by mutation: with the bound removed the new test reports
"the webhook must be abandoned at its own budget, took 30.0s"; with it, the
webhook is abandoned at its own budget and the record and push both survive.

Also assert the daily_summary_webhook_failed log line in the containment test.
Containment without the log is the old swallowed Future by another name -- the
fault disappears and #12530's evidence never reappears -- so the test now pins
the record rather than only that nothing raised.

The source pin follows the new wiring: it still forbids the submit, and now
requires the timeout constant rather than a bare asyncio.run call.

Failure-Class: none

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

* docs(backend): correct the webhook wiring docstring and failure-class evidence

Two documentation-accuracy notes from review.

The TestNotificationWebhookWiring docstring still said the webhook is "wired
through storage_executor" -- stale across two rewirings. It was storage_executor,
then postprocess_executor (#7387), and is now an inline awaited call bounded by
its own budget. The class name predates all of that, so the docstring now records
the sequence and why the current shape is what it is.

evidence_prs cited #12588, which was closed unmerged. Replaced with #12742 rather
than the suggested #12635: #12635 landed c82237e, the batching/cursor fix that
belongs to FC-batch-fault-domain-head-of-line-poison, and it did not touch the
pool-lifecycle defect this class describes. Citing it would attribute this class
to a change that never addressed it. This PR is where the class is both defined
and fixed, which matches FC-task-candidate-unowned-commitment citing its own
defining PR.

scripts/failure-class validate: OK (fix commits=True; declaration=new).

Failure-Class: none

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

* fix(backend): run the daily-summary webhook after the owner's backfill

Review point, and it is right. Running the webhook inline gave it an owner but
put its cost inside DAILY_SUMMARY_USER_BUDGET_SECONDS, which the owner's own
backfill walk also spends. Sitting ahead of the backfill, a slow receiver could
take up to DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS that the owner's missing days
needed, and tip a marginal user into user_budget_exceeded -- counting toward
DAILY_SUMMARY_MAX_ABANDONED_USERS and abandoning the rest of the hour group.

That contradicted the rule this change exists to uphold, which the code comments
already stated: a developer webhook must never cost the owner their recap.
Backfill is owner work. Last in the per-user budget means the webhook can only
ever spend what nobody else still wants.

Lifted out of _deliver_current_day_summary into _deliver_day_summary_webhook and
driven from _send_summary_notification's finally. finally rather than a trailing
call, because the dormant-owner branch returns before the backfill and the
backfill itself can raise: either would drop the webhook for a user whose summary
was already generated, stored and pushed -- the same unowned-work loss this PR
exists to stop, just moved to a different exit.

The bound, the containment and the daily_summary_webhook_failed log are
unchanged, as is the payload call, so TestSendSummaryNotificationWiresSummaryJson
still pins day_summary_webhook(uid, str(summary_data), summary_data) exactly.

Three tests. Ordering is mutation-checked: with the webhook restored to its old
position the assertion reports "the webhook must run after every backfill
generation, not before them", assert 1 == 4. The other two cover the finally --
a raising backfill still sends the webhook, and a dormant owner is unaffected.

Suites: generation 30, async_http_infrastructure 50, async_webhooks 29,
job_resilience 21, lock_bypass_fixes 62, other_notifications_async_boundaries 6,
race_condition 16, empty_overview 2.

Failure-Class: none

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

* test: name the dormant-day webhook test for what it asserts

The test asserts no webhook is sent when a dormant owner declines the day,
but was named as though it proved one survives. Review on #12742 caught it:
a dormant decline means created=False, so pending_webhook is already None
and the finally has nothing to deliver.

Renamed to test_a_dormant_day_sends_no_webhook and rewrote the docstring to
state the real guarantee -- the finally must not push an empty recap on the
early-return path -- and to point at the raising-backfill test, which is what
actually exercises delivery through finally.

---------

Co-authored-by: Claude Opus 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.

Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups

1 participant