Skip to content

feat(notes): open-loop daily pass, loop store with expiry, task-aware dedupe, ranking (Open loops PR 2) - #23639

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/open-loops-daily
Oct 25, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/open-loops-daily

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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 a
matching 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)

  1. Recap time budget. The pass no longer runs inside the user's 90 s
    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_executor under
    OPEN_LOOPS_PASS_BUDGET_SECONDS (45 s, asyncio.wait_for, abandoned
    cleanly past it — exactly like a timed-out recap worker, but it never
    touches a recap recipient metric, timed_out, the abandoned-user limit or
    user 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.
  2. Double spend. An atomic per-user-per-local-day claim
    (users/{uid}/open_loop_claims/{date}, Firestore create-if-absent) is
    taken before the model call, so retried ticks, abandoned threads and
    the recap's locked-retry path (declined=None) all see the claim and
    skip. 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).
  3. Wrong-task completion. answer_card(done) completes a task only
    through a strong link: the model returned an explicit from_task_id
    for that loop (task_link='model') and the answered card's text names
    the 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_completed stamps completed_at, then
    sync_action_item_reminder reconciles the client reminder, BUG: Receiving Notifications for Already-Completed Tasks #5085) — not
    raw action_items_db.update_action_item. find_task_match now requires
    Jaccard ≥ 0.6 and containment ≥ 0.8 and the same who when both
    sides name one (documented Jev seam). Regression test:
    "Tyler: send deck" vs "send deck to investors" neither links nor
    auto-completes.
  4. Dropped/terminal loops resurfacing. Terminal loops
    (resolved/dropped/expired) are excluded from update matching and from
    merge_duplicates; a re-mentioned dropped item never revives the dropped
    loop and may open a NEW loop only after a 14-day cool-off
    (store.remention_blocked). merge_duplicates/loops_match now require
    the same normalized who and 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_cards defaults to the recap's completed local day (the
recap'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_at triage mirror.
  • Upsert identity is the stable key (normalized who+what+kind); near-duplicate
    wording merges (same normalized who required; 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).
  • Expiry: no signal for 7 days (default; own_commitment 10,
    owed_to_user 14) → expired; dropped via the Drop answer; resolved
    closes. 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)

  • One structured call per user per local day, feature key open_loop_daily
    (gpt-6-luna, reasoning_effort: low pinned in the gateway route overrides,
    usage-tracked) — wired exactly like PR 1's open_loop_card: model_config
    two-tier map, gateway inventory row + call site, non-dream route snapshot,
    QoS tier expectation.
  • Runs off the recap critical path: the recap sibling step
    (utils/other/notifications._run_open_loops_daily_pass) executes on the
    dedicated open_loops_executor only 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.
  • Reuses the recap's render for a consistent view of the day: same
    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 with
    created_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 owns
    question copy).
  • Merge donors (sync_merged_into), locked, discarded, and content-excluded
    conversations never contribute.
  • Model proposes, deterministic post-processing decides: statuses only for
    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 the
    stricter same-who thresholds. Model output is defensively capped.
  • Cooldown: no re-ask within 2 days unless the loop became 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).
  • Cards persist in 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.
  • Kill switch + cost guard: OPEN_LOOPS_ENABLED off → the pass is
    skipped, 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 was
    lock-contended or budget-declined spends nothing on the pass.
  • Per-user-day cost estimate: ~2k input tokens on a quiet day, ~6.5k on a busy
    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 completed
    local day's unanswered cards (noon-split default; date_str overrides) in
    ranked order.
  • answer_card(uid, card_id, done|remind|drop) — done → loop resolved, plus
    task completion only through a strong link (model-asserted
    from_task_id and the card text naming the task), executed through the
    app's own path (mark_action_item_completed + sync_action_item_reminder
    BUG: 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, terminal
retention, 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 and
no-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 with
recap-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-day
synthetic 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 pytest process: 497 passed / 17 failed — those 17 are a
pre-existing sys.modules cross-file contamination that reproduces
identically 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 notes
    section.
  • config/feature-flags.yaml + regenerated backend/docs/feature-flag-registry.md
    — OPEN_LOOPS_ENABLED notes now cover the daily-pass skip.

Known gaps (later PRs)

  • Nothing serves the cards yet: no router endpoint, no client surface. PR 3
    adds the Review source and mobile UI over service.py.
  • The task matcher is the documented normalized-token heuristic (both
    thresholds + who compatibility); the Jev-based matcher replaces
    store.find_task_match only.
  • The pass rides the recap cohort (daily-summary-enabled recipients), by
    design of "sibling step in the daily recap job".

