Repository navigation
feat(notes): open-loop daily pass, loop store with expiry, task-aware dedupe, ranking (Open loops PR 2) - #23639
Conversation
… dedupe, ranking (Open loops PR 2)
Open loops PR 2 (backend, no UI, cards not yet served). One structured call
per user per local day runs as a fail-open sibling step of the daily recap
job, over the recap's own render of the day plus a per-user loop store, and
stores up to three self-contained Review cards per day server-side. PR 3
adds the Review source and mobile UI over utils/open_loops/service.py.
- Loop store (users/{uid}/open_loops): whole-loop derived JSON blob,
compressed and encrypted for every user; stable-key upsert identity,
duplicate merges with a task-linked survivor, expiry (no signal: 7d
default / own_commitment 10 / owed_to_user 14; terminal docs deleted
after 14d; open cap 60), streamed whole so no new Firestore indexes.
- Daily pass (utils/open_loops/daily.py, feature key open_loop_daily on
gpt-6-luna with reasoning_effort pinned, usage-tracked, wired like PR 1's
open_loop_card across inventory/route overrides/snapshot/QoS tiers):
statuses only with signal, resolve on evidence, task-aware dedupe that
links (never drops) via the documented token-heuristic seam for Jev,
two-day re-ask cooldown (due_soon re-arms), snoozes, and deterministic
ranking (value >= 3, due_soon first, work first, <= 3 slots).
- Cards doc per local day (users/{uid}/open_loop_cards/{date}) doubles as
the once-per-day marker; OPEN_LOOPS_ENABLED off skips the pass and writes
nothing; no extractions + no open loops skips the model call; locked or
budget-declined recap days spend nothing on the pass; the fail-open catch
owns the pass module's own import so the recap can never notice it.
- answer_card: done resolves the loop and completes the linked task through
the existing action-item update path (best effort), remind snoozes 2 days,
drop keeps the card as a negative example on the loop.
- Tests: store/expiry/dedupe/cooldown/ranking, daily guards and ingestion,
service transitions, recap sibling-step integration (incl. import-failure
containment), and a 70-day synthetic replay proving the store stays
bounded and resolved loops stop surfacing. Firestore guard registry gains
the reasoned skip, runtime caller witness and profile for the new reader.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c48474141a
ℹ️ 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".
| # task description still matches. | ||
| MATCH_THRESHOLD = 0.6 | ||
|
|
||
| _WORD_RE = re.compile(r'[a-z0-9]+') |
There was a problem hiding this comment.
Preserve Unicode text in loop identities
When who and what contain only non-Latin text, such as Chinese or Cyrillic, this ASCII-only pattern removes their entire contents. stable_key() consequently assigns every such loop of the same kind the same ID; for example, two unrelated Chinese names and deliverables both produce ol-1b18ff525df8c2f3 for owed_to_user. Ingestion then treats these unrelated promises as updates to one document, silently losing follow-ups. Preserve Unicode letters and numbers when normalizing the identity.
Useful? React with 👍 / 👎.
| if loop.get('status') != status: | ||
| loop = store.append_history(loop, today, status, str(entry.get('evidence') or '')) | ||
| loop['status'] = status | ||
| loop['last_activity_at'] = _iso(now) |
There was a problem hiding this comment.
Keep inactivity decisions from refreshing the activity clock
For an important loop with no new conversation evidence, the prompt explicitly permits a stale decision supported by “no mention since ”. This unconditional timestamp update counts that absence of progress as fresh activity. Repeated stale decisions therefore prevent store.expiry_due() from ever reaching its 7/10/14-day inactivity window and reset the age_days supplied to subsequent passes. Only advance the activity clock for actual new source evidence, not an age-based stale or due-soon assessment.
Useful? React with 👍 / 👎.
| if loop.get('status') != status: | ||
| loop = store.append_history(loop, today, status, str(entry.get('evidence') or '')) | ||
| loop['status'] = status |
There was a problem hiding this comment.
Preserve dropped state when an open task is proposed again
When the owner drops a task-linked card, answer_card() marks its loop dropped but intentionally leaves the underlying task open. The next daily pass still supplies that task in open_tasks while excluding its dropped loop from carried_loops, so the model can legitimately propose task-<id> as stale or due soon. Ingestion finds the existing terminal document and unconditionally replaces its status here, making the dismissed card eligible to surface again without any new evidence. Preserve the terminal decision for the same task identity rather than reopening it solely because the task remains open.
Useful? React with 👍 / 👎.
| def _local_date_str(tz: Optional[str], now: Optional[datetime], date_str: Optional[str]) -> str: | ||
| return date_str or local_today(tz, now).isoformat() |
There was a problem hiding this comment.
Align the cards lookup date with the completed-day producer
For a morning recap, the producer and this default lookup address different documents: _send_summary_notification() passes the completed day's date into run_daily_pass(), which stores cards under that date, whereas this lookup requests today's date. For example, a pass processing October 26 at 01:00 on October 27 writes open_loop_cards/2026-10-26, but list_pending_cards(uid, tz=...) later that morning reads 2026-10-27 and returns nothing. This occurs with the completed-day recap scheduler and with legacy morning delivery. Align the default lookup and answer date with the producer, or store a separate Review delivery date.
Useful? React with 👍 / 👎.
| parsed = parse_model_output(response) or {} | ||
| raw_loops = parsed.get('loops') | ||
| model_loops: List[Any] = list(raw_loops) if isinstance(raw_loops, list) else [] | ||
| raw_surface = parsed.get('surface') | ||
| surface_entries: List[Any] = list(raw_surface) if isinstance(raw_surface, list) else [] |
There was a problem hiding this comment.
Reject malformed model responses before marking the day complete
If the model returns truncated JSON, a refusal, or another non-JSON response, parse_model_output() returns None, but this fallback treats it as a successful empty result. The pass then persists an empty cards document and returns ran, so the once-per-day guard permanently suppresses retries for that day and the recap's failure handler never records the failure. A valid empty decision should remain successful, but an unparsable response should fail before writing the completion marker so it can follow the existing fail-open error path.
Useful? React with 👍 / 👎.
| card = {**card, 'state': CARD_STATE_BY_ACTION[action], 'answered_at': moment.isoformat()} | ||
| cards[position] = card | ||
| open_loops_db.set_cards(uid, day, cards, firestore_client=firestore_client) |
There was a problem hiding this comment.
Serialize updates to the shared daily cards document
If two answers for different cards in the same day overlap, both calls can read the same pending cards list, update their own entry, and overwrite the entire document here. The last write restores the other answered card to pending, even though both calls returned success and already applied their loop transitions. This is reproducible with two concurrent calls answering cards A and B: only one answer remains persisted. Use a transactional read-modify-write or independently addressable card state so answering one card cannot discard another answer.
Useful? React with 👍 / 👎.
…ong-link completion, terminal-loop cool-off (Open loops PR 2 review fixes)
Four review blockers on the daily pass:
1. Recap time budget: the pass no longer runs inside the user's 90s recap
window. The recap worker finishes summary, push, backfill and webhook and
only returns a pass request; the coordinator dispatches it on the new
dedicated open_loops_executor under OPEN_LOOPS_PASS_BUDGET_SECONDS (45s)
- a slow or failing pass never spends recap budget, delays the webhook,
marks a recipient timed_out or counts toward abandoned users, and passes
are dropped loudly once the job budget is spent.
2. Double spend: an atomic per-user-per-local-day claim
(open_loop_claims/{date}, Firestore create-if-absent, <=2 attempts) is
taken before the model call, so retried ticks, abandoned threads and the
recap's locked-retry path see the claim and skip; a failed day releases
for exactly one bounded retry.
3. Wrong-task completion: answer_card(done) completes a task only through a
strong link (model-asserted from_task_id AND the answered card's text
naming the task; strong links render the task description with the
"(your task from Thu)" clause). Heuristic links stay ask-only. Completion
routes through the app's own path - mark_action_item_completed +
sync_action_item_reminder (#5085) - and find_task_match requires Jaccard
>= 0.6 AND containment >= 0.8 with who compatibility (the Jev seam).
4. Terminal loops never resurface: resolved/dropped/expired loops are
excluded from update matching and merging; a re-mentioned dropped item
never revives and may open a NEW loop only after a 14-day cool-off;
merging requires the same normalized who and Jaccard >= 0.7 AND
containment >= 0.8.
Also: defensive caps on the pass's model output, corrected false
prompt-cache-reuse comments, list_pending_cards defaults to the recap's
completed local day (noon split), snooze/history use the user's timezone,
and the pass skips the model call when the day has no conversations and no
due-soon loop.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9d670b0c6
ℹ️ 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".
| if pass_requests and (deadline is None or monotonic() < deadline): | ||
| await _dispatch_open_loops_passes(pass_requests) |
There was a problem hiding this comment.
Dispatch open-loop work after all recap batches finish
When an open-loop pass is slow, this await blocks the next eight-recipient recap batch for up to 45 seconds, despite using a separate executor. That time also consumes the shared recap-job deadline checked at the start of the next iteration, so optional open-loop work can cause remaining users' recaps to be deferred. Executing this coordinator with nine instantaneous recaps, 40 seconds remaining, and a 45-second pass sends only eight recaps and skips the ninth. Dispatch the optional work after recap scheduling finishes, or otherwise prevent it from blocking subsequent recap batches.
Useful? React with 👍 / 👎.
| if attempts >= MAX_PASS_ATTEMPTS: | ||
| return False | ||
| ref.update({'state': CLAIM_STATE_CLAIMED, 'attempts': attempts + 1, 'updated_at': moment.isoformat()}) | ||
| return True |
There was a problem hiding this comment.
Atomically acquire retry claims
If two workers encounter the same failed or stale claim, both can read attempts == 1, pass these checks, and unconditionally update it to attempts == 2. Both then return True and invoke the model concurrently, defeating the spend guard and allowing their loop/card writes to overwrite each other. The initial create() serializes fresh claims, but does not protect this retry path; use a transaction or snapshot-update precondition for the retry acquisition.
Useful? React with 👍 / 👎.
| elif task_id: | ||
| target = by_id.get(f'task-{task_id}') | ||
| else: |
There was a problem hiding this comment.
Match task-origin proposals against existing linked loops
If an existing heuristically task-linked loop falls outside the 20 carried loops supplied to the model, the model can legitimately propose task-<id> for that open task. This branch checks only the task-shaped document ID, bypassing both existing linked_task_id values and similarity matching, so ingestion creates another document for the same follow-up. The final merge only examines updates, leaving the original document intact and resetting the new copy's surfacing history and cooldown. Reuse or absorb the existing linked loop before creating the task-shaped identity.
Useful? React with 👍 / 👎.
| module's own import — the recap must never notice this step. | ||
| """ | ||
| try: | ||
| from utils.open_loops.daily import run_daily_pass |
There was a problem hiding this comment.
Keep the daily-pass import at module scope
This function-local import violates the explicit rule in backend/AGENTS.md: “All imports at module top level — never inside functions.” Preserving the optional pass's fail-open behavior should not introduce an exception to the backend import convention; keep the import at module scope and make optional initialization lazy behind callable boundaries, while retaining execution-time failure containment.
AGENTS.md reference: backend/AGENTS.md:L165-L171
Useful? React with 👍 / 👎.
| except Exception as error: | ||
| logger.error('open_loops_daily_pass_dispatch_failed uid=%s date=%s error=%s', uid, date_str, error) |
There was a problem hiding this comment.
Record dispatch failures through the shared fallback helper
When submission fails, such as when the bounded executor is saturated, this handler skips the pass and continues with only a log message. Because the worker never starts, _run_open_loops_daily_pass() cannot emit its fallback metric, leaving these dropped passes invisible to shared fallback telemetry. backend/AGENTS.md explicitly requires new fallbacks to call utils.observability.fallback.record_fallback; invoke the existing fallback wrapper here with a degraded outcome rather than relying on the worker's catch.
AGENTS.md reference: backend/AGENTS.md:L318-L318
Useful? React with 👍 / 👎.
| expired_writes, deletes = store.sweep(loops, today) | ||
| expired_by_id = {str(w['id']): w for w in expired_writes} | ||
| for loop in expired_writes: | ||
| open_loops_db.upsert_loop(uid, loop, firestore_client=firestore_client) |
There was a problem hiding this comment.
Apply today's evidence before expiring carried loops
When a loop reaches its inactivity threshold on a day containing fresh evidence about that same follow-up, this sweep persists it as expired before the model processes today's conversations. Ingestion then excludes it from update targets, and remention_blocked() rejects the new evidence because the terminal date is today. For example, a 14-day-old owed-to-user loop cannot accept today's renewed promise to deliver tomorrow and remains suppressed for another 14 days. Evaluate today's evidence before finalizing inactivity expiry, or otherwise allow that evidence to prevent the expiry transition.
Useful? React with 👍 / 👎.
| strong_link = loop.get('task_link') == 'model' and store.text_names_task( | ||
| card.get('question'), loop.get('linked_task_title') | ||
| ) | ||
| if strong_link: | ||
| _complete_linked_task(uid, str(linked_task_id), loop.get('id')) |
There was a problem hiding this comment.
Account for template truncation in the task-completion gate
For a strongly linked task with a longer description, the deterministic card clips its task wording to 90 characters in card._what(), but this gate requires at least 80% of the significant tokens from the unabridged linked_task_title. Ordinary descriptions near the ingestion limit of 160 characters can therefore fail the gate even though the card was generated directly from that task and explicitly says “your task from Tuesday.” Answering Done then resolves the loop without completing the task. Validate against the task wording actually rendered, or preserve a trusted task identity on the generated card so truncation does not turn strong links into ask-only answers.
Useful? React with 👍 / 👎.
| loops = [expired_by_id.get(str(loop.get('id')), loop) for loop in loops if str(loop.get('id')) not in set(deletes)] | ||
|
|
||
| open_loops = [loop for loop in loops if store.is_open(loop)] | ||
| due_soon_any = any(loop.get('status') == 'due_soon' for loop in open_loops) |
There was a problem hiding this comment.
Check approaching due dates before skipping quiet days
If a loop was opened with a deadline more than two days away, it can retain opened or progressing status while that deadline approaches. On subsequent days without conversations, this check considers only the stored status, so the pass returns skipped_no_signal even when by_when is tomorrow. Since the skipped model call is also what would transition the loop to due_soon, the follow-up never becomes eligible for its due-date reminder unless the user records another conversation. Include approaching stored deadlines in this guard rather than requiring a previous pass to have already assigned due_soon.
Useful? React with 👍 / 👎.
…per job Passes are queued per batch, never awaited by the recap loop. A semaphore admits at most the executor's 4 workers at a time, so large hour groups wait for a slot instead of tripping the bounded queue, and each pass's 45s budget starts only once it runs. send_daily_summary_notification drains them once after every cohort under OPEN_LOOPS_DRAIN_BUDGET_SECONDS (240s); stragglers are cancelled and counted. Saturation and budget drops emit the shared fallback counter; the comment no longer claims a next-tick retry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad5a71a703
ℹ️ 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".
| candidates.append({'loop': loop, 'value': value}) | ||
|
|
||
| selected = store.select_surface_cards(candidates, today) |
There was a problem hiding this comment.
Deduplicate surface candidates after resolving merged loop IDs
When two model proposals merge into one stored loop, both surface entries are remapped to the same canonical ID but are still appended independently here. Reproducing this with a task-origin proposal and a matching extraction produces two cards with ID task-t1, wasting Review slots. Moreover, answer_card() always finds the first matching ID, so after answering the first card the duplicate remains pending but cannot be answered. Deduplicate candidates by canonical loop ID before ranking and rendering.
Useful? React with 👍 / 👎.
| except Exception as error: | ||
| logger.error( | ||
| 'open_loop_card_task_completion_failed loop_id=%s task_id=%s error=%s', |
There was a problem hiding this comment.
Record task-completion degradation through the fallback helper
If task completion or reminder reconciliation raises, this handler logs the error and allows answer_card() to persist a successful Done answer and resolved loop despite the incomplete task-side operation. This is a new fail-open path, but it never calls the shared fallback helper; the mark_action_item_completed() false-return branch likewise only logs. backend/AGENTS.md explicitly requires new fallbacks to call utils.observability.fallback.record_fallback. Record a degraded outcome for both failure paths so these partial successes appear in shared fallback telemetry.
AGENTS.md reference: backend/AGENTS.md:L318-L318
Useful? React with 👍 / 👎.
| global _open_loop_pass_queue | ||
| loop = asyncio.get_running_loop() | ||
| if _open_loop_pass_queue is None or _open_loop_pass_queue.loop is not loop: | ||
| _open_loop_pass_queue = _OpenLoopPassQueue(loop=loop, slots=asyncio.Semaphore(OPEN_LOOPS_PASS_CONCURRENCY)) |
There was a problem hiding this comment.
Create the pass semaphore through the shared semaphore registry
When the pass queue is initialized, it constructs a raw asyncio.Semaphore in the notifications module. Although this code checks the current event loop, backend/AGENTS.md explicitly says not to create raw semaphores outside http_client.py, which owns the loop-keyed semaphore registry. Add a dedicated accessor there and use it here rather than introducing a second semaphore lifecycle implementation.
AGENTS.md reference: backend/AGENTS.md:L312-L312
Useful? React with 👍 / 👎.
| carried = sorted(open_loops, key=store.carried_relevance)[: store.CARRIED_LOOPS_PROMPT_CAP] | ||
| carried_views = [store.carried_view(loop, today) for loop in carried] | ||
| tasks = open_tasks_view(uid, today) |
There was a problem hiding this comment.
Reconcile task-origin loops with completed task state
If the owner completes a task through the existing Tasks interface after a previous pass created its strongly linked loop, the next pass still carries that loop as open. open_tasks_view() fetches only incomplete tasks, so the completed task disappears from the input without supplying its completion state, while carried_view() retains the stale follow-up. Repository-wide inspection of the open-loop callers found no task-completion hook that closes these loops, and the surface filter still accepts them; the model can therefore legitimately propose another stale reminder for work already marked Done. Fetch strongly linked tasks by ID and reconcile their completion state before constructing carried loops, rather than inferring completion from absence in the capped open-task list.
Useful? React with 👍 / 👎.
…b-0.5s real-clock budgets Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2d4abf1c32
ℹ️ 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".
| for field in ('task_link', 'linked_task_title', 'linked_task_created_at'): | ||
| if incoming.get(field): | ||
| merged[field] = incoming[field] |
There was a problem hiding this comment.
Preserve strong task links when merging heuristic duplicates
When a task-origin proposal is merged with a carried heuristic-linked loop for the same task, this assignment can overwrite the survivor's task_link='model' with 'heuristic'. Reproducing merge_duplicates([strong, heuristic]) yields a heuristic link, while reversing the inputs preserves the model link. Consequently, an explicitly task-origin card becomes ask-only and answering Done no longer completes its task in service._apply_answer_to_loop(). Preserve the strongest link and its associated render fields rather than making task-completion behavior depend on proposal order.
Useful? React with 👍 / 👎.
| def snoozed(loop: Mapping[str, Any], today: date) -> bool: | ||
| until = _as_date(loop.get('snoozed_until')) | ||
| return until is not None and until >= today |
There was a problem hiding this comment.
End snoozes on their target delivery date
With the completed-day recap scheduler, answering Remind on Tuesday sets snoozed_until to Thursday, but the pass evaluates this predicate against the completed conversation day rather than the delivery day. Friday morning's pass still processes Thursday and is blocked by the inclusive comparison; the first eligible delivery is Saturday, turning the advertised two-day snooze into four days. Evaluate snooze eligibility against the current local delivery date and allow resurfacing on the stored target date.
Useful? React with 👍 / 👎.
| carried = sorted(open_loops, key=store.carried_relevance)[: store.CARRIED_LOOPS_PROMPT_CAP] | ||
| carried_views = [store.carried_view(loop, today) for loop in carried] |
There was a problem hiding this comment.
Retract derived loops when their source conversation is deleted
If an owner deletes a conversation after its loops have been extracted, subsequent passes still carry that conversation's wording and evidence into the model here. The existing source-deletion path in utils/conversations/merge_conversations.py::_delete_conversation_and_related_data() retracts memories and action items, and database/conversations.py::delete_conversation() purges proactivity items, but repository-wide searches for the new collection names found no corresponding cleanup for open_loops or open_loop_cards. Neither this carried-loop projection nor service.list_pending_cards() revalidates the source, so deleted content remains stored and can generate further cards. Integrate these derived records into source retraction, removing loops supported exclusively by the deleted conversation and their persisted cards.
Useful? React with 👍 / 👎.
…-intelligence source manifest answer_card completes an existing task on the owner's explicit answer, a direct owner command alongside the mobile manual source. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r you (Open loops PR 3) (#23683) ## 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    Fictional card text only. Manifest: `.agent-artifacts/ui-evidence/open-loops-review/evidence.json`. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Open loops, PR 2: daily pass + loop store with expiry + task-aware dedupe + ranking (backend, no UI, not yet served)
Second PR of the Open loops rebuild (after #23622). Open loops surface in
Review ("Questions for you") as follow-ups the owner may later be asked
about ("did it happen?"). This PR adds the per-user loop store, the
once-per-local-day pass that runs as a fail-open sibling of the daily recap
job, task-aware dedupe that links instead of dropping, expiry so the store
stays bounded, and deterministic ranking into ≤3 slots/day. Cards are stored
server-side per day but not served — PR 3 adds the Review source, the
router and the mobile UI on top of
utils/open_loops/service.py.Product decisions this encodes (David 2026-10-26, KB D31): 47% of wanted
items were unreadable without context → cards stay self-contained via PR 1's
card.py; a stand-in dedupe wrongly dropped 7/12 wanted cards whenever amatching task existed → a matching task is linked, never dropped; one
slot/day was too stingy → 2–3/day; loops piled up without expiry → expiry
windows + a hard open cap.
Review fixes in the latest push (4 blockers)
recap window. The recap worker finishes summary → push → backfill →
webhook and only returns a pass request; the coordinator then runs the
pass on the new dedicated
open_loops_executorunderOPEN_LOOPS_PASS_BUDGET_SECONDS(45 s,asyncio.wait_for, abandonedcleanly past it — exactly like a timed-out recap worker, but it never
touches a recap recipient metric,
timed_out, the abandoned-user limit oruser ordering; passes are dropped loudly once the job budget is spent and
the next tick re-requests the day). Regression tests: a sleeping pass
past its deadline does not mark the recap timed_out, does not delay the
webhook (ordering pinned), and the dispatch never raises.
(
users/{uid}/open_loop_claims/{date}, Firestore create-if-absent) istaken before the model call, so retried ticks, abandoned threads and
the recap's locked-retry path (
declined=None) all see the claim andskip. A failed day releases for exactly one bounded retry (
attempts ≤ 2,10-minute stale-claim takeover). Regression test: two concurrent runs →
exactly one model call (
test_concurrent_runs_make_exactly_one_model_call).answer_card(done)completes a task onlythrough a strong link: the model returned an explicit
from_task_idfor that loop (
task_link='model') and the answered card's text namesthe task — strong links render the task's own description in the card
("Did you send Tyler the bullets for the Stably write-up? (your task from
Thu)"). Heuristic-only links stay ask-only: Done resolves the loop, never
the task. Completion routes through the same path the app's toggle
endpoint uses (
mark_action_item_completedstampscompleted_at, thensync_action_item_reminderreconciles the client reminder, BUG: Receiving Notifications for Already-Completed Tasks #5085) — notraw
action_items_db.update_action_item.find_task_matchnow requiresJaccard ≥ 0.6 and containment ≥ 0.8 and the same
whowhen bothsides name one (documented Jev seam). Regression test:
"Tyler: send deck" vs "send deck to investors" neither links nor
auto-completes.
(resolved/dropped/expired) are excluded from update matching and from
merge_duplicates; a re-mentioned dropped item never revives the droppedloop and may open a NEW loop only after a 14-day cool-off
(
store.remention_blocked).merge_duplicates/loops_matchnow requirethe same normalized
whoand Jaccard ≥ 0.7 and containment ≥ 0.8.Regression tests: "Tyler send deck" vs "Tyler send invoice" don't merge;
a dropped loop never returns to opened.
Also in this push: defensive caps on the pass's model output
(
MODEL_LOOPS_CAP, ≤3 surface entries, clipped loop text), the false"shared bytes for prompt-cache reuse" comment corrected (same renderer and
char budget — the same view of the day — but no byte-shared prompt prefix,
since the recap's system prompt and eligibility filter differ),
list_pending_cardsdefaults to the recap's completed local day (therecap's noon-split rule), snooze/history use the user's timezone, and the
pass skips the model call when the user has no conversations that day and no
loop is
due_soon(no daily spend just to re-stale carried loops).A. Loop store (
database/open_loops.py+utils/open_loops/store.py)users/{uid}/open_loops/{loop_id}— one doc per loop{id, kind (owed_to_user|own_commitment|issue_or_blocker), who, what, by_when?, evidence, source_conversation_id(s) (+source_title/source_started_at for the card), linked_task_id?, task_link? (model|heuristic), status (opened| progressing|stale|due_soon|resolved|dropped|expired), history[{date,status, evidence}], times_surfaced, last_surfaced_at, snoozed_until?, created_at, last_activity_at}. The whole loop dict is one derived JSON blob —zlib-compressed and AES-encrypted for every user (conversation quotes
ride the enhanced-protection shape unconditionally), plus a plain
status/last_activity_attriage mirror.wording merges (same normalized
whorequired; task-linked survivor wins;terminal loops never merge). The collection is streamed whole and filtered
in code — no queries, no new Firestore indexes (registered as a reasoned
skip + runtime caller witness in the Firestore guard registry).
own_commitment10,owed_to_user14) →expired;droppedvia the Drop answer;resolvedcloses. Terminal docs are deleted after 14 more days (the same window as
the re-mention cool-off), and open loops are hard-capped at 60 (least
recently active expire first) — the offline failure mode (0→45 loops in 5
days, unbounded growth) can't recur. A terminal loop is never revived.
B. Daily pass (
utils/open_loops/daily.py)open_loop_daily(gpt-6-luna,
reasoning_effort: lowpinned in the gateway route overrides,usage-tracked) — wired exactly like PR 1's
open_loop_card: model_configtwo-tier map, gateway inventory row + call site, non-dream route snapshot,
QoS tier expectation.
(
utils/other/notifications._run_open_loops_daily_pass) executes on thededicated
open_loops_executoronly after that user's recap work (push,backfill, webhook) fully finished, under its own 45 s budget. Fail-open
by construction: the catch owns everything including the pass module's
own import — a failing pass logs (+ a fallback counter) and the recap
never notices; a regression test pins the import-failure case specifically.
deserializer, the recap's own char budget over whole conversations, same
renderer, leading the user message (no byte-shared cache prefix — the
system prompts differ); the JSON state follows (the day's
open_loop_extractions, ≤20 most-relevant open loops, ≤40 open tasks withcreated_at/due_at/age, the day's recap headline/overview). The system
prompt adapts the offline-validated merged daily prompt (generic owner;
surface entries keep
why_now/value— the deterministic writer ownsquestion copy).
sync_merged_into), locked, discarded, and content-excludedconversations never contribute.
loops with signal; resolve on evidence; task-aware dedupe — a loop
matching an open task is linked (
linked_task_id,task_link='heuristic',ask-only) and the card asks about it, Jaccard ≥ 0.6 and containment
≥ 0.8 with who-compatibility, documented seam for a Jev matcher later
(
store.find_task_match); loop-to-loop duplicates merge under thestricter same-who thresholds. Model output is defensively capped.
due_soon;snoozed loops stay quiet. Ranking: ≤3 cards/day, value ≥ 3, due_soon
first, owner's work first, capped deterministically; each card renders via
PR 1's
build_review_card(self-contained who/what + source conversation +weekday + why-now; a strong task link renders the task description with
the "(your task from Thu)" clause).
users/{uid}/open_loop_cards/{date}(same protection;state pending|done|remind|dropped). The doc's existence — even empty — is
the once-per-day marker; the pre-model-call claim
(
users/{uid}/open_loop_claims/{date}, create-if-absent, ≤2 attempts)makes retried ticks, abandoned workers and the locked-retry path pay at
most once.
OPEN_LOOPS_ENABLEDoff → the pass isskipped, nothing written (flag registry entry updated); a user with no
extractions that day and no open loops — or with no conversations and
nothing
due_soon— skips the model call entirely; a recap that waslock-contended or budget-declined spends nothing on the pass.
day (10 conversations, 20 carried loops, 40 tasks), ~300–600 output tokens;
one call per user per local day.
C. PR 3 service functions (
utils/open_loops/service.py, not yet routed)list_pending_cards(uid, limit=3)— the recap's most recently completedlocal day's unanswered cards (noon-split default;
date_stroverrides) inranked order.
answer_card(uid, card_id, done|remind|drop)— done → loop resolved, plustask completion only through a strong link (model-asserted
from_task_idand the card text naming the task), executed through theapp's own path (
mark_action_item_completed+sync_action_item_reminderBUG: Receiving Notifications for Already-Completed Tasks #5085, best-effort: a task-store failure never rolls back the answer);
remind → snooze +2 days in the user's timezone; drop → dropped, and the
card is kept on the loop as a negative example for future ranking.
Tests
New:
test_open_loops_store.py(identity, expiry windows, terminalretention, cap, cooldown/snooze, ranking, encrypted-at-rest roundtrip,
matcher AND-thresholds + who compatibility, terminal-never-merges, re-mention
cool-off, card-text completion gate, day-claim atomicity + bounded retries),
test_open_loops_daily.py(kill switch, once-per-day marker, no-signal andno-conversations skips, prompt shape + carried cap, ingestion: carried update
/ stable-key identity / task identity / duplicate merge / undecidable
statuses, link-never-drop with link strength, value floor, cooldown,
resolved-never-surfaces, concurrent-runs → one model call, failure releases
the claim for one bounded retry, runaway-output caps, dropped-loop
never-revived + post-cooldown new loop, donor/locked/discarded exclusion,
fence-tolerant parse),
test_open_loops_service.py(pending listing withrecap-day default, done/remind/drop transitions incl. strong-link-only task
completion through the app path, timezone-correct snooze/history, reject
paths, failure containment),
test_open_loops_recap_integration.py(recap returns the pass request only after webhook, dispatcher runs it,
slow-past-deadline abandonment with recap counters untouched, webhook never
delayed, failing/unimportable pass contained, locked and budget-declined days
skip, bulk dispatch + job-budget drop),
test_open_loops_replay.py(70-daysynthetic replay: store bounded well under the cap, resolved loop never
resurfaces however often proposed, exactly one model call per day). Updated:
Firestore guard registry (skip + witness + profile), QoS tiers, dream route
snapshot, executor metrics inventory, two recap harness executor stubs.
Verification:
BACKEND_UNIT_TEST_FILE_LIST=<32 files> bash backend/test.sh(all 9 open-loops suites, all 18 daily-summary/recap suites, wave2,
lock-bypass, executors, gateway coverage guardrails, dream routing) — every
listed file ran and passed, 514 tests green, exit 0. The same 32 files in
one bare
python -m pytestprocess: 497 passed / 17 failed — those 17 are apre-existing
sys.modulescross-file contamination that reproducesidentically on the base commit (each file passes alone and via
test.sh,which is why the runner isolates per file); per-file direct runs are green.
Docs
backend/utils/open_loops/README.md— PR 2 modules, loop-store/cards/claims storage contract, test map.
backend/utils/llm/ARCHITECTURE.md— daily pass paragraph in the notessection.
config/feature-flags.yaml+ regeneratedbackend/docs/feature-flag-registry.md—
OPEN_LOOPS_ENABLEDnotes now cover the daily-pass skip.Known gaps (later PRs)
adds the Review source and mobile UI over
service.py.thresholds + who compatibility); the Jev-based matcher replaces
store.find_task_matchonly.design of "sibling step in the daily recap job".
Failure-Class: none
UI-Evidence: none — backend only
Product invariants named
loop store and cards are new derived, server-only per-user collections; no
memory store is written, no intake route added, consolidation/promotion
untouched.
this PR creates no tasks and no Candidates. Cards are stored server-side
only;
answer_cardcompletes an existing task through the app's owncompletion path when the owner explicitly answers "done" to a card that
names the task — it never creates one. The Review surfacing decision
re-runs when PR 3 adds the surface.
No changed file crosses the 1500-line ratchet (largest growth:
backend/utils/other/notifications.py1240 → 1447), so noLine-Count-Exception declarations are required.
🤖 Generated with Claude Code
Co-Authored-By: Claude Opus 5.5 [email protected]