Repository navigation
fix(backend): ground proactive insights and memory extraction in the current date - #8501
Conversation
There was a problem hiding this comment.
2 issues found across 7 files
Confidence score: 3/5
- In
backend/utils/llm/memories.py, grounding relative time expressions against processing time instead of source-content time can misresolve phrases like “tomorrow” for delayed/retried/backfilled items, producing incorrect stored memories and downstream behavior—anchor extraction to the content/event timestamp (or pass an explicit reference datetime) before merging. - In
backend/utils/llm/temporal.py, the module-level dependency ondatabase.notificationsintroduces DB-layer side effects into a low-level temporal helper, which can trigger unwanted Firestore client initialization and make non-DB usage/tests brittle—decouple this import (e.g., move to call sites or inject the formatter dependency) before merging.
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
|
Both findings were valid and are now fixed. P2, temporal.py coupling: moved the P2, memory extraction date: |
kodjima33
left a comment
There was a problem hiding this comment.
Backend: ground proactive insights/memory extraction in current date — broad prompt change, approve only (>300 lines, leave merge for maintainer).
|
Thanks @ZachL111 — this is a clean, well-scoped fix for a real bug. The root-cause analysis is spot on: the proactive insight and memory-extraction prompts asked the model to reason about dates and deadlines without ever anchoring "today," so it fell back to its training-cutoff year and produced hallucinated clock/calendar warnings. Grounding them in the current date is the right fix and matches the pattern already used in the chat pipeline. A few things that stand out as solid:
The 12 new tests (helper behavior, per-prompt grounding, Leaving the merge call to a human maintainer given the breadth of the prompt change across several user-facing generators, but this looks good to land. |
kodjima33
left a comment
There was a problem hiding this comment.
Backend bug fix with regression test; CI green.
…unding # Conflicts: # backend/test.sh
|
Merged latest main to clear a merge conflict. Only |
|
Maintainer review pass — endorsing this for merge, leaving the merge call to a human maintainer. This is a clean, well-scoped fix for a real bug. The root-cause analysis is correct: the proactive insight and memory-extraction prompts reasoned about dates/deadlines without anchoring "today," so the model fell back to its training-cutoff year and emitted hallucinated clock/calendar warnings. Grounding them in the current date matches the existing pattern in the chat pipeline. What looks solid:
One optional nit (non-blocking): the Thanks @ZachL111 — good work. |
…unding # Conflicts: # backend/test.sh
# Conflicts: # backend/test.sh
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks @ZachL111 — this is a genuinely nice diagnosis and a coherent, well-scoped fix. Grounding the proactive-insight and memory-extraction prompts in the current date (and in the content's capture date) is the right call, and the lazy-DB temporal helper + content-date threading are clean. I'm requesting changes only because the current push is failing CI in a way the diff introduces.
CI status (commit c803e13)
- ❌ Backend unit suite — collection errors (not assertion failures)
- ❌ Lint & Format Check — async-blocker audit gate
- ✅ Hermetic Backend E2E
- ✅ cubic (merge commit, no review)
Blocking issue — Backend unit suite (regression introduced here)
Two pre-existing unit tests can no longer collect:
utils/app_integrations.py:53: in <module>
from utils.llm.temporal import current_date_for_uid
E ModuleNotFoundError: No module named 'utils.llm.temporal'; 'utils.llm' is not a package
ERROR tests/unit/test_async_app_integrations.py
ERROR tests/unit/test_async_realtime_integrations_offload.py
Both test modules stub utils.llm as a fake package and enumerate exactly which submodules exist (utils.llm.clients, utils.llm.proactive_notification, utils.llm.usage_tracker). The new from utils.llm.temporal import current_date_for_uid import isn't in those stub lists, so app_integrations.py fails to import and every test in those files errors out.
Fix: add "utils.llm.temporal" to the _RESTORED_MODULES/stub list in both:
backend/tests/unit/test_async_app_integrations.pybackend/tests/unit/test_async_realtime_integrations_offload.py
e.g. install a lightweight stub sys.modules["utils.llm.temporal"] with current_date_for_uid = MagicMock(return_value="2026-06-29") (and current_date_in_tz, date_in_tz if process_conversation is imported transitively). The new test_insight_date_grounding.py already shows the stubbing pattern you can mirror.
Lint & Format Check — not a formatting issue
Heads-up so the re-run isn't confusing: black --check passed ("7 files would be left unchanged"). The failure is the repo's scan_async_blockers.py audit, which is tripping on pre-existing async-helper-with-blocking findings in app_integrations.py (lines 165 trigger_external_integrations, 179 _single, 685 _async_trigger_realtime_integrations). The audit re-scans any file whose imports changed, and this PR added an import to app_integrations.py.
Your code doesn't add any blocking calls, so this isn't something to fix in-body. The cleanest path to green is to land this after those pre-existing async findings are addressed on main (out of scope here), or for a maintainer to confirm the lint is a known-fail baseline. Worth flagging to maintainers either way.
What looks good
- Root-cause writeup in the PR body is accurate and matches the code.
utils/llm/temporal.pykeeps the pure tz helpers import-free of the DB layer and only touches Firestore lazily — good for testability and import-time cost.- Grounding memory extraction in the capture date rather than processing time is the more correct behavior and handles delayed/backfilled content well.
- The added
test_insight_date_grounding.pycovers the prompt-injection surface and the content-date path, which is the right place for tests.
Merge note
Needs a maintainer's eyes before merge regardless of CI (this touches user-facing insight/memory generation), and CI must go green first. Noting needs-maintainer-review + needs-tests. Once the two stub files are patched and CI is green, happy to re-review.
|
Independently confirmed the CI root cause already noted on this PR — it is the only blocker.
The Lint & Format failure is the pre-existing async-blocker audit re-scanning Once the two stub lists are patched and the unit suite is green, this should be ready for a maintainer's merge call. The fix itself — lazy DB import in |
…-blocker gate) The date-grounding change imported current_date_for_uid into app_integrations.py to pass a user-tz current_date into the proactive-notification calls. That import makes the file import-changed, which pulls its three pre-existing blocking async helpers (trigger_external_integrations, _async_trigger_realtime_integrations, _single) into the async-blocker gate fail scope and turned CI red. It also broke collection of test_async_app_integrations.py and test_async_realtime_integrations_offload.py, which stub utils.llm and enumerate its submodules. proactive_notification.py already grounds every prompt via `current_date or current_date_in_tz(None)`, so this reverts app_integrations.py to main and lets the proactive path self-ground through that fallback. Memory extraction keeps the uid-aware date via memories.py. app_integrations.py and the two async tests are now identical to main again.
|
Fixed in 060f4a5. Both the collection errors and the async-blocker gate traced to one line: app_integrations.py importing current_date_for_uid from utils.llm.temporal. Adding that import made app_integrations.py import-changed, which pulls its three pre-existing blocking async helpers (trigger_external_integrations, _async_trigger_realtime_integrations, _single) into the async-blocker fail scope. So the stub-list fix alone would have cleared the two collection errors but left Lint and Format Check red. Instead I reverted app_integrations.py to main. proactive_notification.py already grounds every prompt with Verified locally:
One tradeoff to flag: the proactive path now uses the in-module fallback (UTC date) rather than the user timezone. The core fix (grounding the year so correctly dated future-year content stops reading as wrong) holds either way, and memory extraction still uses the user timezone. If you would prefer the proactive path to also use the user local date, I can thread uid through the three proactive_notification functions instead, which keeps app_integrations.py import-clean. Happy to do that if you want the extra precision. |
|
Maintainer follow-up after The blocker I raised is resolved. Current GitHub checks are green ( The fix is still coherent and low-risk from an implementation standpoint:
One maintainer-facing tradeoff to be aware of before merge: the proactive-notification path now relies on Given the checks are green and the previous test blocker is gone, I removed |
kodjima33
left a comment
There was a problem hiding this comment.
Backend fix; approve-only (diff >300 lines, beyond auto-merge scope gate).
…unding # Conflicts: # backend/utils/llm/memories.py
…ration extract path BasedHardware#8501 grounds memory extraction in the conversation's content date, so _extract_memories_inner now calls extract_memories_from_text with content_date for external integrations. test_upstream_boundary's routing test predates that change and asserted the old call signature; update it to expect content_date (value via ANY, since this test verifies text-vs-segment routing, not the date value).
|
Maintainer follow-up on the latest head The final update is test-only and correctly adjusts the upstream-boundary assertion for the new
This remains a positive implementation signal: memory extraction is grounded in the conversation capture date, the temporal helpers stay small/dependency-light at import time for the pure paths, and the prompt changes are covered by focused tests. I’m still not formally approving because Thanks @ZachL111 — this looks ready for a human maintainer’s merge decision. |
kodjima33
left a comment
There was a problem hiding this comment.
backend: ground insights/extraction in current date — >300 lines beyond scope gate, approve only
# Conflicts: # backend/utils/conversations/process_conversation.py # backend/utils/llm/proactive_notification.py
|
Maintainer follow-up after the latest main merge ( The implementation is still sound — no code concerns beyond what was already reviewed. One new blocker surfaced from the merge: Hygiene is failing because The fix is to add the invariant under a Once Hygiene is green this still needs a human maintainer merge call given the user-facing prompt-behavior change. Thanks @ZachL111. |
|
Maintainer follow-up on head Hygiene (product-invariants) is failing because the PR touches The Everything from prior passes holds: date-grounding is the right fix, Leaving the merge call to a human maintainer once the invariant citation is added. |
|
Thanks David. The INV-MEM-1 citation is already in the PR body under 'Product invariants affected', and the Hygiene check is green on the current head (the earlier failing Hygiene run was superseded by a passing run once the citation landed; the latest Hygiene conclusion is success and the overall required checks are green). So the invariant disclosure you asked for is in place and this should be ready for the maintainer merge call. Agreed the production_like_model change only grounds the extractor in the capture date and does not alter memory-tier semantics. |
kodjima33
left a comment
There was a problem hiding this comment.
Fix(backend): ground proactive insights/memory extraction in conversation date; additive, 12 tests, 4/5
The arch-guardrails check requires a package-root ARCHITECTURE.md/README.md once a package exceeds the source-file threshold. backend/utils/llm grew to 35 files (on main, via #8501) without one, so the absolute-state check blocks every PR. Add an accurate architecture map (gateway-first routing core + per-feature groups) to unblock; the check forbids raising the baseline in lieu of a map. Failure-Class: none Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
backend/utils/llm crossed its grandfathered package-map baseline (34 -> 35) when BasedHardware#8501 added temporal.py, turning the architecture-guardrails ratchet red on main and on every open PR. The ratchet requires a package map rather than a baseline bump, so document the package boundaries here.
…ng Insight/Focus cards (#12236) * fix(desktop): ground Insight/Focus in the current date; retire the 2026 wrong-year example SCA-358: Insight and Suggestion (Focus) cards told users the system clock was 'stuck in 2026' and to double-check 2026-dated email. Two defects in the same lanes: the shipped default prompts carried a GOOD EXAMPLE teaching that 2026 dates are mistakes, and the analysis requests never stated the year — Insight sent 'h:mm a, EEEE' (time + weekday only), Suggestion sent no date at all. - InsightAssistantSettings v3 / SuggestionAssistantSettings v8: replace the 'scheduled this for 2026 — double-check the year' example with the year- agnostic 'scheduled this for yesterday — double-check the date', and add a DATE GROUNDING section (dates in the current year or later are normal; never say the clock/calendar/year is wrong). - Insight user prompt now carries the full local date, time, and IANA timezone via InsightAssistant.analysisClockLine (SCA-358 class fix; the model also writes SQL over UTC timestamps and needed the anchor). - Suggestion user prompt carries 'Today is yyyy-MM-dd (EEEE)' via SuggestionAssistant.userPrompt, now a static seam with an injectable clock. - New shared helpers on ChatPromptBuilder — currentCalendarDay (date-only, day-stable) and currentLocalDatetime (full local datetime + IANA) — beside currentTimePrompt, for every proactive lane that judges dates. All injection is in the uncached user turn; the static system prompts stay byte-stable for prefix caching (pinned by test). Tests: ProactiveDateGroundingTests — (a) wrong-year example retired from both defaults, (b) user prompts carry today's date from a controllable clock seam, (c) default system prompts contain no live timestamp. Verification: xcrun swift test --package-path Desktop --filter ProactiveDateGroundingTests — 7 tests, 0 failures. Failure-Class: FC-machine-timezone-timestamp-in-prompt * fix(windows): ground Insight in the current date; give pill/task agent turns a clock SCA-358, Windows half. The Insight prompt is Mac's verbatim port and carried the same two defects: the 'scheduled this for 2026 — double-check the year' teaching example in the cached system prompt, and a Phase-1 user prompt that stated only 'Time: 3:07 PM, Monday' — no year, no timezone. - insight/prompt.ts v3: retire the wrong-year example (same year-agnostic replacement as Mac), add the DATE GROUNDING section, and render the Phase-1 head as 'Date/Time: <full local date> at <time> (<IANA zone>)' via a new exported formatDateTime (mirrors Mac's analysisClockLine). promptStore wipes saved custom prompts on the version bump. - agentKernel: extract currentTimeBlock from desktopChatPrompt.currentTimePrompt and inject it into assembleTurnContext for every surface except main_chat (mainChat.ts already wraps that surface's text upstream — injecting here too would double it). Pill/task/workstream agents resolve 'Friday'/'due next week' against tool timestamps (create_action_item due_at) and previously had no clock anywhere. The block rides in the volatile turn section, never in the byte-stable system prompt the pi binding hash keys on. Tests: insight/prompt.test.ts (example retired, version bump wipes custom prompts, deterministic formatDateTime, Phase-1 head regex) and agentKernel/turnContext.test.ts (block present for floating_chat/task_chat, absent for main_chat, injected clock used). desktopChatPrompt.test.ts still passes unchanged against the refactored helper. Verification: pnpm vitest run src/main/assistants/insight/prompt.test.ts src/main/agentKernel/turnContext.test.ts src/main/agentKernel/desktopChatPrompt.test.ts — 27 passed; pnpm typecheck:node clean. Failure-Class: FC-machine-timezone-timestamp-in-prompt * fix(backend): anchor proactive notification prompts to the user's timezone date SCA-358 sibling: _process_mentor_proactive_notification never passed current_date to evaluate_relevance / generate_notification / validate_notification, so all three prompts fell back to current_date_in_tz(None) — UTC. For non-UTC users 'Today is <date>' was wrong by up to a day, and the #8501 never-say-the-year-is-wrong guard desynced near local midnight (and across New Year in e.g. UTC+13). Compute current_date_for_uid(uid) once per pipeline run (lazy user-tz lookup, UTC fallback on any error — temporal.py) and pass it to all three steps so gate/generate/critic share one 'today'. Same in-repo pattern as connector_synthesis.py and memories.py. Test: test_pipeline_anchors_prompts_to_user_timezone_date drives the real pipeline with a sentinel date and asserts every rendered prompt carries it (a caller that dropped the parameter would render the runner's UTC date). Verification: backend/.venv/bin/python -m pytest tests/unit/test_mentor_notifications.py — 50 passed. Failure-Class: FC-machine-timezone-timestamp-in-prompt * fix(desktop): ground task re-ranking and task chat in the current date/time SCA-358 wiring pass over the two remaining macOS lanes the swarm verified as judging 'now' with no anchor (refuter dropped goals/director/home- suggestions/profile-merge as not date-dependent or already anchored): - TaskPrioritizationService: the re-rank prompt weighs 'Time urgency (due date proximity)' against due dates rendered as UTC ISO strings, so the model anchored proximity on its training-cutoff date. The prompt (extracted to a static, clock-injectable rerankPrompt seam) now states 'Today is yyyy-MM-dd (EEEE)' and labels the dues as UTC ISO timestamps. - TaskChatRuntime.query: wrap the user prompt with ChatPromptBuilder.currentTimePrompt — the same wrap main chat applies (ChatProvider.swift:2846/:4959). The task context packet carries due_at ISO strings and the agent resolves relative dates; the block rides in the user turn, nothing downstream hashes it into a cached prefix. Tests: rerankPrompt carries today + UTC labeling (behavioral, injected clock); TaskChatRuntime source tripwire pins the wrap with the repo's omi-test-quality static-contract annotation. Verification: xcrun swift test --package-path Desktop --filter 'ProactiveDateGroundingTests|TaskChatKernelIdentityTests' — 34 tests, 0 failures. Failure-Class: FC-machine-timezone-timestamp-in-prompt * changelog: unreleased fragment for the Insight/Focus date-grounding fix Failure-Class: none * test(desktop): cover TaskChatRuntime in the task-thread e2e flow The scenario-13 send path reaches the kernel through TaskChatRuntime.query, which this PR grounds in the current time (SCA-358). Registers the file in the flow's covers so the strict e2e-coverage gate stays green. Failure-Class: none * fix(desktop): satisfy swiftlint force_unwrapping in the date-grounding tests Replace the two force-unwraps (fixed IANA zone, gregorian date math) with documented fallbacks; the exact-string assertions fail loudly if either fallback ever engaged, so the tests cannot pass vacuously. Failure-Class: none * chore: drop the local PR-body draft from the branch The PR body is passed via --pr-body-file at preflight time; it is not a repo artifact. Failure-Class: none
Summary
Proactive insight notifications and extracted memories sometimes claim that a user's correctly dated content is in the future or that their system clock is wrong, for example "Your system clock is logging as 2026, not 2024. Check your OS date/time settings." or "The schedule is for 5/21/2026. This date is two years in the future." The user's clock is correct. The generators never told the model what today is, so it fell back to its training-cutoff year and treated every real future-year date as an anomaly. This injects the current date into those prompts.
Root cause
The chat and conversation-structuring prompts already ground the model in the present (utils/llm/chat.py and conversation_processing.py inject "Current date time in {tz}" and "today is {date}"). The proactive insight and memory generators did not:
With nothing establishing "now", the model uses its own sense of the year (around its training cutoff), so a correctly recorded 2026 date reads as two years in the future.
Fix
Additive only: every new parameter is optional, and the date lives in the dynamic part of the prompt, so the static prefix used for caching is unchanged.
Testing
Product invariants
INV-MEM-1 (three product memory tiers). This PR touches backend/utils/memory_ingestion/ (a path glob for INV-MEM-1), but only to thread the grounded current date into the extraction adapter. It does not add or remove a memory tier, change the canonical memory_items collection path, or alter the default short_term + long_term access policy. The INV-MEM-1 guard (backend/tests/unit/test_inv_mem_1_guard.py) is unaffected.