Skip to content

feat(review): open-loop Review source and mobile cards — Questions for you (Open loops PR 3) - #23683

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/open-loops-review
Oct 26, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/open-loops-review

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

Open loops PR 3: the daily pass's open-loop cards (PR #23639) now reach the owner. Two Review-scoped routes serve the recap day's pending cards and apply the three answers, and the mobile Review page shows them as "Questions for you" above the existing queue — question and context line verbatim from the card writer, answerable with Done / Remind me later / Drop it, with optimistic removal and rollback. Without cards the Review page looks exactly as before. The cards deliberately stay out of the shared v2/review/items queue: that queue enforces one 3-per-day attention budget and a 3-slot ranked list, while cards carry their own pass-ranked 2–3/day lifecycle that ages out with the day — folding them in would make them compete with speaker/spelling questions and burn the shared budget.

Review fixes (same branch, review round 1):

  • Recap day for V4-recap users (HIGH). The listing now resolves the day with exactly the producer's rule (utils.other.daily_recap.scheduled_date mirrored without its shadow-metrics side effect): uids serving CALLS_RECAP_MODE date cards with completed_day (always yesterday — the pass runs ~01:00 local), everyone else keeps the noon split. A parity test pins the two rules together across every mode/cohort. When the resolved day's pass did not run (or left nothing pending), the listing falls back to the most recent of the previous day's documents that still has pending cards, and the wire's date — the app's answer path — is that day.
  • Atomic answers (MEDIUM). answer_card's whole-document read-modify-write is now one Firestore transaction (database.open_loops.transition_card_state, run through run_transactional): two answers in flight serialize, each preserving the other's committed card state instead of resurrecting it as pending from a stale snapshot. The loop update runs only after this call's own transition committed, so a repeated/racing answer never re-resolves, re-snoozes or records a second negative example. Deterministic interleaving tests drive both shapes (two cards racing; a double tap on one) through the fake client, which now models staged transactions with commit-time read-set validation.
  • Stale rollback + shared conflict flag in the app (LOW-MEDIUM). A failed send now restores only its own card at its original position, keeping concurrent successes and reloads (no duplicated cards). The shared lastOpenLoopConflict bool is gone: answerOpenLoop returns a per-request OpenLoopAnswerStatus (saved/conflict/failed) and the message follows that request's outcome.
  • Path-param validation (LOW). The answer route validates date (^\d{4}-\d{2}-\d{2}$ and a real calendar date) and card_id (the two id formats the pass writes: ol-<16 hex> and task-<task id>) and returns 422 before any Firestore read.

Product invariants affected

none

How it was verified

  • Backend (backend/, BACKEND_PYTEST_WORKERS=1): BACKEND_UNIT_TEST_FILE_LIST run via bash test.sh over every review/open-loop unit test plus the recap-wave and action-item neighbors — 269 passed, including 32 route tests (backend/tests/unit/test_open_loops_review_routes.py) and 20 service tests (backend/tests/unit/test_open_loops_service.py). New coverage: cohort day-resolution at 09:00 and 15:00 local for both the legacy noon split and CALLS_RECAP_MODE serving, a cards_display_day vs daily_recap.scheduled_date parity guard across all modes, the fallback window (falls back one day, only over pending cards, never beyond), concurrent-answer interleaving and double-tap idempotence, and 422 validation for malformed dates and card ids.
  • Route policy: python scripts/check_route_policy_baseline.py — both routes declared in backend/route_policy_manifest.yaml, baseline current (unchanged by the fixes; no new routes).
  • Contracts: app-client OpenAPI regenerated (scripts/openapi_runner.sh scripts/export_openapi.py --surface app-client --write); check_app_client_openapi_compatibility.py --base-ref origin/main passed; generated Dart (--all --check), TS, and Swift clients refreshed and verified (unchanged by the fixes; no path or response-model changes).
  • Image contracts: make runtime-image-source-closure passed for all 19 registered images.
  • App (app/): flutter analyze clean on all touched files; bash scripts/analyze_ratchet.sh passed; the two touched test files — test/providers/review_provider_test.dart and test/pages/review/open_loop_card_test.dart — pass (26 tests), with new cases for the per-card rollback under a concurrent success and a concurrent reload, per-request conflict reporting, and the per-request snackbar message.
  • UI evidence below is rendered by app/test/pages/review/open_loop_evidence_test.dart (real SF Pro fixtures, no simulator): light, dark, and the state after tapping Remind me later. Unchanged by the review fixes (no visual change).

