Skip to content

feat(chat): hard-scope Ask to a conversation or timeframe (#4515) - #11206

Merged
undivisible merged 44 commits into
BasedHardware:mainfrom
aryanorastar:feat/4515-scoped-chat
Aug 25, 2026
Merged

undivisible merged 44 commits into
BasedHardware:mainfrom
aryanorastar:feat/4515-scoped-chat

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes #4515: chat could only hint at the open conversation; tools still searched all memory.
  • Backend: PageContext gains optional start_date/end_date; chat_scope on the agent config fail-closes get_conversations_tool / search_conversations_tool to that conversation and/or window; prompt matches.
  • Web: Today / This week chips (+ clear); existing conversation context now hard-scopes.
  • Flutter: Ask on conversation detail + Today / This week chips; POST /v2/messages sends context.

Product invariants affected

  • INV-MEM-3
  • INV-MEM-1
  • INV-MEM-4 — cited path-based, per the rule that citation follows globs rather than intent: backend/utils/memory/** matches the memory_service.py candidate-limit change. This PR does not touch canonical promotion or Long-term admission; the change separates the presentation cap from timeframe candidate over-fetching.

Honest gaps

  • Claude Agent VM path remains available only for unscoped prompts; scoped ChatPageContext requests use standard /v2/messages so the boundary is not dropped.
  • Desktop macOS PageContext not wired in this PR.
  • No custom date-range picker (Today / This week only).
  • Flutter Ask/chips UI not device-smoked in this PR.

Test plan

  • pytest tests/unit/test_chat_scope.py + test_chat_memory_adapter.py (27 passed: conversation scope, discarded hide, timeframe fail-closed, missing timestamp/status fail-closed, scoped offset, MemoryService search contract)
  • pytest tests/unit/test_conversation_tool_date_range_bound.py (chat_scope stub pass-through)
  • App-client OpenAPI + TS clients regenerated (prior commit)
  • Web chip highlight derived from currentContext dates; title preserved for conversation/task/memory
  • Flutter scope is page-local; chips/tooltip via l10n; end-of-day uses next-midnight − 1µs
  • Physical / Flutter device smoke — not run (no kit); Claude Agent VM path still unscoped; desktop macOS PageContext not wired

Failure-Class: none

Line-Count-Exception: backend/utils/retrieval/agentic.py | 1548 -> 1552 | Passes chat_scope through tool config so Ask about this conversation / Today / This week fail-closes retrieval instead of searching all memory (#4515).

Line-Count-Exception: backend/utils/memory/memory_service.py | 2891 -> 2898 | Separates the 20-result presentation cap from bounded timeframe candidate over-fetching; restores 3× default oversample when candidate_limit is omitted (#4515).

Line-Count-Exception: backend/utils/llm/chat.py | 1497 -> 1514 | Adds the HARD SCOPE prompt lines so the model's instructions match the tool-level scope enforcement, rather than leaving the scope prompt-implicit (#4515).

…are#4515)

PageContext was only a soft prompt hint; tools still searched the whole bank.
Fail-closed chat_scope clamps get/search conversation tools, strengthens the
prompt, and wires Ask-about-this + Today/This week chips on web and Flutter.

Co-authored-by: Cursor <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 18 files

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

Re-trigger cubic

Comment thread backend/models/chat.py Resolved
Comment thread app/lib/pages/chat/page.dart Resolved
Comment thread backend/utils/llm/chat.py Resolved
Comment thread app/lib/pages/chat/page.dart Resolved
Comment thread app/lib/providers/message_provider.dart Resolved
Comment thread backend/tests/unit/test_chat_scope.py Resolved
Fail-closed scoped fetch respects discarded/statuses; gate memory tools
under conversation scope; validate aware PageContext dates; page-local
Flutter scope + l10n chips; derive web chip state from context; expand
unit coverage and bump the agentic line-count ratchet.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed @03b6753a0c addressing cubic + CI:

  • P1 scoped fetch honors discarded/statuses
  • Memory tools gated under conversation scope; dates applied for timeframe scope
  • PageContext aware-date validation; MagicMock-safe prompt dates
  • Flutter page-local scope + l10n + inclusive end-of-day; web chips derived from context; titles preserved
  • Unit coverage expanded; agentic line ratchet bumped; isolation stubs fixed

Test plan updated to checked automated boxes. Physical/Flutter device smoke left honest (no kit).

@Git-on-my-level Git-on-my-level added needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Aug 7, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the thorough work here. The hard-scope direction looks useful, and I like that the backend retrieval path is trying to fail closed instead of leaving this as prompt-only context.

I need to request changes before this can move forward because the current head still has merge-blocking validation failures:

  • Backend type checking is failing in backend/models/chat.py around the new PageContext validator typing. Please clean up the pyright errors in the new date validation path.
  • Generated-file validation is failing for the app localization/API-generated outputs. Please regenerate/format those using the repo’s expected generator flow so the checked-in generated files match CI.
  • Repo hygiene/metadata is failing because backend/utils/retrieval grew a new source file without the required package-root architecture map. Please either add/update the required ARCHITECTURE.md/README.md map or keep the scope helper inside an existing mapped module.

Given this changes chat retrieval scoping across backend tools plus mobile/web UX, a human maintainer should still review the product/UX behavior after CI is green, especially the exact semantics for combining conversation scope with Today/This week and how unsupported memory tools should surface to users.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…RCHITECTURE

Fix PageContext date validator typing for pyright, dart-format
message_provider, and add backend/utils/retrieval/ARCHITECTURE.md so the
new chat_scope module passes architecture guardrails.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

aryanorastar commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks — merge-blocking items addressed in 5739f321f3:

  1. Pyright — PageContext date validator cleaned (_require_aware_iso(value: str, …); info.field_name narrowed). Local: pyright models/chat.py → 0 errors.
  2. Formatting — app/lib/providers/message_provider.dart dart-formatted (--line-length 120).
  3. Architecture map — added backend/utils/retrieval/ARCHITECTURE.md documenting chat_scope.py + package boundaries (fixes architecture-guardrails growth from 30→31 files).

Generated l10n: local flutter gen-l10n on Flutter 3.44.5 and 3.44.8 is clean against this tip (no diff). If CI’s unpinned stable still rewrites locale outputs, I’ll match that tip’s generator output in a follow-up.

Product/UX (for human pass after green CI):

  • Conversation scope + Today/This week: dates apply as an intersection with conversation scope (fail-closed); conversation id alone scopes without dates.
  • Memory tools under conversation scope are gated/refuse rather than searching all memory (same hard-scope intent as conversation tools).
  • Honest gaps unchanged: Claude Agent VM path unscoped; desktop macOS PageContext not wired; no custom date picker; Flutter UI not device-smoked.

Local: pytest tests/unit/test_chat_scope.py → 9 passed. Ready for CI re-check + product/UX glance when you have a moment.

Match app/analysis_options.yaml page_width so flutter gen-l10n on
CI's Flutter 3.44.9 stable tip is a no-op against checked-in files.

Co-authored-by: Cursor <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level pushed 904390b8d9 for the remaining CI blockers:

  1. Pyright — already cleared on prior tip (PageContext aware-date validator typing).
  2. Generated Files — regenerated/formatted app/lib/l10n/app_localizations*.dart at page_width: 120 (matches app/analysis_options.yaml) so CI flutter gen-l10n on Flutter 3.44.9 is a no-op.
  3. Hygiene / Failure-Class — PR body now declares Failure-Class: none (required because the branch has fix: commits). Retrieval ARCHITECTURE.md remains for the new chat_scope module.

Local: scripts/failure-class validate OK with the PR body; l10n format idempotent at 120.

Product/UX notes for the maintainer re-pass once CI is green:

  • Conversation scope ∩ Today/This week: both applied (single conversation, fail-closed to the date window).
  • Memory tools under conversation scope: gated/refuse (not silent all-memory search).

Honest gaps unchanged: no Flutter device smoke (no kit); Claude Agent VM path still unscoped; desktop macOS PageContext not wired.

Generated Files wants Flutter 3.44.9 gen-l10n output (expanded
pluralLogic, no trailing comma on last Locale), not dart-format
rewrites. Restore that style from the previously green tip and keep
the new chatScope keys. Format message_provider with page_width 120
after pub get for the Formatting check.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

aryanorastar commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

tip 904390b8d9 still failed Generated Files + Formatting — fixed on this push:

  1. Generated Files — dart format on app_localizations*.dart had rewritten gen-l10n output (compact plurals + trailing commas). Restored Flutter 3.44.9 gen-l10n style (matches the tip that was previously green) and kept the new chatScope* / askAboutThisConversation keys.
  2. Formatting — message_provider.dart reformatted with page_width: 120 after flutter pub get (CI Flutter 3.44.5).

Ready for CI re-check + product/UX re-pass when green.

Repo Formatting check requires black 26.5.1 at line-length 120 on the
PageContext / chat_scope surfaces.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

aryanorastar commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Generated Files is green on 69295040d2. Remaining miss was Formatting (Python black, not Dart) — reformatted:

  • backend/models/chat.py
  • backend/tests/unit/test_chat_scope.py
  • backend/utils/retrieval/tools/conversation_tools.py
  • backend/utils/retrieval/tools/memory_tools.py

Pushed. Ready for green CI + product/UX re-pass.

Repo Formatting ARB check requires json.dumps(..., indent=4).

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

aryanorastar commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

tip bfff106 left one Formatting miss: ARB (not Python) — app/lib/l10n/app_en.arb wasn’t 4-space indented.

Pushed a tip that runs jq --indent 4 on app_en.arb. Generated Files / black / Hygiene were already green. Ready for CI re-check + product/UX re-pass.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hard-scoped Ask — feature, approve only; needs a rebase (conflicts with main).

Union chatScope l10n keys with main ARBs, regenerate gen-l10n on Flutter 3.44.9,
combine backend-utils ratchet justifications, and harden date-range stub isolation.

Co-authored-by: Cursor <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level @kodjima33 conflicts with main resolved on tip a5f0861715:

  • Merged main into feat/4515-scoped-chat
  • ARBs: union of main locale keys + chatScope* / askAboutThisConversation (kept); regenerated app_localizations*.dart with Flutter 3.44.9 gen-l10n
  • backend-utils ratchet: kept AI Chat with a specific conversation or timeframe #4515 agentic justification + main’s stt/streaming entry
  • Stub isolation: test_conversation_tool_date_range_bound rebinds keyword_search_conversation_ids so sibling unit loads don’t trip reset_mock

Local: pytest tests/unit/test_chat_scope.py + test_conversation_tool_date_range_bound.py → 17 passed.

Prior merge-blocking CI items (pyright / Generated Files / Formatting / architecture map) were already addressed on the pre-rebase tip. Ready for CI re-check + product/UX re-pass; please dismiss the stale CHANGES_REQUESTED when green. kodjima size-gate APPROVE already on file.

Honest gaps unchanged: Claude Agent VM path unscoped; desktop macOS PageContext not wired; no custom date picker; Flutter UI not device-smoked (no kit).

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

10 issues found across 121 files

Confidence score: 3/5

  • backend/utils/retrieval/tools/conversation_tools.py narrows Today/This week end bounds to integer seconds, so conversations created in the final fractional second can be omitted; preserve timestamp precision in scoped retrieval.
  • backend/models/chat.py keeps scope bounds as raw strings, requiring duplicate parsing after validation and risking inconsistent boundary handling; use timezone-aware datetime fields and canonical serialization at the tool boundary.
  • The new chat-scope UI strings remain English placeholders in app/lib/l10n/app_localizations_ta.dart, app_hu.arb, app_localizations_th.dart, app_localizations_pl.dart, app_ja.arb, app_localizations_kn.dart, and app_te.arb (and the added locale entries broadly); provide real translations so users do not see English chips and tooltips.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


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

<violation number="1" location="backend/utils/retrieval/tools/conversation_tools.py:66">
P2: Today/This week conversation scopes drop conversations created during the final fractional second because these integer conversions narrow the end bound; preserve timestamp precision so scoped fetch matches list date filtering.</violation>
</file>

<file name="app/lib/l10n/app_localizations_th.dart">

<violation number="1" location="app/lib/l10n/app_localizations_th.dart:9789">
P2: These new strings are untranslated English in the Thai locale, so Thai users will see 'Today', 'This week', 'About: …', and 'Ask about this' in English on the new chat-scope chips and tooltip while the rest of the app is Thai. Translate the four values in app_th.arb (the dart file is generated from it) — e.g. 'วันนี้', 'สัปดาห์นี้', 'ถามเกี่ยวกับ: $title', 'ถามเกี่ยวกับเรื่องนี้' — and regenerate with flutter gen-l10n.</violation>
</file>

<file name="app/lib/l10n/app_localizations_ta.dart">

<violation number="1" location="app/lib/l10n/app_localizations_ta.dart:9914">
P2: The four new chat-scope strings are left in English inside the Tamil localization: 'Today', 'This week', 'About: {title}', 'Ask about this'. Tamil users of the new Ask/timeframe chips will see English UI. Translate them in app_ta.arb (and the other non-English ARBs, which all mirror the same English values) and regenerate.</violation>
</file>

<file name="app/lib/l10n/app_localizations_en.dart">

<violation number="1" location="app/lib/l10n/app_localizations_en.dart:9837">
P2: The three new chat-scope keys plus `askAboutThisConversation` were added to all 49 locale ARBs as English placeholders ('Today', 'This week', 'About: {title}', 'Ask about this') instead of real translations — e.g. app_zh.arb and app_ja.arb carry English values while every surrounding key is translated. Non-English users will see the new Ask/chips UI in English, and `flutter gen-l10n` will emit untranslated-message warnings that break the analyzer ratchet. Translate these keys in each locale (per AGENTS.md: 'Translate all locales') before regenerating.</violation>
</file>

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

<violation number="1" location="backend/models/chat.py:227">
P2: Scope bounds remain raw strings and require duplicate parsing after request validation; type both fields as timezone-aware `datetime` and serialize canonical values at the tool boundary.

(Based on your team's feedback about typed backend API date fields.)</violation>
</file>

<file name="app/lib/l10n/app_localizations_pl.dart">

<violation number="1" location="app/lib/l10n/app_localizations_pl.dart:9874">
P2: The four new Polish localization strings ('Today', 'This week', 'About: {title}', 'Ask about this') are untranslated English placeholders left in app_pl.arb, so Polish-speaking users will see English text in the new Ask/chips UI instead of Polish. Translate these values in app/lib/l10n/app_pl.arb and regenerate (e.g. chatScopeToday: 'Dziś', chatScopeThisWeek: 'W tym tygodniu', chatScopeAbout: 'Zapytaj o: {title}', askAboutThisConversation: 'Zapytaj o tę rozmowę').</violation>
</file>

<file name="app/lib/l10n/app_hu.arb">

<violation number="1" location="app/lib/l10n/app_hu.arb:3314">
P2: The new keys in app_hu.arb contain untranslated English strings ("Today", "This week", "About: {title}", "Ask about this"), so Hungarian users will see English text for the new chat-scope chips. Please provide Hungarian translations; also add the "@chatScopeAbout" placeholder metadata for {title} to match the template convention.</violation>
</file>

<file name="app/lib/l10n/app_ja.arb">

<violation number="1" location="app/lib/l10n/app_ja.arb:3194">
P2: These new user-facing strings are left in English in the Japanese locale file ("Today", "This week", "About: {title}", "Ask about this"), so Japanese users will see English chips/tooltips instead of translated text. Translate all four keys to Japanese (per AGENTS.md: translate all locales) and mirror the @-metadata (description/placeholders) to match the template.</violation>
</file>

<file name="app/lib/l10n/app_localizations_kn.dart">

<violation number="1" location="app/lib/l10n/app_localizations_kn.dart:9876">
P2: These new localization values are left in English ('Today', 'This week', 'Ask about this', 'About: …') in the Kannada file, so Kannada users will see English UI for the new chat-scope chips and Ask tooltip. Translate each value into Kannada in app_kn.arb (and regenerate) rather than mirroring the template text.</violation>
</file>

<file name="app/lib/l10n/app_te.arb">

<violation number="1" location="app/lib/l10n/app_te.arb:10784">
P2: These new keys are added to the Telugu locale with hardcoded English values instead of Telugu translations, so Telugu users will see "Today"/"This week"/"About: ..."/"Ask about this" in English. Translate the values (and mirror the @chatScopeAbout placeholder metadata) in the Telugu ARB per the l10n workflow that requires real translations in every locale.</violation>
</file>

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

Re-trigger cubic

Comment thread backend/utils/retrieval/chat_scope.py Resolved
Comment on lines +66 to +67
start_ts = int(start_dt.timestamp()) if start_dt is not None else None
end_ts = int(end_dt.timestamp()) if end_dt is not None else None

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: Today/This week conversation scopes drop conversations created during the final fractional second because these integer conversions narrow the end bound; preserve timestamp precision so scoped fetch matches list date filtering.

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

<comment>Today/This week conversation scopes drop conversations created during the final fractional second because these integer conversions narrow the end bound; preserve timestamp precision so scoped fetch matches list date filtering.</comment>

<file context>
@@ -42,6 +43,37 @@ def _agent_config() -> Optional[Dict[str, Any]]:
+        status_val = getattr(raw_status, 'value', raw_status)
+        if status_val is not None and str(status_val) not in statuses:
+            return [], f"No accessible conversation found for scoped id {conversation_id}."
+    start_ts = int(start_dt.timestamp()) if start_dt is not None else None
+    end_ts = int(end_dt.timestamp()) if end_dt is not None else None
+    if start_ts is not None or end_ts is not None:
</file context>
Suggested change
start_ts = int(start_dt.timestamp()) if start_dt is not None else None
end_ts = int(end_dt.timestamp()) if end_dt is not None else None
start_ts = start_dt.timestamp() if start_dt is not None else None
end_ts = end_dt.timestamp() if end_dt is not None else None

Comment thread app/lib/l10n/app_ar.arb Resolved
Comment thread app/lib/l10n/app_mk.arb Resolved
Comment thread app/lib/l10n/app_ja.arb Outdated
"accountCutoverMigrationRollbackMessage": "移行のロールバック後、アカウントはメンテナンス中です。新しいデータの一部が孤立している可能性があります。",
"accountCutoverOpenStore": "ストアを開く"
"accountCutoverOpenStore": "ストアを開く",
"chatScopeToday": "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: These new user-facing strings are left in English in the Japanese locale file ("Today", "This week", "About: {title}", "Ask about this"), so Japanese users will see English chips/tooltips instead of translated text. Translate all four keys to Japanese (per AGENTS.md: translate all locales) and mirror the @-metadata (description/placeholders) to match the template.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/l10n/app_ja.arb, line 3194:

<comment>These new user-facing strings are left in English in the Japanese locale file ("Today", "This week", "About: {title}", "Ask about this"), so Japanese users will see English chips/tooltips instead of translated text. Translate all four keys to Japanese (per AGENTS.md: translate all locales) and mirror the @-metadata (description/placeholders) to match the template.</comment>

<file context>
@@ -3190,5 +3190,9 @@
     "accountCutoverMigrationRollbackMessage": "移行のロールバック後、アカウントはメンテナンス中です。新しいデータの一部が孤立している可能性があります。",
-    "accountCutoverOpenStore": "ストアを開く"
+    "accountCutoverOpenStore": "ストアを開く",
+    "chatScopeToday": "Today",
+    "chatScopeThisWeek": "This week",
+    "chatScopeAbout": "About: {title}",
</file context>

Comment thread app/lib/l10n/app_be.arb Resolved
Comment thread app/lib/l10n/app_ur.arb Resolved
Comment thread app/lib/l10n/app_sk.arb Resolved
@Git-on-my-level Git-on-my-level removed the needs-tests PR introduces logic that should be covered by tests label Aug 8, 2026
@Git-on-my-level
Git-on-my-level dismissed their stale review August 8, 2026 22:55

Resolved on current head: backend typecheck/generator/architecture-map validation blockers are green, and this pass is non-blocking.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the updates here. I re-reviewed the current head and the earlier validation blockers look resolved: backend/models/chat.py now validates timezone-aware PageContext.start_date / end_date, the generated Flutter/API files are checked in, and backend/utils/retrieval/ARCHITECTURE.md now documents the new retrieval package boundary.

Code-specific notes from this pass:

  • backend/utils/retrieval/chat_scope.py now centralizes scope construction and date-bound intersection; the fail-closed empty-intersection error is a good guard for the tool layer.
  • backend/utils/retrieval/tools/conversation_tools.py routes scoped conversation requests through get_conversation() and refuses discarded/locked/out-of-window conversations instead of falling back to broad search.
  • backend/utils/retrieval/tools/memory_tools.py blocks global memory fact tools when a specific conversation scope is active, which avoids silently answering from unrelated memories.
  • backend/utils/llm/chat.py now makes the hard-scope semantics explicit in the system prompt, while backend/utils/retrieval/agentic.py passes the computed chat_scope through tool config.
  • On the clients, app/lib/backend/http/api/messages.dart, app/lib/pages/chat/page.dart, web/app/src/components/chat/ChatPanel.tsx, and web/app/src/lib/api.ts consistently send context.start_date / context.end_date with the chat request.
  • backend/tests/unit/test_chat_scope.py covers scope construction, timezone validation, scoped conversation fetch, discarded/out-of-window failures, and exact-reference escape attempts.

I’m not re-requesting changes. I am leaving this for human maintainer review because the feature changes product/UX semantics for combining “Ask about this conversation” with Today/This week, and non-English localization entries currently use English fallback copy across the generated ARB/localization files.

Agent-behavior note: backend/utils/retrieval/ARCHITECTURE.md is new guidance that coding/review agents may read for this backend package. The guidance is narrow and seems accurate: it documents that standard /v2/messages retrieval should fail closed under chat_scope, that unsupported tools should refuse rather than search globally, and that the Claude Agent VM path is intentionally out of scope until wired. That is safe as repo guidance, but it does mean future agents will treat this scoping contract as authoritative, so maintainer sign-off on those boundaries is worthwhile.

I could not reproduce the focused backend tests locally in this sandbox because the checkout is missing backend test dependencies (ModuleNotFoundError: No module named 'google' from tests/unit/conftest.py), but the PR’s current GitHub checks in the supplied context are green.


by AI on behalf of David — leaving for human maintainer review on the chat-scope product/UX boundary.

…pe fail-closed

Keep agentic.py baseline at measured 1517 with the BasedHardware#4515 justification.
Refuse USE_MEMORY under timeframe scope, force action-item conversation
scope, and preserve fractional end-bound timestamps for scoped fetch.

Co-authored-by: Cursor <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Addressed @9b57a1fc61ea

@Git-on-my-level @kodjima33 conflicts cleared + cubic P1 fail-closed tightenings.

Conflict

Scope harden (cubic P1s / hire-bar)

  • Memory USE_MEMORY under timeframe — get_memories_tool / search_memories_tool now refuse the unbounded default-memory adapter when Today/This week dates are active (no silent all-memory leak).
  • Action items under conversation scope — get_action_items_tool forces conversation_id from chat_scope and rejects foreign ids.
  • Fractional end bounds — scoped conversation fetch keeps float timestamps (no int() truncation of the final second).

Tests

pytest tests/unit/test_chat_scope.py → 12 passed (incl. action-item force/reject + USE_MEMORY timeframe refuse).

Non-English ARB chips still English fallbacks (called out earlier) — leaving that for product/l10n follow-up rather than blocking this tip. Honest gaps unchanged (Claude Agent VM unscoped; desktop macOS PageContext unwired; no kit smoke).

Ready for CI re-check + product/UX merge call when green.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 123 files

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

Re-trigger cubic

Comment thread backend/utils/retrieval/agentic.py Resolved
Comment thread backend/tests/unit/test_chat_scope.py Resolved
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@kodjima33 @Git-on-my-level need Nik's merge call on #11206 / #4515.

Tip cb34c53: APPROVED (kodjima33 write-access) · MERGEABLE/CLEAN · positive-signal. Product/UX hard-scope Ask semantics already confirmed acceptable per prior review passes.

25/34 checks green, only red is Sync Cloud Tasks Stack Gauntlet → Backend Hermetic Merge Gate — 4th recurrence of the same non-code flake in this PR's history: apt-get update hangs on the Ubuntu mirror mid-fetch, runs to the 20-min job timeout, gets cancelled, and the merge gate fails closed on cancelled != success. Not this branch's code — same signature every time, filed as its own issue: #11848.

Same call as last time this hit (Git-on-my-level: "merge if classified as flake") — please merge, or rerun Sync Cloud Tasks Stack Gauntlet if you'd rather see it green first (no admin rights on my side to rerun it).

The hosted runner's Azure Ubuntu mirror repeatedly stalled Redis setup until the 20-minute gauntlet deadline. Use the existing archive.ubuntu.com fallback directly for each Redis-dependent gauntlet.\n\nVerification:\n- actionlint -config-file .github/actionlint.yaml .github/workflows/backend-hermetic-e2e.yml\n- python3 backend/scripts/check_workflow_contracts.py --changed-files .github/workflows/backend-hermetic-e2e.yml\n- git diff --check\n\nFailure-Class: none

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-approving on the new head; scoping Ask to a conversation/timeframe is a feature, maintainer merge.

Same stall as backend-hermetic-e2e's Redis install (69e5a9e): the
hosted runner's Azure Ubuntu mirror hangs InRelease fetches, this time
in desktop-windows-ci's Linux runtime dependency install, until the
job's 6-hour default timeout cancels it. Drop the mirror the same way,
falling back to archive.ubuntu.com directly.

Verification:
- actionlint -config-file .github/actionlint.yaml .github/workflows/desktop-windows-ci.yml
- git diff --check
Failure-Class: none

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for continuing to push this through. I re-reviewed the current head c1e1815; the backend hard-scope work still looks directionally solid, but this head has one concrete mobile regression that should be fixed before merge.

Blocking issue:

  • app/lib/pages/chat/page.dart removes the existing provider.fetchChatApps() call from initState and only replaces that spot with the optional initialChatContext assignment. Normal ChatPage opens still need to fetch enabled chat apps; otherwise the chat-app picker / app-scoped chat state can stay unpopulated for users who are not entering from conversation detail. Please restore provider.fetchChatApps() unconditionally, then apply initialChatContext as an additional step.

Other code-specific notes from this pass:

  • app/lib/backend/http/api/messages.dart now serializes ChatPageContext into the /v2/messages body, including start_date / end_date, so the client can actually send the hard-scope payload.
  • app/lib/pages/conversation_detail/page.dart wires the new Ask button to ChatPage(initialChatContext: ChatPageContext(type: 'conversation', id: convo.id, title: ...)), which is the right entry point for conversation-scoped Ask.
  • backend/models/chat.py validates PageContext.start_date / end_date as timezone-aware ISO strings; that preserves a fail-closed API contract for ambiguous dates.
  • backend/utils/retrieval/chat_scope.py centralizes scope construction and date intersection, including empty-intersection errors instead of silently broadening the query.
  • backend/utils/retrieval/tools/conversation_tools.py now forces scoped conversation fetches through get_conversations_by_id, re-checks visibility/date bounds, and re-filters hydrated search hits against the hard timeframe.
  • backend/utils/retrieval/tools/memory_tools.py blocks global memory tools under a single-conversation scope and filters memory results to the timeframe scope when only dates are active.
  • .github/workflows/backend-hermetic-e2e.yml and .github/workflows/desktop-windows-ci.yml only remove the Azure Ubuntu mirror before apt installs, which matches the recent CI flake mitigation and does not look like a supply-chain attempt.
  • backend/tests/unit/test_chat_scope.py covers the main fail-closed cases: conversation-only scope, date intersections, stale index hit filtering, action-item conversation forcing, and memory timeframe filtering.

Agent-behavior documentation note: backend/utils/retrieval/ARCHITECTURE.md is new guidance for retrieval-package work and says chat_scope should fail closed, including refusing unsupported tools under conversation scope. That will influence future coding/review agents in this area. The guidance is consistent with this implementation, but the product/UX consequence of disabling global memory tools during conversation-scoped Ask is still a maintainer decision.

Leaving this as request changes for the fetchChatApps() regression, plus human maintainer review for the hard-scope Ask behavior and agent-facing retrieval guidance.


AI-generated maintainer review on behalf of @Git-on-my-level.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge and removed positive-signal Automation verified a genuine fix/quality contribution flutter flutter work labels Aug 19, 2026
…ope Ask

The initial hard-scope commit replaced the fetchChatApps() call with
the initialChatContext branch in the same hunk instead of alongside
it, so every ChatPage open silently stopped fetching enabled chat
apps, not just ones without a scope context. Found by Git-on-my-level
on review.

Verification:
- dart format --line-length 120 app/lib/pages/chat/page.dart
- flutter analyze app/lib/pages/chat/page.dart -> no issues

Failure-Class: none

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-approved on the new head. Feature scope (#4515) and currently conflicted, so approve-only.

# Conflicts:
#	app/lib/backend/http/api/messages.dart
#	backend/utils/retrieval/ARCHITECTURE.md
#	web/app/src/components/chat/ChatPanel.tsx
My merge of main auto-resolved web/frontend/src/app/apps/[id]/page.tsx
after BasedHardware#11696 changed it, and left the iOS/Android URL ternary indented
two spaces deeper than main. Frontend Lint fails on it with two
prettier/prettier "Delete ··" errors at 159:5 and 160:1.

This PR has no semantic change to that file — the whole diff against
main was those two indentation lines — so the fix is to take main's
version verbatim rather than re-format a file this branch should not be
touching at all.

Verification:
- git diff origin/main -- the file is now empty
- web/frontend was the only directory affected

Failure-Class: none
# Conflicts:
#	.github/workflows/backend-hermetic-e2e.yml
#	.github/workflows/desktop-windows-ci.yml
Hygiene skips on body-only edits, so the product-invariants check needs a
push to re-read the declaration.
@Git-on-my-level
Git-on-my-level dismissed their stale review August 21, 2026 19:10

Dismissed: the blocking concern from this review (provider.fetchChatApps() removed from ChatPage initState) was resolved by 9ac0df3, which restored the unconditional fetch before applying initialChatContext; verified at the current head d359d0d. Human maintainer approval on 9ac0df3 is also in place.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Aug 21, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @aryanorastar — following up on my last pass (c1e1815): 9ac0df3 resolves the blocking mobile regression, so I've dismissed that request-changes.

  • app/lib/pages/chat/page.dart — the unconditional provider.fetchChatApps() is back in initState, running before the optional initialChatContext assignment; normal ChatPage opens keep populating the chat-app picker. Verified at the current head d359d0d.

Since the human approval on 9ac0df3, the delta is only three merges of main, 2c15aa4 restoring main's indentation in web/frontend/src/app/apps/[id]/page.tsx (dropping that file from the diff), and a hygiene retrigger. I re-checked the feature files at d359d0d for merge-drift: backend/utils/retrieval/chat_scope.py (fail-closed date intersection), backend/utils/retrieval/tools/conversation_tools.py (scoped fetch plus hydrated-hit re-filter), backend/utils/retrieval/tools/memory_tools.py (memory-tool refusal under conversation scope), backend/models/chat.py (tz-aware PageContext dates), and backend/utils/llm/chat.py (HARD SCOPE prompt matching tool enforcement) all match the previously verified behavior — no conflict-resolution drift.

Checks are green with none failing or pending, and no .github workflow changes remain in the net diff. Re-adding positive-signal; what's left is the maintainer merge call on this head for the hard-scope Ask product semantics (in particular memory-tool refusal while a single-conversation scope is active) that the prior approvals already cover.


AI-generated maintainer review on behalf of @Git-on-my-level.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Feature (hard-scope Ask to conversation/timeframe), backend/mobile — approve-only per policy (features don't merge outside desktop). New commits since last review; re-approved on latest head.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@beastoin @undivisible this one needs a merge from someone who can merge features — short version, since the thread is long.

State: MERGEABLE / CLEAN / APPROVED on d359d0dd. All 25 checks green, 0 conflicts, 0 failing, 0 pending. @kodjima33 re-approved the current head an hour ago; @Git-on-my-level dismissed the last blocking review 20h ago (the fetchChatApps() regression, fixed in 9ac0df3) and restored positive-signal.

Why it hasn't merged: every approval on file carries some form of "approve-only per policy — features don't merge outside desktop". So the reviewer approving it isn't the one who can land it. That's the actual blocker, not anything in the diff.

One piece of stale bookkeeping worth clearing: the workflow-review label no longer applies. It was added when this branch carried the Azure apt-mirror workflow fixes; main has since absorbed those, so they dropped out of the diff. There are now zero .github/ files in the net diff — @Git-on-my-level noted the same at the last pass ("no .github workflow changes remain in the net diff") and flagged that the label wasn't theirs to remove. needs-maintainer-review is stale for the same reason: it went back on during the c1e1815 regression pass, which is resolved and dismissed.

To be straight about what I can and can't see: I can't read branch protection, so I don't know whether workflow-review actually gates the merge button or is purely informational. If it gates, that is the thing standing between this and merge. If it doesn't, then it's just the merge call.

Nothing is outstanding on my side. Happy to leave it if the answer is "not now" — I'd just rather that be a decision than the thread going quiet.

@Git-on-my-level Git-on-my-level removed the needs-maintainer-review Needs a human maintainer to sign off before merge label Aug 22, 2026
@undivisible
undivisible merged commit 009132d into BasedHardware:main Aug 25, 2026
48 of 50 checks passed
abunet added a commit to abunet/omi that referenced this pull request Aug 25, 2026
Conflicts: 48 `.arb` locale files plus `backend/main.py`, resolved hunk by hunk (never
`--theirs` on a whole file, BACKLOG L58).

The `.arb` set is one added key on each side landing on the same line: our `signInWithSSO`
from the OIDC sign-in work, and their `chatScope*` from BasedHardware#11206. Both kept — verified after
resolution that all 49 files still parse as JSON and that both keys are present in all 49.

`backend/main.py`: both sides append to the startup block. Kept their
`proactive_message_dispatcher` (BasedHardware#11807) in sequence and our conditional Mongo index
provisioning (ADR-0046) after it, with `_reconcile_mongo_indexes_on_startup` intact.

ADR-0030 audit: no finding. The nine `check_oss_*` guards are all 0 after the merge, so the
twelve commits introduced no raw Firestore, GCS or vector client inside our boundaries — the
way `utils/other/local_storage.py` surfaced in the +16 merge. Our port markers are all still
there (117 `_object_store()`, 151 `_signed_url`, 260 `_store()`, 58 `get_auth_provider`,
53 `_vector_store()`, 48 `get_document_store`).

Verification: pyright 1.1.403 0 errors · guard 0 x9 · contract lane dual-backend 1311 passed /
0 failed, unchanged · sweep 1025 PASS / 5 FAIL = the known residual set (upstream added three
test files), 0 regressions, 2m14s · replay harness Phase 0A GREEN/BOUNDED.
Git-on-my-level added a commit that referenced this pull request Sep 1, 2026
## Summary

- Removes the always-on **Today** / **This week** composer chips from
the Flutter `ChatPage` (`app/lib/pages/chat/page.dart`) and the
**Scope** row (Today / This week / Clear) from the web `ChatPanel`
(`web/app/src/components/chat/ChatPanel.tsx`).
- Keeps everything the chips fed: backend `chat_scope` / `PageContext`
fail-closed retrieval, `ChatPageContext` +
`sendMessageStreamToServer(..., context:)`, conversation-detail **Ask
about this** (`initialChatContext`), the conversation **About: {title}**
chip that clears an active scope, and the web `currentContext` plumbing
(header `Context: {title}` + context on Ask).
- Drops the now-unreferenced `chatScopeToday` / `chatScopeThisWeek` keys
from `app_en.arb` plus the 48 translations and regenerates the
checked-in gen-l10n output. `chatScopeAbout` and
`askAboutThisConversation` stay (still referenced).

Follow-up to #11206 / #4515: this strips only the timeframe preset UI;
#4515's backend hard-scope capability is untouched. Not a revert of
#11206.

Why: dogfooding showed the chips look tappable but only preset
`_chatScope` for the next typed Ask — selected vs unselected are
near-identical dark pills, PTT/voice never sends the scope, and no
visible Scope label makes the state discoverable.

## Verification

Flutter (`app/`):

- `dart format --line-length 120 lib/pages/chat/page.dart` → 0 changed
- `flutter analyze lib/pages/chat/page.dart` → No issues found
- `bash scripts/analyze_ratchet.sh` → passed
- `flutter gen-l10n` → checked-in output changes only drop the two
chatScope keys
- `bash test.sh` → 1656 passed, 5 skipped, 1 failed:
`conversation_location_capture_test` "shares one deadline between
capture and compatibility upload" fails only under full-suite load on
this machine and passes in isolation (`flutter test
test/unit/conversation_location_capture_test.dart` → 10/10). Timing
flake unrelated to this diff (chat page + l10n only).

Web (`web/app/`):

- `bun run lint` → zero findings for ChatPanel.tsx
- `bun run typecheck` → clean
- `bunx vitest run src/components/chat` → 8 files / 30 tests passed

No device smoke run; the composer change is verified via analyzer,
widget suite, and web tests only.

Failure-Class: none

Closes SCA-396


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12510?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app backend Backend Task (python) human Human-authored pull request mobile positive-signal Automation verified a genuine fix/quality contribution workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI Chat with a specific conversation or timeframe

4 participants