Failure-Class: none
UI-Evidence: none — backend only

Product invariants named

  • INV-MEM-4 (canonical promotion is the sole Long-term authority): the
    loop store and cards are new derived, server-only per-user collections; no
    memory store is written, no intake route added, consolidation/promotion
    untouched.
  • INV-TASK-2 (capture proposes only where a Suggested surface exists):
    this PR creates no tasks and no Candidates. Cards are stored server-side
    only; answer_card completes an existing task through the app's own
    completion 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.py 1240 → 1447), so no
Line-Count-Exception declarations are required.

🤖 Generated with Claude Code

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

… 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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T23:21:20.408295Z 2d4abf1 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: 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]+')

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 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 👍 / 👎.

Comment on lines +275 to +278
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)

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 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 👍 / 👎.

Comment on lines +275 to +277
if loop.get('status') != status:
loop = store.append_history(loop, today, status, str(entry.get('evidence') or ''))
loop['status'] = status

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 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 👍 / 👎.

Comment thread backend/utils/open_loops/service.py Outdated
Comment on lines +33 to +34
def _local_date_str(tz: Optional[str], now: Optional[datetime], date_str: Optional[str]) -> str:
return date_str or local_today(tz, now).isoformat()

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 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 👍 / 👎.

Comment on lines +421 to +425
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 []

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 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 👍 / 👎.

Comment on lines +94 to +96
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)

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 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]>

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

Comment thread backend/utils/other/notifications.py Outdated
Comment on lines +1259 to +1260
if pass_requests and (deadline is None or monotonic() < deadline):
await _dispatch_open_loops_passes(pass_requests)

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 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 👍 / 👎.

Comment on lines +205 to +208
if attempts >= MAX_PASS_ATTEMPTS:
return False
ref.update({'state': CLAIM_STATE_CLAIMED, 'attempts': attempts + 1, 'updated_at': moment.isoformat()})
return True

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 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 👍 / 👎.

Comment on lines +252 to +254
elif task_id:
target = by_id.get(f'task-{task_id}')
else:

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

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 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 👍 / 👎.

Comment thread backend/utils/other/notifications.py Outdated
Comment on lines +1010 to +1011
except Exception as error:
logger.error('open_loops_daily_pass_dispatch_failed uid=%s date=%s error=%s', uid, date_str, error)

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 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 👍 / 👎.

Comment on lines +406 to +409
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)

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 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 👍 / 👎.

Comment on lines +172 to +176
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'))

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 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)

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 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]>

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

Comment on lines +535 to +537
candidates.append({'loop': loop, 'value': value})

selected = store.select_surface_cards(candidates, today)

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 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 👍 / 👎.

Comment on lines +153 to +155
except Exception as error:
logger.error(
'open_loop_card_task_completion_failed loop_id=%s task_id=%s error=%s',

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 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))

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 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 👍 / 👎.

Comment on lines +467 to +469
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)

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 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]>

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

Comment on lines +279 to +281
for field in ('task_link', 'linked_task_title', 'linked_task_created_at'):
if incoming.get(field):
merged[field] = incoming[field]

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 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 👍 / 👎.

Comment on lines +420 to +422
def snoozed(loop: Mapping[str, Any], today: date) -> bool:
until = _as_date(loop.get('snoozed_until'))
return until is not None and until >= today

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 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 👍 / 👎.

Comment on lines +467 to +468
carried = sorted(open_loops, key=store.carried_relevance)[: store.CARRIED_LOOPS_PROMPT_CAP]
carried_views = [store.carried_view(loop, today) for loop in carried]

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 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]>
@Git-on-my-level
Git-on-my-level merged commit fca00e4 into main Oct 25, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/open-loops-daily branch October 25, 2026 23:49
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
…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

![Review with open-loop cards,
light](https://raw.githubusercontent.com/BasedHardware/omi/19380c5583859f92b4735ce4beaec30222f49122/.agent-artifacts/ui-evidence/open-loops-review/001-mobile-ios-review-open-loops-light.png)

![Review with open-loop cards,
dark](https://raw.githubusercontent.com/BasedHardware/omi/19380c5583859f92b4735ce4beaec30222f49122/.agent-artifacts/ui-evidence/open-loops-review/002-mobile-ios-review-open-loops-dark.png)

![Review after Remind me
later](https://raw.githubusercontent.com/BasedHardware/omi/19380c5583859f92b4735ce4beaec30222f49122/.agent-artifacts/ui-evidence/open-loops-review/003-mobile-ios-review-open-loops-reminded.png)

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)
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