Tests

  • Core path: backend/tests/unit/test_open_loops_review_routes.py (wiring per action, producer-day listing + fallback day on the wire, path-param validation), backend/tests/unit/test_open_loops_service.py (cohort day rules, answer transaction interleaving), app/test/pages/review/open_loop_card_test.dart, app/test/providers/review_provider_test.dart (open-loop group).
  • Main error path: kill switch 404/empty, invalid action 422, malformed date/card id 422, already-answered 409 (backend); failed send restores only its card (concurrent success/reload kept), answered-elsewhere card stays gone with a per-request conflict message (app).

UI evidence

Review with open-loop cards, light

Review with open-loop cards, dark

Review after Remind me later

Fictional card text only. Manifest: .agent-artifacts/ui-evidence/open-loops-review/evidence.json.

Failure-Class: none

🤖 Generated with Claude Code

…ew (Open loops PR 3)

- GET /v1/review/open-loops lists the recap day's pending cards (zone from
  request, then the stored profile zone, then UTC); POST
  /v1/review/open-loops/{date}/{card_id}/answer applies done|remind|drop
  through the PR 2 service. OPEN_LOOPS_ENABLED off means an empty list / 404;
  an already-answered card maps to 409; only the card writer's question and
  context line cross the wire. Both routes are declared in the route-policy
  manifest; the app-client OpenAPI and the generated TS/Swift clients are
  refreshed.
- Mobile: open-loop cards render at the top of Review ("Questions for you")
  with Done / Remind me later / Drop it, optimistic removal with rollback,
  verbatim wrapping text; strings localized across all 49 locales.
- Tests: backend route tests (auth, kill switch, action validation, wiring,
  wire hygiene); app provider and widget tests; widget-render UI evidence for
  light, dark, and the post-remind state.

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

mintlify Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
omi 🟢 Ready View Preview Oct 26, 2026, 7:52 AM

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T08:49:54.928493Z e2e3b98 New commits
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 19380c5583

ℹ️ About Codex in GitHub

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

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

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

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

