AI plumbing 2b: routing and consent

Merged
JO
8d ago
+2213-332

Part 2b of the AI plumbing series, stacked: 2a (#4773) → 2b (#4774) → 2c (#4775) → 2d (#4765) → 2e (#4771). Merge them in that order. This branch contains the parts before it, so its diff shows their commits until they merge; this part is its last 19 commits (not counting merges). Compare 2b alone: feat/ai-2a-transports...feat/ai-2b-routing.

Part 2b of the AI plumbing redesign proposed in #4440. Split out of #4765, which held 2a to 2d and now holds 2d only. Implementation plan:
pr-2b-routing-and-consent.md; its place in the series is in
§19.

Close #2292 AI rule actions hidden when Anthropic-only — router/Ai.available? (drift bug 1)

Problem

Seven or more checks decide whether an AI feature is available, each reading providers its own
way, and they have drifted:

  • Drift bug 1: the Enhance merchants button looks only for OpenAI
    (get_provider(:openai)), so on an Anthropic-only install it's hidden, though the enhancer
    runs on Anthropic. The enhance action itself has no check.
  • Drift bug 5: embeddings read only OPENAI_URI_BASE and OPENAI_ACCESS_TOKEN from ENV,
    never the values saved in Settings, so an install configured in the UI sends embeddings to
    api.openai.com without a key.
  • Rule actions, the bills dialogs, PDF import, MCP's import_bank_statement, document upload and
    document search each check providers differently. Bill AI also turns off whenever chat
    can't run (User#ai_enabled? includes "chat works").

What this adds

flowchart TB
  ENV[("ENV + Setting<br/>(today's values)")] --> LEC["Ai::LegacyEnvConfig<br/>§4.5 table, today's resolvers"]
  LEC --> CFG["Ai::Config.current<br/>endpoints, models, routes per feature"]
  CFG --> R["Ai::Router#resolve(feature)"]
  RT["Ai::Routes::MATRIX<br/>lane, needs, consent, sends"] --> R
  CON["Ai::Consent<br/>the user's AI switch (chat, bills)"] --> R
  R --> AV["Ai.available? / Ai.availability / Ai.plan"]
  AV --> G["requires_ai<br/>smart fill, smart configure, merchants#enhance"]
  AV --> V["Enhance button, rule actions, document upload,<br/>MCP tool list, PDF job, document search"]
  CFG --> VS["VectorStore: store, embedding server, model"]
  CFG --> AH["AiHealth::Probe endpoints"]
flowchart LR
  F["feature"] --> L{"routes listed?"}
  L -- no --> NC[":not_configured"]
  L -- yes --> C{"Ai::Consent"}
  C -- denied --> UD[":user_disabled"]
  C -- ok --> K{"a model meets the feature's needs?"}
  K -- no --> CM[":capability_missing"]
  K -- yes --> P["Ai::Plan (ordered routes)"]
  • Ai::Config, built in each process by Ai::LegacyEnvConfig from today's AI ENV and
    Setting fields (§4.5), calling today's resolvers (Provider::Registry, effective_model,
    Assistant::External.config), so it can't disagree with the calls not yet on the router.
    Endpoints, models with the capabilities today's providers accept, and one ordered list of routes
    per feature. It's rebuilt when one of its inputs changes, so a value saved in the UI applies at
    once.
  • Ai::Routes, the routing table: each feature's lane, needs, consent level and the data it
    sends (sends:), with descriptions in config/locales/models/ai/en.yml and a generated table
    in docs/llm-guides/ai-pipeline.md (bin/rails ai:routes_doc).
  • Ai::Router with Ai.available?, Ai.availability (a reason and a message) and Ai.plan.
  • Ai::Consent, keeping today's checks: chat and bills need the user's own AI switch
    (users.ai_enabled), nothing else needs consent. PR 7 adds the family's consent.
  • AiFeatureGuard (requires_ai :feature): HTML is sent back with the reason; JSON gets
    403 { "error": "ai_unavailable", "reason": ... }.
  • Family::AiSettings: family.rb's AI settings moved, unchanged, into one concern.
  • Sure/NoAiEnv: no ENV reads of AI configuration outside Ai::LegacyEnvConfig. Today's
    readers are allowlisted with the part that replaces each; the list only shrinks.
  • Every non-chat availability check asks the router: the Enhance button and action, both
    AI rule actions, the uncategorized-transactions diagnostic, smart-fill and smart-configure, PDF
    import's job and MCP tool, document upload, document search, the PDF job's vector store upload,
    and the rule cost estimates. VectorStore takes its store and embedding server from
    Ai::Config (drift bug 5), and the health probes use the configured endpoints.
  • import_bank_statement is listed in chat and MCP only while extract_pdf is available
    (§14). search_family_files stays listed; its fallback comes in 2e.

Reviewer guide

Read in this order:

  1. app/models/ai/routes.rb and app/models/ai/router.rb.
  2. app/models/ai/legacy_env_config.rb, the §4.5 table in code.
  3. test/architecture/ai_agreement_test.rb and ai_config_test.rb. They run every setup from
    #4440's E2 experiment (C1–C9) plus mixed ones (test/support/ai_legacy_setups.rb), and check
    that every entry point and today's provider resolution agree with the router.
  4. The call sites, in the commit "Ask the router in every other non-chat AI availability check".

Deleted: FamilyMerchantsController's OpenAI-only check, bills_one_shot_ai_available?
(its chat buttons keep the same expression as bills_ai_chat_available? until PR 6),
Family#categorization_model_name, VectorStore::Registry's own resolution, the ENV-only
embedding settings, and the availability stubs in their tests (preferred_llm_provider,
resolved_categorization_provider, categorization_model_name, VectorStore::Registry.adapter).

Decided during development of #4440 (@josh-sanders):

  • Chat's buttons outside chat keep today's gate until PR 6: the bills AI review and prompt
    chips, "Review with AI" and "Dig in with AI". They're on the agreement test's allowlist with
    chat's other known disagreements (C6, C8 and mcp_only), and PR 6 empties it.
  • PDF import checks in the job, as today. The upload still always queues the job; the job asks
    for extract_pdf and fails with today's message.
  • The user switch keeps today's checks (chat and bills), with nothing added to the prompt.

Worth a look:

  • Jev serves only families that chose it, through a route condition 2d deletes with
    families.categorization_provider. That's today's per-family rule.
  • Capabilities on today's models reproduce today's answers: chat's prefix allow-list decides
    tools, so with o4-mini the router says chat can't run, which is what happens today when a
    turn is sent.
  • The health probes now send only static extra headers. 2a's probe sent a {session_id}
    header value literally.
  • New strings are in en.yml only.

Upgrade notes

  • Enhance merchants appears on Anthropic-only installs.
  • Embeddings fall back to the OpenAI URL and key saved in Settings when EMBEDDING_* isn't
    set; before, they used only ENV.
  • Bill AI follows the user's AI switch, not whether chat works, so an mcp_only family's
    smart-fill and smart-configure follow each member's switch.
  • MCP clients don't see import_bank_statement when no model can extract a statement.
  • Give the web and worker containers the same AI variables. Each builds its own Ai::Config
    until PR 7.

Still on old code

  • The calls themselves: generations still pick their provider with preferred_llm_provider
    (until 2c and 2e) and resolved_categorization_provider (2c); Jev until 2d. The config test
    checks that the router's first route is the provider those pick.
  • Chat's availability: User#ai_available?, RequiresAiConsent, the API's
    require_ai_enabled, Dig in and the bills chat buttons, until PR 6.
  • Configuration is edited on the hostings page, and read from ENV and Setting, until PR 7.

Validation

Run on this branch alone at 78874007a (with main at 4f2970b0f merged in through 2a):

  • bin/rails test: 15,471 runs, 0 errors, 13 failures. Each also fails on main in the same
    environment (Wise ×10, BinanceItems, Budget and FinanceKit-demo date tests). None touches AI code.
  • bin/rubocop, with Sure/NoAiEnv and Sure/NoPromptHeredoc: no offenses
  • bundle exec erb_lint --lint-all: no errors (at 52391bc40; nothing since touches views)
  • npm run lint (Biome): clean (at 52391bc40; nothing since touches JavaScript)
  • bin/brakeman: no warnings
  • Pipelock 3.6.0 git scan-diff of main...HEAD: no findings (at d98ddd129)
  • System tests: the full system suite ran at the top of the stack (#4765): 333 runs, with only
    the 2 combobox dark-theme colour checks failing, as on main. CI runs them on this head.
  • Live, at 52391bc40, against real servers (Ai.availability for every feature, the health
    probes, an embed round trip and a bill-setup generation):
    • llama.cpp (qwen3.6 + granite embeddings on pgvector): every feature routed; probes pass (the
      tool probe needs AI_HEALTH_PROBE_TIMEOUT above 5 s on CPU); embeddings stored and searched;
      bill setup ran end to end.
    • Settings only, no AI ENV: embeddings go to the saved URL (drift bug 5 fixed).
    • OpenRouter: routing right; calls got 429 on the free tier. Anthropic only: every feature
      available, including enhance_merchants.
    • Two cases match today but fail at run time: a custom OpenAI URL gets OpenAI's vector store,
      and Anthropic-only routes embeddings to api.openai.com without a key. Both are fixed in 2e.

Review on this PR

  • @jjmata's three notes are fixed in 77b8a8f49: Ai::Routes.row_key names a feature's consent
    row in one place (shadows and consent_as:, not route_of:), the router reuses its spec, and
    Ai::Consent.denial drops the unused argument.
  • CodeRabbit's and Codex's review after it went ready: fixed in 2a (a07d7af0d: a proxy leak on
    port-qualified NO_PROXY, OpenRouter's proxy, retry waits against the budget, secrets scrubbed from Langfuse
    content, invalid model lists and embeddings, the backfill's JSON check) and 2b (8c0a651f3: the vector store
    nil check, the probe's API choice and cache key, chat's caveat in the docs). The rest have replies with reasons.
  • CodeRabbit's review of 52391bc40: the buildable nitpick is fixed in e66e7f368: a preferred
    provider whose client can't be built (Anthropic on a custom URL with no model) now ends the route
    list, as preferred_llm_provider raises there instead of reaching OpenAI. Shadow routes (2d),
    chat for mcp_only (PR 6) and PDF support in extract_pdf (2e) have replies. Its findings on
    2a's files are fixed in 2a (5f04861ed, 4a27814e1, 6dd8328ee, 5ad3004c7).
  • Comments say what the code does, not which PR brings what (AGENTS.md), as on 2a: e967c6b58.
    The Sure/NoAiEnv allowlist names the feature each entry serves.

Merged forward

This branch merges 2a, and through it main (up to 4f2970b0f, 2026-11-09). From 2a:

  • live-testing fixes: Anthropic's models probe through Sure's proxy, and metadata tracing flushed
    at exit;
  • #4773's review: the RubyLLM TLS adapter, an error per failed request, cache tokens counted and
    priced, header values scrubbed from errors, stricter probe model names and timeouts, probes kept
    out of traces, whole calls and cancellations on the usage page, and comments without PR history;
  • CodeRabbit's later transport findings: a retry's timeout no longer rounded up, NO_PROXY CIDR
    blocks matched against the resolved host, and the 2a findings from this PR's review.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ

Summary by CodeRabbit

  • New Features
    • AI-powered features now use consistent routing and availability checks across bills, transaction categorization, merchant enhancement, document imports, and assistant tools.
    • When an AI feature is unavailable, affected actions provide a relevant message; document uploads are blocked before import begins.
    • AI usage settings now show total calls, average cost per call, and how many calls have cost data.
  • Documentation
    • Added guidance on AI routing, consent, configuration, and data handling; updated hosting instructions.
  • Bug Fixes
    • PDF imports skip vector-store uploads when embedding is unavailable.