Proposal documents for AI plumbing redesign
What this is
Proposal documents under docs/proposals/v0.8/, with no code changes. Start with ai-plumbing-redesign.md: a redesign of the plumbing behind every AI call in Sure, and the pull requests that deliver it. The other documents are the evidence it draws on. Corrections and disagreements are welcome, as review comments or follow-up PRs. This PR stays a draft until the whole plan is done; the code comes as separate PRs into main, merged in order, and the spike branch is never merged (only its report is here).
| File | What it is | Read it if you… |
|---|---|---|
ai-plumbing-redesign.md | Proposal. Start here. The target structure for the AI layer: configuration, routing, consent, transports, generations, chat, the sequencer, health, controllers, invariants as tests and cops, breaking changes, and delivery in eight PRs after a spike. Opens with a one-screen summary. | want the design, or have to decide on it |
rubyllm-spike-prompt.md | Spike brief. The agent prompt for PR 1: a one-week RubyLLM spike, judged against the proposal's criteria, that decides whether the transports are hand-written. | will run or review the spike |
rubyllm-spike-report.md | Spike report. The result: a recommendation to adopt ruby_llm (tested on 2.1.1), every §19 criterion with its evidence, and a decisions register sorting the plan's choices into product decisions and technical limits, with evidence for and against each. | want to know what the spike found, or to challenge a decision |
pr-2a-transports-and-instrumentation.md | Implementation plan, 2a, #4773. The compatible and anthropic transports with probe, Ai::Error, the per-attempt time budget, instrumentation subscribers, usage per request, tracing and the proxy fix. | will build or review 2a |
pr-2b-routing-and-consent.md | Implementation plan, 2b, #4774. Ai::Config from today's ENV and settings, Ai::Routes with its data manifest, Ai::Router, Ai::Consent, Ai.available? and AiFeatureGuard; every non-chat availability check asks the router. | will build or review 2b |
pr-2c-generations.md | Implementation plan, 2c, #4775. transport.generate, Ai::Generation, Ai::Batch, Ai::GenerationJob with failover and escalation, ERB prompts and reasoning effort; bill setup, categorization and merchant detection and enhancement move onto them. | will build or review 2c |
pr-2d-jev-and-shadow-runs.md | Implementation plan, 2d, #4765. The jev transport over RubyLLM's judge, categorization's judgement, and shadow runs with Ai::Comparison for any feature. | will build or review 2d |
pr-2e-documents.md | Implementation plan, 2e, #4771. transport.embed, PDF reading with "Read as", extraction checks, OCR, embed and search_documents, the vector store fixes, and #3422's pieces on the plumbing. | will build or review 2e |
pr-3-off-the-web-thread.md | Implementation plan, PR 3. Every model call moves off the web thread: smart-fill and smart-configure, document indexing, health probes and the MCP AI tools run as jobs, with cancellation and a capsule-only check. Built in parallel with PR 4; checked against the open issues and PRs; all decisions recorded. | will build or review PR 3 |
pr-4-sequencer.md | Implementation plan, PR 4. Three lane queues, a chat thread of its own, and one gate per local model host where chat interrupts background work; #4444's typing hold moves into the gate. Starts from PR 3's first step; all decisions recorded. | will build or review PR 4 |
00-ai-ml-block-diagram.md | Orientation. One flowchart of the main blocks, an ER diagram of the AI/ML models, a legend, and how a request flows. | are new to the AI code and want the map before the detail |
01-ai-ml-workflow-map.md | Reference. Every workflow that calls an LLM, Jev, embeddings or a Ruby ML model (W1–W24), its quirks, and the interface register (D5). | are changing anything AI-, rules- or sync-related |
02-ai-architecture-review.md | Review. The AI pipeline from the Rails + Sidekiq and agent-written-contribution angles: challenges and simplifications. | maintain the codebase or review PRs |
03-ai-user-perspective-review.md | Review. The same workflows from the user's side: personas, settings scope, migration, recommendations U1–U24. | work on UX, onboarding, settings or docs |
04-rubyllm-thought-experiment.md | Thought experiment. What if every model call went through RubyLLM? The background to the spike. | are weighing a client library |
05-ai-breaking-change-option.md | Option. What the refactor would look like with breaking changes (BC1–BC11). | want the wider menu the proposal picked from |
06-ai-file-split-review.md | Review. Merge hotspots and files to split, and when. | plan PRs that touch hot files |
chatwoot-rubyllm-lessons-learned.md | Background. How Chatwoot moved its AI features to RubyLLM, and the lessons. | are weighing a client library |
The proposal
Each AI feature in Sure resolves its own provider, builds its own prompt, parses its own output and records its own usage, and the copies have drifted. The plan puts every AI call on one path:
- Configuration in the database: endpoints, their models and one ordered model list per feature, loaded from
AI_CONFIGfor config as code. The old AI ENV keeps working for a deprecation period. - One router: every feature asks it for a model, or for the reason none is available. The ordered list covers failover and escalation to a bigger model.
- One shape for every call: thin transports over
ruby_llm, oneAi::Generationfile per feature, ERB prompt files, one job, one error taxonomy, instrumentation as subscribers. - Chat first: no model call on a web thread; one gate per local host, sized from its server, where chat interrupts background work.
- Consent per feature: a family AI features page with each feature's data manifest, allowed endpoints, the family's own keys with an optional cost cap, and a member switch.
- Delivery: a RubyLLM spike (done: see below), then eight PRs: generations (in five parts, 2a to 2e), off the web thread (3a to 3d), the sequencer, RubyLLM 2.2, chat, configuration in the database (7a to 7d), health and settings pages, and allowed endpoints with own keys. Each PR replaces code outright; wrappers and temporary code only where they make the whole order clearly better.
- First place to stop: the top of stack #5504 (2c to 2f, 3a, the generation windowing and the review follow-ups), landing through
refactor/ai-plumbingin the first alpha of December. From there only bug fixes stack on #5504, and each later PR, or part, is a feature on its own stack, a release and a place to stop.
The RubyLLM spike
The spike ran, and its report is rubyllm-spike-report.md. The evidence (tests and recorded live runs, replayable without keys) is on josh-sanders/sure@spike/ruby-llm, which is never merged.
- Recommendation: adopt
ruby_llm. Every §19 criterion passes on 2.1.1 or needs a small fix in Sure's adapter; none fails. Adopted by @josh-sanders during development of this PR: 2.1.1 from PR 2, 2.2 from PR 5 (not waited for),~> 2.1during delivery, pinned when PR 9 lands. Like every product decision it stays open. - A decisions register. The spike's second purpose was to sort the plan's choices into product decisions and technical limits, with evidence for and against every product decision. No product decision, and no in-scope or out-of-scope line, is final. Calls @josh-sanders made during development of this PR are marked; they're proposals for the maintainers to accept or overturn. Some choices the plan presents as constraints turned out to be decisions: "failover only at the start of a turn" (provider state can move, with Google's placeholder signature) and "Sure is never an MCP client" (RubyLLM's client worked against Sure's own
/mcp). - Changes the plan needs, among others:
- store each message's producer and provider state (
messages.provider_state); - give an empty balance its own error (Anthropic's 400, OpenAI's retried 429);
- PDF import: the PDF itself where the model takes one, otherwise the text layer first, then page images or OCR when it fails its checks; every page read, in batches sized to the model (the five-page cap came from sending every page in one request); check every extraction (reconciles, dates anchored to amounts) and offer a failing one for review; a hardened
pdftoppm; - time budgets per attempt, since the
autoJSON-mode chain multiplies a slow model's time. - mark the smallest thing a failure proves broken (the server, the key or the model), so one model's 503 on a gateway doesn't take the whole gateway out;
- one turn per chat: today two jobs can run one chat and run a write tool twice;
- on one slot, llama.cpp kept a chat's prompt across other calls between its rounds, and closing a background call's connection stopped even a prompt read (a chat's wait fell from about 209 s to about 20 s), so chat interrupts by closing the connection.
- store each message's producer and provider state (
- Bugs on
mainit found: statements uploaded to OpenAI vector stores are never deleted;pdftoppmrenders every page to send five and exits 0 with a blank 1×1 page when it can't allocate one. - Tested beyond the brief: every RubyLLM 2.1 feature on its feature list and its ecosystem gems.
ruby_llm-monitoringwould rename Sure'sLlm…classes app-wide, andruby_llm-instructorandruby_llm-red_candleinstall beside 2.x but fail on it. - Not judged: Anthropic's and OpenAI's successful paths (the keys had no credits), OCR through RubyLLM (no key), and web search, batches and caching (refused by Gemini's free tier).
Decisions made so far
@josh-sanders has made the product decisions for PRs 2 to 4 during development of this PR; the plan and the register mark each one ("call by @josh-sanders during development of PR #4440"). PRs 5 and 6 are decided after PR 4's work. Before each PR's decisions, the PRs and issues that built the features it replaces were read, and any departure from their contributors' goals is justified in the plan. Among them:
- Usage is recorded per request and shown per call; Sure's list of models is the only failover layer, marking the smallest thing a failure proves broken; a family's own key never falls back to the operator's, and can have a cost cap (PR 9).
- Prompts are ERB files, every one of today's prompts kept word for word; family overrides stay plain text.
- Shadow runs work for any feature, with each family opting in from PR 7.
- PDF import gets a per-upload "Read as" choice, with Auto tuning itself per account; the document store stays pluggable.
- Smart-fill, smart-configure and health probes move off the web thread; MCP's two AI tools move only their model call, with no change for MCP clients.
- Chat can be stopped; #4444's typing hold moves into the gate, and #4237's health signals carry over.
What changed from the RFC
- Replace, don't wrap. No delegating router over today's code; each PR deletes what it replaces.
- Breaking changes are allowed, each with a migration and an upgrade note, instead of waiting for a minor release behind its own ADR.
- Configuration moves into the database instead of an
AiConfigregistry over ENV. - Open decisions are made: per-feature family consent with a member switch (D4), instance AI settings only for instance managers (D5), tuning out of ENV (D7), and
previous_response_idkept on the same endpoint (D8). - RubyLLM was tested by a timeboxed spike, not deferred. It recommends adoption; the decision stays open (see above).
- Out of scope: the MCP server's own changes (a separate proposal, including an asynchronous
import_bank_statement), suggestions instead of AI locks, and rule ordering (D2, D3, D6). Like every scope line, these stay open to evidence.
How to review
- Read the plan's summary, sections 2–3 (who the AI layer serves, the target shape) and 19 (delivery), then the sections each PR names. Section 21 lists the related documents and the terms the plan defines.
- For the spike, start with the report's decisions register, then the sections it links to.
- The proposal targets
main@a6767e931; the commits up to5ed910330(after v0.7.6) were checked for impact.
🤖 Generated with Claude Code