switch (cardsResult) {
case ApiSuccess(:final data):
// The cards share the Review surface — when it is off, none can exist.
if (availability != ReviewAvailability.off) openLoopCards = data.cards;

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 Badge Include open-loop cards in the Review entry's visibility and count

When an account has pending open-loop cards but no ordinary review items, these cards load successfully but cannot be reached through the app. ReviewEntryCard.build in app/lib/pages/review/widgets/review_entry_card.dart still counts only provider.items and returns SizedBox.shrink() when that count is zero (lines 61–63). A repository-wide search for ReviewPage( shows that this entry card is the only navigation path to the page. Include openLoopCards in the entry's visibility and badge count so users can answer these questions without an unrelated review item also being pending.

Useful? React with 👍 / 👎.

Comment thread app/lib/providers/review_provider.dart Outdated
Comment on lines +252 to +253
if (!openLoopCards.any((c) => c.cardId == card.cardId)) {
openLoopCards = before;

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 Badge Restore only the failed card instead of the entire snapshot

If a user answers two cards before the first request settles, a failure for the first answer restores its entire before list, including the second card even if that answer succeeded. Conversely, if both requests fail, restoring the second request's snapshot after the first rollback can remove the first restored card. The UI allows answers on the remaining cards while requests are pending, so these overlapping requests are possible. Reinsert only the failed card into the current list rather than replacing the list with an older snapshot.

Useful? React with 👍 / 👎.

Comment thread backend/routers/review.py
def answer_review_open_loop(date: str, card_id: str, request: OpenLoopAnswerRequest, uid: str = WriteUser):
if not open_loops_enabled():
raise HTTPException(status_code=404, detail='open_loops_disabled')
card = open_loops_service.answer_card(uid, card_id, request.action, date_str=date)

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 Badge Pass the owner's time zone when applying an answer

For users whose local date differs from UTC, answering “Remind me later” computes the wrong snooze date because this call omits tz. In utils/open_loops/service.py, _apply_answer_to_loop derives today through local_today(tz, moment) and sets snoozed_until to that date plus two days; a missing zone defaults to UTC. Listing already resolves the owner's stored zone, but answering does not, so the snooze can expire one local day early or late. Resolve and pass the owner's zone here as well.

Useful? React with 👍 / 👎.

… rollback

Review round 1 fixes for the open-loops PR (#23683):

- Listing day now follows the producer's rule (daily_recap.scheduled_date
  mirrored without its shadow metrics): CALLS_RECAP_MODE-served uids list
  completed_day (yesterday, no noon split), so noon no longer points the
  GET at a cards document that does not exist until the next pass; when the
  resolved day has nothing pending the listing falls back one local day and
  the wire date is the day the cards actually live in.
- answer_card's whole-document read-modify-write is now a Firestore
  transaction (read-check-update via run_transactional); the loop update
  runs only after this call's own transition committed, so racing answers
  serialize — no resurrected pending cards, no duplicate negative examples —
  and repeated answers are no-ops (the route's 409). The store fake models
  staged transactions with commit-time read-set validation; both
  interleavings (two cards racing, a double tap) are tested deterministically.
- The app restores only the failed card at its original position (concurrent
  successes and reloads are kept, never a stale snapshot) and reports
  conflicts per request via OpenLoopAnswerStatus instead of the shared
  lastOpenLoopConflict flag.
- The answer route validates the date and card-id path params against the
  formats the pass writes and returns 422 before any Firestore read.

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a17db552ef

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +160 to +162
card = open_loops_db.transition_card_state(
uid, day, str(card_id), CARD_STATE_BY_ACTION[action], moment.isoformat(), firestore_client=firestore_client
)

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 Badge Commit the loop mutation durably with the card answer

If get_loops or upsert_loop fails after this transaction commits, the card is permanently marked answered even though the loop was never resolved, snoozed, or dropped. The first request returns an error, but retrying returns 409 because transition_card_state now rejects the card; the mobile client consequently removes it without applying the requested change. Previously, these storage failures occurred before the card was marked answered. Commit the card and loop changes atomically, or persist a retryable operation alongside the card transition so downstream failures cannot permanently lose the answer.

Useful? React with 👍 / 👎.

Comment on lines +164 to +166

def get(self, ref: _DocumentRef) -> _Snapshot:
with self._store._lock:

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 Badge Use the required strict Firestore transaction fixture

The new transaction tests use a custom fake whose get permits reads after set has staged a write, so they can pass transaction sequences that production Firestore rejects. This violates the explicit “Firestore transaction fakes” guidance in backend/AGENTS.md, which requires StrictFirestore for document-reference transaction tests and emulator coverage before extending retry/contention behavior. Use that fixture for the transaction guards and validate contention through the emulator rather than relying solely on this permissive implementation.

AGENTS.md reference: backend/AGENTS.md:L229-L229

Useful? React with 👍 / 👎.

Comment thread backend/utils/open_loops/service.py Outdated
Comment on lines +125 to +129
for offset in range(OWNER_FALLBACK_DAYS + 1):
candidate = (base - timedelta(days=offset)).isoformat()
pending = list_pending_cards(uid, limit=limit, date_str=candidate, firestore_client=firestore_client)
if pending:
return candidate, pending

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 Badge Exclude already-handled loops from previous-day fallback

When a due-soon loop has pending cards on consecutive days, answering today's card and refreshing can immediately bring back yesterday's question about the same loop. This is a supported producer scenario: store.surfaceable exempts due_soon loops from the recent-surfacing cooldown. Once today's cards are answered, this fallback returns yesterday's pending card without checking the loop's current resolved, dropped, or snoozed state, undoing the visible effect of Done, Drop, or Remind me later. Filter fallback cards against current loop state and newer answers, or avoid falling back merely because an existing day's cards have all been answered.

Useful? React with 👍 / 👎.

Review round 2: the app-client schema inventory flagged the open-loop wire
DTOs as the last hand-written Dart JSON schemas (2 remaining manual files).
The OpenLoop routes were already exported in the app-client OpenAPI spec,
so the fix is to model them like every other Review surface:

- The review schema group (backend/scripts/dart_model_groups.py) now
  includes OpenLoopCard, OpenLoopCardsResponse, OpenLoopAnswerRequest and
  OpenLoopAnswerResponse; review_wire.g.dart regenerates them.
- app/lib/backend/schema/open_loops.dart keeps the app-facing card type and
  its drop-malformed-rows strictness but parses every row through
  wire.GeneratedOpenLoopCard.fromJson: a row failing the wire contract
  throws and is dropped, and a row losing an identity field (empty id,
  date or question) is dropped in fromGenerated.
- app/lib/backend/http/api/open_loops.dart decodes both responses through
  the generated types and encodes the answer request with
  GeneratedOpenLoopAnswerRequest. The strict _object() helper also turns a
  non-object body into a typed ApiFailure(decode) instead of the uncaught
  TypeError the previous `as Map` cast could raise.

test_app_client_schema_inventory.py passes with
remaining_manual_dart_json_schema_file_count == 0; generate_dart_models
--all --check and the Dart wire hardening check stay green; the Review
provider and review-page widget tests pass.

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 38c227eaeb

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +128 to +129
if pending:
return candidate, pending

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 Badge Instrument the previous-day recovery path

When the resolved day's pass has not run but yesterday has pending cards, this branch silently substitutes older content without recording the degraded recovery. Operators therefore cannot distinguish a healthy current-day listing from a missing producer run through the shared fallback telemetry. The “New fallbacks” rule in backend/AGENTS.md requires utils.observability.fallback.record_fallback; emit it when taking the older-day recovery path, using bounded fields and an appropriate outcome.

AGENTS.md reference: backend/AGENTS.md:L318-L318

Useful? React with 👍 / 👎.

switch (cardsResult) {
case ApiSuccess(:final data):
// The cards share the Review surface — when it is off, none can exist.
if (availability != ReviewAvailability.off) openLoopCards = data.cards;

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 Badge Reconcile refreshed cards with answers made during the load

If a refresh reads a pending card before its answer commits, its response can overwrite the optimistic removal and bring the card back even after the answer succeeds. This can happen immediately after opening Review: ReviewPage.initState starts a load while the previously loaded cards remain interactive. The success and 409 branches of answerOpenLoop do not remove the card again, so the answered question remains visible until another refresh or tap. Reconcile load results against in-flight and subsequently acknowledged answers, scoped by card date and ID, rather than assigning the stale response directly.

Useful? React with 👍 / 👎.

Comment thread backend/routers/review.py
# loop). Malformed values are rejected here, before any Firestore read, instead
# of surfacing as a store error.
_OPEN_LOOP_DATE = re.compile(r'^\d{4}-\d{2}-\d{2}$')
_OPEN_LOOP_CARD_ID = re.compile(r'^(ol-[0-9a-f]{16}|task-[A-Za-z0-9_-]{1,64})$')

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 Badge Accept task IDs produced by automatic conversation refresh

For cards originating from automatically refreshed tasks, this pattern rejects valid IDs: backend/database/action_item_refresh_policy.py:139 creates task IDs as refresh- plus a full SHA-256 digest, totaling 72 characters. open_tasks_view passes those IDs unchanged to the daily model, and apply_model_updates constructs task-born loop IDs as task-<task_id>. Such cards are returned by the listing endpoint, but all three answer actions receive 422 because the task-ID suffix exceeds this 64-character limit; the mobile client then restores the unanswerable card. Allow the task-ID formats and lengths the existing task producers actually generate.

Useful? React with 👍 / 👎.

…ailed loop write; skip terminal loops

Fall back to the previous day only when the resolved day has no cards
document; a day the pass ran stays empty once answered. Answering a card
whose loop already ended keeps the loop and its task untouched. If the loop
write fails after the card transition commits, the card goes back to pending
so the owner's retry applies the answer instead of a 409.

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e2e3b98b21

ℹ️ About Codex in GitHub

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

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

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

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

}
}
}
return OpenLoopCardsResponse(cards: cards);

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 Badge Reject malformed or entirely undecodable card listings

When a 200 response contains a non-list cards value or a nonempty list whose rows all fail decoding, this method returns a successful empty listing. The provider then replaces previously loaded cards with that empty list, making a broken response indistinguishable from having no pending questions. The C3 HTTP contract referenced by the app guide explicitly requires malformed envelopes and all-invalid nonempty inputs to produce decode failures. Validate the envelope and throw FormatException when every supplied row is rejected, while retaining support for partially valid listings.

AGENTS.md reference: app/AGENTS.md:L112-L112

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 54584f3 into main Oct 26, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/open-loops-review branch October 26, 2026 09:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant